Nordic stack and drivers for the mbed BLE API

Fork of nRF51822 by Nordic Semiconductor

Files at this revision

API Documentation at this revision

Comitter:
Vincent Coubard
Date:
Wed Sep 14 14:39:43 2016 +0100
Parent:
637:f7faad332abc
Commit message:
Sync with bdab10dc0f90748b6989c8b577771bb403ca6bd8 from ARMmbed/mbed-os.

Changed in this revision

CHANGELOG.md Show diff for this revision Revisions of this file
LICENSE Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/CHANGELOG.md Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/LICENSE Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/apache-2.0.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/bootloader/s110_nrf51822_8.0.0_bootloader.hex Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/bootloader/s130_nrf51_1.0.0_bootloader.hex Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/bootloader/softdevice_nrf51822_licence_agreement.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/module.json Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/BSD-3clause-Nordic.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/CHANGELOG.md Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/LICENSE Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/README.md Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/apache-2.0.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/module.json Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/script/copyright_header.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/script/pick_nrf51_files.py Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/script/replace_headers.py Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/script/required_files.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_date_time.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_gatt_db.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_sensor_location.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/device_manager/config/device_manager_cnfg.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager_peripheral.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_manager_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/device/compiler_abstraction.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/device/nrf.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/device/nrf51.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/device/nrf51_bitfields.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/device/nrf51_deprecated.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpio.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpiote.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_temp.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_wdt.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/config/pstorage_platform.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_bank_internal.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc_internal.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init_template.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_transport.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/experimental_section_vars/section_vars.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_config.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_types_internal.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_config.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_nosd.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/timer/app_timer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/nordic_common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_errors.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_os.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/prevent_bootloader_frame_pointer.cmake Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ant_stack_handler_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ble_stack_handler_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.c Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_err.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatt.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gattc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatts.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_hci.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_l2cap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_ranges.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_types.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_ble.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_sdm.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_soc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_mbr.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_sdm.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_soc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_svc.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/softdevice_assert.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/supress-warnings.cmake Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/sdk/source/toolchain/system_nrf51.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/softdevice_nrf51822_licence_agreement.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_advertising.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_advertising.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_discovery.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_discovery.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_gap.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_gap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_security.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/btle_security.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/custom/custom_helper.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/btle/custom/custom_helper.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/ansi_escape.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/assertion.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/binary.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/ble_error.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/common/compiler.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGap.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGattClient.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGattClient.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGattServer.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xGattServer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xSecurityManager.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xn.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/nRF5xn.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/projectconfig.h Show annotated file Show diff for this revision Revisions of this file
TARGET_MCU_NRF51822/source/supress-warnings.cmake Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/CHANGELOG.md Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/LICENSE Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/apache-2.0.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/module.json Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/softdevice_nrf51822_licence_agreement.txt Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_advertising.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_advertising.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_clock.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_discovery.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_discovery.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_gap.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_gap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_security.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/btle_security.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/custom/custom_helper.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/btle/custom/custom_helper.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/ansi_escape.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/assertion.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/binary.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/ble_error.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/common.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/common/compiler.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGap.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGap.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGattClient.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGattClient.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGattServer.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xGattServer.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xSecurityManager.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xServiceDiscovery.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xServiceDiscovery.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xn.cpp Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/nRF5xn.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/projectconfig.h Show annotated file Show diff for this revision Revisions of this file
TARGET_NRF5/source/supress-warnings.cmake Show annotated file Show diff for this revision Revisions of this file
apache-2.0.txt Show diff for this revision Revisions of this file
bootloader/s110_nrf51822_8.0.0_bootloader.hex Show diff for this revision Revisions of this file
bootloader/s130_nrf51_1.0.0_bootloader.hex Show diff for this revision Revisions of this file
bootloader/softdevice_nrf51822_licence_agreement.txt Show diff for this revision Revisions of this file
module.json Show diff for this revision Revisions of this file
nrf51-sdk.lib Show diff for this revision Revisions of this file
softdevice_nrf51822_licence_agreement.txt Show diff for this revision Revisions of this file
source/btle/btle.cpp Show diff for this revision Revisions of this file
source/btle/btle.h Show diff for this revision Revisions of this file
source/btle/btle_advertising.cpp Show diff for this revision Revisions of this file
source/btle/btle_advertising.h Show diff for this revision Revisions of this file
source/btle/btle_discovery.cpp Show diff for this revision Revisions of this file
source/btle/btle_discovery.h Show diff for this revision Revisions of this file
source/btle/btle_gap.cpp Show diff for this revision Revisions of this file
source/btle/btle_gap.h Show diff for this revision Revisions of this file
source/btle/btle_security.cpp Show diff for this revision Revisions of this file
source/btle/btle_security.h Show diff for this revision Revisions of this file
source/btle/custom/custom_helper.cpp Show diff for this revision Revisions of this file
source/btle/custom/custom_helper.h Show diff for this revision Revisions of this file
source/common/ansi_escape.h Show diff for this revision Revisions of this file
source/common/assertion.h Show diff for this revision Revisions of this file
source/common/binary.h Show diff for this revision Revisions of this file
source/common/ble_error.h Show diff for this revision Revisions of this file
source/common/common.h Show diff for this revision Revisions of this file
source/common/compiler.h Show diff for this revision Revisions of this file
source/nRF5xCharacteristicDescriptorDiscoverer.cpp Show diff for this revision Revisions of this file
source/nRF5xCharacteristicDescriptorDiscoverer.h Show diff for this revision Revisions of this file
source/nRF5xDiscoveredCharacteristic.cpp Show diff for this revision Revisions of this file
source/nRF5xDiscoveredCharacteristic.h Show diff for this revision Revisions of this file
source/nRF5xGap.cpp Show diff for this revision Revisions of this file
source/nRF5xGap.h Show diff for this revision Revisions of this file
source/nRF5xGattClient.cpp Show diff for this revision Revisions of this file
source/nRF5xGattClient.h Show diff for this revision Revisions of this file
source/nRF5xGattServer.cpp Show diff for this revision Revisions of this file
source/nRF5xGattServer.h Show diff for this revision Revisions of this file
source/nRF5xSecurityManager.h Show diff for this revision Revisions of this file
source/nRF5xServiceDiscovery.cpp Show diff for this revision Revisions of this file
source/nRF5xServiceDiscovery.h Show diff for this revision Revisions of this file
source/nRF5xn.cpp Show diff for this revision Revisions of this file
source/nRF5xn.h Show diff for this revision Revisions of this file
source/projectconfig.h Show diff for this revision Revisions of this file
source/supress-warnings.cmake Show diff for this revision Revisions of this file
diff -r f7faad332abc -r c90ae1400bf2 CHANGELOG.md
--- a/CHANGELOG.md	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,344 +0,0 @@
-# Change Log
-
-## [v2.5.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.3) (2016-02-16)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.2...v2.5.3)
-
-**Merged pull requests:**
-
-- Fix for compilation errors with S110 softdevice in btle.cpp [\#109](https://github.com/ARMmbed/ble-nrf51822/pull/109) ([ddavidebor](https://github.com/ddavidebor))
-
-## [v2.5.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.2) (2016-02-16)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.1...v2.5.2)
-
-**Merged pull requests:**
-
-- Sync develop against master [\#113](https://github.com/ARMmbed/ble-nrf51822/pull/113) ([pan-](https://github.com/pan-))
-- Fix incorrect handles of characteristics descriptors. [\#112](https://github.com/ARMmbed/ble-nrf51822/pull/112) ([pan-](https://github.com/pan-))
-
-## [v2.5.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.1) (2016-01-27)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.0...v2.5.1)
-
-**Merged pull requests:**
-
-- Remove Gap::state updates from this module [\#108](https://github.com/ARMmbed/ble-nrf51822/pull/108) ([andresag01](https://github.com/andresag01))
-- merge version  [\#106](https://github.com/ARMmbed/ble-nrf51822/pull/106) ([pan-](https://github.com/pan-))
-
-## [v2.5.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.0) (2016-01-12)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.1...v2.5.0)
-
-**Merged pull requests:**
-
-- Fix access to enum member [\#105](https://github.com/ARMmbed/ble-nrf51822/pull/105) ([pan-](https://github.com/pan-))
-- Hotfix dependency [\#104](https://github.com/ARMmbed/ble-nrf51822/pull/104) ([pan-](https://github.com/pan-))
-- Finish implementation of getAddressesFromBondTable [\#103](https://github.com/ARMmbed/ble-nrf51822/pull/103) ([andresag01](https://github.com/andresag01))
-
-## [v2.4.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.1) (2016-01-11)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.0...v2.4.1)
-
-**Merged pull requests:**
-
-- merge branch develop \(v2.4.0\) [\#100](https://github.com/ARMmbed/ble-nrf51822/pull/100) ([pan-](https://github.com/pan-))
-
-## [v2.4.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.0) (2016-01-10)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.1...v2.4.0)
-
-**Merged pull requests:**
-
-- Add implementation of experimental whitelisting API [\#99](https://github.com/ARMmbed/ble-nrf51822/pull/99) ([andresag01](https://github.com/andresag01))
-
-## [v2.3.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.1) (2016-01-07)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.0...v2.3.1)
-
-**Merged pull requests:**
-
-- Update yotta module dependencies [\#98](https://github.com/ARMmbed/ble-nrf51822/pull/98) ([pan-](https://github.com/pan-))
-
-## [v2.3.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.0) (2015-12-23)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.10...v2.3.0)
-
-**Merged pull requests:**
-
-- Implementation of Characteristic descriptor discovery [\#74](https://github.com/ARMmbed/ble-nrf51822/pull/74) ([pan-](https://github.com/pan-))
-
-## [v2.2.10](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.10) (2015-12-23)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.9...v2.2.10)
-
-**Fixed bugs:**
-
-- nRF5xn::init don't verify if errors have occurred during btle\_init [\#59](https://github.com/ARMmbed/ble-nrf51822/issues/59)
-
-**Closed issues:**
-
-- A call to shutdown does not clear the state of some components of BLE API [\#85](https://github.com/ARMmbed/ble-nrf51822/issues/85)
-- Memory allocation issue on the NRF51DK board. [\#76](https://github.com/ARMmbed/ble-nrf51822/issues/76)
-- Terrible handling of initLen / minLen and variable length characteristics. [\#56](https://github.com/ARMmbed/ble-nrf51822/issues/56)
-
-**Merged pull requests:**
-
-- Fix shutdown of Gap instance to avoid NULL refs [\#96](https://github.com/ARMmbed/ble-nrf51822/pull/96) ([andresag01](https://github.com/andresag01))
-- Add check for return code of ble\_init [\#95](https://github.com/ARMmbed/ble-nrf51822/pull/95) ([andresag01](https://github.com/andresag01))
-
-## [v2.2.9](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.9) (2015-12-18)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.8...v2.2.9)
-
-**Closed issues:**
-
-- Cannot open source input file "system\_nrf51.h" [\#52](https://github.com/ARMmbed/ble-nrf51822/issues/52)
-
-**Merged pull requests:**
-
-- Remove occurrence of deprecated appearance enum [\#92](https://github.com/ARMmbed/ble-nrf51822/pull/92) ([andresag01](https://github.com/andresag01))
-
-## [v2.2.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.8) (2015-12-16)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.7...v2.2.8)
-
-## [v2.2.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.7) (2015-12-15)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.6...v2.2.7)
-
-**Merged pull requests:**
-
-- Replace deprecated inclusions of mbed.h [\#89](https://github.com/ARMmbed/ble-nrf51822/pull/89) ([andresag01](https://github.com/andresag01))
-- Improve shutdown to clear BLE API and not just SD [\#87](https://github.com/ARMmbed/ble-nrf51822/pull/87) ([andresag01](https://github.com/andresag01))
-
-## [v2.2.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.6) (2015-12-15)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.5...v2.2.6)
-
-**Merged pull requests:**
-
-- follow the extraction of address related types from Gap.h into BLEProtocol.h [\#88](https://github.com/ARMmbed/ble-nrf51822/pull/88) ([rgrover](https://github.com/rgrover))
-
-## [v2.2.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.5) (2015-12-11)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.3...v2.2.5)
-
-**Merged pull requests:**
-
-- Added SecurityManager::setLinkSecurity call for elevating security settings on a particular connection. [\#86](https://github.com/ARMmbed/ble-nrf51822/pull/86) ([marcuschangarm](https://github.com/marcuschangarm))
-
-## [v2.2.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.3) (2015-12-10)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.2...v2.2.3)
-
-## [v2.2.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.2) (2015-12-08)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.1...v2.2.2)
-
-**Merged pull requests:**
-
-- Add -Wno-unused-function to supress-warnings.cmake [\#83](https://github.com/ARMmbed/ble-nrf51822/pull/83) ([andresag01](https://github.com/andresag01))
-
-## [v2.2.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.1) (2015-12-08)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.0...v2.2.1)
-
-**Merged pull requests:**
-
-- WIP: UUID endian change [\#82](https://github.com/ARMmbed/ble-nrf51822/pull/82) ([marcuschangarm](https://github.com/marcuschangarm))
-
-## [v2.2.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.0) (2015-12-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.4...v2.2.0)
-
-## [v2.1.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.4) (2015-12-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.3...v2.1.4)
-
-## [v2.1.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.3) (2015-12-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.2...v2.1.3)
-
-## [v2.1.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.2) (2015-12-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.1...v2.1.2)
-
-**Merged pull requests:**
-
-- Allow GattAttributes to have variable length [\#81](https://github.com/ARMmbed/ble-nrf51822/pull/81) ([andresag01](https://github.com/andresag01))
-
-## [v2.1.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.1) (2015-12-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.0...v2.1.1)
-
-**Merged pull requests:**
-
-- Fixed endianness bug in nRF5xServiceDiscovery::processDiscoverUUIDResponse so it is consistent with BLE API. [\#80](https://github.com/ARMmbed/ble-nrf51822/pull/80) ([marcuschangarm](https://github.com/marcuschangarm))
-- Fixed bug in nRF5xGap.setAddress where random adresses where not set properly. [\#79](https://github.com/ARMmbed/ble-nrf51822/pull/79) ([marcuschangarm](https://github.com/marcuschangarm))
-- Separate concept of minlen and len for BLE chars [\#78](https://github.com/ARMmbed/ble-nrf51822/pull/78) ([andresag01](https://github.com/andresag01))
-- Split nordic sdk into its own module [\#75](https://github.com/ARMmbed/ble-nrf51822/pull/75) ([LiyouZhou](https://github.com/LiyouZhou))
-
-## [v2.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.0) (2015-11-27)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.8...v2.1.0)
-
-**Merged pull requests:**
-
-- Update to sdk 8.1 [\#77](https://github.com/ARMmbed/ble-nrf51822/pull/77) ([LiyouZhou](https://github.com/LiyouZhou))
-
-## [v2.0.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.8) (2015-11-26)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.7...v2.0.8)
-
-## [v2.0.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.7) (2015-11-26)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.6...v2.0.7)
-
-**Closed issues:**
-
-- test2000 [\#72](https://github.com/ARMmbed/ble-nrf51822/issues/72)
-- test1000000 [\#71](https://github.com/ARMmbed/ble-nrf51822/issues/71)
-- test4 [\#70](https://github.com/ARMmbed/ble-nrf51822/issues/70)
-- test3 [\#69](https://github.com/ARMmbed/ble-nrf51822/issues/69)
-- test2 [\#68](https://github.com/ARMmbed/ble-nrf51822/issues/68)
-
-**Merged pull requests:**
-
-- use Extern c around \#include to use nordic sdk headers implemented in C [\#73](https://github.com/ARMmbed/ble-nrf51822/pull/73) ([LiyouZhou](https://github.com/LiyouZhou))
-
-## [v2.0.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.6) (2015-11-17)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.5...v2.0.6)
-
-**Closed issues:**
-
-- test [\#66](https://github.com/ARMmbed/ble-nrf51822/issues/66)
-
-**Merged pull requests:**
-
-- add Nordic's license agreement. [\#67](https://github.com/ARMmbed/ble-nrf51822/pull/67) ([rgrover](https://github.com/rgrover))
-
-## [v2.0.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.5) (2015-11-16)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.4...v2.0.5)
-
-**Merged pull requests:**
-
-- Post radio notification callback through minar [\#65](https://github.com/ARMmbed/ble-nrf51822/pull/65) ([andresag01](https://github.com/andresag01))
-
-## [v2.0.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.4) (2015-11-13)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.3...v2.0.4)
-
-**Merged pull requests:**
-
-- Fix assembly sequence to start bootloader in GCC [\#64](https://github.com/ARMmbed/ble-nrf51822/pull/64) ([andresag01](https://github.com/andresag01))
-
-## [v2.0.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.3) (2015-11-09)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.2...v2.0.3)
-
-**Merged pull requests:**
-
-- Added watchdog header file from Nordic SDK 8.1 [\#62](https://github.com/ARMmbed/ble-nrf51822/pull/62) ([marcuschangarm](https://github.com/marcuschangarm))
-
-## [v2.0.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.2) (2015-11-03)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-release-15-11...v2.0.2)
-
-## [mbedos-release-15-11](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-release-15-11) (2015-11-03)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.1...mbedos-release-15-11)
-
-## [v2.0.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.1) (2015-11-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.0...v2.0.1)
-
-**Merged pull requests:**
-
-- Ensure that the initialization flags is set to false if the BLE stack is shutdown properly. [\#58](https://github.com/ARMmbed/ble-nrf51822/pull/58) ([pan-](https://github.com/pan-))
-
-## [v2.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.0) (2015-11-02)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.1.0...v2.0.0)
-
-**Closed issues:**
-
-- Nordic SDK and SoftDevice [\#57](https://github.com/ARMmbed/ble-nrf51822/issues/57)
-- shouldn't eab6631cb be merged into master? [\#54](https://github.com/ARMmbed/ble-nrf51822/issues/54)
-
-**Merged pull requests:**
-
-- Introduced changes for memory savings [\#55](https://github.com/ARMmbed/ble-nrf51822/pull/55) ([andresag01](https://github.com/andresag01))
-
-## [v1.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.1.0) (2015-10-28)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.0.0...v1.1.0)
-
-**Closed issues:**
-
-- target dependencies in module.json [\#50](https://github.com/ARMmbed/ble-nrf51822/issues/50)
-
-**Merged pull requests:**
-
-- When connecting, if no scanning parameters are passed, use values from Gap parent. [\#53](https://github.com/ARMmbed/ble-nrf51822/pull/53) ([marcuschangarm](https://github.com/marcuschangarm))
-
-## [v1.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.0.0) (2015-10-19)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-techcon-oob2...v1.0.0)
-
-## [mbedos-techcon-oob2](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-techcon-oob2) (2015-10-19)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.8...mbedos-techcon-oob2)
-
-**Closed issues:**
-
-- rename the bootloader files with \_fota in the name? [\#51](https://github.com/ARMmbed/ble-nrf51822/issues/51)
-
-**Merged pull requests:**
-
-- Update S110 detection macros, again [\#49](https://github.com/ARMmbed/ble-nrf51822/pull/49) ([jpbrucker](https://github.com/jpbrucker))
-- Error check number of characteristics [\#48](https://github.com/ARMmbed/ble-nrf51822/pull/48) ([Timmmm](https://github.com/Timmmm))
-
-## [v0.4.8](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.8) (2015-09-25)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.7...v0.4.8)
-
-**Closed issues:**
-
-- Error real cause loss in nRF5xGattServer.cpp [\#44](https://github.com/ARMmbed/ble-nrf51822/issues/44)
-
-**Merged pull requests:**
-
-- rgrover patch fixed [\#47](https://github.com/ARMmbed/ble-nrf51822/pull/47) ([fabiencomte](https://github.com/fabiencomte))
-- Update S110 detection macros [\#43](https://github.com/ARMmbed/ble-nrf51822/pull/43) ([jpbrucker](https://github.com/jpbrucker))
-- remove some unnecessary include paths [\#42](https://github.com/ARMmbed/ble-nrf51822/pull/42) ([autopulated](https://github.com/autopulated))
-- Add FOTA bootloader image [\#41](https://github.com/ARMmbed/ble-nrf51822/pull/41) ([jpbrucker](https://github.com/jpbrucker))
-
-## [v0.4.7](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.7) (2015-08-13)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.6...v0.4.7)
-
-## [v0.4.6](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.6) (2015-08-11)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.5...v0.4.6)
-
-**Closed issues:**
-
-- remove duplication of global static variable BLE\_EVT\_BUFFER [\#39](https://github.com/ARMmbed/ble-nrf51822/issues/39)
-- clearScanResponse\(\)  [\#30](https://github.com/ARMmbed/ble-nrf51822/issues/30)
-- Debug builds fail due to missing bsp.h [\#11](https://github.com/ARMmbed/ble-nrf51822/issues/11)
-
-**Merged pull requests:**
-
-- Disable GattClient features when using S110 SoftDevice [\#38](https://github.com/ARMmbed/ble-nrf51822/pull/38) ([jpbrucker](https://github.com/jpbrucker))
-
-## [v0.4.5](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.5) (2015-08-10)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.4...v0.4.5)
-
-## [v0.4.4](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.4) (2015-08-07)
-[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.3...v0.4.4)
-
-**Closed issues:**
-
-- nrf51822 hangs after calling sd\_flash\_page\_erase\(\) [\#35](https://github.com/ARMmbed/ble-nrf51822/issues/35)
-- nRF5xn::getVersion return \(Unknown\) with version 8 soft device [\#29](https://github.com/ARMmbed/ble-nrf51822/issues/29)
-
-**Merged pull requests:**
-
-- Changed Gap:: to GapAdvertisingParams:: because of change in BLE [\#34](https://github.com/ARMmbed/ble-nrf51822/pull/34) ([jslater8](https://github.com/jslater8))
-- Select the clock source dynamically on SoftDevice initialisation [\#32](https://github.com/ARMmbed/ble-nrf51822/pull/32) ([jpbrucker](https://github.com/jpbrucker))
-- Add S110 SoftDevice compatibility [\#28](https://github.com/ARMmbed/ble-nrf51822/pull/28) ([jpbrucker](https://github.com/jpbrucker))
-
-## [v0.4.3](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.3) (2015-07-22)
-**Closed issues:**
-
-- Target polling failed [\#24](https://github.com/ARMmbed/ble-nrf51822/issues/24)
-- support  handling of HVX Events \(notifications and indications\). [\#22](https://github.com/ARMmbed/ble-nrf51822/issues/22)
-- provide an implementation for GattServer::areUpdatesEnabled\(\) [\#21](https://github.com/ARMmbed/ble-nrf51822/issues/21)
-- getValueHandle\(\) returns characteristicIndex instead of attribute-handle [\#20](https://github.com/ARMmbed/ble-nrf51822/issues/20)
-- Clash With Definition And Enum Naming [\#16](https://github.com/ARMmbed/ble-nrf51822/issues/16)
-- Errors in GCC build [\#14](https://github.com/ARMmbed/ble-nrf51822/issues/14)
-- bring s110 support back [\#10](https://github.com/ARMmbed/ble-nrf51822/issues/10)
-- Allow adding a User Description descriptor to a GattCharacteristic. [\#9](https://github.com/ARMmbed/ble-nrf51822/issues/9)
-- device\_manager\_peripheral.c includes app\_trace.h [\#7](https://github.com/ARMmbed/ble-nrf51822/issues/7)
-- linking esb\_gcc.a \(nrf51822 enhanced shock burst\) with mbed [\#5](https://github.com/ARMmbed/ble-nrf51822/issues/5)
-- The app\_timer usage may conflict [\#2](https://github.com/ARMmbed/ble-nrf51822/issues/2)
-- Nordic License [\#1](https://github.com/ARMmbed/ble-nrf51822/issues/1)
-
-**Merged pull requests:**
-
-- Develop [\#25](https://github.com/ARMmbed/ble-nrf51822/pull/25) ([zoujixing](https://github.com/zoujixing))
-- Remove unnecessary 'compiler\_abstraction.h' to get rid of duplicate '… [\#23](https://github.com/ARMmbed/ble-nrf51822/pull/23) ([adfernandes](https://github.com/adfernandes))
-- restructure for minimal yotta compatibility [\#15](https://github.com/ARMmbed/ble-nrf51822/pull/15) ([autopulated](https://github.com/autopulated))
-- Fix various GCC compilation issues. [\#12](https://github.com/ARMmbed/ble-nrf51822/pull/12) ([adfernandes](https://github.com/adfernandes))
-- Fix for GCC lost in SDK v8.0 update [\#8](https://github.com/ARMmbed/ble-nrf51822/pull/8) ([rosterloh](https://github.com/rosterloh))
-- new target DELTA\_DFCM\_NNN40 with nrf51822 chip, config internal RC crystal. [\#6](https://github.com/ARMmbed/ble-nrf51822/pull/6) ([Marcomissyou](https://github.com/Marcomissyou))
-- Updated return value for nRF51GattServer::updateValue. Will now report w... [\#4](https://github.com/ARMmbed/ble-nrf51822/pull/4) ([marcuschangarm](https://github.com/marcuschangarm))
-- Added optional data and length fields to the return struct for authorize... [\#3](https://github.com/ARMmbed/ble-nrf51822/pull/3) ([marcuschangarm](https://github.com/marcuschangarm))
-
-
-
-\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 LICENSE
--- a/LICENSE	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-This module contains softdevice which comes with The Nordic Softdevice License Agreement,
-a BSD-like licence for binary distributions, offered by Nordic for use in mbed. Some
-other files come from the mbed SDK, and are licensed under Apache-2.0. Unless
-specifically indicated otherwise in a file, files are licensed under the
-Apache 2.0 license, as can be found in: apache-2.0.txt. The Nordic Semiconductor Softdevice
-License Agreement can be found in softdevice_nrf51822_licence_agreement.txt.
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/CHANGELOG.md
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/CHANGELOG.md	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,344 @@
+# Change Log
+
+## [v2.5.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.3) (2016-02-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.2...v2.5.3)
+
+**Merged pull requests:**
+
+- Fix for compilation errors with S110 softdevice in btle.cpp [\#109](https://github.com/ARMmbed/ble-nrf51822/pull/109) ([ddavidebor](https://github.com/ddavidebor))
+
+## [v2.5.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.2) (2016-02-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.1...v2.5.2)
+
+**Merged pull requests:**
+
+- Sync develop against master [\#113](https://github.com/ARMmbed/ble-nrf51822/pull/113) ([pan-](https://github.com/pan-))
+- Fix incorrect handles of characteristics descriptors. [\#112](https://github.com/ARMmbed/ble-nrf51822/pull/112) ([pan-](https://github.com/pan-))
+
+## [v2.5.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.1) (2016-01-27)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.0...v2.5.1)
+
+**Merged pull requests:**
+
+- Remove Gap::state updates from this module [\#108](https://github.com/ARMmbed/ble-nrf51822/pull/108) ([andresag01](https://github.com/andresag01))
+- merge version  [\#106](https://github.com/ARMmbed/ble-nrf51822/pull/106) ([pan-](https://github.com/pan-))
+
+## [v2.5.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.0) (2016-01-12)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.1...v2.5.0)
+
+**Merged pull requests:**
+
+- Fix access to enum member [\#105](https://github.com/ARMmbed/ble-nrf51822/pull/105) ([pan-](https://github.com/pan-))
+- Hotfix dependency [\#104](https://github.com/ARMmbed/ble-nrf51822/pull/104) ([pan-](https://github.com/pan-))
+- Finish implementation of getAddressesFromBondTable [\#103](https://github.com/ARMmbed/ble-nrf51822/pull/103) ([andresag01](https://github.com/andresag01))
+
+## [v2.4.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.1) (2016-01-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.0...v2.4.1)
+
+**Merged pull requests:**
+
+- merge branch develop \(v2.4.0\) [\#100](https://github.com/ARMmbed/ble-nrf51822/pull/100) ([pan-](https://github.com/pan-))
+
+## [v2.4.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.0) (2016-01-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.1...v2.4.0)
+
+**Merged pull requests:**
+
+- Add implementation of experimental whitelisting API [\#99](https://github.com/ARMmbed/ble-nrf51822/pull/99) ([andresag01](https://github.com/andresag01))
+
+## [v2.3.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.1) (2016-01-07)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.0...v2.3.1)
+
+**Merged pull requests:**
+
+- Update yotta module dependencies [\#98](https://github.com/ARMmbed/ble-nrf51822/pull/98) ([pan-](https://github.com/pan-))
+
+## [v2.3.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.0) (2015-12-23)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.10...v2.3.0)
+
+**Merged pull requests:**
+
+- Implementation of Characteristic descriptor discovery [\#74](https://github.com/ARMmbed/ble-nrf51822/pull/74) ([pan-](https://github.com/pan-))
+
+## [v2.2.10](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.10) (2015-12-23)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.9...v2.2.10)
+
+**Fixed bugs:**
+
+- nRF5xn::init don't verify if errors have occurred during btle\_init [\#59](https://github.com/ARMmbed/ble-nrf51822/issues/59)
+
+**Closed issues:**
+
+- A call to shutdown does not clear the state of some components of BLE API [\#85](https://github.com/ARMmbed/ble-nrf51822/issues/85)
+- Memory allocation issue on the NRF51DK board. [\#76](https://github.com/ARMmbed/ble-nrf51822/issues/76)
+- Terrible handling of initLen / minLen and variable length characteristics. [\#56](https://github.com/ARMmbed/ble-nrf51822/issues/56)
+
+**Merged pull requests:**
+
+- Fix shutdown of Gap instance to avoid NULL refs [\#96](https://github.com/ARMmbed/ble-nrf51822/pull/96) ([andresag01](https://github.com/andresag01))
+- Add check for return code of ble\_init [\#95](https://github.com/ARMmbed/ble-nrf51822/pull/95) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.9](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.9) (2015-12-18)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.8...v2.2.9)
+
+**Closed issues:**
+
+- Cannot open source input file "system\_nrf51.h" [\#52](https://github.com/ARMmbed/ble-nrf51822/issues/52)
+
+**Merged pull requests:**
+
+- Remove occurrence of deprecated appearance enum [\#92](https://github.com/ARMmbed/ble-nrf51822/pull/92) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.8) (2015-12-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.7...v2.2.8)
+
+## [v2.2.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.7) (2015-12-15)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.6...v2.2.7)
+
+**Merged pull requests:**
+
+- Replace deprecated inclusions of mbed.h [\#89](https://github.com/ARMmbed/ble-nrf51822/pull/89) ([andresag01](https://github.com/andresag01))
+- Improve shutdown to clear BLE API and not just SD [\#87](https://github.com/ARMmbed/ble-nrf51822/pull/87) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.6) (2015-12-15)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.5...v2.2.6)
+
+**Merged pull requests:**
+
+- follow the extraction of address related types from Gap.h into BLEProtocol.h [\#88](https://github.com/ARMmbed/ble-nrf51822/pull/88) ([rgrover](https://github.com/rgrover))
+
+## [v2.2.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.5) (2015-12-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.3...v2.2.5)
+
+**Merged pull requests:**
+
+- Added SecurityManager::setLinkSecurity call for elevating security settings on a particular connection. [\#86](https://github.com/ARMmbed/ble-nrf51822/pull/86) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.2.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.3) (2015-12-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.2...v2.2.3)
+
+## [v2.2.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.2) (2015-12-08)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.1...v2.2.2)
+
+**Merged pull requests:**
+
+- Add -Wno-unused-function to supress-warnings.cmake [\#83](https://github.com/ARMmbed/ble-nrf51822/pull/83) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.1) (2015-12-08)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.0...v2.2.1)
+
+**Merged pull requests:**
+
+- WIP: UUID endian change [\#82](https://github.com/ARMmbed/ble-nrf51822/pull/82) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.2.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.0) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.4...v2.2.0)
+
+## [v2.1.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.4) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.3...v2.1.4)
+
+## [v2.1.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.3) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.2...v2.1.3)
+
+## [v2.1.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.2) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.1...v2.1.2)
+
+**Merged pull requests:**
+
+- Allow GattAttributes to have variable length [\#81](https://github.com/ARMmbed/ble-nrf51822/pull/81) ([andresag01](https://github.com/andresag01))
+
+## [v2.1.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.1) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.0...v2.1.1)
+
+**Merged pull requests:**
+
+- Fixed endianness bug in nRF5xServiceDiscovery::processDiscoverUUIDResponse so it is consistent with BLE API. [\#80](https://github.com/ARMmbed/ble-nrf51822/pull/80) ([marcuschangarm](https://github.com/marcuschangarm))
+- Fixed bug in nRF5xGap.setAddress where random adresses where not set properly. [\#79](https://github.com/ARMmbed/ble-nrf51822/pull/79) ([marcuschangarm](https://github.com/marcuschangarm))
+- Separate concept of minlen and len for BLE chars [\#78](https://github.com/ARMmbed/ble-nrf51822/pull/78) ([andresag01](https://github.com/andresag01))
+- Split nordic sdk into its own module [\#75](https://github.com/ARMmbed/ble-nrf51822/pull/75) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.0) (2015-11-27)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.8...v2.1.0)
+
+**Merged pull requests:**
+
+- Update to sdk 8.1 [\#77](https://github.com/ARMmbed/ble-nrf51822/pull/77) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.0.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.8) (2015-11-26)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.7...v2.0.8)
+
+## [v2.0.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.7) (2015-11-26)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.6...v2.0.7)
+
+**Closed issues:**
+
+- test2000 [\#72](https://github.com/ARMmbed/ble-nrf51822/issues/72)
+- test1000000 [\#71](https://github.com/ARMmbed/ble-nrf51822/issues/71)
+- test4 [\#70](https://github.com/ARMmbed/ble-nrf51822/issues/70)
+- test3 [\#69](https://github.com/ARMmbed/ble-nrf51822/issues/69)
+- test2 [\#68](https://github.com/ARMmbed/ble-nrf51822/issues/68)
+
+**Merged pull requests:**
+
+- use Extern c around \#include to use nordic sdk headers implemented in C [\#73](https://github.com/ARMmbed/ble-nrf51822/pull/73) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.0.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.6) (2015-11-17)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.5...v2.0.6)
+
+**Closed issues:**
+
+- test [\#66](https://github.com/ARMmbed/ble-nrf51822/issues/66)
+
+**Merged pull requests:**
+
+- add Nordic's license agreement. [\#67](https://github.com/ARMmbed/ble-nrf51822/pull/67) ([rgrover](https://github.com/rgrover))
+
+## [v2.0.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.5) (2015-11-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.4...v2.0.5)
+
+**Merged pull requests:**
+
+- Post radio notification callback through minar [\#65](https://github.com/ARMmbed/ble-nrf51822/pull/65) ([andresag01](https://github.com/andresag01))
+
+## [v2.0.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.4) (2015-11-13)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.3...v2.0.4)
+
+**Merged pull requests:**
+
+- Fix assembly sequence to start bootloader in GCC [\#64](https://github.com/ARMmbed/ble-nrf51822/pull/64) ([andresag01](https://github.com/andresag01))
+
+## [v2.0.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.3) (2015-11-09)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.2...v2.0.3)
+
+**Merged pull requests:**
+
+- Added watchdog header file from Nordic SDK 8.1 [\#62](https://github.com/ARMmbed/ble-nrf51822/pull/62) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.0.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.2) (2015-11-03)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-release-15-11...v2.0.2)
+
+## [mbedos-release-15-11](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-release-15-11) (2015-11-03)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.1...mbedos-release-15-11)
+
+## [v2.0.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.1) (2015-11-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.0...v2.0.1)
+
+**Merged pull requests:**
+
+- Ensure that the initialization flags is set to false if the BLE stack is shutdown properly. [\#58](https://github.com/ARMmbed/ble-nrf51822/pull/58) ([pan-](https://github.com/pan-))
+
+## [v2.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.0) (2015-11-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.1.0...v2.0.0)
+
+**Closed issues:**
+
+- Nordic SDK and SoftDevice [\#57](https://github.com/ARMmbed/ble-nrf51822/issues/57)
+- shouldn't eab6631cb be merged into master? [\#54](https://github.com/ARMmbed/ble-nrf51822/issues/54)
+
+**Merged pull requests:**
+
+- Introduced changes for memory savings [\#55](https://github.com/ARMmbed/ble-nrf51822/pull/55) ([andresag01](https://github.com/andresag01))
+
+## [v1.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.1.0) (2015-10-28)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.0.0...v1.1.0)
+
+**Closed issues:**
+
+- target dependencies in module.json [\#50](https://github.com/ARMmbed/ble-nrf51822/issues/50)
+
+**Merged pull requests:**
+
+- When connecting, if no scanning parameters are passed, use values from Gap parent. [\#53](https://github.com/ARMmbed/ble-nrf51822/pull/53) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v1.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.0.0) (2015-10-19)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-techcon-oob2...v1.0.0)
+
+## [mbedos-techcon-oob2](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-techcon-oob2) (2015-10-19)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.8...mbedos-techcon-oob2)
+
+**Closed issues:**
+
+- rename the bootloader files with \_fota in the name? [\#51](https://github.com/ARMmbed/ble-nrf51822/issues/51)
+
+**Merged pull requests:**
+
+- Update S110 detection macros, again [\#49](https://github.com/ARMmbed/ble-nrf51822/pull/49) ([jpbrucker](https://github.com/jpbrucker))
+- Error check number of characteristics [\#48](https://github.com/ARMmbed/ble-nrf51822/pull/48) ([Timmmm](https://github.com/Timmmm))
+
+## [v0.4.8](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.8) (2015-09-25)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.7...v0.4.8)
+
+**Closed issues:**
+
+- Error real cause loss in nRF5xGattServer.cpp [\#44](https://github.com/ARMmbed/ble-nrf51822/issues/44)
+
+**Merged pull requests:**
+
+- rgrover patch fixed [\#47](https://github.com/ARMmbed/ble-nrf51822/pull/47) ([fabiencomte](https://github.com/fabiencomte))
+- Update S110 detection macros [\#43](https://github.com/ARMmbed/ble-nrf51822/pull/43) ([jpbrucker](https://github.com/jpbrucker))
+- remove some unnecessary include paths [\#42](https://github.com/ARMmbed/ble-nrf51822/pull/42) ([autopulated](https://github.com/autopulated))
+- Add FOTA bootloader image [\#41](https://github.com/ARMmbed/ble-nrf51822/pull/41) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.7](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.7) (2015-08-13)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.6...v0.4.7)
+
+## [v0.4.6](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.6) (2015-08-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.5...v0.4.6)
+
+**Closed issues:**
+
+- remove duplication of global static variable BLE\_EVT\_BUFFER [\#39](https://github.com/ARMmbed/ble-nrf51822/issues/39)
+- clearScanResponse\(\)  [\#30](https://github.com/ARMmbed/ble-nrf51822/issues/30)
+- Debug builds fail due to missing bsp.h [\#11](https://github.com/ARMmbed/ble-nrf51822/issues/11)
+
+**Merged pull requests:**
+
+- Disable GattClient features when using S110 SoftDevice [\#38](https://github.com/ARMmbed/ble-nrf51822/pull/38) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.5](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.5) (2015-08-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.4...v0.4.5)
+
+## [v0.4.4](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.4) (2015-08-07)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.3...v0.4.4)
+
+**Closed issues:**
+
+- nrf51822 hangs after calling sd\_flash\_page\_erase\(\) [\#35](https://github.com/ARMmbed/ble-nrf51822/issues/35)
+- nRF5xn::getVersion return \(Unknown\) with version 8 soft device [\#29](https://github.com/ARMmbed/ble-nrf51822/issues/29)
+
+**Merged pull requests:**
+
+- Changed Gap:: to GapAdvertisingParams:: because of change in BLE [\#34](https://github.com/ARMmbed/ble-nrf51822/pull/34) ([jslater8](https://github.com/jslater8))
+- Select the clock source dynamically on SoftDevice initialisation [\#32](https://github.com/ARMmbed/ble-nrf51822/pull/32) ([jpbrucker](https://github.com/jpbrucker))
+- Add S110 SoftDevice compatibility [\#28](https://github.com/ARMmbed/ble-nrf51822/pull/28) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.3](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.3) (2015-07-22)
+**Closed issues:**
+
+- Target polling failed [\#24](https://github.com/ARMmbed/ble-nrf51822/issues/24)
+- support  handling of HVX Events \(notifications and indications\). [\#22](https://github.com/ARMmbed/ble-nrf51822/issues/22)
+- provide an implementation for GattServer::areUpdatesEnabled\(\) [\#21](https://github.com/ARMmbed/ble-nrf51822/issues/21)
+- getValueHandle\(\) returns characteristicIndex instead of attribute-handle [\#20](https://github.com/ARMmbed/ble-nrf51822/issues/20)
+- Clash With Definition And Enum Naming [\#16](https://github.com/ARMmbed/ble-nrf51822/issues/16)
+- Errors in GCC build [\#14](https://github.com/ARMmbed/ble-nrf51822/issues/14)
+- bring s110 support back [\#10](https://github.com/ARMmbed/ble-nrf51822/issues/10)
+- Allow adding a User Description descriptor to a GattCharacteristic. [\#9](https://github.com/ARMmbed/ble-nrf51822/issues/9)
+- device\_manager\_peripheral.c includes app\_trace.h [\#7](https://github.com/ARMmbed/ble-nrf51822/issues/7)
+- linking esb\_gcc.a \(nrf51822 enhanced shock burst\) with mbed [\#5](https://github.com/ARMmbed/ble-nrf51822/issues/5)
+- The app\_timer usage may conflict [\#2](https://github.com/ARMmbed/ble-nrf51822/issues/2)
+- Nordic License [\#1](https://github.com/ARMmbed/ble-nrf51822/issues/1)
+
+**Merged pull requests:**
+
+- Develop [\#25](https://github.com/ARMmbed/ble-nrf51822/pull/25) ([zoujixing](https://github.com/zoujixing))
+- Remove unnecessary 'compiler\_abstraction.h' to get rid of duplicate '… [\#23](https://github.com/ARMmbed/ble-nrf51822/pull/23) ([adfernandes](https://github.com/adfernandes))
+- restructure for minimal yotta compatibility [\#15](https://github.com/ARMmbed/ble-nrf51822/pull/15) ([autopulated](https://github.com/autopulated))
+- Fix various GCC compilation issues. [\#12](https://github.com/ARMmbed/ble-nrf51822/pull/12) ([adfernandes](https://github.com/adfernandes))
+- Fix for GCC lost in SDK v8.0 update [\#8](https://github.com/ARMmbed/ble-nrf51822/pull/8) ([rosterloh](https://github.com/rosterloh))
+- new target DELTA\_DFCM\_NNN40 with nrf51822 chip, config internal RC crystal. [\#6](https://github.com/ARMmbed/ble-nrf51822/pull/6) ([Marcomissyou](https://github.com/Marcomissyou))
+- Updated return value for nRF51GattServer::updateValue. Will now report w... [\#4](https://github.com/ARMmbed/ble-nrf51822/pull/4) ([marcuschangarm](https://github.com/marcuschangarm))
+- Added optional data and length fields to the return struct for authorize... [\#3](https://github.com/ARMmbed/ble-nrf51822/pull/3) ([marcuschangarm](https://github.com/marcuschangarm))
+
+
+
+\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/LICENSE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/LICENSE	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,6 @@
+This module contains softdevice which comes with The Nordic Softdevice License Agreement,
+a BSD-like licence for binary distributions, offered by Nordic for use in mbed. Some
+other files come from the mbed SDK, and are licensed under Apache-2.0. Unless
+specifically indicated otherwise in a file, files are licensed under the
+Apache 2.0 license, as can be found in: apache-2.0.txt. The Nordic Semiconductor Softdevice
+License Agreement can be found in softdevice_nrf51822_licence_agreement.txt.
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/apache-2.0.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/apache-2.0.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,13 @@
+Copyright (c) 2015 ARM Limited
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/bootloader/s110_nrf51822_8.0.0_bootloader.hex
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/bootloader/s110_nrf51822_8.0.0_bootloader.hex	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,463 @@
+:020000040003F7
+:20C00000983C002005DD030017DD030019DD03000000000000000000000000000000000057
+:20C0200000000000000000000000000069C1030000000000000000001DDD03001FDD0300D7
+:20C0400021DD030021DD030021DD030021DD030021DD03000000000021DD030021DD0300D9
+:20C0600021DD030021DD030021DD030021DD030021DD030021DD030021DD030021DD0300B8
+:20C0800021DD030057D8030021DD030021DD03006DD8030021DD03004DF4030021DD0300DD
+:20C0A00021DD030021DD03000000000000000000000000000000000000000000000000007E
+:20C0C00000F002F800F040F80CA030C8083824182D18A246671EAB4654465D46AC4201D18E
+:20C0E00000F032F87E460F3E0FCCB6460126334200D0FB1AA246AB463343184710370000C8
+:20C1000030370000103A02D378C878C1FAD8520701D330C830C101D504680C6070470000D3
+:20C120000023002400250026103A01D378C1FBD8520700D330C100D50B6070471FB5C04655
+:20C14000C0461FBD10B510BD03F0E3FA1146FFF7F5FF00F0D3F803F0FBFA03B4FFF7F2FF19
+:20C1600003BC03F0FFFA00000648704502D1EFF3098101E0EFF30881886902380078024A97
+:20C1800010470000FDFFFFFF39D50300401E00BF00BF00BF00BF00BF00BF00BF00BF00BF28
+:20C1A00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BFB4
+:20C1C00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BF94
+:20C1E00000BF00BF00BFF1D170470000056885F3088846680A4AEFF305839A42304602D183
+:20C20000084CA6463047074C064D0646064FF0B4034C034D024E024FF0B404480047000005
+:20C2200000000000FFFFFFFF00000021F9FFFFFF70B505460C46164602E00FCC0FC5103EEE
+:20C24000102EFAD2082E02D303CC03C5083E042E07D301CC01C5361F03E021782970641C63
+:20C260006D1C761EF9D270BD0A4610B50146664803F064F810BD10B502F078FC10BD10B5C6
+:20C28000624C86B01ECC03946C460EC4002807D0684618DF002803D00022114603F04EF864
+:20C2A0000F20800313DF002803D00022114603F045F8574B48225749092003F0A3F80028AB
+:20C2C00003D00022114603F039F800200490059001206946087404A860DF002803D0002251
+:20C2E000114603F02BF84C4803F0A8F8002803D00022114603F022F806B010BD08B547485A
+:20C30000C169B12943D0002445480F2140698903884204D000221146104603F00FF8012068
+:20C320000007006901218902884204D000221146104603F003F83B4800903B4B05220321A1
+:20C34000002001F0BAFA002803D00022114602F0F5FF00F067FC00F0AAFC012500281AD09D
+:20C3600000F0B4FC002803D00022114602F0E6FF20466840FFF783FF00F038F800F0CCFC74
+:20C3800000280ED00022114602F0D8FF09E001240021C161B8E720466840FFF770FF00F002
+:20C3A00025F803252D03002C04D1A86800F090FB002807D100F047FC002803D000221146D5
+:20C3C00002F0BCFFA86800F083FB002806D000F06EFC002802D1A86800F041FCBFF34F8F12
+:20C3E00013491248C860BFF34F8FFEE7094A10B548321421082002F00BFF002803D00022E2
+:20C40000114602F09BFF10BDEFBEADDE8CF703006BF30300342B002077C20300000500404D
+:20C4200000100010EFDC0300F42800200400FA0500ED00E070B5FC4C1E46A06815460229A3
+:20C4400002D0042916D108E0052813D1A369002B10D03246294604200BE002280AD1F348B0
+:20C46000406880470320A060A369002B02D0324629469847280003D00022114602F05EFF98
+:20C4800070BD4CB5E84E0120307005200195009400F058FB4CBD10B5E34C2078002801D057
+:20C4A000082010BD206901F0F4FA002803D00022114602F043FF0F2100228904206901F01E
+:20C4C000ABFA040003D00022114602F037FF204610BDD54910B5D448243141610221816012
+:20C4E000C168243002F059FD002803D00022114602F024FF10BDCC4910B5CB481C31416145
+:20C50000022181600320000380680F218903081A4108C5481C3002F040FD002803D000223D
+:20C52000114602F00BFF10BD704700B589B01822BF4902A8FFF77CFE06980799009001917A
+:20C5400002A80FC800F0FEFA09B000BD00B5B64987B049886A461181032109038968069146
+:20C56000B249012050394A6803928A680492C9680591069A0091019202A90EC900F0E2FA6E
+:20C58000002007B000BD30B5A84CA748503C89B02430E16802F001FD002803D00022114679
+:20C5A00002F0CCFEA048E2681C3041680023083002F0C3FC050012D1182102A802F0E6FFEA
+:20C5C00000209949029049886A469181E1680691079A0091019203A90EC900F0B3FA284601
+:20C5E00009B030BD00B5904987B049886A4611818E49032050394A6803928A680492C9683A
+:20C600000591069A0091019202A90EC900F09AFA0020B6E73EB5864A6B46183207CA07C3A4
+:20C62000814D00246C7029466C802431684602F068FC002801D0AC603EBD03207A4900038F
+:20C6400080682431486024390A46526ACA610F218903091A490840187349764A1C31486068
+:20C6600071480021103001F07BF9002803D00022114602F063FE0F2100228904286901F013
+:20C68000CBF9002803D00022114602F057FE01206C60A86000203EBD63498861704770B59A
+:20C6A000426862481468536891685038D26804604360C26081600078440701D5840705D130
+:20C6C0009C0703D18C0701D1940701D0062070BD5B189A18544D0F239B02EA60994213D81A
+:20C6E0005549564B514CC60709D08868181A90420AD3534820605348606053480FE08968F6
+:20C70000591A4908914201D20C2070BD4F4921604F496160800701D54E4800E04E48A0607B
+:20C72000A868012802D00826304670BDFFF7B3FE0600FAD12168E8688847F5E770B50500F7
+:20C7400004D0287A800703D0102070BD0E2070BD354CA068032805D0042801D0052803D0CB
+:20C76000082070BD0520A0606868E168860060688019884204D90020C04360600C2070BD5C
+:20C78000FFF789FE0028FAD1A96832466368606902F0D3FB0028F2D1616889196160E268EB
+:20C7A0009142ECD0092070BD10B51F4C08206168002900D010BDA1680429FBD11B4861786F
+:20C7C000403802F021FC002802D00021617010BD0521A16010BDF8B5134C0746A068032899
+:20C7E00004D0042804D008252846F8BD0420A0606068002801D00820F8BDFFF74CFE05000E
+:20C80000FAD17868860060788119402901D90920F8BD064AB968403A1018324602F057FE82
+:20C82000607880196070DFE7002800201C2D00209CF7030083C403000030000000C003006D
+:20C84000D3C403002BC503004DC50300F7C4030029C50300E5C5030087C5030010B5894CF1
+:20C86000A068052813D1E168606888420FD10620A060FFF710FE002808D16069E1684068FF
+:20C8800002F0FCFB002801D10721A16010BD082010BD10B57B488168072901D0082010BD63
+:20C8A000006901F0F6F8002803D00022114602F045FD75488068804710BD1CB506200195C2
+:20C8C000009400F03FF91CBDF8B51C4617460D46064600F0C1F8002817D001200003854215
+:20C8E00007D92346291B301B1A46FFF7EDFF00280BD13A462946304600F0B9F8002804D117
+:20C900003A462946304600F0A7F8F8BDF0B589B0684600F015FA049800282AD001210903F7
+:20C92000079A4018904226D9501A45081046049A0C468718024668001618001908900320DF
+:20C9400000038068049988420DD261190846042200F08DF800280CD121460422084600F073
+:20C9600086F8002805D1BA1B2B4630460899FFF7ABFF09B0F0BD049A079800F078F8F8E75C
+:20C9800000B58DB004A800F0DBF9099800280DD0089800280CD008990B984018019000219D
+:20C9A0000998009180080290684618DF0DB000BD0320000380680F218903091A4908ECE7FB
+:20C9C00000B58DB004A800F0BBF909980028EDD00F210898890300280CD0089A0B98019158
+:20C9E0008018029003220998009280080390684618DFDBE70320000380680A1A5208EEE7D2
+:20CA000030B591B0684600F09BF90498002814D001210903079A4018904214D9501A43087B
+:20CA20001046049A5C0082180019611803242403A468049DAC4202D20E2011B030BD121AB5
+:20CA4000FFF742FFF9E703200CAB07C3049880080F900CA818DFF0E71FB5032301909008B3
+:20CA6000039000930291684618DF04B010BD1FB5012301909008039000930291684618DF58
+:20CA8000F3E70000002800201C2D002010B5BB480368012B02D1022900D10160100003D099
+:20CAA0000022114602F04AFC10BD10B5B34C48DF002803D00022114602F040FC02F0FCFB82
+:20CAC0002068022803D0032801D00428EFD110BD38B50068401C19D00024684600F058F96F
+:20CAE00000980168012910D1818800290AD0C168032000038068002202F0CEFA0099898861
+:20CB0000814201D1012400E00024204638BD10B504469A482021001D02F0B9F9002803D00E
+:20CB20000022114602F00AFC9448002320222146001D02F01BF9002803D00022114602F053
+:20CB4000FDFB10BD0FB4F8B5684600F021F96846818B069D0122894CFF238948002D13D090
+:20CB6000012D17D0032D2BD00021022D37D02A46052D46D0042D4ED0062A01D10420206071
+:20CB8000F8BC08BC04B0184781800A9983600260C16010E08180099D089949190A9D49195D
+:20CBA000C160A52183600160089901610999856141610B99C16122607148FFF7A8FFDFE7B9
+:20CBC00000990B6803608B888380C968C160AA21816008990161099941610A990BE0009D60
+:20CBE0002E68A52E09D00660AE888680ED68C5600161836041618161DDE781800360C160C5
+:20CC0000F6E700F085F9002803D00022114602F095FB0320B3E781800360C1600099896807
+:20CC20008160C9E70EB557480090202001900120029002F001F8002804D150496846091D98
+:20CC400002F023F80EBD10B5FFF7E4FC002805D100F02FFB0446FFF728FF204610BD70B58A
+:20CC600011DF002803D00022114602F067FB464900200B68444C012180340A4682401A4206
+:20CC800004D0C506ED0E0A46AA402260401C2028F3D303242403A06813DF002803D000226F
+:20CCA000114602F04BFBA06802F0F2F970BD08B5684600F06DF800980168A52904D0806888
+:20CCC000AA2801D0002008BD012008BD10B5FFF797FE002803D1FFF773FE00281BD064209C
+:20CCE00001F0F2FDFFF712FE002803D00022114602F024FBFFF784FE002803D000221146DD
+:20CD000002F01CFBFFF73CFE040003D00022114602F014FB204610BD00B589B018221B49CA
+:20CD200002A8FFF785FA069807990090019102A80FC8FFF707FFFFF7B8FE002009B000BDB5
+:20CD400010B50E4988B0044600232022091D684602F04FF80098206068468088A08003983A
+:20CD6000E0600298A06004982061059860610698A0610798E06108B010BD00002C280020E6
+:20CD8000282D00208DCA030000E100E0C0F70300014901607047000000FC030008280CD0DC
+:20CDA00004DC002807D006280FD108E00B280AD00C280AD105E001207047022070470320C9
+:20CDC000704704207047042901D0062070470520704770B515460A46032823D0042820D1FF
+:20CDE000FE4C002906D0E088FD49884219D0132176DF10E0284602F0A3F9002803D00022F7
+:20CE0000114602F09BFAE069A8420AD101220321F44801F003F8002803D00022114602F051
+:20CE20008DFA70BD01211046FFF7B8FF02460121EEE7F0B5054608790E4685B081070CD07C
+:20CE400003221146284600F0E9FF002803D00022114602F073FA05B0F0BDE04900901831D9
+:20CE600002F047F9010011D1DC4CB168009AA06902F02DFB009802F097F9010006D1204647
+:20CE80006946183002F09CF9010003D0284600F0AFFAE0E704200190009880080290A06902
+:20CEA000039001A8FFF74AFC07000BD0092F10D0A06902F045F9010002D0284600F098FA04
+:20CEC0003946E3E73079616940186061A069E061C1E7307961694118616160780028BAD073
+:20CEE0006089401E0004000C6081B4D1284601F0E9F8002803D00022114602F01FFA20890D
+:20CF00006081A8E710B50022114602F017FA10BD10B5B24C01202070E088B149884208D01B
+:20CF2000132176DF002810D00022114602F006FA0BE0A078002808D074DF002803D0002282
+:20CF4000114602F0FBF90020A07001F034FC002803D00022114602F0F1F9002010BD70B5E1
+:20CF60000D68044601209D4A2B0002F002FC0A2B3043061320575C466012FFF76FFC0421FD
+:20CF8000FFF70CFF024604212EE00022114602F0D5F970BDFFF7BCFF002803D0002211468A
+:20CFA00002F0CCF9FFF775FC002808D170BDFFF7AFFF002803D00022114602F0BFF9FFF76D
+:20CFC0007CFC70BD106188680078107170BD02201061886800780128F8D1FFF7E5FB02213F
+:20CFE000FFF7DCFE02460221204600F017FF0028CBD170BD0320106170BD12692046012ACC
+:20D0000006D0022A07D0032AF6D1FFF712FF70BD00F001FA70BD00F03BFA70BD50708888D5
+:20D020001081508170BD00205070108170BD2046516901F010F8DAE710B5044669488EB0EB
+:20D0400081796846817068490180342101A802F09DFA022001900021684641728472012131
+:20D0600001820590002101A801F03FFA002803D00022114602F062F90EB010BDF0B5574C10
+:20D080008BB0A07800283AD156481821183802F07DFA2046534CC078183C00250126002875
+:20D0A00037D02746483700950195029510226946F81D039502F0DEF9002822D0F81D08909D
+:20D0C00009976846067509A804906846067708A806900420FFF7B0FF25700220207204A813
+:20D0E000E060282020823F486582183873DF002803D00022114602F021F9384886700BB045
+:20D10000F0BD0520FFF798FF2670676025722582E9E70620FFF790FF257065602572E0E7E2
+:20D1200070B52E4C01880022E588A6B017290AD01EDC11293FD008DC022977D0102902D123
+:20D140008088E080A27026B070BD264C303426461836132951D01429F5D1C289638D002106
+:20D160009A4200D1314600238088E21D82DF1BE0512970D00EDC18296CD01929E3D18079F5
+:20D180000028E0D1A270E068401EE0604FD0FFF775FFD8E7522976D05529D4D18079002871
+:20D1A000D1D11321284676DF0028CCD00022114602F0C4F8C7E78020694688803220E06054
+:20D1C000012301AA06A92846AADF002803D00022114602F0B3F82078002807E038280020A2
+:20D1E000FFFF0000602D00203015000001D1FFF745FF0020C043E080A5E70722C14910A839
+:20D2000002F065F91022E11D0CA802F060F91C22314612A802F05BF90CA80A9012A8099039
+:20D2200006ABB94A852128467FDFBDE70DE01822B64906A8FEF7FCFF0A980B9900900191F8
+:20D2400006A80FC8FFF77EFC7DE70021284667DFAAE700E017E0817900299AD0807A042885
+:20D2600003D0062801D0052893D1022909D0012069460872FF208330888102A92846A8DF82
+:20D2800092E70220F4E700F08DF88DE710B5044601F0C2FA9B482146303800F09AFE2046D3
+:20D2A000FFF73EFF10BD10B50022114602F046F810BD30B5944D87B00024203D2C7094483D
+:20D2C0002C6102F0B3F800286AD19248FFF7E4F901F000FF002863D18A4800F059F900288C
+:20D2E00001D10120E87011206946087207228AA102A87CDF002803D00022114602F01EF8B4
+:20D3000000940C2168460194018018214180FF2184809131C1807ADF002803D0002211469A
+:20D3200002F00CF804206946009408807C4801907C4802907348303800F00BFE002803D046
+:20D340000022114601F0FAFF1C21684602F01EF9754801900120800302900094032168468C
+:20D360000173C4810474714806900594684601F0FEF9002803D00022114601F0DFFF624910
+:20D38000E12208784008400010400C30DF22104008700720487010208870FFF76FFE0020A3
+:20D3A00007B030BD70B5584C614D203CE088A84201D1082070BDE178002914D05149012359
+:20D3C00008223431A9DF0028F4D12A460C21E088A7DF5849884204D0082802D0891C88420E
+:20D3E000E8D1002070BD00231A461946A9DF70BD10B50A46044603211046FFF7CFFC0246AE
+:20D400000321204600F00AFD002803D00022114601F094FF10BD30B5054687B000200090AF
+:20D4200001900290039038486A46203800791070364A0C3A1068926804906846069205900E
+:20D4400008790C2806D003221BE00022114601F075FFA5E78C68204600F049F80190201D5E
+:20D4600000F045F802902046083000F040F8039004A8FFF714F9002892D00121FFF78EFCB9
+:20D4800002460121284600F0C9FC0028DDD187E7FEB50446087982070ED08207920F042385
+:20D4A0009B1A0022154604E08E683554401CC0B2521C9A42F8D30871012000908868029048
+:20D4C0000879800801906846FFF785F900280DD00221FFF763FC02460221204600F09EFCB8
+:20D4E000002803D00022114601F028FFFEBD10B5044602F04DF80002E178000A09060843E0
+:20D5000010BD0000902D002058280020E4F703008DD20300D3CD0300446675546172670031
+:20D520005FCF0300A7D20300CD0C000005CF0300FFFF00000230000010B50C46002802D04D
+:20D540000120086010BD2168002911D01C48421A814212D03C2A0DD23C303C3101220B78B9
+:20D5600003701346491E401E521C3C2BF7D904E00E200BE03C2201F0AAFF00223C211048A9
+:20D5800001F08AFD0E49891E08800020206010BD70B5054600223C21094801F07DFD084C21
+:20D5A000A41E2188884201D00B2070BD3C220449284601F08CFF2088401C2080002070BD87
+:20D5C000823F00208307FF22DB0E9A408907090E994000280BDA0007000F08388308FA484C
+:20D5E0009B001B18D86990430843D86170478308F6489B001B1818689043084318607047AA
+:20D6000070B50124F24960040860F24940108860F04940398860F04D6C602F20FEF7B6FDAC
+:20D62000AC60EE4D00242F206C61FEF7AFFD2C7170BDF0B5E94F2821BC6841430D19396962
+:20D640004A1C09D028224A431619AB68B268934204D8D21AB26069623861F0BD0A4602E066
+:20D660000A46796A9B1B4E1C0BD028264E433719BE689E42F4D328264E433619B768FF1A1A
+:20D68000B760AB60696228214A4311194862F0BD70B5D24C2269A5681346114606E0814212
+:20D6A00007D00A46282671434919496A4E1CF6D170BD002EFCD08A420CD1282043435819EC
+:20D6C000406A2061401C05D1C34B01209860002363616071282041434819282381685A4310
+:20D6E000406A52195062421CE2D028225043401982685118816070BDF8B5B84C2569681CF9
+:20D7000035D0B748002640686169401A07023F0A19E028204543A0682A189068B84214D8D0
+:20D72000A3693F1A8619556A002B09D0116AD0699847002807D00022114601F0FFFD02E048
+:20D74000D169106A8847681CE3D1A178E078814206D1401CC0B2E070022801D10020E07079
+:20D760009E490006800D1C310E5000F0BAF9F8BDF8B50446994800270169009146785CE038
+:20D780009648F100C2688D1851E0601C07D0934A28209268604321468018446A24E0287854
+:20D7A000182141436A68401CC0B252182870A978884200D12F70894B516828209B6848434C
+:20D7C000C0181368012B34D1037E002B31D19368C360D368036113694361526902627F4A52
+:20D7E0005279002A00D0C7607C4BC2685B6996469C46D31A1A027B4B120A9A4202D20369C3
+:20D80000D21808E0724663469A1A12020369120A934202D99A1A826000E08760C76001222E
+:20D8200007610276921E42620846FFF702FF601CABD1287869788842A7D13046761EF6B202
+:20D8400000289DD1654801690098814201D00120F8BD0020F8BD644900200860486088607F
+:20D86000C860614940390860486045E7FEB50020C0435A4D02906869019068462E6900F07B
+:20D8800035F9074600F04FF90446002F08D002AA0199009800F08FF90298FFF769FF06E050
+:20D8A0000298FFF765FF002801D1002C02D0304600F0AAF900206871FEBDFFB59807002448
+:20D8C00081B01E4615460F4600280BD1002E09D0FFF796FE41490A9888610F703246002042
+:20D8E0008E6008E0072005B0F0BD28234343D4509B181C76401CB842F7DB28204743BB19C1
+:20D90000032048700F461846CB6019461830002218232E465E43D3005B181C705C709D708A
+:20D9200058603018521C032AF5DB0020C0433861BC70FC7001242D482405046003211420A9
+:20D94000FFF740FE224880380460254C0198A06003211120FFF736FE606878610020C2E71A
+:20D9600070B51E4CA568002D06D0002A06D0002804D00023247809E0082070BD072070BDBB
+:20D9800028265E43AE59002E04D05B1CA342F7DB042070BD282401265C432E516419E261BF
+:20D9A00061600360002070BD07494868C005C00D2CD010381CD50207120F083A9208920097
+:20D9C0005118C96919E0000000ED00E000E400E080E100E040130140001001406028002054
+:20D9E00000150140FFFF7F004011014080E200E08108B14A8900891809688007C00EC1400B
+:20DA00000806800F012803D0032803D0022070470020704701207047FEB50446A74817469E
+:20DA200082680D46002A0CD001788C4201D2052D01D20720FEBD2146282359435358012B7D
+:20DA400001D00820FEBD8818406801281DD00026FFF7AAFFC00099490190C9684018694684
+:20DA600000F018F9002812D0012144600160944949680830E2C091490198C9684118009877
+:20DA8000487000F02EF80020FEBD2E46E0E70420FEBDF8B5894D0446A868002809D0297844
+:20DAA0008C4201D30720F8BD282161434058012801D00820F8BDFFF777FFC600E86869465B
+:20DAC000301800F0E7F8002809D0022112C0E86831180098487000F004F80020F8BD04206B
+:20DAE000F8BD0120774900050860704710B5734900238A78CC78A24212D0521CD2B28A70D0
+:20DB0000022A00D18B708A786C4B92001C339A580260486910180002000A4861012010BDA3
+:20DB20000360002010BDF8B5644801690091457833E06248E900C0680E1834782AE01820A2
+:20DB400060437168641C0818B178E4B2A14200D100240168022902D003291BD113E0574A00
+:20DB600040682821926841438F18397E002911D0FFF78EFD002038760CE028277843C018B1
+:20DB80000276406A03E04D4900228B680869471CF3D108617078A042D1D128466D1EEDB2D0
+:20DBA0000028C6D1454801690098814201D00120F8BD0020F8BDF7B5404C0025A7682369E0
+:20DBC0001EE028215943C9198E68864202D9301A886017E0801B751900268E600E764E6946
+:20DBE0009C464B6AB646002E0AD0019E76193602360ACE6076460E6116684E626146116045
+:20DC0000591CDED12361FEBDF8B52C4801694A1C3DD028225143826889188E6828494C681F
+:20DC200047690079E11B0D022D0AED1C002815D10120254A00045060234A403A506021491D
+:20DC4000400080310860214908602149012008602F20FEF79BFA194901200871B54200D208
+:20DC60003546E81900021649000A4031086014494968001B091B0902090A0002C91C000A88
+:20DC8000814203D901200F4940040860F8BDFFF7B7FCF8BD42788378521C934200D10022C2
+:20DCA0000378934201D1002070470A6041684078182250430818704700E400E06028002090
+:20DCC0000015014000E200E04013014000E100E00010014010B50446082904D000221146F9
+:20DCE000104601F02BFB21686068884710BD1CB501910090024A0821684601F09DFA1CBD53
+:20DD0000D5DC03000A48026803210A4302600948804709480047FEE7FEE7FEE7FEE7FEE797
+:20DD2000FEE7000005480649064A074B70470000240500404DDD0300C1C003009830002007
+:20DD4000983C00209834002098340020F8B500F035F82B4E002804D02A4870602A49F01300
+:20DD600088612A480124018CC9B201290DD1818C09070AD1018D0906090F042905D1808D56
+:20DD80000006000F01D1224884600027B461214D6F60A8058460686800280ED1C820FEF790
+:20DDA00005FA1D487F1C8742F5D30020B06101208007846068680028FCD0F8BD1348018CB5
+:20DDC000C9B2012917D1818C090714D1018D09060A0F03D1828D1206120F0ED0090F0129C2
+:20DDE00003D1828D1206120F07D0032903D1808D0006000F01D0002070470120704700008E
+:20DE000000050040DFFF07C0006C0040C00F00F000060040000100408813000030B585B071
+:20DE2000002822D00388FE4CA34220D0FD4B1B78002B1CD0FB4B10255B1C1D7059700024C0
+:20DE400001259A70032269460A820094019402940394028A0A808D708C8004A902910393E7
+:20DE600000886946A6DF05B030BD0E20FBE70820F9E7F0B58BB0044602276846077300268B
+:20DE800009968784C68408A80A900D46A18A208809AAA5DF002804D0E16A00291AD08847BE
+:20DEA00018E06846008CC007C00F13D068460682208803A9A8DF002813D1A97E28461B30BA
+:20DEC00001220B0001F055FC09430F1B202224263E284300FF20FE3069460882208803A94D
+:20DEE000A8DF0BB0F0BD00960AE0062219E069460A71029022E0204690470020F1E700920D
+:20DF00002B8B022BF3D2F0E700971DE003201AE0042018E0052016E0298B032905D20322BE
+:20DF200008212046FFF77AFFDBE741780278080210436946888003D006200090A26ADAE784
+:20DF40000720FAE7092000906946A26AD3E70322E7E730B585B00D46040038D0002D36D0EC
+:20DF60006868002833D00020C043AF4B20800FCB049301AB07C3AD4869460880891C01A888
+:20DF800063DF002822D1221D69460120A0DF00281CD168468078A071204600F0CEF8002886
+:20DFA00014D1204600F055F900280FD12946204600F002F9002809D16868A062A868002804
+:20DFC00000D0E06297490120087000204BE70E2049E73EB5002828D0002926D0826A002ABE
+:20DFE00023D00A88102A21D0112A30D0502A1FD0512A1AD104460846891D0A78022A14D196
+:20E000004A88238A9A4210D1807A04280DD006280BD0052809D0891C2046FFF72AFF002860
+:20E0200003D0E16A002900D088473EBD898810E0CA8803899A42F8D1082200928A7F6B4605
+:20E040001A7120310291826A694690473EBD0021C94301803EBDF0B585B00A4605002DD00F
+:20E0600028886F4988422BD06E480078002827D06C4C1020641C2070072060700127A770F8
+:20E080000321684601820026E11C104600F04CF801466846008A0918684601820096019680
+:20E0A00002960396298A01808770868004A80394029028886946A6DF05B0F0BD0E20FBE7D3
+:20E0C0000820F9E7F0B585B00A46050028D028885349884226D053480078002822D0514C3B
+:20E0E0001120641C20700127684607820026611C104600F019F801466846008A0918684638
+:20E1000001820096019602960396298A01808770868004A80394029028886946A6DFCBE782
+:20E120000E20C9E70820C7E70870020A4A70020C8A70000EC8700420704730B58FB0054655
+:20E140001C21684601F022FA694608780421084369460870002401940394049405940694E6
+:20E16000A87908A9887031486946801C0884601C00070794000F0C77103048778A7FF920B4
+:20E180000240921CE7200240012002438A77142109A801F0FBF908A8099007A80A906946D3
+:20E1A0008C851420CC8508860D942B46A888083309AAA2DF0FB030BDF0B58FB00F4605465A
+:20E1C0001C21684601F0E2F968460178022631430170002401940394049405940694A97917
+:20E1E00008A8817011496846091D0184601C0107090F103168460794017700200146684618
+:20E200004177817FF9200140891CE72001400120014368468177142109A801F0B7F907E086
+:20E22000FFFF000088280020FCF703003015000008A8099007A80A9068468685C4850686B5
+:20E240000D972B46A888203309AA6946A2DF0FB0F0BD30B58FB005461C21684601F096F9FD
+:20E2600069460878082108431022104369460870002401940394049405940694A87908A962
+:20E280008870144869460884601C00070794000F0C7710304877887FF9210840801CF72123
+:20E2A000084010430121084369468877142109A801F06CF908A8099007A80A9069468C851A
+:20E2C0001720CC8508860D942B46A888103309AAA2DF6FE731150000FFB583B0074600207F
+:20E2E0000C9C8646267805463AE07868A90041180A88684682804988C1800022694601A8F7
+:20E3000065DF002810D1684601780598814226D17046002801D0002200E002222078891824
+:20E3200041181F2902D90C2007B0F0BD7146002908D1401CC0B2411C069B049A21701A54AF
+:20E3400001208646217806980A18694601A865DF0028E9D1694620780978401820706D1CC0
+:20E360003888A842C1DC7046002804D020780699801B401E88550020D6E7F8B51546069C10
+:20E380001E46074602220094FFF7A6FF002806D133461022294638460094FFF79DFFF8BD07
+:20E3A000F7B582B000260546167000681446002805D02846039900F0CAF8060008D168794D
+:20E3C00000281ED02078039F001D1F2802D90C2005B0F0BD684679DF0028F9D1217803226A
+:20E3E000481C20707A5421781922481C20707A542078C1196846008800F0A4F821784018A0
+:20E400002070A8790223002810D02078039A411C2170135420780399471C012227700A54E5
+:20E420002078AA79471C039927700A54A868002815D00021415620788C460246C01C03992E
+:20E440001F28C4D8501C20708B5422780A23501C20708B5420786246431C23700A54A8899B
+:20E46000002809D028460094062202210C30039BFFF783FF0600ABD1A88A002809D02846D9
+:20E480000094072203211430039BFFF776FF06009ED1A88B002809D0284600941522142137
+:20E4A0001C30039BFFF769FF060091D1686A002805D02246039900F07FF8060088D1A86A01
+:20E4C000002805D02246039900F0B5F8060084D13020405D002806D022462846039900F0F6
+:20E4E000DCF80600C7D1304672E770B50C4692B000216A46117007251171002809D0817927
+:20E5000049070CD502A9FFF74BFF002808D102AE00E00026002C0ED0A079002802D028469D
+:20E5200012B070BD01AA0AA92046FFF739FF0028F6D10AAA00E0002268460379017830463C
+:20E5400072DFEDE70870000A487002207047F8B514780746A01C15460E461F2803D83879BF
+:20E56000801C1F2801D90C20F8BD1D20001B80B26946864608803019801C7DDF0028F3D143
+:20E580003868022805D168460088704501D8092107E038790821002801D0704501D96846F6
+:20E5A0000088421C3255641CE2B2B1542978801C081828700020F8BDF8B50D461178064636
+:20E5C000881D14461F2801D90C20F8BD33880720062BFAD31927FF01BB4202D94D4A9342D6
+:20E5E000F3D17288062AF0D3BA4202D9494FBA42EBD1484FBB4203D0BA4201D09342E4D87E
+:20E60000481C052220706A5420781222411C21702A54207841193088FFF794FF21784018C5
+:20E62000C0B2207041197088FFF78CFF2178401820700020F8BD70B5054600790E46801CD6
+:20E640001446C0B21178821C8A181F2A01D90C2070BD0A46491C401C2170B0542078FF224A
+:20E66000411C21703254207881192888FFF76AFF21784018C0B22070AA88002A09D0A968AC
+:20E68000002908D0801900F022FF2078297940182070002070BD072070BDF7B582B0029894
+:20E6A0001446C06A0F46002832D0029800252030009028E00298C16A0C2068430E18217855
+:20E6C00030794A1CC01C2270785421781622481C20707A542078C1193088FFF733FF217873
+:20E6E0004018C0B22070B288002A09D0B16800290ED0C01900F0EBFE207831794018207087
+:20E700006D1C0098EDB2007CA842D3D800205FE607205DE6FFFF000038B56749674A48883D
+:20E7200090420FD04A78664C521CD2B24A70237B934208D3083175DF002803D0A1690029FF
+:20E7400000D0884738BD00254D70217C002907D03B2176DF002803D0A169002900D0884728
+:20E7600061690029EED068460095884738BD70B5054601461C225248FDF75AFD4E4C002647
+:20E7800026702968002907D00822A01800F09FFE204608307ADF02E0474808307BDF0028C1
+:20E7A00008D1401E608044486670464A0021001DFFF7D6F870BD10B53F484068FFF769F9D5
+:20E7C00010BDF8B53C48103000F069F800263A4D3B4C002806D06169002919D001200090EB
+:20E7E000684614E02878002804D0616900290FD00096F5E7687800280CD0A16800226868B8
+:20E80000FFF70AF9002803D0A169002900D088472E70F8BD6168F1E7F8B5294C028800276B
+:20E82000254DE689102A18D029464968112A21D0122A2DD0502A0FD1801D0288B2420BD1FF
+:20E84000028B022A08D1C27E837E10021843C007C00F13D0FFF7B5FFF8BD81886980014667
+:20E86000154808221631103000F031FE6F70002EF0D0F8BD0020C04368806F700846FFF7BB
+:20E8800008F90028F5D0A1690029F2D08847F8BD811D09480822103000F019FEDAE7418827
+:20E8A000054808300288914204D34088814201D8012070470020704790280020FFFF0000B6
+:20E8C000CC2D002019E7030031B5054C04E0401E00902046FDF77AFC00980028F7D138BDC6
+:20E8E000E703000018225043FE4A00218018017181604161012281610261C1607047FFB577
+:20E9000081B0F94C049B039A054626691A4303200092002E03D1002A0ED001222261276919
+:20E92000039A0126360792003B0000F022FF072707162940526127000222EFE770693269FC
+:20E9400092B25043326933691204920C9BB2594329DF002812D102210FE0084628DF00286A
+:20E960000CD10399002901D0032106E00499002916D12978042946D017E0216105B0F0BDAE
+:20E980007069326992B25043326993B24B4301461846039A29DF0028F0D10499002901D0F4
+:20E9A0000421EAE72978042920D00521E5E773693069366980B2434368681B189B18B6B2C7
+:20E9C0004E43301880181946049A29DF0028E9D0D4E7306980B24843696880188A08696902
+:20E9E00029DF0028CAD1009900290CD00621C4E77069316989B24843316989B200F0D9FD08
+:20EA000028DF0028BAD10721B7E7F8B5B54918230A780F205A435418241DB3492278266970
+:20EA2000CF68022A1BD001252D07042A2AD0052A5BD1286981B2304600F0BBFD0146A36877
+:20EA400028699A1980B24843101A820860681818861928694B1C80B25843801B34E0B8023C
+:20EA600062686169121A0918A3683018181801239B029A4202D2920829DF31E0FF220132BA
+:20EA800029DF2DE0E268974914205043F4314018001D0BC8B04203D160685943814218D02E
+:20EAA000022A16D0286981B2304600F082FD0146286980B24843301A820828694B1C80B208
+:20EAC000584363689B19C01A83082046FFF717FF06E0286981B2304600F06BFDC01928DFED
+:20EAE000002802D17F4901228A70F8BDF8B57D4C069E65780A2D1DD027787D19EDB20A2D5B
+:20EB000001D30A3DEDB218277D432D192871AA6103C9EE60AB6069612861A1780020002978
+:20EB200004D1FFF772FF112800D100206178491C6170F8BD0420F8BD38B5024669481823B1
+:20EB400001785943081803690179022B0AD014246343644CF434E4588368009383691030F7
+:20EB6000A04738BD604B14331C68F5E7F8B55D4B9978012914D100255B499D700A69082A77
+:20EB800005D002280FD003280AD10D2006E0022807D00D7000F025FA002801D0FFF7CCFF37
+:20EBA000F8BD0D61F6E74F48182403784E496343CC681818641C001DCC600378022B05D11F
+:20EBC0004668A102B14201D3012700E00027052B01D1072A03D00021042B02D003E00121C1
+:20EBE000FAE7072A03D00026042B02D007E00126FAE74068A302834201D3002A1AD0002000
+:20EC0000314301433943C5D0374E28463561FFF793FF344C2078FFF765FEF5606078401E1E
+:20EC200060702078401CC0B220700A28B2D30A382070AFE70120E3E770B500252A4C2948D3
+:20EC4000E56025610570457085702E463046FFF749FE761C0A2EF9D3012212076560516952
+:20EC600028461269491E92B25143E560A1601D49F4310D608D600D61CD601B4914310D6090
+:20EC8000888001212170206170BDF8B5164A044610780E46002830D0002C30D0002E2ED058
+:20ECA000206800282BD0012000076768016989B28F4228D8102F26D3A168002923D09568E2
+:20ECC000794343694A19006980B243439A421AD801200007006980B2814212D901200007E1
+:20ECE000006903E0E82D0020A828002080B2394600F05FFC002906D103E00820F8BD0E20B9
+:20ED0000F8BDB80701D00720F8BDBD49486801281CD00F461421BB4A21C641438E18756092
+:20ED2000236853506168B160A168F160A268616800235143012212075B1C14699BB2A4B214
+:20ED40008C4205D21469A4B2091B02E00420F8BD00211469A4B265191469A4B28C42EBD985
+:20ED6000BD60401C336178600020F8BDF8B50446A3481E46007815460F46002807D0002F3D
+:20ED800007D0002C05D02068002817D103E00820F8BD0E20F8BD9B48016800290ED0C268E3
+:20EDA000816840684A4310186268904206D9002D04D0A94202D3A819884201D90720F8BD90
+:20EDC000384600F008F9002811D0304600F003F900280CD0606800F0FEF8002807D02B4637
+:20EDE0003A46214602200096FFF780FEF8BD1020F8BDFFB5824881B000781F4616460D462B
+:20EE0000002808D0002D08D00198002805D02868002817D103E00820B0E50E20AEE5794C91
+:20EE2000206800280ED0E168A0686268414389186A68914206D9002E04D0B04202D3F119AD
+:20EE4000814201D9072099E5019800F0C4F800281BD0384600F0BFF8002816D0686800F025
+:20EE6000BAF8002811D068683246C119019800F02EFB00962868142148432458002203215B
+:20EE80002846019BA047002078E5102076E5F8B505465B480F460078002805D0002D05D012
+:20EEA0002868002821D103E00820F8BD0E20F8BD544C00262068002817D0A168E0684843CC
+:20EEC00061684118686881420FD900F084F800280DD0296814225143091968684A68896834
+:20EEE000801A00F066FB002903D00720F8BD1020F8BD3B460022294604200096FFF7F6FDB5
+:20EF0000F8BD3F4A1278002A0DD000280DD000290BD00268002A08D0394A14321368002B3E
+:20EF200005D004207047082070470E20704702230B600068106000207047F8B504463048AF
+:20EF40001E46007817460D46002807D0002D07D0002C05D0206802281BD103E00820F8BDC3
+:20EF60000E20F8BD264814300068002811D0084600F031F800280ED0304600F02CF800286C
+:20EF800009D03B462A46214602200096FFF7AEFDF8BD0720F8BD1020F8BD08B5184A1278C8
+:20EFA000002A05D0002805D00268022A11D103E0082008BD0E2008BD114A14321268002AD5
+:20EFC00007D00B460022014604200092FFF78EFD08BD072008BD800701D000207047012068
+:20EFE0007047084910B5F43949780020002906D0FFF70BFD002802D0112800D1002010BD48
+:20F00000A8280020DC2E002070B500250C290ED304464318008941000919581A0A38C2B2BD
+:20F020001748022A027002D30A318B4201D2092070BD144800F04BFA134914480A8882422E
+:20F0400002D02388934217D14988814202D06088884211D10D4A0323521E20891B03A842DE
+:20F060000AD9690009194989914203D09E896D1CB142F4D1002070BD0B2070BD00207047C6
+:20F08000C4280020F02E002080100010FFFF000010B5FDF7ABF810BD10B50446002A02D054
+:20F0A0001088002210E00A48FBE7030A00020343A05C584003061B0F43401803584083B2EB
+:20F0C0001806C00C5840521C8A42EED310BD0000FFFF00004B48002101704C484A4A026039
+:20F0E0008160C160016108224161426081610846704710B500291DD000220A60434A5368A8
+:20F10000002B1BD0202817D85B1E5360D0682423401CD060106914684343E3180B60012366
+:20F1200083409169401C19434007400F91611061002010BD0E2010BD0C2010BD042010BD8F
+:20F14000F0B5324A0646916800292BD057691020791A4907490F14680B4624254D436519D6
+:20F16000B54206D1012495698C4065400020956104E0491C4907490F8F42EED1491C4E07DC
+:20F18000760F956901210C469C402B4623420AD19368002B07D05B1E936053685B1C53609D
+:20F1A0003346F0E70420F0BD184A2423117C1268491E4907490F594320315050002070470B
+:20F1C00070B500281AD0002918D0104AD368002B16D05B1ED360936824265B1C936053692A
+:20F1E00015681C467343EE1820330660E858641C08606007400F5061002070BD0E2070BD84
+:20F20000042070BDC5280020FC2E00201C30002030B5CB0008339DB293070024002B01D0E6
+:20F22000072030BD3B4B9A605219DA605C701C7058809980002030BDF7B5364C0E466088D5
+:20F24000814237D8344F00F069F822786078A188884201DA401C00E00020C0B2904202D155
+:20F2600000F062F824E065786078884201DA401C00E00020607000F057F8BD4218D0A0688C
+:20F28000EF000299C151009900290CD0002E0AD0608832464543E068281800F018F9A068B3
+:20F2A0003818868002E00021381881800020FEBD0420FEBD0920FEBD0EB504E068468188A8
+:20F2C000029A0098904702AA01A9684600F003F80028F3D00EBD70B50E4B05241D785E786C
+:20F2E000AE4215D01D781C789E88B44201DA641C00E000241C705C88DE686C43A41904600F
+:20F300009B68E800C418A4880C80185800241060204670BDCC280020FFFF000072B606484F
+:20F320000168491C0160704703490868401E086000D162B670470000DC280020BFF34F8F11
+:20F3400003490248C860BFF34F8FFEE70400FA0500ED00E010B5002904D000221146104619
+:20F36000FFF7ECFF00F010F810BD10B50021024A0846FFF761FF10BD55F3030010B50846E6
+:20F380001146FCF771FF10BDF8B5384C2078002837D02069002807D00026E068002805D0FB
+:20F3A0000025002E04D013E00126F6E70125F8E7684651DF052806D0002806D000221146D2
+:20F3C000FFF7BCFF04E0012602E0216900988847002D12D1608869460880A06861DF0528FA
+:20F3E00006D0002806D000221146FFF7A7FF04E0012502E0E168A0688847002ED8D0002D15
+:20F40000CFD0F8BD70B5002901D08C0701D0072070BD164C0125A16062801549636010DF46
+:20F420000028F5D1257016202EDF70BD002803D00E49C860002070470E207047002803D0A8
+:20F440000A490861002070470E20704710B507484068002807D08047002803D0002211463E
+:20F46000FFF76CFF10BDFFF78FFF10BDE02800207DF30300034610B50B439B070FD1042A66
+:20F480000DD308C810C9121FA342F8D018BA21BA884201D9012010BD0020C04310BD002AAC
+:20F4A00003D0D30703D0521C07E0002010BD03780C78401C491C1B1B07D103780C78401C61
+:20F4C000491C1B1B01D1921EF1D1184610BDF8B5042A2CD3830712D00B78491C0370401C25
+:20F4E000521E83070BD00B78491C0370401C521E830704D00B78491C0370401C521E8B07F9
+:20F500009B0F05D0C91ADF002023DE1B08C90AE0FCF78EFEF8BD1D4608C9FD401C46B440B8
+:20F520002C4310C0121F042AF5D2F308C91A521EF0D40B78491C0370401C521EEAD40B78EC
+:20F54000491C0370401C521EE4D409780170F8BD01E004C0091F0429FBD28B0701D50280F7
+:20F56000801CC90700D00270704700290BD0C30702D00270401C491E022904D3830702D5EE
+:20F580000280801C891EE3E70022EEE70022DFE70378C2781946437812061B0219438378A2
+:20F5A000C0781B04194311430902090A000608437047002203098B422CD3030A8B4211D366
+:20F5C00000239C464EE003460B433CD4002243088B4231D303098B421CD3030A8B4201D39D
+:20F5E00094463FE0C3098B4201D3CB01C01A524183098B4201D38B01C01A524143098B422D
+:20F6000001D34B01C01A524103098B4201D30B01C01A5241C3088B4201D3CB00C01A524193
+:20F6200083088B4201D38B00C01A524143088B4201D34B00C01A5241411A00D201465241FB
+:20F64000104670475DE0CA0F00D04942031000D34042534000229C4603098B422DD3030A47
+:20F660008B4212D3FC22890112BA030A8B420CD3890192118B4208D3890192118B4204D305
+:20F6800089013AD0921100E08909C3098B4201D3CB01C01A524183098B4201D38B01C01A88
+:20F6A000524143098B4201D34B01C01A524103098B4201D30B01C01A5241C3088B4201D37F
+:20F6C000CB00C01A524183088B4201D38B00C01A5241D9D243088B4201D34B00C01A52417F
+:20F6E000411A00D20146634652415B10104601D34042002B00D54942704763465B1000D31A
+:20F70000404201B50020C046C04602BD704770477047754600F022F8AE460500694653469B
+:20F72000C008C000854618B020B5FEF7FBFA60BC00274908B6460026C0C5C0C5C0C5C0C525
+:20F74000C0C5C0C5C0C5C0C5403D49008D4670470446C046C0462046FCF7FFFC004870479C
+:20F760003830002001491820ABBEFEE726000200704730B47446641E2578641CAB4200D256
+:20F780001D46635D5B00E31830BC184702000000000000000000000000000000040000009F
+:20F7A000000000000000000000000000000000000000000035C4030000000000000000004D
+:20F7C000020000000000000000000000000000000000000000000000030000000000000024
+:20F7E0000000000005000000000000000000000000000000000000000000000023D1BCEA6A
+:20F800005F782315DEEF1212000000002CF8030000280020F400000004C1030020F90300A1
+:20F82000F4280020A413000020C103000000000000000000000000000000000000000000F1
+:20F840000000000000000000000000000000000000000000000000000000000000000000A8
+:20F8600000000000000000000000FFFF000000003200000000000000000000000000000058
+:20F88000000000000000000000000000000000000000000000000000000000000000000068
+:20F8A000000000000000000000000000000000000024F40000000000000000000000000030
+:20F8C000000000000000000000000000000000000000000000000000000000000000000028
+:20F8E000000000000000000000000000000000000000000000000000000000000000000008
+:20F900000000000000000000000000000000000000000000000000000000000000000000E7
+:20FC00000100000000000000FE0000000000000000000000000000000000000000000000E5
+:020000041000EA
+:0410140000C0030015
+:040000050003C0C173
+:00000001FF
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/bootloader/s130_nrf51_1.0.0_bootloader.hex
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/bootloader/s130_nrf51_1.0.0_bootloader.hex	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,463 @@
+:020000040003F7
+:20C00000983C002005DD030017DD030019DD03000000000000000000000000000000000057
+:20C0200000000000000000000000000069C1030000000000000000001DDD03001FDD0300D7
+:20C0400021DD030021DD030021DD030021DD030021DD03000000000021DD030021DD0300D9
+:20C0600021DD030021DD030021DD030021DD030021DD030021DD030021DD030021DD0300B8
+:20C0800021DD030057D8030021DD030021DD03006DD8030021DD03004DF4030021DD0300DD
+:20C0A00021DD030021DD03000000000000000000000000000000000000000000000000007E
+:20C0C00000F002F800F040F80CA030C8083824182D18A246671EAB4654465D46AC4201D18E
+:20C0E00000F032F87E460F3E0FCCB6460126334200D0FB1AA246AB463343184710370000C8
+:20C1000030370000103A02D378C878C1FAD8520701D330C830C101D504680C6070470000D3
+:20C120000023002400250026103A01D378C1FBD8520700D330C100D50B6070471FB5C04655
+:20C14000C0461FBD10B510BD03F0E3FA1146FFF7F5FF00F0D3F803F0FBFA03B4FFF7F2FF19
+:20C1600003BC03F0FFFA00000648704502D1EFF3098101E0EFF30881886902380078024A97
+:20C1800010470000FDFFFFFF39D50300401E00BF00BF00BF00BF00BF00BF00BF00BF00BF28
+:20C1A00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BFB4
+:20C1C00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BF94
+:20C1E00000BF00BF00BFF1D170470000056885F3088846680A4AEFF305839A42304602D183
+:20C20000084CA6463047074C064D0646064FF0B4034C034D024E024FF0B404480047000005
+:20C2200000000000FFFFFFFF00000021F9FFFFFF70B505460C46164602E00FCC0FC5103EEE
+:20C24000102EFAD2082E02D303CC03C5083E042E07D301CC01C5361F03E021782970641C63
+:20C260006D1C761EF9D270BD0A4610B50146664803F064F810BD10B502F078FC10BD10B5C6
+:20C28000624C86B01ECC03946C460EC4002807D0684618DF002803D00022114603F04EF864
+:20C2A0000F20800313DF002803D00022114603F045F8574B48225749092003F0A3F80028AB
+:20C2C00003D00022114603F039F800200490059001206946087404A860DF002803D0002251
+:20C2E000114603F02BF84C4803F0A8F8002803D00022114603F022F806B010BD08B547485A
+:20C30000C169B12943D0002445480F2140698903884204D000221146104603F00FF8012068
+:20C320000007006901218902884204D000221146104603F003F83B4800903B4B05220321A1
+:20C34000002001F0BAFA002803D00022114602F0F5FF00F067FC00F0AAFC012500281AD09D
+:20C3600000F0B4FC002803D00022114602F0E6FF20466840FFF783FF00F038F800F0CCFC74
+:20C3800000280ED00022114602F0D8FF09E001240021C161B8E720466840FFF770FF00F002
+:20C3A00025F803252D03002C04D1A86800F090FB002807D100F047FC002803D000221146D5
+:20C3C00002F0BCFFA86800F083FB002806D000F06EFC002802D1A86800F041FCBFF34F8F12
+:20C3E00013491248C860BFF34F8FFEE7094A10B548321421082002F00BFF002803D00022E2
+:20C40000114602F09BFF10BDEFBEADDE8CF703006BF30300342B002077C20300000500404D
+:20C4200000100010EFDC0300F42800200400FA0500ED00E070B5FC4C1E46A06815460229A3
+:20C4400002D0042916D108E0052813D1A369002B10D03246294604200BE002280AD1F348B0
+:20C46000406880470320A060A369002B02D0324629469847280003D00022114602F05EFF98
+:20C4800070BD4CB5E84E0120307005200195009400F058FB4CBD10B5E34C2078002801D057
+:20C4A000082010BD206901F0F4FA002803D00022114602F043FF0F2100228904206901F01E
+:20C4C000ABFA040003D00022114602F037FF204610BDD54910B5D448243141610221816012
+:20C4E000C168243002F059FD002803D00022114602F024FF10BDCC4910B5CB481C31416145
+:20C50000022181600320000380680F218903081A4108C5481C3002F040FD002803D000223D
+:20C52000114602F00BFF10BD704700B589B01822BF4902A8FFF77CFE06980799009001917A
+:20C5400002A80FC800F0FEFA09B000BD00B5B64987B049886A461181032109038968069146
+:20C56000B249012050394A6803928A680492C9680591069A0091019202A90EC900F0E2FA6E
+:20C58000002007B000BD30B5A84CA748503C89B02430E16802F001FD002803D00022114679
+:20C5A00002F0CCFEA048E2681C3041680023083002F0C3FC050012D1182102A802F0E6FFEA
+:20C5C00000209949029049886A469181E1680691079A0091019203A90EC900F0B3FA284601
+:20C5E00009B030BD00B5904987B049886A4611818E49032050394A6803928A680492C9683A
+:20C600000591069A0091019202A90EC900F09AFA0020B6E73EB5864A6B46183207CA07C3A4
+:20C62000814D00246C7029466C802431684602F068FC002801D0AC603EBD03207A4900038F
+:20C6400080682431486024390A46526ACA610F218903091A490840187349764A1C31486068
+:20C6600071480021103001F07BF9002803D00022114602F063FE0F2100228904286901F013
+:20C68000CBF9002803D00022114602F057FE01206C60A86000203EBD63498861704770B59A
+:20C6A000426862481468536891685038D26804604360C26081600078440701D5840705D130
+:20C6C0009C0703D18C0701D1940701D0062070BD5B189A18544D0F239B02EA60994213D81A
+:20C6E0005549564B514CC60709D08868181A90420AD3534820605348606053480FE08968F6
+:20C70000591A4908914201D20C2070BD4F4921604F496160800701D54E4800E04E48A0607B
+:20C72000A868012802D00826304670BDFFF7B3FE0600FAD12168E8688847F5E770B50500F7
+:20C7400004D0287A800703D0102070BD0E2070BD354CA068032805D0042801D0052803D0CB
+:20C76000082070BD0520A0606868E168860060688019884204D90020C04360600C2070BD5C
+:20C78000FFF789FE0028FAD1A96832466368606902F0D3FB0028F2D1616889196160E268EB
+:20C7A0009142ECD0092070BD10B51F4C08206168002900D010BDA1680429FBD11B4861786F
+:20C7C000403802F021FC002802D00021617010BD0521A16010BDF8B5134C0746A068032899
+:20C7E00004D0042804D008252846F8BD0420A0606068002801D00820F8BDFFF74CFE05000E
+:20C80000FAD17868860060788119402901D90920F8BD064AB968403A1018324602F057FE82
+:20C82000607880196070DFE7002800201C2D00209CF7030083C403000030000000C003006D
+:20C84000D3C403002BC503004DC50300F7C4030029C50300E5C5030087C5030010B5894CF1
+:20C86000A068052813D1E168606888420FD10620A060FFF710FE002808D16069E1684068FF
+:20C8800002F0FCFB002801D10721A16010BD082010BD10B57B488168072901D0082010BD63
+:20C8A000006901F0F6F8002803D00022114602F045FD75488068804710BD1CB506200195C2
+:20C8C000009400F03FF91CBDF8B51C4617460D46064600F0C1F8002817D001200003854215
+:20C8E00007D92346291B301B1A46FFF7EDFF00280BD13A462946304600F0B9F8002804D117
+:20C900003A462946304600F0A7F8F8BDF0B589B0684600F015FA049800282AD001210903F7
+:20C92000079A4018904226D9501A45081046049A0C468718024668001618001908900320DF
+:20C9400000038068049988420DD261190846042200F08DF800280CD121460422084600F073
+:20C9600086F8002805D1BA1B2B4630460899FFF7ABFF09B0F0BD049A079800F078F8F8E75C
+:20C9800000B58DB004A800F0DBF9099800280DD0089800280CD008990B984018019000219D
+:20C9A0000998009180080290684618DF0DB000BD0320000380680F218903091A4908ECE7FB
+:20C9C00000B58DB004A800F0BBF909980028EDD00F210898890300280CD0089A0B98019158
+:20C9E0008018029003220998009280080390684618DFDBE70320000380680A1A5208EEE7D2
+:20CA000030B591B0684600F09BF90498002814D001210903079A4018904214D9501A43087B
+:20CA20001046049A5C0082180019611803242403A468049DAC4202D20E2011B030BD121AB5
+:20CA4000FFF742FFF9E703200CAB07C3049880080F900CA818DFF0E71FB5032301909008B3
+:20CA6000039000930291684618DF04B010BD1FB5012301909008039000930291684618DF58
+:20CA8000F3E70000002800201C2D002010B5BB480368012B02D1022900D10160100003D099
+:20CAA0000022114602F04AFC10BD10B5B34C48DF002803D00022114602F040FC02F0FCFB82
+:20CAC0002068022803D0032801D00428EFD110BD38B50068401C19D00024684600F058F96F
+:20CAE00000980168012910D1818800290AD0C168032000038068002202F0CEFA0099898861
+:20CB0000814201D1012400E00024204638BD10B504469A482021001D02F0B9F9002803D00E
+:20CB20000022114602F00AFC9448002320222146001D02F01BF9002803D00022114602F053
+:20CB4000FDFB10BD0FB4F8B5684600F021F96846818B069D0122894CFF238948002D13D090
+:20CB6000012D17D0032D2BD00021022D37D02A46052D46D0042D4ED0062A01D10420206071
+:20CB8000F8BC08BC04B0184781800A9983600260C16010E08180099D089949190A9D49195D
+:20CBA000C160A52183600160089901610999856141610B99C16122607148FFF7A8FFDFE7B9
+:20CBC00000990B6803608B888380C968C160AA21816008990161099941610A990BE0009D60
+:20CBE0002E68A52E09D00660AE888680ED68C5600161836041618161DDE781800360C160C5
+:20CC0000F6E700F085F9002803D00022114602F095FB0320B3E781800360C1600099896807
+:20CC20008160C9E70EB557480090202001900120029002F001F8002804D150496846091D98
+:20CC400002F023F80EBD10B5FFF7E4FC002805D100F02FFB0446FFF728FF204610BD70B58A
+:20CC600011DF002803D00022114602F067FB464900200B68444C012180340A4682401A4206
+:20CC800004D0C506ED0E0A46AA402260401C2028F3D303242403A06813DF002803D000226F
+:20CCA000114602F04BFBA06802F0F2F970BD08B5684600F06DF800980168A52904D0806888
+:20CCC000AA2801D0002008BD012008BD10B5FFF797FE002803D1FFF773FE00281BD064209C
+:20CCE00001F0F2FDFFF712FE002803D00022114602F024FBFFF784FE002803D000221146DD
+:20CD000002F01CFBFFF73CFE040003D00022114602F014FB204610BD00B589B018221B49CA
+:20CD200002A8FFF785FA069807990090019102A80FC8FFF707FFFFF7B8FE002009B000BDB5
+:20CD400010B50E4988B0044600232022091D684602F04FF80098206068468088A08003983A
+:20CD6000E0600298A06004982061059860610698A0610798E06108B010BD00002C280020E6
+:20CD8000282D00208DCA030000E100E0C0F70300014901607047000000FC030008280CD0DC
+:20CDA00004DC002807D006280FD108E00B280AD00C280AD105E001207047022070470320C9
+:20CDC000704704207047042901D0062070470520704770B515460A46032823D0042820D1FF
+:20CDE000FE4C002906D0E088FD49884219D0132176DF10E0284602F0A3F9002803D00022F7
+:20CE0000114602F09BFAE069A8420AD101220321F44801F003F8002803D00022114602F051
+:20CE20008DFA70BD01211046FFF7B8FF02460121EEE7F0B5054608790E4685B081070CD07C
+:20CE400003221146284600F0E9FF002803D00022114602F073FA05B0F0BDE04900901831D9
+:20CE600002F047F9010011D1DC4CB168009AA06902F02DFB009802F097F9010006D1204647
+:20CE80006946183002F09CF9010003D0284600F0AFFAE0E704200190009880080290A06902
+:20CEA000039001A8FFF74AFC07000BD0092F10D0A06902F045F9010002D0284600F098FA04
+:20CEC0003946E3E73079616940186061A069E061C1E7307961694118616160780028BAD073
+:20CEE0006089401E0004000C6081B4D1284601F0E9F8002803D00022114602F01FFA20890D
+:20CF00006081A8E710B50022114602F017FA10BD10B5B24C01202070E088B149884208D01B
+:20CF2000132176DF002810D00022114602F006FA0BE0A078002808D074DF002803D0002282
+:20CF4000114602F0FBF90020A07001F034FC002803D00022114602F0F1F9002010BD70B5E1
+:20CF60000D68044601209D4A2B0002F002FC0A2B3043061320575C466012FFF76FFC0421FD
+:20CF8000FFF70CFF024604212EE00022114602F0D5F970BDFFF7BCFF002803D0002211468A
+:20CFA00002F0CCF9FFF775FC002808D170BDFFF7AFFF002803D00022114602F0BFF9FFF76D
+:20CFC0007CFC70BD106188680078107170BD02201061886800780128F8D1FFF7E5FB02213F
+:20CFE000FFF7DCFE02460221204600F017FF0028CBD170BD0320106170BD12692046012ACC
+:20D0000006D0022A07D0032AF6D1FFF712FF70BD00F001FA70BD00F03BFA70BD50708888D5
+:20D020001081508170BD00205070108170BD2046516901F010F8DAE710B5044669488EB0EB
+:20D0400081796846817068490180342101A802F09DFA022001900021684641728472012131
+:20D0600001820590002101A801F03FFA002803D00022114602F062F90EB010BDF0B5574C10
+:20D080008BB0A07800283AD156481821183802F07DFA2046534CC078183C00250126002875
+:20D0A00037D02746483700950195029510226946F81D039502F0DEF9002822D0F81D08909D
+:20D0C00009976846067509A804906846067708A806900420FFF7B0FF25700220207204A813
+:20D0E000E060282020823F486582183873DF002803D00022114602F021F9384886700BB045
+:20D10000F0BD0520FFF798FF2670676025722582E9E70620FFF790FF257065602572E0E7E2
+:20D1200070B52E4C01880022E588A6B017290AD01EDC11293FD008DC022977D0102902D123
+:20D140008088E080A27026B070BD264C303426461836132951D01429F5D1C289638D002106
+:20D160009A4200D1314600238088E21D82DF1BE0512970D00EDC18296CD01929E3D18079F5
+:20D180000028E0D1A270E068401EE0604FD0FFF775FFD8E7522976D05529D4D18079002871
+:20D1A000D1D11321284676DF0028CCD00022114602F0C4F8C7E78020694688803220E06054
+:20D1C000012301AA06A92846AADF002803D00022114602F0B3F82078002807E038280020A2
+:20D1E000FFFF0000602D00203015000001D1FFF745FF0020C043E080A5E70722C14910A839
+:20D2000002F065F91022E11D0CA802F060F91C22314612A802F05BF90CA80A9012A8099039
+:20D2200006ABB94A852128467FDFBDE70DE01822B64906A8FEF7FCFF0A980B9900900191F8
+:20D2400006A80FC8FFF77EFC7DE70021284667DFAAE700E017E0817900299AD0807A042885
+:20D2600003D0062801D0052893D1022909D0012069460872FF208330888102A92846A8DF82
+:20D2800092E70220F4E700F08DF88DE710B5044601F0C2FA9B482146303800F09AFE2046D3
+:20D2A000FFF73EFF10BD10B50022114602F046F810BD30B5944D87B00024203D2C7094483D
+:20D2C0002C6102F0B3F800286AD19248FFF7E4F901F000FF002863D18A4800F059F900288C
+:20D2E00001D10120E87011206946087207228AA102A87CDF002803D00022114602F01EF8B4
+:20D3000000940C2168460194018018214180FF2184809131C1807ADF002803D0002211469A
+:20D3200002F00CF804206946009408807C4801907C4802907348303800F00BFE002803D046
+:20D340000022114601F0FAFF1C21684602F01EF9754801900120800302900094032168468C
+:20D360000173C4810474714806900594684601F0FEF9002803D00022114601F0DFFF624910
+:20D38000E12208784008400010400C30DF22104008700720487010208870FFF76FFE0020A3
+:20D3A00007B030BD70B5584C614D203CE088A84201D1082070BDE178002914D05149012359
+:20D3C00008223431A9DF0028F4D12A460C21E088A7DF5849884204D0082802D0891C88420E
+:20D3E000E8D1002070BD00231A461946A9DF70BD10B50A46044603211046FFF7CFFC0246AE
+:20D400000321204600F00AFD002803D00022114601F094FF10BD30B5054687B000200090AF
+:20D4200001900290039038486A46203800791070364A0C3A1068926804906846069205900E
+:20D4400008790C2806D003221BE00022114601F075FFA5E78C68204600F049F80190201D5E
+:20D4600000F045F802902046083000F040F8039004A8FFF714F9002892D00121FFF78EFCB9
+:20D4800002460121284600F0C9FC0028DDD187E7FEB50446087982070ED08207920F042385
+:20D4A0009B1A0022154604E08E683554401CC0B2521C9A42F8D30871012000908868029048
+:20D4C0000879800801906846FFF785F900280DD00221FFF763FC02460221204600F09EFCB8
+:20D4E000002803D00022114601F028FFFEBD10B5044602F04DF80002E178000A09060843E0
+:20D5000010BD0000902D002058280020E4F703008DD20300D3CD0300446675546172670031
+:20D520005FCF0300A7D20300CD0C000005CF0300FFFF00000230000010B50C46002802D04D
+:20D540000120086010BD2168002911D01C48421A814212D03C2A0DD23C303C3101220B78B9
+:20D5600003701346491E401E521C3C2BF7D904E00E200BE03C2201F0AAFF00223C211048A9
+:20D5800001F08AFD0E49891E08800020206010BD70B5054600223C21094801F07DFD084C21
+:20D5A000A41E2188884201D00B2070BD3C220449284601F08CFF2088401C2080002070BD87
+:20D5C000823F00208307FF22DB0E9A408907090E994000280BDA0007000F08388308FA484C
+:20D5E0009B001B18D86990430843D86170478308F6489B001B1818689043084318607047AA
+:20D6000070B50124F24960040860F24940108860F04940398860F04D6C602F20FEF7B6FDAC
+:20D62000AC60EE4D00242F206C61FEF7AFFD2C7170BDF0B5E94F2821BC6841430D19396962
+:20D640004A1C09D028224A431619AB68B268934204D8D21AB26069623861F0BD0A4602E066
+:20D660000A46796A9B1B4E1C0BD028264E433719BE689E42F4D328264E433619B768FF1A1A
+:20D68000B760AB60696228214A4311194862F0BD70B5D24C2269A5681346114606E0814212
+:20D6A00007D00A46282671434919496A4E1CF6D170BD002EFCD08A420CD1282043435819EC
+:20D6C000406A2061401C05D1C34B01209860002363616071282041434819282381685A4310
+:20D6E000406A52195062421CE2D028225043401982685118816070BDF8B5B84C2569681CF9
+:20D7000035D0B748002640686169401A07023F0A19E028204543A0682A189068B84214D8D0
+:20D72000A3693F1A8619556A002B09D0116AD0699847002807D00022114601F0FFFD02E048
+:20D74000D169106A8847681CE3D1A178E078814206D1401CC0B2E070022801D10020E07079
+:20D760009E490006800D1C310E5000F0BAF9F8BDF8B50446994800270169009146785CE038
+:20D780009648F100C2688D1851E0601C07D0934A28209268604321468018446A24E0287854
+:20D7A000182141436A68401CC0B252182870A978884200D12F70894B516828209B6848434C
+:20D7C000C0181368012B34D1037E002B31D19368C360D368036113694361526902627F4A52
+:20D7E0005279002A00D0C7607C4BC2685B6996469C46D31A1A027B4B120A9A4202D20369C3
+:20D80000D21808E0724663469A1A12020369120A934202D99A1A826000E08760C76001222E
+:20D8200007610276921E42620846FFF702FF601CABD1287869788842A7D13046761EF6B202
+:20D8400000289DD1654801690098814201D00120F8BD0020F8BD644900200860486088607F
+:20D86000C860614940390860486045E7FEB50020C0435A4D02906869019068462E6900F07B
+:20D8800035F9074600F04FF90446002F08D002AA0199009800F08FF90298FFF769FF06E050
+:20D8A0000298FFF765FF002801D1002C02D0304600F0AAF900206871FEBDFFB59807002448
+:20D8C00081B01E4615460F4600280BD1002E09D0FFF796FE41490A9888610F703246002042
+:20D8E0008E6008E0072005B0F0BD28234343D4509B181C76401CB842F7DB28204743BB19C1
+:20D90000032048700F461846CB6019461830002218232E465E43D3005B181C705C709D708A
+:20D9200058603018521C032AF5DB0020C0433861BC70FC7001242D482405046003211420A9
+:20D94000FFF740FE224880380460254C0198A06003211120FFF736FE606878610020C2E71A
+:20D9600070B51E4CA568002D06D0002A06D0002804D00023247809E0082070BD072070BDBB
+:20D9800028265E43AE59002E04D05B1CA342F7DB042070BD282401265C432E516419E261BF
+:20D9A00061600360002070BD07494868C005C00D2CD010381CD50207120F083A9208920097
+:20D9C0005118C96919E0000000ED00E000E400E080E100E040130140001001406028002054
+:20D9E00000150140FFFF7F004011014080E200E08108B14A8900891809688007C00EC1400B
+:20DA00000806800F012803D0032803D0022070470020704701207047FEB50446A74817469E
+:20DA200082680D46002A0CD001788C4201D2052D01D20720FEBD2146282359435358012B7D
+:20DA400001D00820FEBD8818406801281DD00026FFF7AAFFC00099490190C9684018694684
+:20DA600000F018F9002812D0012144600160944949680830E2C091490198C9684118009877
+:20DA8000487000F02EF80020FEBD2E46E0E70420FEBDF8B5894D0446A868002809D0297844
+:20DAA0008C4201D30720F8BD282161434058012801D00820F8BDFFF777FFC600E86869465B
+:20DAC000301800F0E7F8002809D0022112C0E86831180098487000F004F80020F8BD04206B
+:20DAE000F8BD0120774900050860704710B5734900238A78CC78A24212D0521CD2B28A70D0
+:20DB0000022A00D18B708A786C4B92001C339A580260486910180002000A4861012010BDA3
+:20DB20000360002010BDF8B5644801690091457833E06248E900C0680E1834782AE01820A2
+:20DB400060437168641C0818B178E4B2A14200D100240168022902D003291BD113E0574A00
+:20DB600040682821926841438F18397E002911D0FFF78EFD002038760CE028277843C018B1
+:20DB80000276406A03E04D4900228B680869471CF3D108617078A042D1D128466D1EEDB2D0
+:20DBA0000028C6D1454801690098814201D00120F8BD0020F8BDF7B5404C0025A7682369E0
+:20DBC0001EE028215943C9198E68864202D9301A886017E0801B751900268E600E764E6946
+:20DBE0009C464B6AB646002E0AD0019E76193602360ACE6076460E6116684E626146116045
+:20DC0000591CDED12361FEBDF8B52C4801694A1C3DD028225143826889188E6828494C681F
+:20DC200047690079E11B0D022D0AED1C002815D10120254A00045060234A403A506021491D
+:20DC4000400080310860214908602149012008602F20FEF79BFA194901200871B54200D208
+:20DC60003546E81900021649000A4031086014494968001B091B0902090A0002C91C000A88
+:20DC8000814203D901200F4940040860F8BDFFF7B7FCF8BD42788378521C934200D10022C2
+:20DCA0000378934201D1002070470A6041684078182250430818704700E400E06028002090
+:20DCC0000015014000E200E04013014000E100E00010014010B50446082904D000221146F9
+:20DCE000104601F02BFB21686068884710BD1CB501910090024A0821684601F09DFA1CBD53
+:20DD0000D5DC03000A48026803210A4302600948804709480047FEE7FEE7FEE7FEE7FEE797
+:20DD2000FEE7000005480649064A074B70470000240500404DDD0300C1C003009830002007
+:20DD4000983C00209834002098340020F8B500F035F82B4E002804D02A4870602A49F01300
+:20DD600088612A480124018CC9B201290DD1818C09070AD1018D0906090F042905D1808D56
+:20DD80000006000F01D1224884600027B461214D6F60A8058460686800280ED1C820FEF790
+:20DDA00005FA1D487F1C8742F5D30020B06101208007846068680028FCD0F8BD1348018CB5
+:20DDC000C9B2012917D1818C090714D1018D09060A0F03D1828D1206120F0ED0090F0129C2
+:20DDE00003D1828D1206120F07D0032903D1808D0006000F01D0002070470120704700008E
+:20DE000000050040DFFF07C0006C0040C00F00F000060040000100408813000030B585B071
+:20DE2000002822D00388FE4CA34220D0FD4B1B78002B1CD0FB4B10255B1C1D7059700024C0
+:20DE400001259A70032269460A820094019402940394028A0A808D708C8004A902910393E7
+:20DE600000886946A6DF05B030BD0E20FBE70820F9E7F0B58BB0044602276846077300268B
+:20DE800009968784C68408A80A900D46A18A208809AAA5DF002804D0E16A00291AD08847BE
+:20DEA00018E06846008CC007C00F13D068460682208803A9A8DF002813D1A97E28461B30BA
+:20DEC00001220B0001F055FC09430F1B202224263E284300FF20FE3069460882208803A94D
+:20DEE000A8DF0BB0F0BD00960AE0062219E069460A71029022E0204690470020F1E700920D
+:20DF00002B8B022BF3D2F0E700971DE003201AE0042018E0052016E0298B032905D20322BE
+:20DF200008212046FFF77AFFDBE741780278080210436946888003D006200090A26ADAE784
+:20DF40000720FAE7092000906946A26AD3E70322E7E730B585B00D46040038D0002D36D0EC
+:20DF60006868002833D00020C043AF4B20800FCB049301AB07C3AD4869460880891C01A888
+:20DF800063DF002822D1221D69460120A0DF00281CD168468078A071204600F0CEF8002886
+:20DFA00014D1204600F055F900280FD12946204600F002F9002809D16868A062A868002804
+:20DFC00000D0E06297490120087000204BE70E2049E73EB5002828D0002926D0826A002ABE
+:20DFE00023D00A88102A21D0112A30D0502A1FD0512A1AD104460846891D0A78022A14D196
+:20E000004A88238A9A4210D1807A04280DD006280BD0052809D0891C2046FFF72AFF002860
+:20E0200003D0E16A002900D088473EBD898810E0CA8803899A42F8D1082200928A7F6B4605
+:20E040001A7120310291826A694690473EBD0021C94301803EBDF0B585B00A4605002DD00F
+:20E0600028886F4988422BD06E480078002827D06C4C1020641C2070072060700127A770F8
+:20E080000321684601820026E11C104600F04CF801466846008A0918684601820096019680
+:20E0A00002960396298A01808770868004A80394029028886946A6DF05B0F0BD0E20FBE7D3
+:20E0C0000820F9E7F0B585B00A46050028D028885349884226D053480078002822D0514C3B
+:20E0E0001120641C20700127684607820026611C104600F019F801466846008A0918684638
+:20E1000001820096019602960396298A01808770868004A80394029028886946A6DFCBE782
+:20E120000E20C9E70820C7E70870020A4A70020C8A70000EC8700420704730B58FB0054655
+:20E140001C21684601F022FA694608780421084369460870002401940394049405940694E6
+:20E16000A87908A9887031486946801C0884601C00070794000F0C77103048778A7FF920B4
+:20E180000240921CE7200240012002438A77142109A801F0FBF908A8099007A80A906946D3
+:20E1A0008C851420CC8508860D942B46A888083309AAA2DF0FB030BDF0B58FB00F4605465A
+:20E1C0001C21684601F0E2F968460178022631430170002401940394049405940694A97917
+:20E1E00008A8817011496846091D0184601C0107090F103168460794017700200146684618
+:20E200004177817FF9200140891CE72001400120014368468177142109A801F0B7F907E086
+:20E22000FFFF000088280020FCF703003015000008A8099007A80A9068468685C4850686B5
+:20E240000D972B46A888203309AA6946A2DF0FB0F0BD30B58FB005461C21684601F096F9FD
+:20E2600069460878082108431022104369460870002401940394049405940694A87908A962
+:20E280008870144869460884601C00070794000F0C7710304877887FF9210840801CF72123
+:20E2A000084010430121084369468877142109A801F06CF908A8099007A80A9069468C851A
+:20E2C0001720CC8508860D942B46A888103309AAA2DF6FE731150000FFB583B0074600207F
+:20E2E0000C9C8646267805463AE07868A90041180A88684682804988C1800022694601A8F7
+:20E3000065DF002810D1684601780598814226D17046002801D0002200E002222078891824
+:20E3200041181F2902D90C2007B0F0BD7146002908D1401CC0B2411C069B049A21701A54AF
+:20E3400001208646217806980A18694601A865DF0028E9D1694620780978401820706D1CC0
+:20E360003888A842C1DC7046002804D020780699801B401E88550020D6E7F8B51546069C10
+:20E380001E46074602220094FFF7A6FF002806D133461022294638460094FFF79DFFF8BD07
+:20E3A000F7B582B000260546167000681446002805D02846039900F0CAF8060008D168794D
+:20E3C00000281ED02078039F001D1F2802D90C2005B0F0BD684679DF0028F9D1217803226A
+:20E3E000481C20707A5421781922481C20707A542078C1196846008800F0A4F821784018A0
+:20E400002070A8790223002810D02078039A411C2170135420780399471C012227700A54E5
+:20E420002078AA79471C039927700A54A868002815D00021415620788C460246C01C03992E
+:20E440001F28C4D8501C20708B5422780A23501C20708B5420786246431C23700A54A8899B
+:20E46000002809D028460094062202210C30039BFFF783FF0600ABD1A88A002809D02846D9
+:20E480000094072203211430039BFFF776FF06009ED1A88B002809D0284600941522142137
+:20E4A0001C30039BFFF769FF060091D1686A002805D02246039900F07FF8060088D1A86A01
+:20E4C000002805D02246039900F0B5F8060084D13020405D002806D022462846039900F0F6
+:20E4E000DCF80600C7D1304672E770B50C4692B000216A46117007251171002809D0817927
+:20E5000049070CD502A9FFF74BFF002808D102AE00E00026002C0ED0A079002802D028469D
+:20E5200012B070BD01AA0AA92046FFF739FF0028F6D10AAA00E0002268460379017830463C
+:20E5400072DFEDE70870000A487002207047F8B514780746A01C15460E461F2803D83879BF
+:20E56000801C1F2801D90C20F8BD1D20001B80B26946864608803019801C7DDF0028F3D143
+:20E580003868022805D168460088704501D8092107E038790821002801D0704501D96846F6
+:20E5A0000088421C3255641CE2B2B1542978801C081828700020F8BDF8B50D461178064636
+:20E5C000881D14461F2801D90C20F8BD33880720062BFAD31927FF01BB4202D94D4A9342D6
+:20E5E000F3D17288062AF0D3BA4202D9494FBA42EBD1484FBB4203D0BA4201D09342E4D87E
+:20E60000481C052220706A5420781222411C21702A54207841193088FFF794FF21784018C5
+:20E62000C0B2207041197088FFF78CFF2178401820700020F8BD70B5054600790E46801CD6
+:20E640001446C0B21178821C8A181F2A01D90C2070BD0A46491C401C2170B0542078FF224A
+:20E66000411C21703254207881192888FFF76AFF21784018C0B22070AA88002A09D0A968AC
+:20E68000002908D0801900F022FF2078297940182070002070BD072070BDF7B582B0029894
+:20E6A0001446C06A0F46002832D0029800252030009028E00298C16A0C2068430E18217855
+:20E6C00030794A1CC01C2270785421781622481C20707A542078C1193088FFF733FF217873
+:20E6E0004018C0B22070B288002A09D0B16800290ED0C01900F0EBFE207831794018207087
+:20E700006D1C0098EDB2007CA842D3D800205FE607205DE6FFFF000038B56749674A48883D
+:20E7200090420FD04A78664C521CD2B24A70237B934208D3083175DF002803D0A1690029FF
+:20E7400000D0884738BD00254D70217C002907D03B2176DF002803D0A169002900D0884728
+:20E7600061690029EED068460095884738BD70B5054601461C225248FDF75AFD4E4C002647
+:20E7800026702968002907D00822A01800F09FFE204608307ADF02E0474808307BDF0028C1
+:20E7A00008D1401E608044486670464A0021001DFFF7D6F870BD10B53F484068FFF769F9D5
+:20E7C00010BDF8B53C48103000F069F800263A4D3B4C002806D06169002919D001200090EB
+:20E7E000684614E02878002804D0616900290FD00096F5E7687800280CD0A16800226868B8
+:20E80000FFF70AF9002803D0A169002900D088472E70F8BD6168F1E7F8B5294C028800276B
+:20E82000254DE689102A18D029464968112A21D0122A2DD0502A0FD1801D0288B2420BD1FF
+:20E84000028B022A08D1C27E837E10021843C007C00F13D0FFF7B5FFF8BD81886980014667
+:20E86000154808221631103000F031FE6F70002EF0D0F8BD0020C04368806F700846FFF7BB
+:20E8800008F90028F5D0A1690029F2D08847F8BD811D09480822103000F019FEDAE7418827
+:20E8A000054808300288914204D34088814201D8012070470020704790280020FFFF0000B6
+:20E8C000CC2D002019E7030031B5054C04E0401E00902046FDF77AFC00980028F7D138BDC6
+:20E8E000E703000018225043FE4A00218018017181604161012281610261C1607047FFB577
+:20E9000081B0F94C049B039A054626691A4303200092002E03D1002A0ED001222261276919
+:20E92000039A0126360792003B0000F022FF072707162940526127000222EFE770693269FC
+:20E9400092B25043326933691204920C9BB2594329DF002812D102210FE0084628DF00286A
+:20E960000CD10399002901D0032106E00499002916D12978042946D017E0216105B0F0BDAE
+:20E980007069326992B25043326993B24B4301461846039A29DF0028F0D10499002901D0F4
+:20E9A0000421EAE72978042920D00521E5E773693069366980B2434368681B189B18B6B2C7
+:20E9C0004E43301880181946049A29DF0028E9D0D4E7306980B24843696880188A08696902
+:20E9E00029DF0028CAD1009900290CD00621C4E77069316989B24843316989B200F0D9FD08
+:20EA000028DF0028BAD10721B7E7F8B5B54918230A780F205A435418241DB3492278266970
+:20EA2000CF68022A1BD001252D07042A2AD0052A5BD1286981B2304600F0BBFD0146A36877
+:20EA400028699A1980B24843101A820860681818861928694B1C80B25843801B34E0B8023C
+:20EA600062686169121A0918A3683018181801239B029A4202D2920829DF31E0FF220132BA
+:20EA800029DF2DE0E268974914205043F4314018001D0BC8B04203D160685943814218D02E
+:20EAA000022A16D0286981B2304600F082FD0146286980B24843301A820828694B1C80B208
+:20EAC000584363689B19C01A83082046FFF717FF06E0286981B2304600F06BFDC01928DFED
+:20EAE000002802D17F4901228A70F8BDF8B57D4C069E65780A2D1DD027787D19EDB20A2D5B
+:20EB000001D30A3DEDB218277D432D192871AA6103C9EE60AB6069612861A1780020002978
+:20EB200004D1FFF772FF112800D100206178491C6170F8BD0420F8BD38B5024669481823B1
+:20EB400001785943081803690179022B0AD014246343644CF434E4588368009383691030F7
+:20EB6000A04738BD604B14331C68F5E7F8B55D4B9978012914D100255B499D700A69082A77
+:20EB800005D002280FD003280AD10D2006E0022807D00D7000F025FA002801D0FFF7CCFF37
+:20EBA000F8BD0D61F6E74F48182403784E496343CC681818641C001DCC600378022B05D11F
+:20EBC0004668A102B14201D3012700E00027052B01D1072A03D00021042B02D003E00121C1
+:20EBE000FAE7072A03D00026042B02D007E00126FAE74068A302834201D3002A1AD0002000
+:20EC0000314301433943C5D0374E28463561FFF793FF344C2078FFF765FEF5606078401E1E
+:20EC200060702078401CC0B220700A28B2D30A382070AFE70120E3E770B500252A4C2948D3
+:20EC4000E56025610570457085702E463046FFF749FE761C0A2EF9D3012212076560516952
+:20EC600028461269491E92B25143E560A1601D49F4310D608D600D61CD601B4914310D6090
+:20EC8000888001212170206170BDF8B5164A044610780E46002830D0002C30D0002E2ED058
+:20ECA000206800282BD0012000076768016989B28F4228D8102F26D3A168002923D09568E2
+:20ECC000794343694A19006980B243439A421AD801200007006980B2814212D901200007E1
+:20ECE000006903E0E82D0020A828002080B2394600F05FFC002906D103E00820F8BD0E20B9
+:20ED0000F8BDB80701D00720F8BDBD49486801281CD00F461421BB4A21C641438E18756092
+:20ED2000236853506168B160A168F160A268616800235143012212075B1C14699BB2A4B214
+:20ED40008C4205D21469A4B2091B02E00420F8BD00211469A4B265191469A4B28C42EBD985
+:20ED6000BD60401C336178600020F8BDF8B50446A3481E46007815460F46002807D0002F3D
+:20ED800007D0002C05D02068002817D103E00820F8BD0E20F8BD9B48016800290ED0C268E3
+:20EDA000816840684A4310186268904206D9002D04D0A94202D3A819884201D90720F8BD90
+:20EDC000384600F008F9002811D0304600F003F900280CD0606800F0FEF8002807D02B4637
+:20EDE0003A46214602200096FFF780FEF8BD1020F8BDFFB5824881B000781F4616460D462B
+:20EE0000002808D0002D08D00198002805D02868002817D103E00820B0E50E20AEE5794C91
+:20EE2000206800280ED0E168A0686268414389186A68914206D9002E04D0B04202D3F119AD
+:20EE4000814201D9072099E5019800F0C4F800281BD0384600F0BFF8002816D0686800F025
+:20EE6000BAF8002811D068683246C119019800F02EFB00962868142148432458002203215B
+:20EE80002846019BA047002078E5102076E5F8B505465B480F460078002805D0002D05D012
+:20EEA0002868002821D103E00820F8BD0E20F8BD544C00262068002817D0A168E0684843CC
+:20EEC00061684118686881420FD900F084F800280DD0296814225143091968684A68896834
+:20EEE000801A00F066FB002903D00720F8BD1020F8BD3B460022294604200096FFF7F6FDB5
+:20EF0000F8BD3F4A1278002A0DD000280DD000290BD00268002A08D0394A14321368002B3E
+:20EF200005D004207047082070470E20704702230B600068106000207047F8B504463048AF
+:20EF40001E46007817460D46002807D0002D07D0002C05D0206802281BD103E00820F8BDC3
+:20EF60000E20F8BD264814300068002811D0084600F031F800280ED0304600F02CF800286C
+:20EF800009D03B462A46214602200096FFF7AEFDF8BD0720F8BD1020F8BD08B5184A1278C8
+:20EFA000002A05D0002805D00268022A11D103E0082008BD0E2008BD114A14321268002AD5
+:20EFC00007D00B460022014604200092FFF78EFD08BD072008BD800701D000207047012068
+:20EFE0007047084910B5F43949780020002906D0FFF70BFD002802D0112800D1002010BD48
+:20F00000A8280020DC2E002070B500250C290ED304464318008941000919581A0A38C2B2BD
+:20F020001748022A027002D30A318B4201D2092070BD144800F04BFA134914480A8882422E
+:20F0400002D02388934217D14988814202D06088884211D10D4A0323521E20891B03A842DE
+:20F060000AD9690009194989914203D09E896D1CB142F4D1002070BD0B2070BD00207047C6
+:20F08000C4280020F02E002080100010FFFF000010B5FDF7ABF810BD10B50446002A02D054
+:20F0A0001088002210E00A48FBE7030A00020343A05C584003061B0F43401803584083B2EB
+:20F0C0001806C00C5840521C8A42EED310BD0000FFFF00004B48002101704C484A4A026039
+:20F0E0008160C160016108224161426081610846704710B500291DD000220A60434A5368A8
+:20F10000002B1BD0202817D85B1E5360D0682423401CD060106914684343E3180B60012366
+:20F1200083409169401C19434007400F91611061002010BD0E2010BD0C2010BD042010BD8F
+:20F14000F0B5324A0646916800292BD057691020791A4907490F14680B4624254D436519D6
+:20F16000B54206D1012495698C4065400020956104E0491C4907490F8F42EED1491C4E07DC
+:20F18000760F956901210C469C402B4623420AD19368002B07D05B1E936053685B1C53609D
+:20F1A0003346F0E70420F0BD184A2423117C1268491E4907490F594320315050002070470B
+:20F1C00070B500281AD0002918D0104AD368002B16D05B1ED360936824265B1C936053692A
+:20F1E00015681C467343EE1820330660E858641C08606007400F5061002070BD0E2070BD84
+:20F20000042070BDC5280020FC2E00201C30002030B5CB0008339DB293070024002B01D0E6
+:20F22000072030BD3B4B9A605219DA605C701C7058809980002030BDF7B5364C0E466088D5
+:20F24000814237D8344F00F069F822786078A188884201DA401C00E00020C0B2904202D155
+:20F2600000F062F824E065786078884201DA401C00E00020607000F057F8BD4218D0A0688C
+:20F28000EF000299C151009900290CD0002E0AD0608832464543E068281800F018F9A068B3
+:20F2A0003818868002E00021381881800020FEBD0420FEBD0920FEBD0EB504E068468188A8
+:20F2C000029A0098904702AA01A9684600F003F80028F3D00EBD70B50E4B05241D785E786C
+:20F2E000AE4215D01D781C789E88B44201DA641C00E000241C705C88DE686C43A41904600F
+:20F300009B68E800C418A4880C80185800241060204670BDCC280020FFFF000072B606484F
+:20F320000168491C0160704703490868401E086000D162B670470000DC280020BFF34F8F11
+:20F3400003490248C860BFF34F8FFEE70400FA0500ED00E010B5002904D000221146104619
+:20F36000FFF7ECFF00F010F810BD10B50021024A0846FFF761FF10BD55F3030010B50846E6
+:20F380001146FCF771FF10BDF8B5384C2078002837D02069002807D00026E068002805D0FB
+:20F3A0000025002E04D013E00126F6E70125F8E7684651DF052806D0002806D000221146D2
+:20F3C000FFF7BCFF04E0012602E0216900988847002D12D1608869460880A06861DF0528FA
+:20F3E00006D0002806D000221146FFF7A7FF04E0012502E0E168A0688847002ED8D0002D15
+:20F40000CFD0F8BD70B5002901D08C0701D0072070BD164C0125A16062801549636010DF46
+:20F420000028F5D1257016202EDF70BD002803D00E49C860002070470E207047002803D0A8
+:20F440000A490861002070470E20704710B507484068002807D08047002803D0002211463E
+:20F46000FFF76CFF10BDFFF78FFF10BDE02800207DF30300034610B50B439B070FD1042A66
+:20F480000DD308C810C9121FA342F8D018BA21BA884201D9012010BD0020C04310BD002AAC
+:20F4A00003D0D30703D0521C07E0002010BD03780C78401C491C1B1B07D103780C78401C61
+:20F4C000491C1B1B01D1921EF1D1184610BDF8B5042A2CD3830712D00B78491C0370401C25
+:20F4E000521E83070BD00B78491C0370401C521E830704D00B78491C0370401C521E8B07F9
+:20F500009B0F05D0C91ADF002023DE1B08C90AE0FCF78EFEF8BD1D4608C9FD401C46B440B8
+:20F520002C4310C0121F042AF5D2F308C91A521EF0D40B78491C0370401C521EEAD40B78EC
+:20F54000491C0370401C521EE4D409780170F8BD01E004C0091F0429FBD28B0701D50280F7
+:20F56000801CC90700D00270704700290BD0C30702D00270401C491E022904D3830702D5EE
+:20F580000280801C891EE3E70022EEE70022DFE70378C2781946437812061B0219438378A2
+:20F5A000C0781B04194311430902090A000608437047002203098B422CD3030A8B4211D366
+:20F5C00000239C464EE003460B433CD4002243088B4231D303098B421CD3030A8B4201D39D
+:20F5E00094463FE0C3098B4201D3CB01C01A524183098B4201D38B01C01A524143098B422D
+:20F6000001D34B01C01A524103098B4201D30B01C01A5241C3088B4201D3CB00C01A524193
+:20F6200083088B4201D38B00C01A524143088B4201D34B00C01A5241411A00D201465241FB
+:20F64000104670475DE0CA0F00D04942031000D34042534000229C4603098B422DD3030A47
+:20F660008B4212D3FC22890112BA030A8B420CD3890192118B4208D3890192118B4204D305
+:20F6800089013AD0921100E08909C3098B4201D3CB01C01A524183098B4201D38B01C01A88
+:20F6A000524143098B4201D34B01C01A524103098B4201D30B01C01A5241C3088B4201D37F
+:20F6C000CB00C01A524183088B4201D38B00C01A5241D9D243088B4201D34B00C01A52417F
+:20F6E000411A00D20146634652415B10104601D34042002B00D54942704763465B1000D31A
+:20F70000404201B50020C046C04602BD704770477047754600F022F8AE460500694653469B
+:20F72000C008C000854618B020B5FEF7FBFA60BC00274908B6460026C0C5C0C5C0C5C0C525
+:20F74000C0C5C0C5C0C5C0C5403D49008D4670470446C046C0462046FCF7FFFC004870479C
+:20F760003830002001491820ABBEFEE726000200704730B47446641E2578641CAB4200D256
+:20F780001D46635D5B00E31830BC184702000000000000000000000000000000040000009F
+:20F7A000000000000000000000000000000000000000000035C4030000000000000000004D
+:20F7C000020000000000000000000000000000000000000000000000030000000000000024
+:20F7E0000000000005000000000000000000000000000000000000000000000023D1BCEA6A
+:20F800005F782315DEEF1212000000002CF8030000280020F400000004C1030020F90300A1
+:20F82000F4280020A413000020C103000000000000000000000000000000000000000000F1
+:20F840000000000000000000000000000000000000000000000000000000000000000000A8
+:20F8600000000000000000000000FFFF000000003200000000000000000000000000000058
+:20F88000000000000000000000000000000000000000000000000000000000000000000068
+:20F8A000000000000000000000000000000000000024F40000000000000000000000000030
+:20F8C000000000000000000000000000000000000000000000000000000000000000000028
+:20F8E000000000000000000000000000000000000000000000000000000000000000000008
+:20F900000000000000000000000000000000000000000000000000000000000000000000E7
+:20FC00000100000000000000FE0000000000000000000000000000000000000000000000E5
+:020000041000EA
+:0410140000C0030015
+:040000050003C0C173
+:00000001FF
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/bootloader/softdevice_nrf51822_licence_agreement.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/bootloader/softdevice_nrf51822_licence_agreement.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,30 @@
+/*
+ * S110/S120/S130 License Agreement
+ *
+ * Copyright (c) 2015, Nordic Semiconductor ASA, All rights reserved.
+ *
+ * Redistribution. Redistribution and use in binary form, without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * • Redistributions must reproduce the above copyright notice and the following
+ *   disclaimer in the documentation and/or other materials provided with the
+ *   distribution.
+ * • Neither the name of the copyright holder nor the names of its contributors
+ *   may be used to endorse or promote products derived from this software
+ *   without specific prior written permission.
+ * • No reverse engineering, decompilation, or disassembly of this software is
+ *   permitted.
+ *
+ * DISCLAIMER.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * /
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/module.json
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/module.json	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,36 @@
+{
+  "name": "ble-nrf51822",
+  "version": "2.7.1",
+  "description": "Nordic stack and drivers for the mbed BLE API.",
+  "keywords": [
+    "Bluetooth",
+    "BLE",
+    "mbed",
+    "mbed-official"
+  ],
+  "author": "Rohit Grover",
+  "repository": {
+    "url": "git@github.com:ARMmbed/ble-nRF51822.git",
+    "type": "git"
+  },
+  "homepage": "https://developer.mbed.org/teams/Nordic-Semiconductor/",
+  "licenses": [
+    {
+      "url": "https://spdx.org/licenses/Apache-2.0",
+      "type": "Apache-2.0"
+    },
+    {
+      "type": "LicenseRef-softdevice_nrf51822_licence_agreement.txt"
+    }
+  ],
+  "dependencies": {
+    "ble": "^2.6.0",
+    "nrf51-sdk": "^2.4.0"
+  },
+  "extraIncludes": [
+    "source/btle",
+    "source/btle/custom",
+    "source/common"
+  ],
+  "targetDependencies": {}
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/BSD-3clause-Nordic.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/BSD-3clause-Nordic.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/CHANGELOG.md
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/CHANGELOG.md	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,78 @@
+# Change Log
+
+## [v2.2.1](https://github.com/ARMmbed/nrf51-sdk/tree/v2.2.1) (2016-01-27)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v2.2.0...v2.2.1)
+
+**Closed issues:**
+
+- It's not possible to generate a debug build with nrf51-sdk 1.0.1 [\#11](https://github.com/ARMmbed/nrf51-sdk/issues/11)
+
+**Merged pull requests:**
+
+- Optimise to omit frame pointer even in a debug build [\#19](https://github.com/ARMmbed/nrf51-sdk/pull/19) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.2.0](https://github.com/ARMmbed/nrf51-sdk/tree/v2.2.0) (2016-01-11)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v2.1.0...v2.2.0)
+
+**Closed issues:**
+
+- Update bootloader branch to sdk V10 [\#14](https://github.com/ARMmbed/nrf51-sdk/issues/14)
+
+**Merged pull requests:**
+
+- Add missing implementations for peer\_manager.  [\#18](https://github.com/ARMmbed/nrf51-sdk/pull/18) ([pan-](https://github.com/pan-))
+- Expose function in DM to calculate BLE hash [\#17](https://github.com/ARMmbed/nrf51-sdk/pull/17) ([andresag01](https://github.com/andresag01))
+
+## [v2.1.0](https://github.com/ARMmbed/nrf51-sdk/tree/v2.1.0) (2016-01-08)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v2.0.0...v2.1.0)
+
+**Merged pull requests:**
+
+- Add files from peer manager from nRF51 SDK 10.0.0 [\#15](https://github.com/ARMmbed/nrf51-sdk/pull/15) ([andresag01](https://github.com/andresag01))
+
+## [v2.0.0](https://github.com/ARMmbed/nrf51-sdk/tree/v2.0.0) (2016-01-07)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v1.0.1...v2.0.0)
+
+**Closed issues:**
+
+- nrf51-sdk generates warnings for old style declarations [\#10](https://github.com/ARMmbed/nrf51-sdk/issues/10)
+
+**Merged pull requests:**
+
+- Nordic sdk 10.0.0 [\#13](https://github.com/ARMmbed/nrf51-sdk/pull/13) ([LiyouZhou](https://github.com/LiyouZhou))
+- Add ifdef to include correct mbed.h file in mbedOS [\#9](https://github.com/ARMmbed/nrf51-sdk/pull/9) ([andresag01](https://github.com/andresag01))
+- Update files to Nordic sdk 9.0.0 [\#8](https://github.com/ARMmbed/nrf51-sdk/pull/8) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v1.0.1](https://github.com/ARMmbed/nrf51-sdk/tree/v1.0.1) (2015-12-10)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v1.0.0...v1.0.1)
+
+**Closed issues:**
+
+- Need the ability to do version bump [\#1](https://github.com/ARMmbed/nrf51-sdk/issues/1)
+
+**Merged pull requests:**
+
+- Add GCC diagnostics to suppress unused-parameter warnings [\#7](https://github.com/ARMmbed/nrf51-sdk/pull/7) ([andresag01](https://github.com/andresag01))
+
+## [v1.0.0](https://github.com/ARMmbed/nrf51-sdk/tree/v1.0.0) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v0.0.1...v1.0.0)
+
+**Closed issues:**
+
+- Need to keep previous improvements while moving to nrf51-sdk [\#2](https://github.com/ARMmbed/nrf51-sdk/issues/2)
+
+**Merged pull requests:**
+
+- supress warnings for the sources in nRF51 SDK [\#6](https://github.com/ARMmbed/nrf51-sdk/pull/6) ([rgrover](https://github.com/rgrover))
+
+## [v0.0.1](https://github.com/ARMmbed/nrf51-sdk/tree/v0.0.1) (2015-12-01)
+[Full Changelog](https://github.com/ARMmbed/nrf51-sdk/compare/v8.1.0...v0.0.1)
+
+**Merged pull requests:**
+
+- Migrate changes from ble nrf51822 [\#4](https://github.com/ARMmbed/nrf51-sdk/pull/4) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v8.1.0](https://github.com/ARMmbed/nrf51-sdk/tree/v8.1.0) (2015-11-17)
+
+
+\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/LICENSE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/LICENSE	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,6 @@
+Many of the files in this module have been inherited from the Nordic SDK for
+nRF51822; they come with a BSD-like license offered by Nordic for use in mbed.
+Some other files come from the mbed SDK, and are licensed under Apache-2.0.
+Unless specifically indicated otherwise in a file, files are licensed
+under the Apache 2.0 license, as can be found in: apache-2.0.txt.
+The BSD-like Nordic license can be found in BSD-3clause-Nordic.txt
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/README.md
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/README.md	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,32 @@
+# nrf51-sdk
+Module to contain files provided by the nordic nRF51 SDK. The latest version of this module uses files from Nordic SDK 10.0.0. The files are extracted from [here](https://developer.nordicsemi.com/nRF5_SDK/nRF51_SDK_v10.x.x/nRF51_SDK_10.0.0_dc26b5e.zip).
+
+## Changes made to Nordic files
+The files are kept the same as much as possible to the Nordic SDK. Modifications are made in order to integrate with mbed.
+    - ble/common/ble_conn_state.c: Preprocessor tests regarding S110, S120 or S130 macro should be replace by TARGET_MCU_NRF51_XXK_SXXX tests
+    - `ble.h` in `source/nordic_sdk/components/softdevice/s130/headers/ble.h` has to be renamed `nrf_ble.h`. All files which include this file should be updated accordingly.
+
+
+## Porting new versions of Nordic SDK
+A list of files currently requierd by mbed is maintained in [script/required_files.txt](https://github.com/ARMmbed/nrf51-sdk/blob/master/script/required_files.txt). [A python script](https://github.com/ARMmbed/nrf51-sdk/blob/master/script/pick_nrf51_files.py) is written to help porting from nordic sdk releases. **required_files.txt** is parsed to find a list of filenames. The script searches for these filenames in the sdk folder, and copy then into the yotta module mirroring the folder structure in the sdk. **extraIncludes** is automatically added to module.json to allow direct inclusion of noridc headers with just the filename.
+
+### Script usage
+```
+python pick_nrf51_files.py [options] <full-noridc-sdk-path> <nrf51-sdk-yotta-module-path>
+options: --purge   : to delete all existing files and start again
+         --dry-run : to list the files to be copied but not actually copy them
+```
+
+There are files in the sdk with the same filename but in different folder. This is dealt with by excluding certain directories. The excluded directories are listed in [pick_nrf51_files.py](https://github.com/ARMmbed/nrf51-sdk/blob/master/script/pick_nrf51_files.py).
+
+After running the script, the changes in [the previous section](#changes-made-to-nordic-files) will have to be applied manually again.
+
+Folder structure or even file name can change between releases of the nordic sdk, hence a degree of manual adjustment is needed when porting.
+
+## Using Noridc Headers
+The nordic sdk is written in C and yotta modules support C++. If you are trying to include Nordic files in a cpp program, you need to use the `extern "C"` keyword around the includes.
+```c
+extern "C" {
+#include "softdevice_handler.h"
+}
+```
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/apache-2.0.txt
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/module.json
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/module.json	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,51 @@
+{
+  "name": "nrf51-sdk",
+  "version": "2.4.0",
+  "description": "Module to contain files provided by the nordic nRF51 SDK",
+  "keywords": [
+    "nordic",
+    "nrf51",
+    "sdk"
+  ],
+  "author": "",
+  "repository": {
+    "url": "git@github.com:ARMmbed/nrf51-sdk.git",
+    "type": "git"
+  },
+  "license": "nordic",
+  "targetDependencies": {
+    "mbed-classic": {
+      "mbed-classic": "~0.0.1"
+    },
+    "mbed-os": {
+      "mbed-drivers": "*"
+    }
+  },
+  "extraIncludes": [
+    "source/nordic_sdk/components/ble/ble_radio_notification",
+    "source/nordic_sdk/components/ble/ble_services/ble_dfu",
+    "source/nordic_sdk/components/ble/common",
+    "source/nordic_sdk/components/ble/device_manager",
+    "source/nordic_sdk/components/ble/device_manager/config",
+    "source/nordic_sdk/components/ble/peer_manager",
+    "source/nordic_sdk/components/device",
+    "source/nordic_sdk/components/drivers_nrf/ble_flash",
+    "source/nordic_sdk/components/drivers_nrf/delay",
+    "source/nordic_sdk/components/drivers_nrf/hal",
+    "source/nordic_sdk/components/drivers_nrf/pstorage",
+    "source/nordic_sdk/components/drivers_nrf/pstorage/config",
+    "source/nordic_sdk/components/libraries/bootloader_dfu",
+    "source/nordic_sdk/components/libraries/bootloader_dfu/hci_transport",
+    "source/nordic_sdk/components/libraries/crc16",
+    "source/nordic_sdk/components/libraries/hci",
+    "source/nordic_sdk/components/libraries/scheduler",
+    "source/nordic_sdk/components/libraries/timer",
+    "source/nordic_sdk/components/libraries/util",
+    "source/nordic_sdk/components/libraries/fds",
+    "source/nordic_sdk/components/libraries/fstorage",
+    "source/nordic_sdk/components/libraries/experimental_section_vars",
+    "source/nordic_sdk/components/softdevice/common/softdevice_handler",
+    "source/nordic_sdk/components/softdevice/s130/headers",
+    "source/nordic_sdk/components/toolchain"
+  ]
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/script/copyright_header.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/script/copyright_header.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/script/pick_nrf51_files.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/script/pick_nrf51_files.py	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,141 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2015-2016 ARM Limited
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os, shutil, json, pprint, sys
+from collections import OrderedDict
+
+help_text = """
+Usage: python {} [options] <full-noridc-sdk-path> <nrf51-sdk-yotta-module-path>
+options: --purge   : to delete all existing files and start again
+         --dry-run : to list the files to be copied but not actually copy them
+""".format(os.path.basename(__file__))
+
+# exclude path to avoid confusion over files of the same name
+exclude_path = ["examples", "SVD", "s110", "s120", "s210", "s310", "nrf_soc_nosd", "serialization/connectivity",
+                'components/libraries/hci/config', 'components/libraries/bootloader_dfu/ble_transport']
+
+def find(name, path):
+    paths = []
+    for root, dirs, files in os.walk(path):
+        if True not in [x in root for x in exclude_path]:
+            if name in files:
+                paths.append(os.path.join(root, name))
+
+    if len(paths) == 0:
+        print "-"*30
+        print "Warning! No {} found!!!!".format(name)
+        print "-"*30
+        return None
+    elif len(paths) > 1:
+        print "-"*30
+        print "Warning! More than one {} found!!!!".format(name)
+        print paths
+        print "-"*30
+        return None
+    else:
+        return paths[0]
+
+def find_dir(dir_name, path):
+    paths = []
+    for root, dirs, files in os.walk(path):
+        if dir_name in root:
+            for fn in files:
+                paths.append(os.path.join(root, fn))
+    return paths
+
+if __name__ == "__main__":
+    # define source and destination of copy
+    arg_valid = True
+    if len(sys.argv) not in [3, 4]:
+        arg_valid = False
+    else:
+        src_folder = sys.argv[-2]
+        yt_module_dir = sys.argv[-1]
+
+        for d in [src_folder, yt_module_dir]:
+            if not os.path.isdir(d):
+                arg_valid = False
+                print src_folder, "is not a folder"
+
+    purge = ("--purge" in sys.argv)
+    dry_run = ("--dry-run" in sys.argv)
+
+    if not arg_valid:
+        print help_text
+        sys.exit(1)
+
+    dst_folder = os.path.join(yt_module_dir, "source/nordic_sdk")
+
+    # build a file_list from required_files.txt
+    file_list = []
+    with open("required_files.txt", "r") as fd:
+        for line in fd:
+            line = line.strip()
+            if line.startswith("D "):
+                directory = line.split(" ")[-1]
+                file_list += find_dir(directory, src_folder)
+            elif not line.startswith("#") and line != '':
+                fn = os.path.basename(line).strip()
+                fn = find(fn, src_folder)
+                file_list.append(fn)
+
+    # remove everything from the destination folder
+    if purge and not dry_run and os.path.exists(dst_folder):
+        shutil.rmtree(dst_folder)
+
+    # copy files
+    extra_includes = []
+    for src in file_list:
+        if src:
+            rel_dst = os.path.relpath(src, src_folder)
+            dst = os.path.join(dst_folder, rel_dst)
+            print src, "->", dst
+
+            directory = os.path.dirname(dst)
+            if not os.path.exists(directory):
+                print "Creating directory:", directory
+                if not dry_run:
+                    os.makedirs(directory)
+            if not os.path.isfile(dst):
+                print "Copying file", dst
+                if not dry_run:
+                    shutil.copyfile(src, dst)
+
+            # build a list of extra includes to be added to module.json
+            if dst.endswith(".h"):
+                inc_rel_path = os.path.relpath(dst, yt_module_dir)
+                inc_dir_path = os.path.dirname(inc_rel_path)
+                if inc_dir_path not in extra_includes:
+                    extra_includes.append(inc_dir_path)
+
+    # write extraIncludes in the module.json file
+    mod_json = os.path.join(yt_module_dir, "module.json")
+    print "-"*30
+    print "Writing extra_includes to {}".format(mod_json)
+    print "-"*30
+    for n in sorted(extra_includes):
+        print n
+
+    if not dry_run:
+        with open(mod_json, 'r+') as fd:
+            jobj = json.loads(fd.read(), object_pairs_hook=OrderedDict)
+            jobj['extraIncludes'] = sorted(extra_includes)
+            jdump = json.dumps(jobj, indent=2, separators=(',', ': '))
+            fd.seek(0)
+            fd.write(jdump)
+            fd.write("\n")
+            fd.truncate()
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/script/replace_headers.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/script/replace_headers.py	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,38 @@
+# Copyright (c) 2015-2016 ARM Limited
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+with open("copyright_header.txt", "r") as fd:
+	header = fd.read()
+
+path = "../source/nordic_sdk"
+for root, dirs, files in os.walk(path):
+	for fn in [os.path.join(root, x) for x in files]:
+		with open(fn, "r+") as fd:
+			print "+"*35
+			print fn
+			s = fd.read()
+			start = s.find("/*")
+			end = s.find("*/")
+			copyright_str = s[start:end+2]
+			if "copyright (c)" not in copyright_str.lower():
+				s = header + "\n\n" + s
+			elif copyright_str is not header:
+				s = s.replace(copyright_str, header)
+
+			fd.seek(0)
+			fd.write(s)
+			fd.truncate()
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/script/required_files.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/script/required_files.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,136 @@
+# from cmsis-core-nrf51822:
+	cmsis-core-nrf51822/compiler_abstraction.h
+	cmsis-core-nrf51822/nrf.h
+	cmsis-core-nrf51822/nrf51.h
+	cmsis-core-nrf51822/nrf51_bitfields.h
+	cmsis-core-nrf51822/nrf_delay.h
+	cmsis-core-nrf51822/system_nrf51.h
+	source/system_nrf51.c
+
+# from ble-nrf51822
+	source/nordic-sdk/components/ble/ble_radio_notification/ble_radio_notification.c
+	source/nordic-sdk/components/ble/ble_radio_notification/ble_radio_notification.h
+	source/nordic-sdk/components/ble/ble_services/ble_dfu/ble_dfu.c
+	source/nordic-sdk/components/ble/ble_services/ble_dfu/ble_dfu.h
+	source/nordic-sdk/components/ble/common/ble_advdata.c
+	source/nordic-sdk/components/ble/common/ble_advdata.h
+	source/nordic-sdk/components/ble/common/ble_advdata_parser.c
+	source/nordic-sdk/components/ble/common/ble_advdata_parser.h
+	source/nordic-sdk/components/ble/peer_manager/id_manager.h
+	source/nordic-sdk/components/ble/peer_manager/id_manager.c
+	source/nordic-sdk/components/ble/peer_manager/peer_manager_types.h
+	source/nordic-sdk/components/ble/peer_manager/ble_gatt_db.h
+	source/nordic-sdk/components/ble/peer_manager/ble_conn_state.h
+	source/nordic-sdk/components/ble/peer_manager/sdk_mapped_flags.h
+	source/nordic-sdk/components/ble/peer_manager/peer_database.h
+# source/nordic-sdk/components/ble/common/ble_conn_params.cpp the file is called
+	source/nordic-sdk/components/ble/common/ble_conn_params.c
+	source/nordic-sdk/components/ble/common/ble_conn_params.h
+	source/nordic-sdk/components/ble/common/ble_date_time.h
+	source/nordic-sdk/components/ble/common/ble_sensor_location.h
+	source/nordic-sdk/components/ble/common/ble_srv_common.c
+	source/nordic-sdk/components/ble/common/ble_srv_common.h
+	source/nordic-sdk/components/ble/device_manager/config/device_manager_cnfg.h
+	source/nordic-sdk/components/ble/device_manager/device_manager.h
+	source/nordic-sdk/components/ble/device_manager/device_manager_peripheral.c
+	source/nordic-sdk/components/drivers_nrf/ble_flash/ble_flash.c
+	source/nordic-sdk/components/drivers_nrf/ble_flash/ble_flash.h
+	source/nordic-sdk/components/drivers_nrf/hal/compiler_abstraction.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf51.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf51_bitfields.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf51_deprecated.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_delay.c
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_ecb.c
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_ecb.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_gpio.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_gpiote.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_nvmc.c
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_nvmc.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_temp.h
+	source/nordic-sdk/components/drivers_nrf/pstorage/config/pstorage_platform.h
+	source/nordic-sdk/components/drivers_nrf/pstorage/pstorage.c
+	source/nordic-sdk/components/drivers_nrf/pstorage/pstorage.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/bootloader.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/bootloader_types.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/bootloader_util.h
+# source/nordic-sdk/components/libraries/bootloader_dfu/bootloader_util_arm.c new file is called:
+	source/nordic-sdk/components/libraries/bootloader_dfu/bootloader_util.c
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_bank_internal.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_ble_svc.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_ble_svc_internal.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_init.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_init_template.c
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_transport.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/dfu_types.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/experimental/dfu_app_handler.c
+	source/nordic-sdk/components/libraries/bootloader_dfu/experimental/dfu_app_handler.h
+	source/nordic-sdk/components/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h
+	source/nordic-sdk/components/libraries/crc16/crc16.c
+	source/nordic-sdk/components/libraries/hci/hci_mem_pool.c
+	source/nordic-sdk/components/libraries/hci/hci_mem_pool.h
+	source/nordic-sdk/components/libraries/scheduler/app_scheduler.c
+	source/nordic-sdk/components/libraries/util/app_error.c
+	source/nordic-sdk/components/libraries/util/app_util_platform.c
+	source/nordic-sdk/components/libraries/util/app_util_platform.h
+	source/nordic-sdk/components/libraries/util/common.h
+	source/nordic-sdk/components/libraries/util/nordic_common.h
+	source/nordic-sdk/components/libraries/util/nrf_assert.c
+	source/nordic-sdk/components/libraries/util/nrf_assert.h
+	source/nordic-sdk/components/libraries/util/sdk_common.h
+	source/nordic-sdk/components/libraries/util/sdk_errors.h
+	source/nordic-sdk/components/libraries/util/sdk_os.h
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/ant_stack_handler_types.h
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/ble_stack_handler_types.h
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/softdevice_handler.c
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/softdevice_handler.h
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/softdevice_handler_appsh.c
+	source/nordic-sdk/components/softdevice/common/softdevice_handler/softdevice_handler_appsh.h
+# source/nordic-sdk/components/softdevice/s130/doc/ble_api.dox uncertain of the origin of this file
+	source/nordic-sdk/components/softdevice/s130/include/ble.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_err.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_gap.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_gatt.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_gattc.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_gatts.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_hci.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_l2cap.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_ranges.h
+	source/nordic-sdk/components/softdevice/s130/include/ble_types.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_error.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_error_sdm.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_error_soc.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_mbr.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_sdm.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_soc.h
+	source/nordic-sdk/components/softdevice/s130/include/nrf_svc.h
+	source/nordic-sdk/components/softdevice/s130/include/softdevice_assert.h
+	source/nordic-sdk/components/drivers_nrf/hal/nrf_wdt.h
+	source/nordic-sdk/components/ble/common/ble_conn_state.c
+	source/nordic-sdk/components/ble/peer_manager/peer_data.c
+	source/nordic-sdk/components/ble/peer_manager/peer_data.h
+	source/nordic-sdk/components/ble/peer_manager/peer_data_storage.c
+	source/nordic-sdk/components/ble/peer_manager/peer_data_storage.h
+	source/nordic-sdk/components/ble/peer_manager/peer_database.c
+	source/nordic-sdk/components/ble/peer_manager/peer_id.c
+	source/nordic-sdk/components/ble/peer_manager/peer_id.h
+	source/nordic-sdk/components/ble/peer_manager/pm_buffer.c
+	source/nordic-sdk/components/ble/peer_manager/pm_buffer.h
+	source/nordic-sdk/components/ble/peer_manager/pm_mutex.c
+	source/nordic-sdk/components/ble/peer_manager/pm_mutex.h
+	source/nordic-sdk/components/libraries/experimental_section_vars/
+	source/nordic-sdk/components/libraries/fds/
+	source/nordic-sdk/components/libraries/fstorage/
+	source/nordic-sdk/components/libraries/util/sdk_mapped_flags.c
+
+
+# from mbed-hal-nrf51822-mcu
+	mbed-hal-nrf51822-mcu/lib/nordic_sdk/components/libraries/crc16/crc16.h
+	mbed-hal-nrf51822-mcu/lib/nordic_sdk/components/libraries/scheduler/app_scheduler.h
+	mbed-hal-nrf51822-mcu/lib/nordic_sdk/components/libraries/util/app_error.h
+	mbed-hal-nrf51822-mcu/lib/nordic_sdk/components/libraries/util/app_util.h
+
+# included from ble_conn_params.c
+	app_timer.h
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_radio_notification.h"
+#include <stdlib.h>
+
+
+static bool                                 m_radio_active = false;  /**< Current radio state. */
+static ble_radio_notification_evt_handler_t m_evt_handler  = NULL;   /**< Application event handler for handling Radio Notification events. */
+
+
+void SWI1_IRQHandler(void)
+{
+    m_radio_active = !m_radio_active;
+    if (m_evt_handler != NULL)
+    {
+        m_evt_handler(m_radio_active);
+    }
+}
+
+
+uint32_t ble_radio_notification_init(nrf_app_irq_priority_t               irq_priority,
+                                     nrf_radio_notification_distance_t    distance,
+                                     ble_radio_notification_evt_handler_t evt_handler)
+{
+    uint32_t err_code;
+
+    m_evt_handler = evt_handler;
+
+    // Initialize Radio Notification software interrupt
+    err_code = sd_nvic_ClearPendingIRQ(SWI1_IRQn);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    err_code = sd_nvic_SetPriority(SWI1_IRQn, irq_priority);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    err_code = sd_nvic_EnableIRQ(SWI1_IRQn);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    // Configure the event
+    return sd_radio_notification_cfg_set(NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, distance);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/ble_radio_notification/ble_radio_notification.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup ble_radio_notification Radio Notification Event Handler
+ * @{
+ * @ingroup ble_sdk_lib
+ * @brief Module for propagating Radio Notification events to the application.
+ */
+
+#ifndef BLE_RADIO_NOTIFICATION_H__
+#define BLE_RADIO_NOTIFICATION_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "nrf_soc.h"
+
+/**@brief Application radio notification event handler type. */
+typedef void (*ble_radio_notification_evt_handler_t) (bool radio_active);
+
+/**@brief Function for initializing the Radio Notification module.
+ *
+ * @param[in]  irq_priority   Interrupt priority for the Radio Notification interrupt handler.
+ * @param[in]  distance       The time from an Active event until the radio is activated.
+ * @param[in]  evt_handler    Handler to be executed when a radio notification event has been
+ *                            received.
+ *
+ * @return     NRF_SUCCESS on successful initialization, otherwise an error code.
+ */
+uint32_t ble_radio_notification_init(nrf_app_irq_priority_t               irq_priority,
+                                     nrf_radio_notification_distance_t    distance,
+                                     ble_radio_notification_evt_handler_t evt_handler);
+
+#endif // BLE_RADIO_NOTIFICATION_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,686 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_dfu.h"
+#include "nrf_error.h"
+#include "ble_types.h"
+#include "ble_gatts.h"
+#include "app_util.h"
+#include "ble_srv_common.h"
+#include "nordic_common.h"
+#include <stdint.h>
+#include <string.h>
+#include <stddef.h>
+
+#define MAX_DFU_PKT_LEN         20                                              /**< Maximum length (in bytes) of the DFU Packet characteristic. */
+#define PKT_START_DFU_PARAM_LEN 2                                               /**< Length (in bytes) of the parameters for Packet Start DFU Request. */
+#define PKT_INIT_DFU_PARAM_LEN  2                                               /**< Length (in bytes) of the parameters for Packet Init DFU Request. */
+#define PKT_RCPT_NOTIF_REQ_LEN  3                                               /**< Length (in bytes) of the Packet Receipt Notification Request. */
+#define MAX_PKTS_RCPT_NOTIF_LEN 6                                               /**< Maximum length (in bytes) of the Packets Receipt Notification. */
+#define MAX_RESPONSE_LEN        7                                               /**< Maximum length (in bytes) of the response to a Control Point command. */
+#define MAX_NOTIF_BUFFER_LEN    MAX(MAX_PKTS_RCPT_NOTIF_LEN, MAX_RESPONSE_LEN)  /**< Maximum length (in bytes) of the buffer needed by DFU Service while sending notifications to peer. */
+
+enum
+{
+    OP_CODE_START_DFU          = 1,                                             /**< Value of the Op code field for 'Start DFU' command.*/
+    OP_CODE_RECEIVE_INIT       = 2,                                             /**< Value of the Op code field for 'Initialize DFU parameters' command.*/
+    OP_CODE_RECEIVE_FW         = 3,                                             /**< Value of the Op code field for 'Receive firmware image' command.*/
+    OP_CODE_VALIDATE           = 4,                                             /**< Value of the Op code field for 'Validate firmware' command.*/
+    OP_CODE_ACTIVATE_N_RESET   = 5,                                             /**< Value of the Op code field for 'Activate & Reset' command.*/
+    OP_CODE_SYS_RESET          = 6,                                             /**< Value of the Op code field for 'Reset System' command.*/
+    OP_CODE_IMAGE_SIZE_REQ     = 7,                                             /**< Value of the Op code field for 'Report received image size' command.*/
+    OP_CODE_PKT_RCPT_NOTIF_REQ = 8,                                             /**< Value of the Op code field for 'Request packet receipt notification.*/
+    OP_CODE_RESPONSE           = 16,                                            /**< Value of the Op code field for 'Response.*/
+    OP_CODE_PKT_RCPT_NOTIF     = 17                                             /**< Value of the Op code field for 'Packets Receipt Notification'.*/
+};
+
+static bool     m_is_dfu_service_initialized = false;                           /**< Variable to check if the DFU service was initialized by the application.*/
+static uint8_t  m_notif_buffer[MAX_NOTIF_BUFFER_LEN];                           /**< Buffer used for sending notifications to peer. */
+
+/**@brief       Function for adding DFU Packet characteristic to the BLE Stack.
+ *
+ * @param[in]   p_dfu DFU Service structure.
+ *
+ * @return      NRF_SUCCESS on success. Otherwise an error code.
+ */
+static uint32_t dfu_pkt_char_add(ble_dfu_t * const p_dfu)
+{
+    ble_gatts_char_md_t char_md;
+    ble_gatts_attr_t    attr_char_value;
+    ble_uuid_t          char_uuid;
+    ble_gatts_attr_md_t attr_md;
+
+    memset(&char_md, 0, sizeof(char_md));
+
+    char_md.char_props.write_wo_resp = 1;
+    char_md.p_char_user_desc         = NULL;
+    char_md.p_char_pf                = NULL;
+    char_md.p_user_desc_md           = NULL;
+    char_md.p_cccd_md                = NULL;
+    char_md.p_sccd_md                = NULL;
+
+    char_uuid.type = p_dfu->uuid_type;
+    char_uuid.uuid = BLE_DFU_PKT_CHAR_UUID;
+
+    memset(&attr_md, 0, sizeof(attr_md));
+
+    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&attr_md.read_perm);
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
+
+    attr_md.vloc    = BLE_GATTS_VLOC_STACK;
+    attr_md.rd_auth = 0;
+    attr_md.wr_auth = 0;
+    attr_md.vlen    = 1;
+
+    memset(&attr_char_value, 0, sizeof(attr_char_value));
+
+    attr_char_value.p_uuid    = &char_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.init_len  = 0;
+    attr_char_value.init_offs = 0;
+    attr_char_value.max_len   = MAX_DFU_PKT_LEN;
+    attr_char_value.p_value   = NULL;
+
+    return sd_ble_gatts_characteristic_add(p_dfu->service_handle,
+                                           &char_md,
+                                           &attr_char_value,
+                                           &p_dfu->dfu_pkt_handles);
+}
+
+
+/**@brief       Function for adding DFU Revision characteristic to the BLE Stack.
+ *
+ * @param[in]   p_dfu DFU Service structure.
+ *
+ * @return      NRF_SUCCESS on success. Otherwise an error code.
+ */
+static uint32_t dfu_rev_char_add(ble_dfu_t * const p_dfu, ble_dfu_init_t const * const p_dfu_init)
+{
+    ble_gatts_char_md_t char_md;
+    ble_gatts_attr_t    attr_char_value;
+    ble_uuid_t          char_uuid;
+    ble_gatts_attr_md_t attr_md;
+
+    memset(&char_md, 0, sizeof(char_md));
+
+    char_md.char_props.read          = 1;
+    char_md.p_char_user_desc         = NULL;
+    char_md.p_char_pf                = NULL;
+    char_md.p_user_desc_md           = NULL;
+    char_md.p_cccd_md                = NULL;
+    char_md.p_sccd_md                = NULL;
+
+    char_uuid.type = p_dfu->uuid_type;
+    char_uuid.uuid = BLE_DFU_REV_CHAR_UUID;
+
+    memset(&attr_md, 0, sizeof(attr_md));
+
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
+    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&attr_md.write_perm);
+
+    attr_md.vloc    = BLE_GATTS_VLOC_STACK;
+    attr_md.rd_auth = 0;
+    attr_md.wr_auth = 0;
+    attr_md.vlen    = 1;
+
+    memset(&attr_char_value, 0, sizeof(attr_char_value));
+
+    attr_char_value.p_uuid    = &char_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.init_len  = sizeof(uint16_t);
+    attr_char_value.init_offs = 0;
+    attr_char_value.max_len   = sizeof(uint16_t);
+    attr_char_value.p_value   = (uint8_t *)&p_dfu_init->revision;
+
+    return sd_ble_gatts_characteristic_add(p_dfu->service_handle,
+                                           &char_md,
+                                           &attr_char_value,
+                                           &p_dfu->dfu_rev_handles);
+}
+
+
+/**@brief       Function for adding DFU Control Point characteristic to the BLE Stack.
+ *
+ * @param[in]   p_dfu DFU Service structure.
+ *
+ * @return      NRF_SUCCESS on success. Otherwise an error code.
+ */
+static uint32_t dfu_ctrl_pt_add(ble_dfu_t * const p_dfu)
+{
+    ble_gatts_char_md_t char_md;
+    ble_gatts_attr_t    attr_char_value;
+    ble_uuid_t          char_uuid;
+    ble_gatts_attr_md_t attr_md;
+
+    memset(&char_md, 0, sizeof(char_md));
+
+    char_md.char_props.write  = 1;
+    char_md.char_props.notify = 1;
+    char_md.p_char_user_desc  = NULL;
+    char_md.p_char_pf         = NULL;
+    char_md.p_user_desc_md    = NULL;
+    char_md.p_cccd_md         = NULL;
+    char_md.p_sccd_md         = NULL;
+
+    char_uuid.type = p_dfu->uuid_type;
+    char_uuid.uuid = BLE_DFU_CTRL_PT_UUID;
+
+    memset(&attr_md, 0, sizeof(attr_md));
+
+    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(&attr_md.read_perm);
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
+
+    attr_md.vloc    = BLE_GATTS_VLOC_STACK;
+    attr_md.rd_auth = 0;
+    attr_md.wr_auth = 1;
+    attr_md.vlen    = 1;
+
+    memset(&attr_char_value, 0, sizeof(attr_char_value));
+
+    attr_char_value.p_uuid    = &char_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.init_len  = 0;
+    attr_char_value.init_offs = 0;
+    attr_char_value.max_len   = BLE_L2CAP_MTU_DEF;
+    attr_char_value.p_value   = NULL;
+
+    return sd_ble_gatts_characteristic_add(p_dfu->service_handle,
+                                           &char_md,
+                                           &attr_char_value,
+                                           &p_dfu->dfu_ctrl_pt_handles);
+}
+
+
+/**@brief     Function for handling the @ref BLE_GAP_EVT_CONNECTED event from the S110 SoftDevice.
+ *
+ * @param[in] p_dfu     DFU Service Structure.
+ * @param[in] p_ble_evt Pointer to the event received from BLE stack.
+ */
+static void on_connect(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt)
+{
+    p_dfu->conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
+}
+
+
+/**@brief     Function for checking if the CCCD of DFU Control point is configured for Notification.
+ *
+ * @details   This function checks if the CCCD of DFU Control Point characteristic is configured
+ *            for Notification by the DFU Controller.
+ *
+ * @param[in] p_dfu DFU Service structure.
+ *
+ * @return    True if the CCCD of DFU Control Point characteristic is configured for Notification.
+ *            False otherwise.
+ */
+static bool is_cccd_configured(ble_dfu_t * p_dfu)
+{
+    // Check if the CCCDs are configured.
+    uint8_t  cccd_val_buf[BLE_CCCD_VALUE_LEN];
+    ble_gatts_value_t gatts_value;
+
+    // Initialize value struct.
+    memset(&gatts_value, 0, sizeof(gatts_value));
+
+    gatts_value.len     = BLE_CCCD_VALUE_LEN;
+    gatts_value.offset  = 0;
+    gatts_value.p_value = cccd_val_buf;
+
+    // Check the CCCD Value of DFU Control Point.
+    uint32_t err_code = sd_ble_gatts_value_get(p_dfu->conn_handle,
+                                               p_dfu->dfu_ctrl_pt_handles.cccd_handle,
+                                               &gatts_value);
+    if (err_code != NRF_SUCCESS)
+    {
+        if (p_dfu->error_handler != NULL)
+        {
+            p_dfu->error_handler(err_code);
+        }
+        return false;
+    }
+
+    return ble_srv_is_notification_enabled(cccd_val_buf);
+}
+
+
+/**@brief     Function for handling a Write event on the Control Point characteristic.
+ *
+ * @param[in] p_dfu             DFU Service Structure.
+ * @param[in] p_ble_write_evt   Pointer to the write event received from BLE stack.
+ *
+ * @return    NRF_SUCCESS on successful processing of control point write. Otherwise an error code.
+ */
+static uint32_t on_ctrl_pt_write(ble_dfu_t * p_dfu, ble_gatts_evt_write_t * p_ble_write_evt)
+{
+    ble_gatts_rw_authorize_reply_params_t write_authorize_reply;
+
+    write_authorize_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
+
+    if (!is_cccd_configured(p_dfu))
+    {
+        // Send an error response to the peer indicating that the CCCD is improperly configured.
+        write_authorize_reply.params.write.gatt_status =
+            BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR;
+
+        return (sd_ble_gatts_rw_authorize_reply(p_dfu->conn_handle, &write_authorize_reply));
+
+    }
+    else
+    {
+        uint32_t err_code;
+
+        write_authorize_reply.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
+
+        err_code = (sd_ble_gatts_rw_authorize_reply(p_dfu->conn_handle, &write_authorize_reply));
+
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    ble_dfu_evt_t ble_dfu_evt;
+
+    switch (p_ble_write_evt->data[0])
+    {
+        case OP_CODE_START_DFU:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_START;
+
+            if (p_ble_write_evt->len < PKT_START_DFU_PARAM_LEN)
+            {
+                return ble_dfu_response_send(p_dfu,
+                                             (ble_dfu_procedure_t) p_ble_write_evt->data[0],
+                                             BLE_DFU_RESP_VAL_OPER_FAILED);
+            }
+
+            ble_dfu_evt.evt.ble_dfu_pkt_write.len    = 1;
+            ble_dfu_evt.evt.ble_dfu_pkt_write.p_data = &(p_ble_write_evt->data[1]);
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_RECEIVE_INIT:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_RECEIVE_INIT_DATA;
+
+            if (p_ble_write_evt->len < PKT_INIT_DFU_PARAM_LEN)
+            {
+                return ble_dfu_response_send(p_dfu,
+                                             (ble_dfu_procedure_t) p_ble_write_evt->data[0],
+                                             BLE_DFU_RESP_VAL_OPER_FAILED);
+            }
+            
+            ble_dfu_evt.evt.ble_dfu_pkt_write.len    = 1;
+            ble_dfu_evt.evt.ble_dfu_pkt_write.p_data = &(p_ble_write_evt->data[1]);
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_RECEIVE_FW:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_RECEIVE_APP_DATA;
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_VALIDATE:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_VALIDATE;
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_ACTIVATE_N_RESET:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_ACTIVATE_N_RESET;
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_SYS_RESET:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_SYS_RESET;
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        case OP_CODE_PKT_RCPT_NOTIF_REQ:
+            if (p_ble_write_evt->len < PKT_RCPT_NOTIF_REQ_LEN)
+            {
+                return (ble_dfu_response_send(p_dfu,
+                                              BLE_DFU_PKT_RCPT_REQ_PROCEDURE,
+                                              BLE_DFU_RESP_VAL_NOT_SUPPORTED));
+            }
+
+            ble_dfu_evt.evt.pkt_rcpt_notif_req.num_of_pkts =
+                uint16_decode(&(p_ble_write_evt->data[1]));
+
+            if (ble_dfu_evt.evt.pkt_rcpt_notif_req.num_of_pkts == 0)
+            {
+                ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_PKT_RCPT_NOTIF_DISABLED;
+            }
+            else
+            {
+                ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_PKT_RCPT_NOTIF_ENABLED;
+            }
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+
+            break;
+
+        case OP_CODE_IMAGE_SIZE_REQ:
+            ble_dfu_evt.ble_dfu_evt_type = BLE_DFU_BYTES_RECEIVED_SEND;
+
+            p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+            break;
+
+        default:
+            // Unsupported op code.
+            return ble_dfu_response_send(p_dfu,
+                                         (ble_dfu_procedure_t) p_ble_write_evt->data[0],
+                                         BLE_DFU_RESP_VAL_NOT_SUPPORTED);
+    }
+    return NRF_SUCCESS;
+}
+
+
+/**@brief     Function for handling the @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST event from the S110
+ *            Stack.
+ *
+ * @param[in] p_dfu     DFU Service Structure.
+ * @param[in] p_ble_evt Pointer to the event received from BLE stack.
+ */
+static void on_rw_authorize_req(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt)
+{
+    ble_gatts_evt_rw_authorize_request_t * p_authorize_request;
+
+    p_authorize_request = &(p_ble_evt->evt.gatts_evt.params.authorize_request);
+
+    if (
+        (p_authorize_request->type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
+        &&
+        (p_authorize_request->request.write.handle == p_dfu->dfu_ctrl_pt_handles.value_handle)
+        && 
+        (p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.op != BLE_GATTS_OP_PREP_WRITE_REQ)
+        &&
+        (p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.op != BLE_GATTS_OP_EXEC_WRITE_REQ_NOW)
+        &&
+        (p_ble_evt->evt.gatts_evt.params.authorize_request.request.write.op != BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL)
+       )
+    {
+        uint32_t err_code;
+
+        err_code = on_ctrl_pt_write(p_dfu, &(p_authorize_request->request.write));
+
+        if (err_code != NRF_SUCCESS && p_dfu->error_handler != NULL)
+        {
+            p_dfu->error_handler(err_code);
+        }
+    }
+}
+
+
+/**@brief     Function for handling the @ref BLE_GATTS_EVT_WRITE event from the S110 SoftDevice.
+ *
+ * @param[in] p_dfu     DFU Service Structure.
+ * @param[in] p_ble_evt Pointer to the event received from BLE stack.
+ */
+static void on_write(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt)
+{
+    if (p_ble_evt->evt.gatts_evt.params.write.handle == p_dfu->dfu_pkt_handles.value_handle)
+    {
+        // DFU Packet written
+
+        ble_dfu_evt_t ble_dfu_evt;
+
+        ble_dfu_evt.ble_dfu_evt_type             = BLE_DFU_PACKET_WRITE;
+        ble_dfu_evt.evt.ble_dfu_pkt_write.len    = p_ble_evt->evt.gatts_evt.params.write.len;
+        ble_dfu_evt.evt.ble_dfu_pkt_write.p_data = p_ble_evt->evt.gatts_evt.params.write.data;
+
+        p_dfu->evt_handler(p_dfu, &ble_dfu_evt);
+    }
+}
+
+
+/**@brief     Function for handling the BLE_GAP_EVT_DISCONNECTED event from the S110 SoftDevice.
+ *
+ * @param[in] p_dfu     DFU Service Structure.
+ * @param[in] p_ble_evt Pointer to the event received from BLE stack.
+ */
+static void on_disconnect(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt)
+{
+    p_dfu->conn_handle = BLE_CONN_HANDLE_INVALID;
+}
+
+
+uint32_t ble_dfu_init(ble_dfu_t * p_dfu, ble_dfu_init_t * p_dfu_init)
+{
+    if ((p_dfu == NULL) || (p_dfu_init == NULL) || (p_dfu_init->evt_handler == NULL))
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    p_dfu->conn_handle = BLE_CONN_HANDLE_INVALID;
+
+    ble_uuid_t service_uuid;
+    uint32_t   err_code;
+
+    const ble_uuid128_t base_uuid128 =
+    {
+        {
+            0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15,
+            0xDE, 0xEF, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00
+        }
+    };
+
+    service_uuid.uuid = BLE_DFU_SERVICE_UUID;
+
+    err_code = sd_ble_uuid_vs_add(&base_uuid128, &(service_uuid.type));
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
+                                        &service_uuid,
+                                        &(p_dfu->service_handle));
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    p_dfu->uuid_type = service_uuid.type;
+
+    err_code = dfu_pkt_char_add(p_dfu);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    err_code = dfu_ctrl_pt_add(p_dfu);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    err_code = dfu_rev_char_add(p_dfu, p_dfu_init);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    p_dfu->evt_handler = p_dfu_init->evt_handler;
+
+    if (p_dfu_init->error_handler != NULL)
+    {
+        p_dfu->error_handler = p_dfu_init->error_handler;
+    }
+
+    m_is_dfu_service_initialized = true;
+
+    return NRF_SUCCESS;
+}
+
+
+void ble_dfu_on_ble_evt(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt)
+{
+    if ((p_dfu == NULL) || (p_ble_evt == NULL))
+    {
+        return;
+    }
+
+    if (p_dfu->evt_handler != NULL)
+    {
+        switch (p_ble_evt->header.evt_id)
+        {
+            case BLE_GAP_EVT_CONNECTED:
+                on_connect(p_dfu, p_ble_evt);
+                break;
+
+            case BLE_GATTS_EVT_WRITE:
+                on_write(p_dfu, p_ble_evt);
+                break;
+
+            case BLE_GAP_EVT_DISCONNECTED:
+                on_disconnect(p_dfu, p_ble_evt);
+                break;
+
+            case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
+                on_rw_authorize_req(p_dfu, p_ble_evt);
+                break;
+
+            default:
+                // No implementation needed.
+                break;
+        }
+    }
+}
+
+
+uint32_t ble_dfu_bytes_rcvd_report(ble_dfu_t * p_dfu, uint32_t num_of_firmware_bytes_rcvd)
+{
+    if (p_dfu == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if ((p_dfu->conn_handle == BLE_CONN_HANDLE_INVALID) || !m_is_dfu_service_initialized)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    ble_gatts_hvx_params_t hvx_params;
+    uint16_t               index = 0;
+
+    // Encode the Op Code.
+    m_notif_buffer[index++] = OP_CODE_RESPONSE;
+
+    // Encode the Reqest Op Code.
+    m_notif_buffer[index++] = OP_CODE_IMAGE_SIZE_REQ;
+
+    // Encode the Response Value.
+    m_notif_buffer[index++] = (uint8_t)BLE_DFU_RESP_VAL_SUCCESS;
+
+    index += uint32_encode(num_of_firmware_bytes_rcvd, &m_notif_buffer[index]);
+
+    memset(&hvx_params, 0, sizeof(hvx_params));
+
+    hvx_params.handle = p_dfu->dfu_ctrl_pt_handles.value_handle;
+    hvx_params.type   = BLE_GATT_HVX_NOTIFICATION;
+    hvx_params.offset = 0;
+    hvx_params.p_len  = &index;
+    hvx_params.p_data = m_notif_buffer;
+
+    return sd_ble_gatts_hvx(p_dfu->conn_handle, &hvx_params);
+}
+
+
+uint32_t ble_dfu_pkts_rcpt_notify(ble_dfu_t * p_dfu, uint32_t num_of_firmware_bytes_rcvd)
+{
+    if (p_dfu == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if ((p_dfu->conn_handle == BLE_CONN_HANDLE_INVALID) || !m_is_dfu_service_initialized)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    ble_gatts_hvx_params_t hvx_params;
+    uint16_t               index = 0;
+
+    m_notif_buffer[index++] = OP_CODE_PKT_RCPT_NOTIF;
+
+    index += uint32_encode(num_of_firmware_bytes_rcvd, &m_notif_buffer[index]);
+
+    memset(&hvx_params, 0, sizeof(hvx_params));
+
+    hvx_params.handle = p_dfu->dfu_ctrl_pt_handles.value_handle;
+    hvx_params.type   = BLE_GATT_HVX_NOTIFICATION;
+    hvx_params.offset = 0;
+    hvx_params.p_len  = &index;
+    hvx_params.p_data = m_notif_buffer;
+
+    return sd_ble_gatts_hvx(p_dfu->conn_handle, &hvx_params);
+}
+
+
+uint32_t ble_dfu_response_send(ble_dfu_t         * p_dfu,
+                               ble_dfu_procedure_t dfu_proc,
+                               ble_dfu_resp_val_t  resp_val)
+{
+    if (p_dfu == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if ((p_dfu->conn_handle == BLE_CONN_HANDLE_INVALID) || !m_is_dfu_service_initialized)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    ble_gatts_hvx_params_t hvx_params;
+    uint16_t               index = 0;
+
+    m_notif_buffer[index++] = OP_CODE_RESPONSE;
+
+    // Encode the Request Op code
+    m_notif_buffer[index++] = (uint8_t)dfu_proc;
+
+    // Encode the Response Value.
+    m_notif_buffer[index++] = (uint8_t)resp_val;
+
+    memset(&hvx_params, 0, sizeof(hvx_params));
+
+    hvx_params.handle = p_dfu->dfu_ctrl_pt_handles.value_handle;
+    hvx_params.type   = BLE_GATT_HVX_NOTIFICATION;
+    hvx_params.offset = 0;
+    hvx_params.p_len  = &index;
+    hvx_params.p_data = m_notif_buffer;
+
+    return sd_ble_gatts_hvx(p_dfu->conn_handle, &hvx_params);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/ble_services/ble_dfu/ble_dfu.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,259 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup ble_sdk_srv_dfu Device Firmware Update Service
+ * @{
+ * @ingroup  ble_sdk_srv
+ * @brief    Device Firmware Update Service
+ *
+ * @details  The Device Firmware Update (DFU) service is a GATT based service that can be used for
+ *           performing firmware updates over BLE. Note that this implementation uses vendor
+ *           specific UUIDs for service and characteristics and is intended to demonstrate the
+ *           firmware updates over BLE. Refer @ref bledfu_transport_bleservice and @ref
+ *            bledfu_transport_bleprofile for more information on the service and profile respectively.
+ */
+
+#ifndef BLE_DFU_H__
+#define BLE_DFU_H__
+
+#include <stdint.h>
+#include "ble_gatts.h"
+#include "ble_gap.h"
+#include "nrf_ble.h"
+#include "ble_srv_common.h"
+
+#define BLE_DFU_SERVICE_UUID                 0x1530                       /**< The UUID of the DFU Service. */
+#define BLE_DFU_PKT_CHAR_UUID                0x1532                       /**< The UUID of the DFU Packet Characteristic. */
+#define BLE_DFU_CTRL_PT_UUID                 0x1531                       /**< The UUID of the DFU Control Point. */
+#define BLE_DFU_STATUS_REP_UUID              0x1533                       /**< The UUID of the DFU Status Report Characteristic. */
+#define BLE_DFU_REV_CHAR_UUID                0x1534                       /**< The UUID of the DFU Revision Characteristic. */
+
+/**@brief   DFU Event type.
+ *
+ * @details This enumeration contains the types of events that will be received from the DFU Service.
+ */
+typedef enum
+{
+    BLE_DFU_START,                                                      /**< The event indicating that the peer wants the application to prepare for a new firmware update. */
+    BLE_DFU_RECEIVE_INIT_DATA,                                          /**< The event indicating that the peer wants the application to prepare to receive init parameters. */
+    BLE_DFU_RECEIVE_APP_DATA,                                           /**< The event indicating that the peer wants the application to prepare to receive the new firmware image. */
+    BLE_DFU_VALIDATE,                                                   /**< The event indicating that the peer wants the application to validate the newly received firmware image. */
+    BLE_DFU_ACTIVATE_N_RESET,                                           /**< The event indicating that the peer wants the application to undergo activate new firmware and restart with new valid application */
+    BLE_DFU_SYS_RESET,                                                  /**< The event indicating that the peer wants the application to undergo a reset and start the currently valid application image.*/
+    BLE_DFU_PKT_RCPT_NOTIF_ENABLED,                                     /**< The event indicating that the peer has enabled packet receipt notifications. It is the responsibility of the application to call @ref ble_dfu_pkts_rcpt_notify each time the number of packets indicated by num_of_pkts field in @ref ble_dfu_evt_t is received.*/
+    BLE_DFU_PKT_RCPT_NOTIF_DISABLED,                                    /**< The event indicating that the peer has disabled the packet receipt notifications.*/
+    BLE_DFU_PACKET_WRITE,                                               /**< The event indicating that the peer has written a value to the 'DFU Packet' characteristic. The data received from the peer will be present in the @ref BLE_DFU_PACKET_WRITE element contained within @ref ble_dfu_evt_t.*/
+    BLE_DFU_BYTES_RECEIVED_SEND                                         /**< The event indicating that the peer is requesting for the number of bytes of firmware data last received by the application. It is the responsibility of the application to call @ref ble_dfu_pkts_rcpt_notify in response to this event. */
+} ble_dfu_evt_type_t;
+
+/**@brief   DFU Procedure type.
+ *
+ * @details This enumeration contains the types of DFU procedures.
+ */
+typedef enum
+{
+    BLE_DFU_START_PROCEDURE        = 1,                                 /**< DFU Start procedure.*/
+    BLE_DFU_INIT_PROCEDURE         = 2,                                 /**< DFU Initialization procedure.*/
+    BLE_DFU_RECEIVE_APP_PROCEDURE  = 3,                                 /**< Firmware receiving procedure.*/
+    BLE_DFU_VALIDATE_PROCEDURE     = 4,                                 /**< Firmware image validation procedure .*/
+    BLE_DFU_PKT_RCPT_REQ_PROCEDURE = 8                                  /**< Packet receipt notification request procedure. */
+} ble_dfu_procedure_t;
+
+/**@brief   DFU Response value type.
+ */
+typedef enum
+{
+    BLE_DFU_RESP_VAL_SUCCESS = 1,                                       /**< Success.*/
+    BLE_DFU_RESP_VAL_INVALID_STATE,                                     /**< Invalid state.*/
+    BLE_DFU_RESP_VAL_NOT_SUPPORTED,                                     /**< Operation not supported.*/
+    BLE_DFU_RESP_VAL_DATA_SIZE,                                         /**< Data size exceeds limit.*/
+    BLE_DFU_RESP_VAL_CRC_ERROR,                                         /**< CRC Error.*/
+    BLE_DFU_RESP_VAL_OPER_FAILED                                        /**< Operation failed.*/
+} ble_dfu_resp_val_t;
+
+
+/**@brief   DFU Packet structure.
+ *
+ * @details This structure contains the value of the DFU Packet characteristic as written by the
+ *          peer and the length of the value written. It will be filled by the DFU Service when the
+ *          peer writes to the DFU Packet characteristic.
+ */
+typedef struct
+{
+    uint8_t *                    p_data;                                /**< Pointer to the received packet. This will point to a word aligned memory location.*/
+    uint8_t                      len;                                   /**< Length of the packet received. */
+} ble_dfu_pkt_write_t;
+
+/**@brief   Packet receipt notification request structure.
+ *
+ * @details This structure contains the contents of the packet receipt notification request
+ *          sent by the DFU Controller.
+ */
+typedef struct
+{
+    uint16_t                     num_of_pkts;                           /**< The number of packets of firmware data to be received by application before sending the next Packet Receipt Notification to the peer. */
+} ble_pkt_rcpt_notif_req_t;
+
+/**@brief   DFU Event structure.
+ *
+ * @details This structure contains the event generated by the DFU Service based on the data
+ *          received from the peer.
+ */
+typedef struct
+{
+    ble_dfu_evt_type_t           ble_dfu_evt_type;                      /**< Type of the event.*/
+    union
+    {
+        ble_dfu_pkt_write_t      ble_dfu_pkt_write;                     /**< The DFU packet received. This field is when the @ref ble_dfu_evt_type field is set to @ref BLE_DFU_PACKET_WRITE.*/
+        ble_pkt_rcpt_notif_req_t pkt_rcpt_notif_req;                    /**< Packet receipt notification request. This field is when the @ref ble_dfu_evt_type field is set to @ref BLE_DFU_PKT_RCPT_NOTIF_ENABLED.*/
+    } evt;
+} ble_dfu_evt_t;
+
+// Forward declaration of the ble_dfu_t type.
+typedef struct ble_dfu_s ble_dfu_t;
+
+/**@brief DFU Service event handler type. */
+typedef void (*ble_dfu_evt_handler_t) (ble_dfu_t * p_dfu, ble_dfu_evt_t * p_evt);
+
+/**@brief   DFU service structure.
+ *
+ * @details This structure contains status information related to the service.
+ */
+struct ble_dfu_s
+{
+    uint16_t                     conn_handle;                           /**< Handle of the current connection (as provided by the S110 SoftDevice). This will be BLE_CONN_HANDLE_INVALID when not in a connection. */
+    uint16_t                     revision;                              /**< Handle of DFU Service (as provided by the S110 SoftDevice). */
+    uint16_t                     service_handle;                        /**< Handle of DFU Service (as provided by the S110 SoftDevice). */
+    uint8_t                      uuid_type;                             /**< UUID type assigned for DFU Service by the S110 SoftDevice. */
+    ble_gatts_char_handles_t     dfu_pkt_handles;                       /**< Handles related to the DFU Packet characteristic. */
+    ble_gatts_char_handles_t     dfu_ctrl_pt_handles;                   /**< Handles related to the DFU Control Point characteristic. */
+    ble_gatts_char_handles_t     dfu_status_rep_handles;                /**< Handles related to the DFU Status Report characteristic. */
+    ble_gatts_char_handles_t     dfu_rev_handles;                       /**< Handles related to the DFU Revision characteristic. */
+    ble_dfu_evt_handler_t        evt_handler;                           /**< The event handler to be called when an event is to be sent to the application.*/
+    ble_srv_error_handler_t      error_handler;                         /**< Function to be called in case of an error. */
+};
+
+/**@brief      DFU service initialization structure.
+ *
+ * @details    This structure contains the initialization information for the DFU Service. The
+ *             application needs to fill this structure and pass it to the DFU Service using the
+ *             @ref ble_dfu_init function.
+ */
+typedef struct
+{
+    uint16_t                     revision;                              /**< Revision number to be exposed by the DFU service. */
+    ble_dfu_evt_handler_t        evt_handler;                           /**< Event handler to be called for handling events in the Device Firmware Update Service. */
+    ble_srv_error_handler_t      error_handler;                         /**< Function to be called in case of an error. */
+} ble_dfu_init_t;
+
+/**@brief      Function for handling a BLE event.
+ *
+ * @details    The DFU service expects the application to call this function each time an event
+ *             is received from the S110 SoftDevice. This function processes the event, if it is
+ *             relevant for the DFU service and calls the DFU event handler of the application if
+ *             necessary.
+ *
+ * @param[in]  p_dfu        Pointer to the DFU service structure.
+ * @param[in]  p_ble_evt    Pointer to the event received from S110 SoftDevice.
+ */
+void ble_dfu_on_ble_evt(ble_dfu_t * p_dfu, ble_evt_t * p_ble_evt);
+
+/**@brief      Function for initializing the DFU service.
+ *
+ * @param[out] p_dfu        Device Firmware Update service structure. This structure will have to be
+ *                          supplied by the application. It will be initialized by this function,
+ *                          and will later be used to identify the service instance.
+ * @param[in]  p_dfu_init   Information needed to initialize the service.
+ *
+ * @return     NRF_SUCCESS if the DFU service and its characteristics were successfully added to the
+ *             S110 SoftDevice. Otherwise an error code.
+ *             This function returns NRF_ERROR_NULL if the value of evt_handler in p_dfu_init
+ *             structure provided is NULL or if the pointers supplied as input are NULL.
+ */
+uint32_t ble_dfu_init(ble_dfu_t * p_dfu, ble_dfu_init_t * p_dfu_init);
+
+/**@brief       Function for sending response to a control point command.
+ *
+ * @details     This function will encode a DFU Control Point response using the given input
+ *              parameters and will send a notification of the same to the peer.
+ *
+ * @param[in]   p_dfu       Pointer to the DFU service structure.
+ * @param[in]   dfu_proc    Procedure for which this response is to be sent.
+ * @param[in]   resp_val    Response value.
+ *
+ * @return      NRF_SUCCESS if the DFU Service has successfully requested the S110 SoftDevice to
+ *              send the notification. Otherwise an error code.
+ *              This function returns NRF_ERROR_INVALID_STATE if the device is not connected to a
+ *              peer or if the DFU service is not initialized or if the notification of the DFU
+ *              Status Report characteristic was not enabled by the peer. It returns NRF_ERROR_NULL
+ *              if the pointer p_dfu is NULL.
+ */
+uint32_t ble_dfu_response_send(ble_dfu_t *          p_dfu,
+                               ble_dfu_procedure_t  dfu_proc,
+                               ble_dfu_resp_val_t   resp_val);
+
+/**@brief      Function for notifying the peer about the number of bytes of firmware data received.
+ *
+ * @param[in]  p_dfu                      Pointer to the DFU service structure.
+ * @param[in]  num_of_firmware_bytes_rcvd Number of bytes.
+ *
+ * @return     NRF_SUCCESS if the DFU Service has successfully requested the S110 SoftDevice to send
+ *             the notification. Otherwise an error code.
+ *             This function returns NRF_ERROR_INVALID_STATE if the device is not connected to a
+ *             peer or if the DFU service is not initialized or if the notification of the DFU
+ *             Status Report characteristic was not enabled by the peer. It returns NRF_ERROR_NULL
+ *             if the pointer p_dfu is NULL.
+ */
+uint32_t ble_dfu_bytes_rcvd_report(ble_dfu_t * p_dfu, uint32_t num_of_firmware_bytes_rcvd);
+
+/**@brief      Function for sending Packet Receipt Notification to the peer.
+ *
+ *             This function will encode the number of bytes received as input parameter into a
+ *             notification of the control point characteristic and send it to the peer.
+ *
+ * @param[in]  p_dfu                      Pointer to the DFU service structure.
+ * @param[in]  num_of_firmware_bytes_rcvd Number of bytes of firmware image received.
+ *
+ * @return     NRF_SUCCESS if the DFU Service has successfully requested the S110 SoftDevice to send
+ *             the notification. Otherwise an error code.
+ *             This function returns NRF_ERROR_INVALID_STATE if the device is not connected to a
+ *             peer or if the DFU service is not initialized or if the notification of the DFU
+ *             Status Report characteristic was not enabled by the peer. It returns NRF_ERROR_NULL
+ *             if the pointer p_dfu is NULL.
+ */
+uint32_t ble_dfu_pkts_rcpt_notify(ble_dfu_t * p_dfu, uint32_t num_of_firmware_bytes_rcvd);
+
+#endif // BLE_DFU_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,861 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_advdata.h"
+#include "nordic_common.h"
+#include "nrf_error.h"
+#include "ble_gap.h"
+#include "ble_srv_common.h"
+#include "app_util.h"
+
+// NOTE: For now, Security Manager Out of Band Flags (OOB) are omitted from the advertising data.
+
+// Types of LE Bluetooth Device Address AD type
+#define AD_TYPE_BLE_DEVICE_ADDR_TYPE_PUBLIC 0UL
+#define AD_TYPE_BLE_DEVICE_ADDR_TYPE_RANDOM 1UL
+
+static uint32_t tk_value_encode(ble_advdata_tk_value_t * p_tk_value,
+                                uint8_t                * p_encoded_data,
+                                uint16_t               * p_offset,
+                                uint16_t                 max_size)
+{
+    int8_t i;
+
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_TK_VALUE_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode LE Role.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_TK_VALUE_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_SECURITY_MANAGER_TK_VALUE;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+
+    for (i = AD_TYPE_TK_VALUE_DATA_SIZE - 1; i >= 0; i--, (*p_offset)++)
+    {
+        p_encoded_data[*p_offset] = p_tk_value->tk[i];
+    }
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t le_role_encode(ble_advdata_le_role_t   le_role,
+                               uint8_t               * p_encoded_data,
+                               uint16_t              * p_offset,
+                               uint16_t                max_size)
+{
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_LE_ROLE_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode LE Role.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_LE_ROLE_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_LE_ROLE;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    switch(le_role)
+    {
+        case BLE_ADVDATA_ROLE_ONLY_PERIPH:
+            p_encoded_data[*p_offset] = 0;
+            break;
+        case BLE_ADVDATA_ROLE_ONLY_CENTRAL:
+            p_encoded_data[*p_offset] = 1;
+            break;
+        case BLE_ADVDATA_ROLE_BOTH_PERIPH_PREFERRED:
+            p_encoded_data[*p_offset] = 2;
+            break;
+        case BLE_ADVDATA_ROLE_BOTH_CENTRAL_PREFERRED:
+            p_encoded_data[*p_offset] = 3;
+            break;
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+    *p_offset += AD_TYPE_LE_ROLE_DATA_SIZE;
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t ble_device_addr_encode(uint8_t  * p_encoded_data,
+                                       uint16_t * p_offset,
+                                       uint16_t   max_size)
+{
+    uint32_t err_code;
+    ble_gap_addr_t device_addr;
+
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_BLE_DEVICE_ADDR_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Get BLE address
+    err_code = sd_ble_gap_address_get(&device_addr);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    // Encode LE Bluetooth Device Address
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE +
+                                               AD_TYPE_BLE_DEVICE_ADDR_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_LE_BLUETOOTH_DEVICE_ADDRESS;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    memcpy(&p_encoded_data[*p_offset], &device_addr.addr[0], BLE_GAP_ADDR_LEN);
+    *p_offset                 += BLE_GAP_ADDR_LEN;
+    if(BLE_GAP_ADDR_TYPE_PUBLIC == device_addr.addr_type)
+    {
+        p_encoded_data[*p_offset] = AD_TYPE_BLE_DEVICE_ADDR_TYPE_PUBLIC;
+    }
+    else
+    {
+        p_encoded_data[*p_offset] = AD_TYPE_BLE_DEVICE_ADDR_TYPE_RANDOM;
+    }
+    *p_offset += AD_TYPE_BLE_DEVICE_ADDR_TYPE_SIZE;
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t name_encode(const ble_advdata_t * p_advdata,
+                            uint8_t             * p_encoded_data,
+                            uint16_t            * p_offset,
+                            uint16_t              max_size)
+{
+    uint32_t err_code;
+    uint16_t rem_adv_data_len;
+    uint16_t actual_length;
+    uint8_t  adv_data_format;
+
+
+    // Validate parameters
+    if((BLE_ADVDATA_SHORT_NAME == p_advdata->name_type) && (0 == p_advdata->short_name_len))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Check for buffer overflow.
+    if ( (((*p_offset) + ADV_AD_DATA_OFFSET) > max_size) ||
+         ( (BLE_ADVDATA_SHORT_NAME == p_advdata->name_type) &&
+           (((*p_offset) + ADV_AD_DATA_OFFSET + p_advdata->short_name_len) > max_size)))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    rem_adv_data_len = max_size - (*p_offset) - ADV_AD_DATA_OFFSET;
+    actual_length    = rem_adv_data_len;
+
+    // Get GAP device name and length
+    err_code = sd_ble_gap_device_name_get(&p_encoded_data[(*p_offset) + ADV_AD_DATA_OFFSET],
+                                          &actual_length);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+    
+    // Check if device intend to use short name and it can fit available data size.
+    if ((p_advdata->name_type == BLE_ADVDATA_FULL_NAME) && (actual_length <= rem_adv_data_len))
+    {
+        // Complete device name can fit, setting Complete Name in Adv Data.
+        adv_data_format = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME;
+    }
+    else
+    {
+        // Else short name needs to be used. Or application has requested use of short name.
+        adv_data_format = BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME;
+
+        // If application has set a preference on the short name size, it needs to be considered,
+        // else fit what can be fit.
+        if ((BLE_ADVDATA_SHORT_NAME == p_advdata->name_type) &&
+                (p_advdata->short_name_len <= rem_adv_data_len))
+        {
+            // Short name fits available size.
+            actual_length = p_advdata->short_name_len;
+        }
+        // Else whatever can fit the data buffer will be packed.
+        else
+        {
+            actual_length = rem_adv_data_len;
+        }
+    }
+
+    // There is only 1 byte intended to encode length which is (actual_length + ADV_AD_TYPE_FIELD_SIZE)
+    if(actual_length > (0x00FF - ADV_AD_TYPE_FIELD_SIZE))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Complete name field in encoded data.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + actual_length);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = adv_data_format;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    *p_offset                 += actual_length;
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t appearance_encode(uint8_t  * p_encoded_data,
+                                  uint16_t * p_offset,
+                                  uint16_t   max_size)
+{
+    uint32_t err_code;
+    uint16_t appearance;
+
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_APPEARANCE_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Get GAP appearance field.
+    err_code = sd_ble_gap_appearance_get(&appearance);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    // Encode Length, AD Type and Appearance.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_APPEARANCE_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_APPEARANCE;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    *p_offset                 += uint16_encode(appearance, &p_encoded_data[*p_offset]);
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t flags_encode(int8_t     flags,
+                             uint8_t  * p_encoded_data,
+                             uint16_t * p_offset,
+                             uint16_t   max_size)
+{
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_FLAGS_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode flags.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_FLAGS_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_FLAGS;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = flags;
+    *p_offset                 += AD_TYPE_FLAGS_DATA_SIZE;
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t sec_mgr_oob_flags_encode(uint8_t    oob_flags,
+                                         uint8_t  * p_encoded_data,
+                                         uint16_t * p_offset,
+                                         uint16_t   max_size)
+{
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_OOB_FLAGS_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode flags.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_OOB_FLAGS_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_SECURITY_MANAGER_OOB_FLAGS;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = oob_flags;
+    *p_offset                 += AD_TYPE_OOB_FLAGS_DATA_SIZE;
+
+    return NRF_SUCCESS;
+}
+
+static uint32_t tx_power_level_encode(int8_t     tx_power_level,
+                                      uint8_t  * p_encoded_data,
+                                      uint16_t * p_offset,
+                                      uint16_t   max_size)
+{
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_TX_POWER_LEVEL_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode TX Power Level.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE +
+                                                  AD_TYPE_TX_POWER_LEVEL_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_TX_POWER_LEVEL;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = tx_power_level;
+    *p_offset                 += AD_TYPE_TX_POWER_LEVEL_DATA_SIZE;
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t uuid_list_sized_encode(const ble_advdata_uuid_list_t * p_uuid_list,
+                                       uint8_t                         adv_type,
+                                       uint8_t                         uuid_size,
+                                       uint8_t                       * p_encoded_data,
+                                       uint16_t                      * p_offset,
+                                       uint16_t                        max_size)
+{
+    int      i;
+    bool     is_heading_written = false;
+    uint16_t start_pos          = *p_offset;
+    uint16_t length;
+
+    for (i = 0; i < p_uuid_list->uuid_cnt; i++)
+    {
+        uint32_t   err_code;
+        uint8_t    encoded_size;
+        ble_uuid_t uuid = p_uuid_list->p_uuids[i];
+        
+        // Find encoded uuid size.
+        err_code = sd_ble_uuid_encode(&uuid, &encoded_size, NULL);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+
+        // Check size.
+        if (encoded_size == uuid_size)
+        {
+            uint8_t heading_bytes = (is_heading_written) ? 0 : ADV_AD_DATA_OFFSET;
+            
+            // Check for buffer overflow
+            if (((*p_offset) + encoded_size + heading_bytes) > max_size)
+            {
+                return NRF_ERROR_DATA_SIZE;
+            }
+
+            if (!is_heading_written)
+            {
+                // Write AD structure heading.
+                *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+                p_encoded_data[*p_offset]  = adv_type;
+                *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+                is_heading_written         = true;
+            }
+
+            // Write UUID.
+            err_code = sd_ble_uuid_encode(&uuid, &encoded_size, &p_encoded_data[*p_offset]);
+            if (err_code != NRF_SUCCESS)
+            {
+                return err_code;
+            }
+            *p_offset += encoded_size;
+        }
+    }
+
+    if (is_heading_written)
+    {
+        // Write length.
+        length = (*p_offset) - (start_pos + ADV_LENGTH_FIELD_SIZE);
+        // There is only 1 byte intended to encode length
+        if(length > 0x00FF)
+        {
+            return NRF_ERROR_DATA_SIZE;
+        }
+        p_encoded_data[start_pos] = (uint8_t)length;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t uuid_list_encode(const ble_advdata_uuid_list_t * p_uuid_list,
+                                 uint8_t                         adv_type_16,
+                                 uint8_t                         adv_type_128,
+                                 uint8_t                       * p_encoded_data,
+                                 uint16_t                      * p_offset,
+                                 uint16_t                        max_size)
+{
+    uint32_t err_code;
+
+    // Encode 16 bit UUIDs.
+    err_code = uuid_list_sized_encode(p_uuid_list,
+                                      adv_type_16,
+                                      sizeof(uint16_le_t),
+                                      p_encoded_data,
+                                      p_offset,
+                                      max_size);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    // Encode 128 bit UUIDs.
+    err_code = uuid_list_sized_encode(p_uuid_list,
+                                      adv_type_128,
+                                      sizeof(ble_uuid128_t),
+                                      p_encoded_data,
+                                      p_offset,
+                                      max_size);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t conn_int_check(const ble_advdata_conn_int_t *p_conn_int)
+{
+    // Check Minimum Connection Interval.
+    if ((p_conn_int->min_conn_interval < 0x0006) ||
+        (
+            (p_conn_int->min_conn_interval > 0x0c80) &&
+            (p_conn_int->min_conn_interval != 0xffff)
+        )
+       )
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Check Maximum Connection Interval.
+    if ((p_conn_int->max_conn_interval < 0x0006) || 
+        (
+            (p_conn_int->max_conn_interval > 0x0c80) && 
+            (p_conn_int->max_conn_interval != 0xffff)
+        )
+       )
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Make sure Minimum Connection Interval is not bigger than Maximum Connection Interval.
+    if ((p_conn_int->min_conn_interval != 0xffff) &&
+        (p_conn_int->max_conn_interval != 0xffff) &&
+        (p_conn_int->min_conn_interval > p_conn_int->max_conn_interval)
+        )
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t conn_int_encode(const ble_advdata_conn_int_t * p_conn_int,
+                                uint8_t                      * p_encoded_data,
+                                uint16_t                     * p_offset,
+                                uint16_t                       max_size)
+{
+    uint32_t err_code;
+
+    // Check for buffer overflow.
+    if (((*p_offset) + AD_TYPE_CONN_INT_SIZE) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Check parameters.
+    err_code = conn_int_check(p_conn_int);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    // Encode Length and AD Type.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + AD_TYPE_CONN_INT_DATA_SIZE);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+
+    // Encode Minimum and Maximum Connection Intervals.
+    *p_offset += uint16_encode(p_conn_int->min_conn_interval, &p_encoded_data[*p_offset]);
+    *p_offset += uint16_encode(p_conn_int->max_conn_interval, &p_encoded_data[*p_offset]);
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t manuf_specific_data_encode(const ble_advdata_manuf_data_t * p_manuf_sp_data,
+                                           uint8_t                        * p_encoded_data,
+                                           uint16_t                       * p_offset,
+                                           uint16_t                         max_size)
+{
+    uint32_t data_size = AD_TYPE_MANUF_SPEC_DATA_ID_SIZE + p_manuf_sp_data->data.size;
+
+    // Check for buffer overflow.
+    if (((*p_offset) + ADV_AD_DATA_OFFSET + data_size) > max_size)
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // There is only 1 byte intended to encode length which is (data_size + ADV_AD_TYPE_FIELD_SIZE)
+    if(data_size > (0x00FF - ADV_AD_TYPE_FIELD_SIZE))
+    {
+        return NRF_ERROR_DATA_SIZE;
+    }
+
+    // Encode Length and AD Type.
+    p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + data_size);
+    *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+    p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA;
+    *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+    
+    // Encode Company Identifier.
+    *p_offset += uint16_encode(p_manuf_sp_data->company_identifier, &p_encoded_data[*p_offset]);
+    
+    // Encode additional manufacturer specific data.
+    if (p_manuf_sp_data->data.size > 0)
+    {
+        if (p_manuf_sp_data->data.p_data == NULL)
+        {
+            return NRF_ERROR_INVALID_PARAM;
+        }
+        memcpy(&p_encoded_data[*p_offset], p_manuf_sp_data->data.p_data, p_manuf_sp_data->data.size);
+        *p_offset += p_manuf_sp_data->data.size;
+    }
+
+    return NRF_SUCCESS;
+}
+
+// Implemented only for 16-bit UUIDs
+static uint32_t service_data_encode(const ble_advdata_t * p_advdata,
+                                    uint8_t             * p_encoded_data,
+                                    uint16_t            * p_offset,
+                                    uint16_t              max_size)
+{
+    uint8_t i;
+
+    // Check parameter consistency.
+    if (p_advdata->p_service_data_array == NULL)
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    for (i = 0; i < p_advdata->service_data_count; i++)
+    {
+        ble_advdata_service_data_t * p_service_data;
+        uint32_t                     data_size;
+
+        p_service_data = &p_advdata->p_service_data_array[i];
+        // For now implemented only for 16-bit UUIDs
+        data_size      = AD_TYPE_SERV_DATA_16BIT_UUID_SIZE + p_service_data->data.size;
+
+        // There is only 1 byte intended to encode length which is (data_size + ADV_AD_TYPE_FIELD_SIZE)
+        if(data_size > (0x00FF - ADV_AD_TYPE_FIELD_SIZE))
+        {
+            return NRF_ERROR_DATA_SIZE;
+        }
+
+        // Encode Length and AD Type.
+        p_encoded_data[*p_offset]  = (uint8_t)(ADV_AD_TYPE_FIELD_SIZE + data_size);
+        *p_offset                 += ADV_LENGTH_FIELD_SIZE;
+        p_encoded_data[*p_offset]  = BLE_GAP_AD_TYPE_SERVICE_DATA;
+        *p_offset                 += ADV_AD_TYPE_FIELD_SIZE;
+
+        // Encode service 16-bit UUID.
+        *p_offset += uint16_encode(p_service_data->service_uuid, &p_encoded_data[*p_offset]);
+
+        // Encode additional service data.
+        if (p_service_data->data.size > 0)
+        {
+            if (p_service_data->data.p_data == NULL)
+            {
+                return NRF_ERROR_INVALID_PARAM;
+            }
+            memcpy(&p_encoded_data[*p_offset], p_service_data->data.p_data, p_service_data->data.size);
+            *p_offset += p_service_data->data.size;
+        }
+    }
+
+    return NRF_SUCCESS;
+}
+
+uint32_t adv_data_encode(ble_advdata_t const * const p_advdata,
+                         uint8_t             * const p_encoded_data,
+                         uint16_t            * const p_len)
+{
+    uint32_t err_code = NRF_SUCCESS;
+    uint16_t max_size = *p_len;
+    *p_len = 0;
+
+    //Encode Security Manager OOB Flags
+    if (p_advdata->p_sec_mgr_oob_flags != NULL)
+    {
+        err_code = sec_mgr_oob_flags_encode(*p_advdata->p_sec_mgr_oob_flags,
+                                             p_encoded_data,
+                                             p_len,
+                                             max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+		
+    // Encode Security Manager TK value
+    if (NULL != p_advdata->p_tk_value)
+    {
+        err_code = tk_value_encode(p_advdata->p_tk_value, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode LE Role
+    if (BLE_ADVDATA_ROLE_NOT_PRESENT != p_advdata->le_role)
+    {
+        err_code = le_role_encode(p_advdata->le_role, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode LE Bluetooth Device Address
+    if (p_advdata->include_ble_device_addr)
+    {
+        err_code = ble_device_addr_encode(p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode appearance.
+    if (p_advdata->include_appearance)
+    {
+        err_code = appearance_encode(p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    //Encode Flags
+    if(p_advdata->flags != 0 )
+    {
+        err_code = flags_encode(p_advdata->flags, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    } 
+
+    // Encode TX power level.
+    if (p_advdata->p_tx_power_level != NULL)
+    {
+        err_code = tx_power_level_encode(*p_advdata->p_tx_power_level,
+                                         p_encoded_data,
+                                         p_len,
+                                         max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+    
+    // Encode 'more available' uuid list.
+    if (p_advdata->uuids_more_available.uuid_cnt > 0)
+    {
+        err_code = uuid_list_encode(&p_advdata->uuids_more_available,
+                                    BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE,
+                                    BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE,
+                                    p_encoded_data,
+                                    p_len,
+                                    max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode 'complete' uuid list.
+    if (p_advdata->uuids_complete.uuid_cnt > 0)
+    {
+        err_code = uuid_list_encode(&p_advdata->uuids_complete,
+                                    BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE,
+                                    BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE,
+                                    p_encoded_data,
+                                    p_len,
+                                    max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode 'solicited service' uuid list.
+    if (p_advdata->uuids_solicited.uuid_cnt > 0)
+    {
+        err_code = uuid_list_encode(&p_advdata->uuids_solicited,
+                                    BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_16BIT,
+                                    BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_128BIT,
+                                    p_encoded_data,
+                                    p_len,
+                                    max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode Slave Connection Interval Range.
+    if (p_advdata->p_slave_conn_int != NULL)
+    {
+        err_code = conn_int_encode(p_advdata->p_slave_conn_int, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode Manufacturer Specific Data.
+    if (p_advdata->p_manuf_specific_data != NULL)
+    {
+        err_code = manuf_specific_data_encode(p_advdata->p_manuf_specific_data,
+                                              p_encoded_data,
+                                              p_len,
+                                              max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode Service Data.
+    if (p_advdata->service_data_count > 0)
+    {
+        err_code = service_data_encode(p_advdata, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    // Encode name. WARNING: it is encoded last on purpose since too long device name is truncated.
+    if (p_advdata->name_type != BLE_ADVDATA_NO_NAME)
+    {
+        err_code = name_encode(p_advdata, p_encoded_data, p_len, max_size);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    return err_code;
+}
+
+
+static uint32_t advdata_check(const ble_advdata_t * p_advdata)
+{
+    // Flags must be included in advertising data, and the BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED flag must be set.
+    if (
+        ((p_advdata->flags & BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED) == 0)
+       )
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+static uint32_t srdata_check(const ble_advdata_t * p_srdata)
+{
+    // Flags shall not be included in the scan response data.
+    if (p_srdata->flags)
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_advdata_set(const ble_advdata_t * p_advdata, const ble_advdata_t * p_srdata)
+{
+    uint32_t  err_code;
+    uint16_t  len_advdata = BLE_GAP_ADV_MAX_SIZE;
+    uint16_t  len_srdata  = BLE_GAP_ADV_MAX_SIZE;
+    uint8_t   encoded_advdata[BLE_GAP_ADV_MAX_SIZE];
+    uint8_t   encoded_srdata[BLE_GAP_ADV_MAX_SIZE];
+    uint8_t * p_encoded_advdata;
+    uint8_t * p_encoded_srdata;
+
+    // Encode advertising data (if supplied).
+    if (p_advdata != NULL)
+    {
+        err_code = advdata_check(p_advdata);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+
+        err_code = adv_data_encode(p_advdata, encoded_advdata, &len_advdata);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+        p_encoded_advdata = encoded_advdata;
+    }
+    else
+    {
+        p_encoded_advdata = NULL;
+        len_advdata = 0;
+    }
+
+    // Encode scan response data (if supplied).
+    if (p_srdata != NULL)
+    {
+        err_code = srdata_check(p_srdata);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+
+        err_code = adv_data_encode(p_srdata, encoded_srdata, &len_srdata);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+        p_encoded_srdata = encoded_srdata;
+    }
+    else
+    {
+        p_encoded_srdata = NULL;
+        len_srdata = 0;
+    }
+
+    // Pass encoded advertising data and/or scan response data to the stack.
+    return sd_ble_gap_adv_data_set(p_encoded_advdata, len_advdata, p_encoded_srdata, len_srdata);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_advdata.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup ble_sdk_lib_advdata Advertising and Scan Response Data Encoder
+ * @{
+ * @ingroup ble_sdk_lib
+ * @brief Functions for encoding data in the Advertising and Scan Response Data format,
+ *        and for passing the data to the stack.
+ */
+
+#ifndef BLE_ADVDATA_H__
+#define BLE_ADVDATA_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include "nrf_ble.h"
+#include "app_util.h"
+
+
+#define ADV_LENGTH_FIELD_SIZE              1UL                                 /**< Advertising Data and Scan Response format contains 1 octet for the length. */
+#define ADV_AD_TYPE_FIELD_SIZE             1UL                                 /**< Advertising Data and Scan Response format contains 1 octet for the AD type. */
+#define ADV_AD_DATA_OFFSET                 (ADV_LENGTH_FIELD_SIZE + \
+                                            ADV_AD_TYPE_FIELD_SIZE)            /**< Offset for the AD data field of the Advertising Data and Scan Response format. */
+#define AD_TYPE_TK_VALUE_DATA_SIZE         (sizeof(ble_advdata_tk_value_t))    /**< Data size (in octets) of the Security Manager TK value AD type. */
+#define AD_TYPE_TK_VALUE_SIZE              (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_TK_VALUE_DATA_SIZE)        /**< Size (in octets) of the Security Manager TK value AD type. */
+#define AD_TYPE_LE_ROLE_DATA_SIZE          1UL                                 /**< Data size (in octets) of the LE Bluetooth Device Address AD type. */
+#define AD_TYPE_LE_ROLE_SIZE               (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_LE_ROLE_DATA_SIZE)         /**< Size (in octets) of the LE Bluetooth Device Address AD type. */
+#define AD_TYPE_BLE_DEVICE_ADDR_TYPE_SIZE  1UL                                 /**< Data size (in octets) of the Address type of the LE Bluetooth Device Address AD type. */
+#define AD_TYPE_BLE_DEVICE_ADDR_DATA_SIZE  (BLE_GAP_ADDR_LEN + \
+                                            AD_TYPE_BLE_DEVICE_ADDR_TYPE_SIZE) /**< Data size (in octets) of the LE Bluetooth Device Address AD type. */
+#define AD_TYPE_BLE_DEVICE_ADDR_SIZE       (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_BLE_DEVICE_ADDR_DATA_SIZE) /**< Size (in octets) of the LE Bluetooth Device Address AD type. */
+#define AD_TYPE_APPEARANCE_DATA_SIZE       2UL                                 /**< Data size (in octets) of the Appearance AD type. */
+#define AD_TYPE_APPEARANCE_SIZE            (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_APPEARANCE_DATA_SIZE)      /**< Size (in octets) of the Appearance AD type. */
+#define AD_TYPE_FLAGS_DATA_SIZE            1UL                                 /**< Data size (in octets) of the Flags AD type. */
+#define AD_TYPE_FLAGS_SIZE                 (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_FLAGS_DATA_SIZE)           /**< Size (in octets) of the Flags AD type. */
+#define AD_TYPE_TX_POWER_LEVEL_DATA_SIZE   1UL                                 /**< Data size (in octets) of the TX Power Level AD type. */
+#define AD_TYPE_TX_POWER_LEVEL_SIZE        (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_TX_POWER_LEVEL_DATA_SIZE)  /**< Size (in octets) of the TX Power Level AD type. */
+#define AD_TYPE_CONN_INT_DATA_SIZE         4UL                                 /**< Data size (in octets) of the Slave Connection Interval Range AD type. */
+#define AD_TYPE_CONN_INT_SIZE              (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_CONN_INT_DATA_SIZE)        /**< Data size (in octets) of the Slave Connection Interval Range AD type. */
+#define AD_TYPE_MANUF_SPEC_DATA_ID_SIZE    2UL                                 /**< Size (in octets) of the Company Identifier Code, which is a part of the Manufacturer Specific Data AD type. */
+#define AD_TYPE_SERV_DATA_16BIT_UUID_SIZE  2UL                                 /**< Size (in octets) of the 16-bit UUID, which is a part of the Service Data AD type. */
+#define AD_TYPE_OOB_FLAGS_DATA_SIZE        1UL                                 /**< Data size (in octets) of the Security Manager OOB Flags AD type. */
+#define AD_TYPE_OOB_FLAGS_SIZE             (ADV_AD_DATA_OFFSET + \
+                                            AD_TYPE_OOB_FLAGS_DATA_SIZE)       /**< Size (in octets) of the Security Manager OOB Flags AD type. */
+
+#define AD_TYPE_SEC_MGR_OOB_FLAG_SET                   1U                      /**< Security Manager OOB Flag set. Flag selection is done using _POS defines */
+#define AD_TYPE_SEC_MGR_OOB_FLAG_CLEAR                 0U                      /**< Security Manager OOB Flag clear. Flag selection is done using _POS defines */
+#define AD_TYPE_SEC_MGR_OOB_FLAG_OOB_DATA_PRESENT_POS  0UL                     /**< Security Manager OOB Data Present Flag position. */
+#define AD_TYPE_SEC_MGR_OOB_FLAG_OOB_LE_SUPPORTED_POS  1UL                     /**< Security Manager OOB Low Energy Supported Flag position. */
+#define AD_TYPE_SEC_MGR_OOB_FLAG_SIM_LE_AND_EP_POS     2UL                     /**< Security Manager OOB Simultaneous LE and BR/EDR to Same Device Capable Flag position. */
+#define AD_TYPE_SEC_MGR_OOB_ADDRESS_TYPE_PUBLIC        0UL                     /**< Security Manager OOB Public Address type. */
+#define AD_TYPE_SEC_MGR_OOB_ADDRESS_TYPE_RANDOM        1UL                     /**< Security Manager OOB Random Address type. */
+#define AD_TYPE_SEC_MGR_OOB_FLAG_ADDRESS_TYPE_POS      3UL                     /**< Security Manager OOB Address type Flag (0 = Public Address, 1 = Random Address) position. */
+
+
+/**@brief Security Manager TK value. */
+typedef struct
+{
+  uint8_t tk[BLE_GAP_SEC_KEY_LEN];   /**< Array containing TK value. */
+} ble_advdata_tk_value_t;
+
+/**@brief Advertising data LE Role types. This enumeration contains the options available for the LE role inside
+ *        the advertising data. */
+typedef enum
+{
+    BLE_ADVDATA_ROLE_NOT_PRESENT = 0,                                 /**< LE Role AD structure not present. */
+    BLE_ADVDATA_ROLE_ONLY_PERIPH,                                     /**< Only Peripheral Role supported. */
+    BLE_ADVDATA_ROLE_ONLY_CENTRAL,                                    /**< Only Central Role supported. */
+    BLE_ADVDATA_ROLE_BOTH_PERIPH_PREFERRED,                           /**< Peripheral and Central Role supported. Peripheral Role preferred for connection establishment. */
+    BLE_ADVDATA_ROLE_BOTH_CENTRAL_PREFERRED                           /**< Peripheral and Central Role supported. Central Role preferred for connection establishment */
+} ble_advdata_le_role_t;
+
+/**@brief Advertising data name type. This enumeration contains the options available for the device name inside
+ *        the advertising data. */
+typedef enum
+{
+    BLE_ADVDATA_NO_NAME,                                              /**< Include no device name in advertising data. */
+    BLE_ADVDATA_SHORT_NAME,                                           /**< Include short device name in advertising data. */
+    BLE_ADVDATA_FULL_NAME                                             /**< Include full device name in advertising data. */
+} ble_advdata_name_type_t;
+
+/**@brief UUID list type. */
+typedef struct
+{
+    uint16_t                     uuid_cnt;                            /**< Number of UUID entries. */
+    ble_uuid_t *                 p_uuids;                             /**< Pointer to UUID array entries. */
+} ble_advdata_uuid_list_t;
+
+/**@brief Connection interval range structure. */
+typedef struct
+{
+    uint16_t                     min_conn_interval;                   /**< Minimum connection interval, in units of 1.25 ms, range 6 to 3200 (7.5 ms to 4 s). */
+    uint16_t                     max_conn_interval;                   /**< Maximum connection interval, in units of 1.25 ms, range 6 to 3200 (7.5 ms to 4 s). The value 0xFFFF indicates no specific maximum. */
+} ble_advdata_conn_int_t;
+
+/**@brief Manufacturer specific data structure. */
+typedef struct
+{
+    uint16_t                     company_identifier;                  /**< Company identifier code. */
+    uint8_array_t                data;                                /**< Additional manufacturer specific data. */
+} ble_advdata_manuf_data_t;
+
+/**@brief Service data structure. */
+typedef struct
+{
+    uint16_t                     service_uuid;                        /**< Service UUID. */
+    uint8_array_t                data;                                /**< Additional service data. */
+} ble_advdata_service_data_t;
+
+/**@brief Advertising data structure. This structure contains all options and data needed for encoding and
+ *        setting the advertising data. */
+typedef struct
+{
+    ble_advdata_name_type_t      name_type;                           /**< Type of device name. */
+    uint8_t                      short_name_len;                      /**< Length of short device name (if short type is specified). */
+    bool                         include_appearance;                  /**< Determines if Appearance shall be included. */
+    uint8_t                      flags;                               /**< Advertising data Flags field. */
+    int8_t *                     p_tx_power_level;                    /**< TX Power Level field. */
+    ble_advdata_uuid_list_t      uuids_more_available;                /**< List of UUIDs in the 'More Available' list. */
+    ble_advdata_uuid_list_t      uuids_complete;                      /**< List of UUIDs in the 'Complete' list. */
+    ble_advdata_uuid_list_t      uuids_solicited;                     /**< List of solicited UUIDs. */
+    ble_advdata_conn_int_t *     p_slave_conn_int;                    /**< Slave Connection Interval Range. */
+    ble_advdata_manuf_data_t *   p_manuf_specific_data;               /**< Manufacturer specific data. */
+    ble_advdata_service_data_t * p_service_data_array;                /**< Array of Service data structures. */
+    uint8_t                      service_data_count;                  /**< Number of Service data structures. */
+    bool                         include_ble_device_addr;             /**< Determines if LE Bluetooth Device Address shall be included. */
+    ble_advdata_le_role_t        le_role;                             /**< LE Role field. Included when different from @ref BLE_ADVDATA_ROLE_NOT_PRESENT.*/
+    ble_advdata_tk_value_t *     p_tk_value;                          /**< Security Manager TK value field. Included when different from NULL.*/
+    uint8_t *                    p_sec_mgr_oob_flags;                 /**< Security Manager Out Of Band Flags field. Included when different from NULL.*/
+} ble_advdata_t;
+
+/**@brief Function for encoding data in the Advertising and Scan Response data format
+ *        (AD structures).
+ *
+ * @details This function encodes data into the Advertising and Scan Response data format
+ *          (AD structures) based on the selections in the supplied structures. This function can be used to
+ *          create a payload of Advertising packet or Scan Response packet, or a payload of NFC
+ *          message intended for initiating the Out-of-Band pairing.
+ *
+ * @param[in]      p_advdata       Pointer to the structure for specifying the content of encoded data.
+ * @param[out]     p_encoded_data  Pointer to the buffer where encoded data will be returned.
+ * @param[in,out]  p_len           \c in: Size of \p p_encoded_data buffer.
+ *                                 \c out: Length of encoded data.
+ *
+ * @retval NRF_SUCCESS             If the operation was successful.
+ * @retval NRF_ERROR_INVALID_PARAM If the operation failed because a wrong parameter was provided in \p p_advdata.
+ * @retval NRF_ERROR_DATA_SIZE     If the operation failed because not all the requested data could fit into the
+ *                                 provided buffer or some encoded AD structure is too long and its
+ *                                 length cannot be encoded with one octet.
+ *
+ * @warning This API may override the application's request to use the long name and use a short name
+ * instead. This truncation will occur in case the long name does not fit the provided buffer size.
+ * The application can specify a preferred short name length if truncation is required.
+ * For example, if the complete device name is ABCD_HRMonitor, the application can specify the short name
+ * length to be 8, so that the short device name appears as ABCD_HRM instead of ABCD_HRMo or ABCD_HRMoni
+ * if the available size for the short name is 9 or 12 respectively, to have a more appropriate short name.
+ * However, it should be noted that this is just a preference that the application can specify, and
+ * if the preference is too large to fit in the provided buffer, the name can be truncated further.
+ */
+uint32_t adv_data_encode(ble_advdata_t const * const p_advdata,
+                         uint8_t             * const p_encoded_data,
+                         uint16_t            * const p_len);
+
+/**@brief Function for encoding and setting the advertising data and/or scan response data.
+ *
+ * @details This function encodes advertising data and/or scan response data based on the selections
+ *          in the supplied structures, and passes the encoded data to the stack.
+ *
+ * @param[in]   p_advdata   Structure for specifying the content of the advertising data.
+ *                          Set to NULL if advertising data is not to be set.
+ * @param[in]   p_srdata    Structure for specifying the content of the scan response data.
+ *                          Set to NULL if scan response data is not to be set.
+ *
+ * @retval NRF_SUCCESS             If the operation was successful.
+ * @retval NRF_ERROR_INVALID_PARAM If the operation failed because a wrong parameter was provided in \p p_advdata.
+ * @retval NRF_ERROR_DATA_SIZE     If the operation failed because not all the requested data could fit into the
+ *                                 advertising packet. The maximum size of the advertisement packet
+ *                                 is @ref BLE_GAP_ADV_MAX_SIZE.
+ *
+ * @warning This API may override the application's request to use the long name and use a short name
+ * instead. This truncation will occur in case the long name does not fit the provided buffer size.
+ * The application can specify a preferred short name length if truncation is required.
+ * For example, if the complete device name is ABCD_HRMonitor, the application can specify the short name
+ * length to be 8, so that the short device name appears as ABCD_HRM instead of ABCD_HRMo or ABCD_HRMoni
+ * if the available size for the short name is 9 or 12 respectively, to have a more appropriate short name.
+ * However, it should be noted that this is just a preference that the application can specify, and
+ * if the preference is too large to fit in the provided buffer, the name can be truncated further.
+ */
+uint32_t ble_advdata_set(const ble_advdata_t * p_advdata, const ble_advdata_t * p_srdata);
+
+#endif // BLE_ADVDATA_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,386 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_conn_params.h"
+#include <stdlib.h>
+#include "nordic_common.h"
+#include "ble_hci.h"
+#include "ble_srv_common.h"
+#include "app_util.h"
+
+#ifdef USE_APP_TIMER
+#include "app_timer.h"
+#else
+    #ifdef YOTTA_CFG_MBED_OS
+        #include "mbed-drivers/mbed.h"
+    #else
+        #include "mbed.h"
+    #endif
+#endif
+
+static ble_conn_params_init_t m_conn_params_config;     /**< Configuration as specified by the application. */
+static ble_gap_conn_params_t  m_preferred_conn_params;  /**< Connection parameters preferred by the application. */
+static uint8_t                m_update_count;           /**< Number of Connection Parameter Update messages that has currently been sent. */
+static uint16_t               m_conn_handle;            /**< Current connection handle. */
+static ble_gap_conn_params_t  m_current_conn_params;    /**< Connection parameters received in the most recent Connect event. */
+#ifdef USE_APP_TIMER
+static app_timer_id_t         m_conn_params_timer_id;   /**< Connection parameters timer. */
+#else
+static Ticker                 m_conn_params_timer;
+#endif
+
+static bool m_change_param = false;
+
+static bool is_conn_params_ok(ble_gap_conn_params_t * p_conn_params)
+{
+    // Check if interval is within the acceptable range.
+    // NOTE: Using max_conn_interval in the received event data because this contains
+    //       the client's connection interval.
+    if (
+        (p_conn_params->max_conn_interval >= m_preferred_conn_params.min_conn_interval)
+        && 
+        (p_conn_params->max_conn_interval <= m_preferred_conn_params.max_conn_interval)
+       )
+    {
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+}
+
+
+#ifdef USE_APP_TIMER
+static void update_timeout_handler(void * p_context)
+{
+    UNUSED_PARAMETER(p_context);
+
+#else /* #if !USE_APP_TIMER */
+static void update_timeout_handler(void)
+{
+    m_conn_params_timer.detach(); /* this is supposed to be a single-shot timer callback */
+#endif /* #if !USE_APP_TIMER */
+    if (m_conn_handle != BLE_CONN_HANDLE_INVALID)
+    {
+        // Check if we have reached the maximum number of attempts
+        m_update_count++;
+        if (m_update_count <= m_conn_params_config.max_conn_params_update_count)
+        {
+            uint32_t err_code;
+
+            // Parameters are not ok, send connection parameters update request.
+            err_code = sd_ble_gap_conn_param_update(m_conn_handle, &m_preferred_conn_params);
+            if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL))
+            {
+                m_conn_params_config.error_handler(err_code);
+            }
+        }
+        else
+        {
+            m_update_count = 0;
+
+            // Negotiation failed, disconnect automatically if this has been configured
+            if (m_conn_params_config.disconnect_on_fail)
+            {
+                uint32_t err_code;
+
+                err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
+                if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL))
+                {
+                    m_conn_params_config.error_handler(err_code);
+                }
+            }
+
+            // Notify the application that the procedure has failed
+            if (m_conn_params_config.evt_handler != NULL)
+            {
+                ble_conn_params_evt_t evt;
+
+                evt.evt_type = BLE_CONN_PARAMS_EVT_FAILED;
+                m_conn_params_config.evt_handler(&evt);
+            }
+        }
+    }
+}
+
+
+uint32_t ble_conn_params_init(const ble_conn_params_init_t * p_init)
+{
+    uint32_t err_code;
+
+    m_conn_params_config = *p_init;
+    m_change_param = false;
+    if (p_init->p_conn_params != NULL)
+    {
+        m_preferred_conn_params = *p_init->p_conn_params;
+
+        // Set the connection params in stack
+        err_code = sd_ble_gap_ppcp_set(&m_preferred_conn_params);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+    else
+    {
+        // Fetch the connection params from stack
+        err_code = sd_ble_gap_ppcp_get(&m_preferred_conn_params);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    m_conn_handle  = BLE_CONN_HANDLE_INVALID;
+    m_update_count = 0;
+
+#ifdef USE_APP_TIMER
+    return app_timer_create(&m_conn_params_timer_id,
+                            APP_TIMER_MODE_SINGLE_SHOT,
+                            update_timeout_handler);
+#else
+    return NRF_SUCCESS;
+#endif
+}
+
+
+uint32_t ble_conn_params_stop(void)
+{
+#ifdef USE_APP_TIMER
+    return app_timer_stop(m_conn_params_timer_id);
+#else /* #if !USE_APP_TIMER */
+    m_conn_params_timer.detach();
+    return NRF_SUCCESS;
+#endif /* #if !USE_APP_TIMER */
+}
+
+
+static void conn_params_negotiation(void)
+{
+    // Start negotiation if the received connection parameters are not acceptable
+    if (!is_conn_params_ok(&m_current_conn_params))
+    {
+#ifdef USE_APP_TIMER
+        uint32_t err_code;
+#endif
+        uint32_t timeout_ticks;
+
+        if (m_change_param)
+        {
+            // Notify the application that the procedure has failed
+            if (m_conn_params_config.evt_handler != NULL)
+            {
+                ble_conn_params_evt_t evt;
+
+                evt.evt_type = BLE_CONN_PARAMS_EVT_FAILED;
+                m_conn_params_config.evt_handler(&evt);
+            }
+        }
+        else
+        {
+            if (m_update_count == 0)
+            {
+                // First connection parameter update
+                timeout_ticks = m_conn_params_config.first_conn_params_update_delay;
+            }
+            else
+            {
+                timeout_ticks = m_conn_params_config.next_conn_params_update_delay;
+            }
+
+#ifdef USE_APP_TIMER
+            err_code = app_timer_start(m_conn_params_timer_id, timeout_ticks, NULL);
+            if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL))
+            {
+                m_conn_params_config.error_handler(err_code);
+            }
+#else
+            m_conn_params_timer.attach(update_timeout_handler, timeout_ticks / 32768);
+#endif
+        }
+    }
+    else
+    {
+        // Notify the application that the procedure has succeded
+        if (m_conn_params_config.evt_handler != NULL)
+        {
+            ble_conn_params_evt_t evt;
+
+            evt.evt_type = BLE_CONN_PARAMS_EVT_SUCCEEDED;
+            m_conn_params_config.evt_handler(&evt);
+        }
+    }
+    m_change_param = false;
+}
+
+
+static void on_connect(ble_evt_t * p_ble_evt)
+{
+    // Save connection parameters
+    m_conn_handle         = p_ble_evt->evt.gap_evt.conn_handle;
+    m_current_conn_params = p_ble_evt->evt.gap_evt.params.connected.conn_params;
+    m_update_count        = 0;  // Connection parameter negotiation should re-start every connection
+
+    // Check if we shall handle negotiation on connect
+    if (m_conn_params_config.start_on_notify_cccd_handle == BLE_GATT_HANDLE_INVALID)
+    {
+        conn_params_negotiation();
+    }
+}
+
+
+static void on_disconnect(ble_evt_t * p_ble_evt)
+{
+#ifdef USE_APP_TIMER
+    uint32_t err_code;
+#endif
+
+    m_conn_handle = BLE_CONN_HANDLE_INVALID;
+
+    // Stop timer if running
+    m_update_count = 0; // Connection parameters updates should happen during every connection
+
+#ifdef USE_APP_TIMER
+    err_code = app_timer_stop(m_conn_params_timer_id);
+    if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL))
+    {
+        m_conn_params_config.error_handler(err_code);
+    }
+#else
+    m_conn_params_timer.detach();
+#endif
+}
+
+
+static void on_write(ble_evt_t * p_ble_evt)
+{
+    ble_gatts_evt_write_t * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write;
+
+    // Check if this the correct CCCD
+    if (
+        (p_evt_write->handle == m_conn_params_config.start_on_notify_cccd_handle)
+        &&
+        (p_evt_write->len == 2)
+       )
+    {
+        // Check if this is a 'start notification'
+        if (ble_srv_is_notification_enabled(p_evt_write->data))
+        {
+            // Do connection parameter negotiation if necessary
+            conn_params_negotiation();
+        }
+        else
+        {
+#ifdef USE_APP_TIMER
+            uint32_t err_code;
+
+            // Stop timer if running
+            err_code = app_timer_stop(m_conn_params_timer_id);
+            if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL))
+            {
+                m_conn_params_config.error_handler(err_code);
+            }
+#else /* #if !USE_APP_TIMER */
+            m_conn_params_timer.detach();
+#endif /* #if !USE_APP_TIMER */
+        }
+    }
+}
+
+
+static void on_conn_params_update(ble_evt_t * p_ble_evt)
+{
+    // Copy the parameters
+    m_current_conn_params = p_ble_evt->evt.gap_evt.params.conn_param_update.conn_params;
+
+    conn_params_negotiation();
+}
+
+
+void ble_conn_params_on_ble_evt(ble_evt_t * p_ble_evt)
+{
+    switch (p_ble_evt->header.evt_id)
+    {
+        case BLE_GAP_EVT_CONNECTED:
+            on_connect(p_ble_evt);
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+            on_disconnect(p_ble_evt);
+            break;
+
+        case BLE_GATTS_EVT_WRITE:
+            on_write(p_ble_evt);
+            break;
+
+        case BLE_GAP_EVT_CONN_PARAM_UPDATE:
+            on_conn_params_update(p_ble_evt);
+            break;
+
+        default:
+            // No implementation needed.
+            break;
+    }
+}
+
+
+uint32_t ble_conn_params_change_conn_params(ble_gap_conn_params_t * new_params)
+{
+    uint32_t err_code;
+
+    m_preferred_conn_params = *new_params;
+    // Set the connection params in stack
+    err_code = sd_ble_gap_ppcp_set(&m_preferred_conn_params);
+    if (err_code == NRF_SUCCESS)
+    {
+        if (!is_conn_params_ok(&m_current_conn_params))
+        {
+            m_change_param = true;
+            err_code = sd_ble_gap_conn_param_update(m_conn_handle, &m_preferred_conn_params);
+            m_update_count = 1;
+        }
+        else
+        {
+            // Notify the application that the procedure has succeded
+            if (m_conn_params_config.evt_handler != NULL)
+            {
+                ble_conn_params_evt_t evt;
+
+                evt.evt_type = BLE_CONN_PARAMS_EVT_SUCCEEDED;
+                m_conn_params_config.evt_handler(&evt);
+            }
+            err_code = NRF_SUCCESS;
+        }
+    }
+    return err_code;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_params.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup ble_sdk_lib_conn_params Connection Parameters Negotiation
+ * @{
+ * @ingroup ble_sdk_lib
+ * @brief Module for initiating and executing a connection parameters negotiation procedure.
+ */
+
+#ifndef BLE_CONN_PARAMS_H__
+#define BLE_CONN_PARAMS_H__
+
+#include <stdint.h>
+#include "nrf_ble.h"
+#include "ble_srv_common.h"
+
+/**@brief Connection Parameters Module event type. */
+typedef enum
+{
+    BLE_CONN_PARAMS_EVT_FAILED   ,                                  /**< Negotiation procedure failed. */
+    BLE_CONN_PARAMS_EVT_SUCCEEDED                                   /**< Negotiation procedure succeeded. */
+} ble_conn_params_evt_type_t;
+
+/**@brief Connection Parameters Module event. */
+typedef struct
+{
+    ble_conn_params_evt_type_t evt_type;                            /**< Type of event. */
+} ble_conn_params_evt_t;
+
+/**@brief Connection Parameters Module event handler type. */
+typedef void (*ble_conn_params_evt_handler_t) (ble_conn_params_evt_t * p_evt);
+
+/**@brief Connection Parameters Module init structure. This contains all options and data needed for
+ *        initialization of the connection parameters negotiation module. */
+typedef struct
+{
+    ble_gap_conn_params_t *       p_conn_params;                    /**< Pointer to the connection parameters desired by the application. When calling ble_conn_params_init, if this parameter is set to NULL, the connection parameters will be fetched from host. */
+    uint32_t                      first_conn_params_update_delay;   /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (in number of timer ticks). */
+    uint32_t                      next_conn_params_update_delay;    /**< Time between each call to sd_ble_gap_conn_param_update after the first (in number of timer ticks). Recommended value 30 seconds as per BLUETOOTH SPECIFICATION Version 4.0. */
+    uint8_t                       max_conn_params_update_count;     /**< Number of attempts before giving up the negotiation. */
+    uint16_t                      start_on_notify_cccd_handle;      /**< If procedure is to be started when notification is started, set this to the handle of the corresponding CCCD. Set to BLE_GATT_HANDLE_INVALID if procedure is to be started on connect event. */
+    bool                          disconnect_on_fail;               /**< Set to TRUE if a failed connection parameters update shall cause an automatic disconnection, set to FALSE otherwise. */
+    ble_conn_params_evt_handler_t evt_handler;                      /**< Event handler to be called for handling events in the Connection Parameters. */
+    ble_srv_error_handler_t       error_handler;                    /**< Function to be called in case of an error. */
+} ble_conn_params_init_t;
+
+
+/**@brief Function for initializing the Connection Parameters module.
+ *
+ * @note If the negotiation procedure should be triggered when notification/indication of 
+ *       any characteristic is enabled by the peer, then this function must be called after
+ *       having initialized the services.
+ *
+ * @param[in]   p_init  This contains information needed to initialize this module.
+ *
+ * @return      NRF_SUCCESS on successful initialization, otherwise an error code.
+ */
+uint32_t ble_conn_params_init(const ble_conn_params_init_t * p_init);
+
+/**@brief Function for stopping the Connection Parameters module.
+ *
+ * @details This function is intended to be used by the application to clean up the connection
+ *          parameters update module. This will stop the connection parameters update timer if
+ *          running, thereby preventing any impending connection parameters update procedure. This
+ *          function must be called by the application when it needs to clean itself up (for
+ *          example, before disabling the bluetooth SoftDevice) so that an unwanted timer expiry
+ *          event can be avoided.
+ *
+ * @return      NRF_SUCCESS on successful initialization, otherwise an error code.
+ */
+uint32_t ble_conn_params_stop(void);
+
+/**@brief Function for changing the current connection parameters to a new set.
+ *
+ *  @details Use this function to change the connection parameters to a new set of parameter 
+ *       (ie different from the ones given at init of the module).
+ *       This function is usefull for scenario where most of the time the application
+ *       needs a relatively big connection interval, and just sometimes, for a temporary
+ *       period requires shorter connection interval, for example to transfer a higher
+ *       amount of data.
+ *       If the given parameters does not match the current connection's parameters
+ *       this function initiates a new negotiation.
+ *
+ * @param[in]   new_params  This contains the new connections parameters to setup.
+ *
+ * @return      NRF_SUCCESS on successful initialization, otherwise an error code.
+ */
+uint32_t ble_conn_params_change_conn_params(ble_gap_conn_params_t *new_params);
+
+/**@brief Function for handling the Application's BLE Stack events.
+ *
+ * @details Handles all events from the BLE stack that are of interest to this module.
+ *
+ * @param[in]   p_ble_evt  The event received from the BLE stack.
+ */
+void ble_conn_params_on_ble_evt(ble_evt_t * p_ble_evt);
+
+#endif // BLE_CONN_PARAMS_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_conn_state.h"
+#include <stdbool.h>
+#include <stdint.h>
+#include <string.h>
+#include "nrf_ble.h"
+#include "sdk_mapped_flags.h"
+#include "app_error.h"
+
+
+#if defined(__CC_ARM)
+  #pragma push
+  #pragma anon_unions
+#elif defined(__ICCARM__)
+  #pragma language=extended
+#elif defined(__GNUC__)
+  /* anonymous unions are enabled by default */
+#endif
+
+
+#define BLE_CONN_STATE_N_DEFAULT_FLAGS 5                                                       /**< The number of flags kept for each connection, excluding user flags. */
+#define BLE_CONN_STATE_N_FLAGS (BLE_CONN_STATE_N_DEFAULT_FLAGS + BLE_CONN_STATE_N_USER_FLAGS)  /**< The number of flags kept for each connection, including user flags. */
+
+
+/**@brief Structure containing all the flag collections maintained by the Connection State module.
+ */
+typedef struct
+{
+    sdk_mapped_flags_t valid_flags;                                 /**< Flags indicating which connection handles are valid. */
+    sdk_mapped_flags_t connected_flags;                             /**< Flags indicating which connections are connected, since disconnected connection handles will not immediately be invalidated. */
+    sdk_mapped_flags_t central_flags;                               /**< Flags indicating in which connections the local device is the central. */
+    sdk_mapped_flags_t encrypted_flags;                             /**< Flags indicating which connections are encrypted. */
+    sdk_mapped_flags_t mitm_protected_flags;                        /**< Flags indicating which connections have encryption with protection from man-in-the-middle attacks. */
+    sdk_mapped_flags_t user_flags[BLE_CONN_STATE_N_USER_FLAGS];     /**< Flags that can be reserved by the user. The flags will be cleared when a connection is invalidated, otherwise, the user is wholly responsible for the flag states. */
+} ble_conn_state_flag_collections_t;
+
+
+/**@brief Structure containing the internal state of the Connection State module.
+ */
+typedef struct
+{
+    uint16_t           acquired_flags;                              /**< Bitmap for keeping track of which user flags have been acquired. */
+    uint16_t           valid_conn_handles[SDK_MAPPED_FLAGS_N_KEYS]; /**< List of connection handles used as keys for the sdk_mapped_flags module. */
+    union
+    {
+        ble_conn_state_flag_collections_t flags;                              /**< Flag collections kept by the Connection State module. */
+        sdk_mapped_flags_t                flag_array[BLE_CONN_STATE_N_FLAGS]; /**< Flag collections as array to allow use of @ref sdk_mapped_flags_bulk_update_by_key() when setting all flags. */
+    };
+} ble_conn_state_t;
+
+
+#if defined(__CC_ARM)
+  #pragma pop
+#elif defined(__ICCARM__)
+  /* leave anonymous unions enabled */
+#elif defined(__GNUC__)
+  /* anonymous unions are enabled by default */
+#endif
+
+
+static ble_conn_state_t m_bcs = {0}; /**< Instantiation of the internal state. */
+
+
+/**@brief Function for resetting all internal memory to the values it had at initialization.
+ */
+void bcs_internal_state_reset(void)
+{
+    memset( &m_bcs, 0, sizeof(ble_conn_state_t) );
+}
+
+
+/**@brief Function for activating a connection record.
+ *
+ * @param p_record     The record to activate.
+ * @param conn_handle  The connection handle to copy into the record.
+ * @param role         The role of the connection.
+ *
+ * @return whether the record was activated successfully.
+ */
+static bool record_activate(uint16_t conn_handle)
+{
+    uint16_t available_index = sdk_mapped_flags_first_key_index_get(~m_bcs.flags.valid_flags);
+
+    if (available_index != SDK_MAPPED_FLAGS_INVALID_INDEX)
+    {
+        m_bcs.valid_conn_handles[available_index] = conn_handle;
+        sdk_mapped_flags_update_by_key(m_bcs.valid_conn_handles,
+                                      &m_bcs.flags.connected_flags,
+                                       conn_handle,
+                                       1);
+        sdk_mapped_flags_update_by_key(m_bcs.valid_conn_handles,
+                                      &m_bcs.flags.valid_flags,
+                                       conn_handle,
+                                       1);
+
+        return true;
+    }
+
+    return false;
+}
+
+
+/**@brief Function for marking a connection record as invalid and resetting the values.
+ *
+ * @param p_record  The record to invalidate.
+ */
+static void record_invalidate(uint16_t conn_handle)
+{
+    sdk_mapped_flags_bulk_update_by_key(m_bcs.valid_conn_handles,
+                                        m_bcs.flag_array,
+                                        BLE_CONN_STATE_N_FLAGS,
+                                        conn_handle,
+                                        0);
+}
+
+
+/**@brief Function for marking a connection as disconnected. See @ref BLE_CONN_STATUS_DISCONNECTED.
+ *
+ * @param p_record   The record of the connection to set as disconnected.
+ */
+static void record_set_disconnected(uint16_t conn_handle)
+{
+    sdk_mapped_flags_update_by_key(m_bcs.valid_conn_handles,
+                                  &m_bcs.flags.connected_flags,
+                                   conn_handle,
+                                   0);
+}
+
+
+/**@brief Function for invalidating records with a @ref BLE_CONN_STATUS_DISCONNECTED
+ *        connection status
+ */
+static void record_purge_disconnected()
+{
+    sdk_mapped_flags_key_list_t disconnected_list;
+
+    disconnected_list = sdk_mapped_flags_key_list_get(
+                                   m_bcs.valid_conn_handles,
+                                 (~m_bcs.flags.connected_flags) & (m_bcs.flags.valid_flags));
+
+    for (int i = 0; i < disconnected_list.len; i++)
+    {
+        record_invalidate(disconnected_list.flag_keys[i]);
+    }
+}
+
+
+/**@brief Function for checking if a user flag has been acquired.
+ *
+ * @param[in]  flag_id  Which flag to check.
+ *
+ * @return  Whether the flag has been acquired.
+ */
+static bool user_flag_is_acquired(ble_conn_state_user_flag_id_t flag_id)
+{
+    return ((m_bcs.acquired_flags & (1 << flag_id)) != 0);
+}
+
+
+/**@brief Function for marking a user flag as acquired.
+ *
+ * @param[in]  flag_id  Which flag to mark.
+ */
+static void user_flag_acquire(ble_conn_state_user_flag_id_t flag_id)
+{
+    m_bcs.acquired_flags |= (1 << flag_id);
+}
+
+
+void ble_conn_state_init(void)
+{
+    bcs_internal_state_reset();
+}
+
+
+void ble_conn_state_on_ble_evt(ble_evt_t * p_ble_evt)
+{
+    switch (p_ble_evt->header.evt_id)
+    {
+        case BLE_GAP_EVT_CONNECTED:
+            record_purge_disconnected();
+
+            if ( !record_activate(p_ble_evt->evt.gap_evt.conn_handle) )
+            {
+                // No more records available. Should not happen.
+                APP_ERROR_HANDLER(NRF_ERROR_NO_MEM);
+            }
+            else
+            {
+#if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110)
+                bool is_central = false;
+#elif defined(TARGET_MCU_NRF51_16K_S120) || defined(TARGET_MCU_NRF51_32K_S120)
+                bool is_central = true;
+#else
+                bool is_central =
+                        (p_ble_evt->evt.gap_evt.params.connected.role == BLE_GAP_ROLE_CENTRAL);
+#endif
+
+                sdk_mapped_flags_update_by_key(m_bcs.valid_conn_handles,
+                                              &m_bcs.flags.central_flags,
+                                               p_ble_evt->evt.gap_evt.conn_handle,
+                                               is_central);
+            }
+
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+            record_set_disconnected(p_ble_evt->evt.gap_evt.conn_handle);
+            break;
+
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            sdk_mapped_flags_update_by_key(
+                          m_bcs.valid_conn_handles,
+                         &m_bcs.flags.encrypted_flags,
+                          p_ble_evt->evt.gap_evt.conn_handle,
+                         (p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv > 1));
+            sdk_mapped_flags_update_by_key(
+                          m_bcs.valid_conn_handles,
+                         &m_bcs.flags.mitm_protected_flags,
+                          p_ble_evt->evt.gap_evt.conn_handle,
+                         (p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv > 2));
+            break;
+    }
+}
+
+
+bool ble_conn_state_valid(uint16_t conn_handle)
+{
+    return sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                       m_bcs.flags.valid_flags,
+                                       conn_handle);
+}
+
+
+uint8_t ble_conn_state_role(uint16_t conn_handle)
+{
+    uint8_t role = BLE_GAP_ROLE_INVALID;
+
+    if ( sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles, m_bcs.flags.valid_flags, conn_handle) )
+    {
+        bool central = sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                                   m_bcs.flags.central_flags,
+                                                   conn_handle);
+
+        role = central ? BLE_GAP_ROLE_CENTRAL : BLE_GAP_ROLE_PERIPH;
+    }
+
+    return role;
+}
+
+
+ble_conn_state_status_t ble_conn_state_status(uint16_t conn_handle)
+{
+    ble_conn_state_status_t conn_status = BLE_CONN_STATUS_INVALID;
+    bool valid = sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                             m_bcs.flags.valid_flags,
+                                             conn_handle);
+
+    if (valid)
+    {
+        bool connected = sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                                     m_bcs.flags.connected_flags,
+                                                     conn_handle);
+
+        conn_status = connected ? BLE_CONN_STATUS_CONNECTED : BLE_CONN_STATUS_DISCONNECTED;
+    }
+
+    return conn_status;
+}
+
+
+bool ble_conn_state_encrypted(uint16_t conn_handle)
+{
+    return sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                       m_bcs.flags.encrypted_flags,
+                                       conn_handle);
+}
+
+
+bool ble_conn_state_mitm_protected(uint16_t conn_handle)
+{
+    return sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                       m_bcs.flags.mitm_protected_flags,
+                                       conn_handle);
+}
+
+
+uint32_t ble_conn_state_n_connections(void)
+{
+    return sdk_mapped_flags_n_flags_set(m_bcs.flags.connected_flags);
+}
+
+
+uint32_t ble_conn_state_n_centrals(void)
+{
+    return sdk_mapped_flags_n_flags_set((m_bcs.flags.central_flags) & (m_bcs.flags.connected_flags));
+}
+
+
+uint32_t ble_conn_state_n_peripherals(void)
+{
+    return sdk_mapped_flags_n_flags_set((~m_bcs.flags.central_flags) & (m_bcs.flags.connected_flags));
+}
+
+
+sdk_mapped_flags_key_list_t ble_conn_state_conn_handles(void)
+{
+    return sdk_mapped_flags_key_list_get(m_bcs.valid_conn_handles, m_bcs.flags.valid_flags);
+}
+
+
+sdk_mapped_flags_key_list_t ble_conn_state_central_handles(void)
+{
+    return sdk_mapped_flags_key_list_get(m_bcs.valid_conn_handles,
+                                        (m_bcs.flags.central_flags) & (m_bcs.flags.connected_flags));
+}
+
+
+sdk_mapped_flags_key_list_t ble_conn_state_periph_handles(void)
+{
+    return sdk_mapped_flags_key_list_get(m_bcs.valid_conn_handles,
+                                        (~m_bcs.flags.central_flags) & (m_bcs.flags.connected_flags));
+}
+
+
+ble_conn_state_user_flag_id_t ble_conn_state_user_flag_acquire(void)
+{
+    for (ble_conn_state_user_flag_id_t i = BLE_CONN_STATE_USER_FLAG0;
+                                       i < BLE_CONN_STATE_N_USER_FLAGS;
+                                       i++)
+    {
+        if ( !user_flag_is_acquired(i) )
+        {
+            user_flag_acquire(i);
+            return i;
+        }
+    }
+
+    return BLE_CONN_STATE_USER_FLAG_INVALID;
+}
+
+
+bool ble_conn_state_user_flag_get(uint16_t conn_handle, ble_conn_state_user_flag_id_t flag_id)
+{
+    if (user_flag_is_acquired(flag_id))
+    {
+        return sdk_mapped_flags_get_by_key(m_bcs.valid_conn_handles,
+                                           m_bcs.flags.user_flags[flag_id],
+                                           conn_handle);
+    }
+    else
+    {
+        return false;
+    }
+}
+
+
+void ble_conn_state_user_flag_set(uint16_t                      conn_handle,
+                                  ble_conn_state_user_flag_id_t flag_id,
+                                  bool                          value)
+{
+    if (user_flag_is_acquired(flag_id))
+    {
+        sdk_mapped_flags_update_by_key(m_bcs.valid_conn_handles,
+                                      &m_bcs.flags.user_flags[flag_id],
+                                       conn_handle,
+                                       value);
+    }
+}
+
+
+sdk_mapped_flags_t ble_conn_state_user_flag_collection(ble_conn_state_user_flag_id_t flag_id)
+{
+    if ( user_flag_is_acquired(flag_id) )
+    {
+        return m_bcs.flags.user_flags[flag_id];
+    }
+    else
+    {
+        return 0;
+    }
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_conn_state.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * @file
+ *
+ * @defgroup ble_conn_state Connection state
+ * @ingroup ble_sdk_lib
+ * @{
+ * @brief Module for storing data on BLE connections.
+ *
+ * @details This module stores certain states for each connection, which can be queried by
+ *          connection handle. The module uses BLE events to keep the states updated.
+ *
+ *          In addition to the preprogrammed states, this module can also keep track of a number of
+ *          binary user states, or <i>user flags</i>. These are reset to 0 for new connections, but
+ *          otherwise not touched by this module.
+ *
+ *          This module uses the @ref sdk_mapped_flags module, with connection handles as keys and
+ *          the connection states as flags.
+ *
+ * @note A connection handle is not immediately invalidated when it is disconnected. Certain states,
+ *       such as the role, can still be queried until the next time a new connection is established
+ *       to any device.
+ *
+ *          To function properly, this module must be provided with BLE events from the SoftDevice
+ *          through the @ref ble_conn_state_on_ble_evt() function. This module should be the first
+ *          to receive BLE events if they are dispatched to multiple modules.
+ */
+
+#ifndef BLE_CONN_STATE_H__
+#define BLE_CONN_STATE_H__
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "nrf_ble.h"
+#include "sdk_mapped_flags.h"
+
+/**@brief Connection handle statuses.
+ */
+typedef enum
+{
+    BLE_CONN_STATUS_INVALID,       /**< The connection handle is invalid. */
+    BLE_CONN_STATUS_DISCONNECTED,  /**< The connection handle refers to a connection that has been disconnected, but not yet invalidated. */
+    BLE_CONN_STATUS_CONNECTED,     /**< The connection handle refers to an active connection. */
+} ble_conn_state_status_t;
+
+#define BLE_CONN_STATE_N_USER_FLAGS 16  /**< The number of available user flags. */
+
+
+/**@brief One ID for each user flag collection.
+ *
+ * @details These IDs are used to identify user flag collections in the API calls.
+ */
+typedef enum
+{
+    BLE_CONN_STATE_USER_FLAG0 = 0,
+    BLE_CONN_STATE_USER_FLAG1,
+    BLE_CONN_STATE_USER_FLAG2,
+    BLE_CONN_STATE_USER_FLAG3,
+    BLE_CONN_STATE_USER_FLAG4,
+    BLE_CONN_STATE_USER_FLAG5,
+    BLE_CONN_STATE_USER_FLAG6,
+    BLE_CONN_STATE_USER_FLAG7,
+    BLE_CONN_STATE_USER_FLAG8,
+    BLE_CONN_STATE_USER_FLAG9,
+    BLE_CONN_STATE_USER_FLAG10,
+    BLE_CONN_STATE_USER_FLAG11,
+    BLE_CONN_STATE_USER_FLAG12,
+    BLE_CONN_STATE_USER_FLAG13,
+    BLE_CONN_STATE_USER_FLAG14,
+    BLE_CONN_STATE_USER_FLAG15,
+    BLE_CONN_STATE_USER_FLAG_INVALID,
+} ble_conn_state_user_flag_id_t;
+
+
+/**
+ * @defgroup ble_conn_state_functions BLE connection state functions
+ * @{
+ */
+
+
+/**@brief Function for initializing or resetting the module.
+ *
+ * @details This function sets all states to their default, removing all records of connection handles.
+ */
+void ble_conn_state_init(void);
+
+
+/**@brief Function for providing BLE SoftDevice events to the connection state module.
+ *
+ * @param[in]  p_ble_evt    The SoftDevice event.
+ */
+void ble_conn_state_on_ble_evt(ble_evt_t * p_ble_evt);
+
+
+/**@brief Function for querying whether a connection handle represents a valid connection.
+ *
+ * @details A connection might be valid and have a BLE_CONN_STATUS_DISCONNECTED status.
+ *          Those connections are invalidated after a new connection occurs.
+ *
+ * @param[in]  conn_handle  Handle of the connection.
+ *
+ * @retval true   If conn_handle represents a valid connection, thus a connection for which
+                  we have a record.
+ * @retval false  If conn_handle is @ref BLE_GAP_ROLE_INVALID, or if it has never been recorded.
+ */
+bool ble_conn_state_valid(uint16_t conn_handle);
+
+
+/**@brief Function for querying the role of the local device in a connection.
+ *
+ * @param[in]  conn_handle  Handle of the connection to get the role for.
+ *
+ * @return  The role of the local device in the connection (see @ref BLE_GAP_ROLES).
+ *          If conn_handle is not valid, the function returns BLE_GAP_ROLE_INVALID.
+ */
+uint8_t ble_conn_state_role(uint16_t conn_handle);
+
+
+/**@brief Function for querying the status of a connection.
+ *
+ * @param[in]  conn_handle  Handle of the connection.
+ *
+ * @return  The status of the connection.
+ *          If conn_handle is not valid, the function returns BLE_CONN_STATE_INVALID.
+ */
+ble_conn_state_status_t ble_conn_state_status(uint16_t conn_handle);
+
+
+/**@brief Function for querying whether a connection is encrypted.
+ *
+ * @param[in]  conn_handle  Handle of connection to get the encryption state for.
+ *
+ * @retval true   If the connection is encrypted.
+ * @retval false  If the connection is not encrypted or conn_handle is invalid.
+ */
+bool ble_conn_state_encrypted(uint16_t conn_handle);
+
+
+/**@brief Function for querying whether a connection encryption is protected from Man in the Middle
+ *        attacks.
+ *
+ * @param[in]  conn_handle  Handle of connection to get the MITM state for.
+ *
+ * @retval true   If the connection is encrypted with MITM protection.
+ * @retval false  If the connection is not encrypted, or encryption is not MITM protected, or
+ *                conn_handle is invalid.
+ */
+bool ble_conn_state_mitm_protected(uint16_t conn_handle);
+
+
+/**@brief Function for querying the total number of connections.
+ *
+ * @return  The total number of valid connections for which the module has a record.
+ */
+uint32_t ble_conn_state_n_connections(void);
+
+
+/**@brief Function for querying the total number of connections in which the role of the local
+ *        device is @ref BLE_GAP_ROLE_CENTRAL.
+ *
+ * @return  The number of connections in which the role of the local device is
+ *          @ref BLE_GAP_ROLE_CENTRAL.
+ */
+uint32_t ble_conn_state_n_centrals(void);
+
+
+/**@brief Function for querying the total number of connections in which the role of the local
+ *        device is @ref BLE_GAP_ROLE_PERIPH.
+ *
+ * @return  The number of connections in which the role of the local device is
+ *          @ref BLE_GAP_ROLE_PERIPH.
+ */
+uint32_t ble_conn_state_n_peripherals(void);
+
+
+/**@brief Function for obtaining a list of all connection handles for which the module has a record.
+ *
+ * @details This function takes into account connections whose state is BLE_CONN_STATUS_DISCONNECTED.
+ *
+ * @return  A list of all valid connection handles for which the module has a record.
+ */
+sdk_mapped_flags_key_list_t ble_conn_state_conn_handles(void);
+
+
+/**@brief Function for obtaining a list of connection handles in which the role of the local
+ *        device is @ref BLE_GAP_ROLE_CENTRAL.
+ *
+ * @details This function takes into account connections whose state is BLE_CONN_STATUS_DISCONNECTED.
+ *
+ * @return  A list of all valid connection handles for which the module has a record and in which
+ *          the role of local device is @ref BLE_GAP_ROLE_CENTRAL.
+ */
+sdk_mapped_flags_key_list_t ble_conn_state_central_handles(void);
+
+
+/**@brief Function for obtaining the handle for the connection in which the role of the local device
+ *        is @ref BLE_GAP_ROLE_PERIPH.
+ *
+ * @details This function takes into account connections whose state is BLE_CONN_STATUS_DISCONNECTED.
+ *
+ * @return  A list of all valid connection handles for which the module has a record and in which
+ *          the role of local device is @ref BLE_GAP_ROLE_PERIPH.
+ */
+sdk_mapped_flags_key_list_t ble_conn_state_periph_handles(void);
+
+
+/**@brief Function for obtaining exclusive access to one of the user flag collections.
+ *
+ * @details The acquired collection contains one flag for each connection. These flags can be set
+ *          and read individually for each connection.
+ *
+ *          The state of user flags will not be modified by the connection state module, except to
+ *          set it to 0 for a connection when that connection is invalidated.
+ *
+ * @return  The ID of the acquired flag, or BLE_CONN_STATE_USER_FLAG_INVALID if none are available.
+ */
+ble_conn_state_user_flag_id_t ble_conn_state_user_flag_acquire(void);
+
+
+/**@brief Function for reading the value of a user flag.
+ *
+ * @param[in]  conn_handle  Handle of connection to get the flag state for.
+ * @param[in]  flag_id      Which flag to get the state for.
+ *
+ * @return  The state of the flag. If conn_handle is invalid, the function returns false.
+ */
+bool ble_conn_state_user_flag_get(uint16_t conn_handle, ble_conn_state_user_flag_id_t flag_id);
+
+
+/**@brief Function for setting the value of a user flag.
+ *
+ * @param[in]  conn_handle  Handle of connection to set the flag state for.
+ * @param[in]  flag_id      Which flag to set the state for.
+ * @param[in]  value        Value to set the flag state to.
+ */
+void ble_conn_state_user_flag_set(uint16_t                      conn_handle,
+                                  ble_conn_state_user_flag_id_t flag_id,
+                                  bool                          value);
+
+
+/**@brief Function for getting the state of a user flag for all connection handles.
+ *
+ * @details The returned collection can be used with the @ref sdk_mapped_flags API. The returned
+ *          collection is a copy, so modifying it has no effect on the conn_state module.
+ *
+ * @param[in]  flag_id  Which flag to get states for.
+ *
+ * @return  The collection of flag states. The collection is always all zeros when the flag_id is
+ *          unregistered.
+ */
+sdk_mapped_flags_t ble_conn_state_user_flag_collection(ble_conn_state_user_flag_id_t flag_id);
+
+/** @} */
+/** @} */
+
+#endif /* BLE_CONN_STATE_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_date_time.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_date_time.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Attention! 
+*  To maintain compliance with Nordic Semiconductor ASA's Bluetooth profile 
+*  qualification listings, this section of source code must not be modified.
+*/
+
+/** @file
+ * @brief Contains definition of ble_date_time structure.
+ */
+
+/** @file
+ *
+ * @defgroup ble_sdk_srv_date_time BLE Date Time characteristic type
+ * @{
+ * @ingroup ble_sdk_lib
+ * @brief Definition of ble_date_time_t type.
+ */
+
+#ifndef BLE_DATE_TIME_H__
+#define BLE_DATE_TIME_H__
+
+#include <stdint.h>
+
+/**@brief Date and Time structure. */
+typedef struct
+{
+    uint16_t year;
+    uint8_t  month;
+    uint8_t  day;
+    uint8_t  hours;
+    uint8_t  minutes;
+    uint8_t  seconds;
+} ble_date_time_t;
+
+static __INLINE uint8_t ble_date_time_encode(const ble_date_time_t * p_date_time,
+                                             uint8_t *               p_encoded_data)
+{
+    uint8_t len = uint16_encode(p_date_time->year, p_encoded_data);
+    
+    p_encoded_data[len++] = p_date_time->month;
+    p_encoded_data[len++] = p_date_time->day;
+    p_encoded_data[len++] = p_date_time->hours;
+    p_encoded_data[len++] = p_date_time->minutes;
+    p_encoded_data[len++] = p_date_time->seconds;
+    
+    return len;
+}
+
+static __INLINE uint8_t ble_date_time_decode(ble_date_time_t * p_date_time,
+                                             const uint8_t *   p_encoded_data)
+{
+    uint8_t len = sizeof(uint16_t);
+    
+    p_date_time->year    = uint16_decode(p_encoded_data);
+    p_date_time->month   = p_encoded_data[len++];
+    p_date_time->day     = p_encoded_data[len++]; 
+    p_date_time->hours   = p_encoded_data[len++];
+    p_date_time->minutes = p_encoded_data[len++];
+    p_date_time->seconds = p_encoded_data[len++];
+    
+    return len;
+}
+
+#endif // BLE_DATE_TIME_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_gatt_db.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_gatt_db.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef BLE_GATT_DB_H__
+#define BLE_GATT_DB_H__
+
+#include "stdint.h"
+#include "nrf_ble.h"
+#include "ble_gattc.h"
+
+#define BLE_GATT_DB_MAX_CHARS                                 4          /**< The maximum number of characteristics present in a service record. */
+
+/**@brief Structure for holding the characteristic and the handle of its CCCD present on a server.
+ */
+typedef struct
+{
+    ble_gattc_char_t characteristic;  /**< Structure containing information about the characteristic. */
+    uint16_t         cccd_handle;     /**< CCCD Handle value for this characteristic. This will be set to BLE_GATT_HANDLE_INVALID if a CCCD is not present at the server. */
+} ble_gatt_db_char_t;
+
+/**@brief Structure for holding information about the service and the characteristics present on a
+ *        server.
+ */
+typedef struct
+{
+    ble_uuid_t               srv_uuid;                                  /**< UUID of the service. */    
+    uint8_t                  char_count;                                /**< Number of characteristics present in the service. */
+    ble_gattc_handle_range_t handle_range;                              /**< Service Handle Range. */
+    ble_gatt_db_char_t       charateristics[BLE_GATT_DB_MAX_CHARS];     /**< Array of information related to the characteristics present in the service. This list can extend further than one. */
+} ble_gatt_db_srv_t;
+
+#endif /* BLE_GATT_DB_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_sensor_location.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_sensor_location.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+ /* Attention!
+*  To maintain compliance with Nordic Semiconductor ASA's Bluetooth profile
+*  qualification listings, this section of source code must not be modified.
+*/
+ 
+#ifndef BLE_SENSOR_LOCATION_H__
+#define BLE_SENSOR_LOCATION_H__
+
+typedef enum {
+    BLE_SENSOR_LOCATION_OTHER        = 0 ,  /**<-- Other        */
+    BLE_SENSOR_LOCATION_TOP_OF_SHOE  = 1 ,  /**<-- Top of shoe  */
+    BLE_SENSOR_LOCATION_IN_SHOE      = 2 ,  /**<-- In shoe      */
+    BLE_SENSOR_LOCATION_HIP          = 3 ,  /**<-- Hip          */
+    BLE_SENSOR_LOCATION_FRONT_WHEEL  = 4 ,  /**<-- Front Wheel  */
+    BLE_SENSOR_LOCATION_LEFT_CRANK   = 5 ,  /**<-- Left Crank   */
+    BLE_SENSOR_LOCATION_RIGHT_CRANK  = 6 ,  /**<-- Right Crank  */
+    BLE_SENSOR_LOCATION_LEFT_PEDAL   = 7 ,  /**<-- Left Pedal   */
+    BLE_SENSOR_LOCATION_RIGHT_PEDAL  = 8 ,  /**<-- Right Pedal  */
+    BLE_SENSOR_LOCATION_FRONT_HUB    = 9 ,  /**<-- Front Hub    */
+    BLE_SENSOR_LOCATION_REAR_DROPOUT = 10,  /**<-- Rear Dropout */
+    BLE_SENSOR_LOCATION_CHAINSTAY    = 11,  /**<-- Chainstay    */
+    BLE_SENSOR_LOCATION_REAR_WHEEL   = 12,  /**<-- Rear Wheel   */
+    BLE_SENSOR_LOCATION_REAR_HUB     = 13,  /**<-- Rear Hub     */
+}ble_sensor_location_t;
+
+#define BLE_NB_MAX_SENSOR_LOCATIONS 14
+
+#endif // BLE_SENSOR_LOCATION_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Attention!
+*  To maintain compliance with Nordic Semiconductor ASA's Bluetooth profile
+*  qualification listings, this section of source code must not be modified.
+*/
+
+#include "ble_srv_common.h"
+#include <string.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "nrf_ble.h"
+
+uint8_t ble_srv_report_ref_encode(uint8_t                    * p_encoded_buffer,
+                                  const ble_srv_report_ref_t * p_report_ref)
+{
+    uint8_t len = 0;
+
+    p_encoded_buffer[len++] = p_report_ref->report_id;
+    p_encoded_buffer[len++] = p_report_ref->report_type;
+
+    APP_ERROR_CHECK_BOOL(len == BLE_SRV_ENCODED_REPORT_REF_LEN);
+    return len;
+}
+
+
+void ble_srv_ascii_to_utf8(ble_srv_utf8_str_t * p_utf8, char * p_ascii)
+{
+    p_utf8->length = (uint16_t)strlen(p_ascii);
+    p_utf8->p_str  = (uint8_t *)p_ascii;
+}
+
+
+/**@brief Function for setting security requirements of a characteristic.
+ *
+ * @param[in]  level   required security level.
+ * @param[out] p_perm  Characteristic security requirements.
+ *
+ * @return     encoded security level and security mode.
+ */
+static inline void set_security_req(security_req_t level, ble_gap_conn_sec_mode_t * p_perm)
+{
+
+
+    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(p_perm);
+    switch (level)
+    {
+        case SEC_NO_ACCESS:
+            BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(p_perm);
+        break;
+        case SEC_OPEN:
+            BLE_GAP_CONN_SEC_MODE_SET_OPEN(p_perm);
+        break;
+        case SEC_JUST_WORKS:
+            BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(p_perm);
+        break;
+        case SEC_MITM:
+            BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(p_perm);
+        break;
+        case SEC_SIGNED:
+            BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(p_perm);
+        break;
+        case SEC_SIGNED_MITM:
+            BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(p_perm);
+        break;
+    }
+    return;
+}
+
+
+uint32_t characteristic_add(uint16_t                   service_handle,
+                            ble_add_char_params_t *    p_char_props,
+                            ble_gatts_char_handles_t * p_char_handle)
+{
+    ble_gatts_char_md_t char_md;
+    ble_gatts_attr_t    attr_char_value;
+    ble_uuid_t          char_uuid;
+    ble_gatts_attr_md_t attr_md;
+    ble_gatts_attr_md_t user_descr_attr_md;
+    ble_gatts_attr_md_t cccd_md;
+
+    if (p_char_props->uuid_type == 0)
+    {
+        char_uuid.type = BLE_UUID_TYPE_BLE;
+    }
+    else
+    {
+        char_uuid.type = p_char_props->uuid_type;
+    }
+    char_uuid.uuid = p_char_props->uuid;
+
+    memset(&attr_md, 0, sizeof(ble_gatts_attr_md_t));
+    set_security_req(p_char_props->read_access, &attr_md.read_perm);
+    set_security_req(p_char_props->write_access, & attr_md.write_perm);
+    attr_md.rd_auth    = (p_char_props->is_defered_read ? 1 : 0);
+    attr_md.wr_auth    = (p_char_props->is_defered_write ? 1 : 0);
+    attr_md.vlen       = (p_char_props->is_var_len ? 1 : 0);
+    attr_md.vloc       = (p_char_props->is_value_user ? BLE_GATTS_VLOC_USER : BLE_GATTS_VLOC_STACK);
+
+
+    memset(&char_md, 0, sizeof(ble_gatts_char_md_t));
+    if ((p_char_props->char_props.notify == 1)||(p_char_props->char_props.indicate == 1))
+    {
+
+        memset(&cccd_md, 0, sizeof(cccd_md));
+        set_security_req(p_char_props->cccd_write_access, &cccd_md.write_perm);
+        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
+
+        cccd_md.vloc       = BLE_GATTS_VLOC_STACK;
+
+        char_md.p_cccd_md  = &cccd_md;
+    }
+    char_md.char_props = p_char_props->char_props;
+
+    memset(&attr_char_value, 0, sizeof(ble_gatts_attr_t));
+    attr_char_value.p_uuid    = &char_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.max_len   = p_char_props->max_len;
+    if (p_char_props->p_init_value != NULL)
+    {
+        attr_char_value.init_len  = p_char_props->init_len;
+        attr_char_value.p_value   = p_char_props->p_init_value;
+    }
+    if (p_char_props->p_user_descr != NULL)
+    {
+        memset(&user_descr_attr_md, 0, sizeof(ble_gatts_attr_md_t));
+        char_md.char_user_desc_max_size = p_char_props->p_user_descr->max_size;
+        char_md.char_user_desc_size     = p_char_props->p_user_descr->size;
+        char_md.p_char_user_desc        = p_char_props->p_user_descr->p_char_user_desc;
+
+        char_md.p_user_desc_md          = &user_descr_attr_md;
+
+        set_security_req(p_char_props->p_user_descr->read_access, &user_descr_attr_md.read_perm);
+        set_security_req(p_char_props->p_user_descr->write_access, &user_descr_attr_md.write_perm);
+
+        user_descr_attr_md.rd_auth      = (p_char_props->p_user_descr->is_defered_read ? 1 : 0);
+        user_descr_attr_md.wr_auth      = (p_char_props->p_user_descr->is_defered_write ? 1 : 0);
+        user_descr_attr_md.vlen         = (p_char_props->p_user_descr->is_var_len ? 1 : 0);
+        user_descr_attr_md.vloc         = (p_char_props->p_user_descr->is_value_user ? BLE_GATTS_VLOC_USER : BLE_GATTS_VLOC_STACK);
+    }
+    if (p_char_props->p_presentation_format != NULL)
+    {
+        char_md.p_char_pf = p_char_props->p_presentation_format;
+    }
+    return sd_ble_gatts_characteristic_add(service_handle,
+                                           &char_md,
+                                           &attr_char_value,
+                                           p_char_handle);
+}
+
+
+uint32_t descriptor_add(uint16_t                   char_handle,
+                        ble_add_descr_params_t *   p_descr_props,
+                        uint16_t *                 p_descr_handle)
+{
+    ble_gatts_attr_t    descr_params;
+    ble_uuid_t          desc_uuid;
+    ble_gatts_attr_md_t attr_md;
+
+    memset(&descr_params, 0, sizeof(descr_params));
+    if (p_descr_props->uuid_type == 0)
+    {
+        desc_uuid.type = BLE_UUID_TYPE_BLE;
+    }
+    else
+    {
+        desc_uuid.type = p_descr_props->uuid_type;
+    }
+    desc_uuid.uuid = p_descr_props->uuid;
+    descr_params.p_uuid = &desc_uuid;
+
+    set_security_req(p_descr_props->read_access, &attr_md.read_perm);
+    set_security_req(p_descr_props->write_access,&attr_md.write_perm);
+
+    attr_md.rd_auth        = (p_descr_props->is_defered_read ? 1 : 0);
+    attr_md.wr_auth        = (p_descr_props->is_defered_write ? 1 : 0);
+    attr_md.vlen           = (p_descr_props->is_var_len ? 1 : 0);
+    attr_md.vloc           = (p_descr_props->is_value_user ? BLE_GATTS_VLOC_USER : BLE_GATTS_VLOC_STACK);
+    descr_params.p_attr_md = &attr_md;
+
+    descr_params.init_len  = p_descr_props->init_len;
+    descr_params.init_offs = p_descr_props->init_offs;
+    descr_params.max_len   = p_descr_props->max_len;
+    descr_params.p_value   = p_descr_props->p_value;
+
+    return sd_ble_gatts_descriptor_add(char_handle, &descr_params, p_descr_handle);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/common/ble_srv_common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,368 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup ble_sdk_srv_common Common service definitions
+ * @{
+ * @ingroup ble_sdk_srv
+ * @brief Constants, type definitions, and functions that are common to all services.
+ */
+
+#ifndef BLE_SRV_COMMON_H__
+#define BLE_SRV_COMMON_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "ble_types.h"
+#include "app_util.h"
+#include "nrf_ble.h"
+#include "ble_gap.h"
+#include "ble_gatt.h"
+
+/** @defgroup UUID_SERVICES Service UUID definitions
+ * @{ */
+#define BLE_UUID_ALERT_NOTIFICATION_SERVICE                      0x1811     /**< Alert Notification service UUID. */
+#define BLE_UUID_BATTERY_SERVICE                                 0x180F     /**< Battery service UUID. */
+#define BLE_UUID_BLOOD_PRESSURE_SERVICE                          0x1810     /**< Blood Pressure service UUID. */
+#define BLE_UUID_CURRENT_TIME_SERVICE                            0x1805     /**< Current Time service UUID. */
+#define BLE_UUID_CYCLING_SPEED_AND_CADENCE                       0x1816     /**< Cycling Speed and Cadence service UUID. */
+#define BLE_UUID_LOCATION_AND_NAVIGATION_SERVICE                 0x1819     /**< Location and Navigation service UUID. */
+#define BLE_UUID_DEVICE_INFORMATION_SERVICE                      0x180A     /**< Device Information service UUID. */
+#define BLE_UUID_GLUCOSE_SERVICE                                 0x1808     /**< Glucose service UUID. */
+#define BLE_UUID_HEALTH_THERMOMETER_SERVICE                      0x1809     /**< Health Thermometer service UUID. */
+#define BLE_UUID_HEART_RATE_SERVICE                              0x180D     /**< Heart Rate service UUID. */
+#define BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE                  0x1812     /**< Human Interface Device service UUID. */
+#define BLE_UUID_IMMEDIATE_ALERT_SERVICE                         0x1802     /**< Immediate Alert service UUID. */
+#define BLE_UUID_LINK_LOSS_SERVICE                               0x1803     /**< Link Loss service UUID. */
+#define BLE_UUID_NEXT_DST_CHANGE_SERVICE                         0x1807     /**< Next Dst Change service UUID. */
+#define BLE_UUID_PHONE_ALERT_STATUS_SERVICE                      0x180E     /**< Phone Alert Status service UUID. */
+#define BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE                   0x1806     /**< Reference Time Update service UUID. */
+#define BLE_UUID_RUNNING_SPEED_AND_CADENCE                       0x1814     /**< Running Speed and Cadence service UUID. */
+#define BLE_UUID_SCAN_PARAMETERS_SERVICE                         0x1813     /**< Scan Parameters service UUID. */
+#define BLE_UUID_TX_POWER_SERVICE                                0x1804     /**< TX Power service UUID. */
+#define BLE_UUID_IPSP_SERVICE                                    0x1820     /**< Internet Protocol Support service UUID. */
+/** @} */
+
+/** @defgroup UUID_CHARACTERISTICS Characteristic UUID definitions
+ * @{ */
+#define BLE_UUID_BATTERY_LEVEL_STATE_CHAR                        0x2A1B     /**< Battery Level State characteristic UUID. */
+#define BLE_UUID_BATTERY_POWER_STATE_CHAR                        0x2A1A     /**< Battery Power State characteristic UUID. */
+#define BLE_UUID_REMOVABLE_CHAR                                  0x2A3A     /**< Removable characteristic UUID. */
+#define BLE_UUID_SERVICE_REQUIRED_CHAR                           0x2A3B     /**< Service Required characteristic UUID. */
+#define BLE_UUID_ALERT_CATEGORY_ID_CHAR                          0x2A43     /**< Alert Category Id characteristic UUID. */
+#define BLE_UUID_ALERT_CATEGORY_ID_BIT_MASK_CHAR                 0x2A42     /**< Alert Category Id Bit Mask characteristic UUID. */
+#define BLE_UUID_ALERT_LEVEL_CHAR                                0x2A06     /**< Alert Level characteristic UUID. */
+#define BLE_UUID_ALERT_NOTIFICATION_CONTROL_POINT_CHAR           0x2A44     /**< Alert Notification Control Point characteristic UUID. */
+#define BLE_UUID_ALERT_STATUS_CHAR                               0x2A3F     /**< Alert Status characteristic UUID. */
+#define BLE_UUID_BATTERY_LEVEL_CHAR                              0x2A19     /**< Battery Level characteristic UUID. */
+#define BLE_UUID_BLOOD_PRESSURE_FEATURE_CHAR                     0x2A49     /**< Blood Pressure Feature characteristic UUID. */
+#define BLE_UUID_BLOOD_PRESSURE_MEASUREMENT_CHAR                 0x2A35     /**< Blood Pressure Measurement characteristic UUID. */
+#define BLE_UUID_BODY_SENSOR_LOCATION_CHAR                       0x2A38     /**< Body Sensor Location characteristic UUID. */
+#define BLE_UUID_BOOT_KEYBOARD_INPUT_REPORT_CHAR                 0x2A22     /**< Boot Keyboard Input Report characteristic UUID. */
+#define BLE_UUID_BOOT_KEYBOARD_OUTPUT_REPORT_CHAR                0x2A32     /**< Boot Keyboard Output Report characteristic UUID. */
+#define BLE_UUID_BOOT_MOUSE_INPUT_REPORT_CHAR                    0x2A33     /**< Boot Mouse Input Report characteristic UUID. */
+#define BLE_UUID_CURRENT_TIME_CHAR                               0x2A2B     /**< Current Time characteristic UUID. */
+#define BLE_UUID_DATE_TIME_CHAR                                  0x2A08     /**< Date Time characteristic UUID. */
+#define BLE_UUID_DAY_DATE_TIME_CHAR                              0x2A0A     /**< Day Date Time characteristic UUID. */
+#define BLE_UUID_DAY_OF_WEEK_CHAR                                0x2A09     /**< Day Of Week characteristic UUID. */
+#define BLE_UUID_DST_OFFSET_CHAR                                 0x2A0D     /**< Dst Offset characteristic UUID. */
+#define BLE_UUID_EXACT_TIME_256_CHAR                             0x2A0C     /**< Exact Time 256 characteristic UUID. */
+#define BLE_UUID_FIRMWARE_REVISION_STRING_CHAR                   0x2A26     /**< Firmware Revision String characteristic UUID. */
+#define BLE_UUID_GLUCOSE_FEATURE_CHAR                            0x2A51     /**< Glucose Feature characteristic UUID. */
+#define BLE_UUID_GLUCOSE_MEASUREMENT_CHAR                        0x2A18     /**< Glucose Measurement characteristic UUID. */
+#define BLE_UUID_GLUCOSE_MEASUREMENT_CONTEXT_CHAR                0x2A34     /**< Glucose Measurement Context characteristic UUID. */
+#define BLE_UUID_HARDWARE_REVISION_STRING_CHAR                   0x2A27     /**< Hardware Revision String characteristic UUID. */
+#define BLE_UUID_HEART_RATE_CONTROL_POINT_CHAR                   0x2A39     /**< Heart Rate Control Point characteristic UUID. */
+#define BLE_UUID_HEART_RATE_MEASUREMENT_CHAR                     0x2A37     /**< Heart Rate Measurement characteristic UUID. */
+#define BLE_UUID_HID_CONTROL_POINT_CHAR                          0x2A4C     /**< Hid Control Point characteristic UUID. */
+#define BLE_UUID_HID_INFORMATION_CHAR                            0x2A4A     /**< Hid Information characteristic UUID. */
+#define BLE_UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST_CHAR    0x2A2A     /**< IEEE Regulatory Certification Data List characteristic UUID. */
+#define BLE_UUID_INTERMEDIATE_CUFF_PRESSURE_CHAR                 0x2A36     /**< Intermediate Cuff Pressure characteristic UUID. */
+#define BLE_UUID_INTERMEDIATE_TEMPERATURE_CHAR                   0x2A1E     /**< Intermediate Temperature characteristic UUID. */
+#define BLE_UUID_LOCAL_TIME_INFORMATION_CHAR                     0x2A0F     /**< Local Time Information characteristic UUID. */
+#define BLE_UUID_MANUFACTURER_NAME_STRING_CHAR                   0x2A29     /**< Manufacturer Name String characteristic UUID. */
+#define BLE_UUID_MEASUREMENT_INTERVAL_CHAR                       0x2A21     /**< Measurement Interval characteristic UUID. */
+#define BLE_UUID_MODEL_NUMBER_STRING_CHAR                        0x2A24     /**< Model Number String characteristic UUID. */
+#define BLE_UUID_UNREAD_ALERT_CHAR                               0x2A45     /**< Unread Alert characteristic UUID. */
+#define BLE_UUID_NEW_ALERT_CHAR                                  0x2A46     /**< New Alert characteristic UUID. */
+#define BLE_UUID_PNP_ID_CHAR                                     0x2A50     /**< PNP Id characteristic UUID. */
+#define BLE_UUID_PROTOCOL_MODE_CHAR                              0x2A4E     /**< Protocol Mode characteristic UUID. */
+#define BLE_UUID_RECORD_ACCESS_CONTROL_POINT_CHAR                0x2A52     /**< Record Access Control Point characteristic UUID. */
+#define BLE_UUID_REFERENCE_TIME_INFORMATION_CHAR                 0x2A14     /**< Reference Time Information characteristic UUID. */
+#define BLE_UUID_REPORT_CHAR                                     0x2A4D     /**< Report characteristic UUID. */
+#define BLE_UUID_REPORT_MAP_CHAR                                 0x2A4B     /**< Report Map characteristic UUID. */
+#define BLE_UUID_RINGER_CONTROL_POINT_CHAR                       0x2A40     /**< Ringer Control Point characteristic UUID. */
+#define BLE_UUID_RINGER_SETTING_CHAR                             0x2A41     /**< Ringer Setting characteristic UUID. */
+#define BLE_UUID_SCAN_INTERVAL_WINDOW_CHAR                       0x2A4F     /**< Scan Interval Window characteristic UUID. */
+#define BLE_UUID_SCAN_REFRESH_CHAR                               0x2A31     /**< Scan Refresh characteristic UUID. */
+#define BLE_UUID_SERIAL_NUMBER_STRING_CHAR                       0x2A25     /**< Serial Number String characteristic UUID. */
+#define BLE_UUID_SOFTWARE_REVISION_STRING_CHAR                   0x2A28     /**< Software Revision String characteristic UUID. */
+#define BLE_UUID_SUPPORTED_NEW_ALERT_CATEGORY_CHAR               0x2A47     /**< Supported New Alert Category characteristic UUID. */
+#define BLE_UUID_SUPPORTED_UNREAD_ALERT_CATEGORY_CHAR            0x2A48     /**< Supported Unread Alert Category characteristic UUID. */
+#define BLE_UUID_SYSTEM_ID_CHAR                                  0x2A23     /**< System Id characteristic UUID. */
+#define BLE_UUID_TEMPERATURE_MEASUREMENT_CHAR                    0x2A1C     /**< Temperature Measurement characteristic UUID. */
+#define BLE_UUID_TEMPERATURE_TYPE_CHAR                           0x2A1D     /**< Temperature Type characteristic UUID. */
+#define BLE_UUID_TIME_ACCURACY_CHAR                              0x2A12     /**< Time Accuracy characteristic UUID. */
+#define BLE_UUID_TIME_SOURCE_CHAR                                0x2A13     /**< Time Source characteristic UUID. */
+#define BLE_UUID_TIME_UPDATE_CONTROL_POINT_CHAR                  0x2A16     /**< Time Update Control Point characteristic UUID. */
+#define BLE_UUID_TIME_UPDATE_STATE_CHAR                          0x2A17     /**< Time Update State characteristic UUID. */
+#define BLE_UUID_TIME_WITH_DST_CHAR                              0x2A11     /**< Time With Dst characteristic UUID. */
+#define BLE_UUID_TIME_ZONE_CHAR                                  0x2A0E     /**< Time Zone characteristic UUID. */
+#define BLE_UUID_TX_POWER_LEVEL_CHAR                             0x2A07     /**< TX Power Level characteristic UUID. */
+#define BLE_UUID_CSC_FEATURE_CHAR                                0x2A5C     /**< Cycling Speed and Cadence Feature characteristic UUID. */
+#define BLE_UUID_CSC_MEASUREMENT_CHAR                            0x2A5B     /**< Cycling Speed and Cadence Measurement characteristic UUID. */
+#define BLE_UUID_RSC_FEATURE_CHAR                                0x2A54     /**< Running Speed and Cadence Feature characteristic UUID. */
+#define BLE_UUID_SC_CTRLPT_CHAR                                  0x2A55     /**< Speed and Cadence Control Point UUID. */
+#define BLE_UUID_RSC_MEASUREMENT_CHAR                            0x2A53     /**< Running Speed and Cadence Measurement characteristic UUID. */
+#define BLE_UUID_SENSOR_LOCATION_CHAR                            0x2A5D     /**< Sensor Location characteristic UUID. */
+#define BLE_UUID_EXTERNAL_REPORT_REF_DESCR                       0x2907     /**< External Report Reference descriptor UUID. */
+#define BLE_UUID_REPORT_REF_DESCR                                0x2908     /**< Report Reference descriptor UUID. */
+#define BLE_UUID_LN_FEATURE_CHAR                                 0x2A6A     /**< Location Navigation Service, Feature characteristic UUID. */
+#define BLE_UUID_LN_POSITION_QUALITY_CHAR                        0x2A69     /**< Location Navigation Service, Position quality UUID. */
+#define BLE_UUID_LN_LOCATION_AND_SPEED_CHAR                      0x2A67     /**< Location Navigation Service, Location and Speed characteristic UUID. */
+#define BLE_UUID_LN_NAVIGATION_CHAR                              0x2A68     /**< Location Navigation Service, Navigation characteristic UUID. */
+#define BLE_UUID_LN_CONTROL_POINT_CHAR                           0x2A6B     /**< Location Navigation Service, Control point characteristic UUID. */
+/** @} */
+
+/** @defgroup ALERT_LEVEL_VALUES Definitions for the Alert Level characteristic values
+ * @{ */
+#define BLE_CHAR_ALERT_LEVEL_NO_ALERT                            0x00       /**< No Alert. */
+#define BLE_CHAR_ALERT_LEVEL_MILD_ALERT                          0x01       /**< Mild Alert. */
+#define BLE_CHAR_ALERT_LEVEL_HIGH_ALERT                          0x02       /**< High Alert. */
+/** @} */
+
+#define BLE_SRV_ENCODED_REPORT_REF_LEN                           2          /**< The length of an encoded Report Reference Descriptor. */
+#define BLE_CCCD_VALUE_LEN                                       2          /**< The length of a CCCD value. */
+
+/**@brief Type definition for error handler function that will be called in case of an error in
+ *        a service or a service library module. */
+typedef void (*ble_srv_error_handler_t) (uint32_t nrf_error);
+
+
+
+/**@brief Value of a Report Reference descriptor. 
+ *
+ * @details This is mapping information that maps the parent characteristic to the Report ID(s) and
+ *          Report Type(s) defined within a Report Map characteristic.
+ */
+typedef struct
+{
+    uint8_t report_id;                                  /**< Non-zero value if there is more than one instance of the same Report Type */
+    uint8_t report_type;                                /**< Type of Report characteristic (see @ref BLE_HIDS_REPORT_TYPE) */
+} ble_srv_report_ref_t;
+
+/**@brief UTF-8 string data type.
+ *
+ * @note The type can only hold a pointer to the string data (i.e. not the actual data).
+ */
+typedef struct
+{
+    uint16_t  length;                                   /**< String length. */
+    uint8_t * p_str;                                    /**< String data. */
+} ble_srv_utf8_str_t;
+
+
+/**@brief Security settings structure.
+ * @details This structure contains the security options needed during initialization of the
+ *          service.
+ */
+typedef struct
+{
+    ble_gap_conn_sec_mode_t read_perm;                  /**< Read permissions. */
+    ble_gap_conn_sec_mode_t write_perm;                 /**< Write permissions. */
+} ble_srv_security_mode_t;
+
+/**@brief Security settings structure.
+ * @details This structure contains the security options needed during initialization of the
+ *          service. It can be used when the characteristics contains a CCCD.
+ */
+typedef struct
+{
+    ble_gap_conn_sec_mode_t cccd_write_perm;            /**< Write permissions for Client Characteristic Configuration Descriptor. */
+    ble_gap_conn_sec_mode_t read_perm;                  /**< Read permissions. */
+    ble_gap_conn_sec_mode_t write_perm;                 /**< Write permissions. */
+} ble_srv_cccd_security_mode_t;
+
+/**@brief Function for decoding a CCCD value, and then testing if notification is
+ *        enabled.
+ *
+ * @param[in]   p_encoded_data   Buffer where the encoded CCCD is stored.
+ *
+ * @retval      TRUE If notification is enabled.
+ * @retval      FALSE Otherwise.
+ */
+static __INLINE bool ble_srv_is_notification_enabled(uint8_t * p_encoded_data)
+{
+    uint16_t cccd_value = uint16_decode(p_encoded_data);
+    return ((cccd_value & BLE_GATT_HVX_NOTIFICATION) != 0);
+}
+    
+/**@brief Function for decoding a CCCD value, and then testing if indication is
+ *        enabled.
+ *
+ * @param[in]   p_encoded_data   Buffer where the encoded CCCD is stored.
+ *
+ * @retval      TRUE If indication is enabled.
+ * @retval      FALSE Otherwise.
+ */
+static __INLINE bool ble_srv_is_indication_enabled(uint8_t * p_encoded_data)
+{
+    uint16_t cccd_value = uint16_decode(p_encoded_data);
+    return ((cccd_value & BLE_GATT_HVX_INDICATION) != 0);
+}
+
+/**@brief Function for encoding a Report Reference Descriptor.
+ *
+ * @param[in]   p_encoded_buffer  The buffer of the encoded data.
+ * @param[in]   p_report_ref      Report Reference value to be encoded.
+ *
+ * @return      Length of the encoded data.
+ */
+uint8_t ble_srv_report_ref_encode(uint8_t *                    p_encoded_buffer,
+                                  const ble_srv_report_ref_t * p_report_ref);
+
+/**@brief Function for making a UTF-8 structure refer to an ASCII string.
+ *
+ * @param[out]  p_utf8   UTF-8 structure to be set.
+ * @param[in]   p_ascii  ASCII string to be referred to.
+ */
+void ble_srv_ascii_to_utf8(ble_srv_utf8_str_t * p_utf8, char * p_ascii);
+
+
+/**@brief Security Access enumeration.
+ * @details This enumeration gives the possible requirements for accessing a characteristic value.
+ */
+typedef enum
+{
+    SEC_NO_ACCESS    = 0,            /**< Not possible to access. */
+    SEC_OPEN         = 1,            /**< Access open. */
+    SEC_JUST_WORKS   = 2,            /**< Access possible with 'Just Works' security at least. */
+    SEC_MITM         = 3,            /**< Access possible with 'MITM' security at least. */
+    SEC_SIGNED       = 4,            /**< Access possible with 'signed' security at least. */
+    SEC_SIGNED_MITM  = 5             /**< Access possible with 'signed and MITM' security at least. */
+}security_req_t;
+
+
+/**@brief Characteristic User Descriptor parameters.
+ * @details This structure contains the parameters for User Descriptor.
+ */
+typedef struct
+{
+    uint16_t               max_size;                      /**< Maximum size of the user descriptor*/
+    uint16_t               size;                          /**< Size of the user descriptor*/
+    uint8_t                *p_char_user_desc;             /**< User descriptor content, pointer to a UTF-8 encoded string (non-NULL terminated)*/
+    bool                   is_var_len;                    /**< Indicates if the user descriptor has variable length.*/
+    ble_gatt_char_props_t  char_props;                    /**< user descriptor properties.*/
+    bool                   is_defered_read;               /**< Indicate if deferred read operations are supported.*/
+    bool                   is_defered_write;              /**< Indicate if deferred write operations are supported.*/
+    security_req_t         read_access;                   /**< Security requirement for reading the user descriptor.*/
+    security_req_t         write_access;                  /**< Security requirement for writing the user descriptor.*/
+    bool                   is_value_user;                 /**< Indicate if the content of the characteristic is to be stored in the application (user) or in the stack.*/
+}ble_add_char_user_desc_t;
+
+
+/**@brief Add characteristic parameters structure.
+ * @details This structure contains the parameters needed to use the @ref characteristic_add function.
+ */
+typedef struct
+{
+    uint16_t                    uuid;                     /**< Characteristic UUID (16 bits UUIDs).*/
+    uint8_t                     uuid_type;                /**< Base UUID. If 0, the Bluetooth SIG UUID will be used. Otherwise, this should be a value returned by @ref sd_ble_uuid_vs_add when adding the base UUID.*/
+    uint16_t                    max_len;                  /**< Maximum length of the characteristic value.*/
+    uint16_t                    init_len;                 /**< Initial length of the characteristic value.*/
+    uint8_t *                   p_init_value;             /**< Initial encoded value of the characteristic.*/
+    bool                        is_var_len;               /**< Indicates if the characteristic value has variable length.*/
+    ble_gatt_char_props_t       char_props;               /**< Characteristic properties.*/
+    bool                        is_defered_read;          /**< Indicate if deferred read operations are supported.*/
+    bool                        is_defered_write;         /**< Indicate if deferred write operations are supported.*/
+    security_req_t              read_access;              /**< Security requirement for reading the characteristic value.*/
+    security_req_t              write_access;             /**< Security requirement for writing the characteristic value.*/
+    security_req_t              cccd_write_access;        /**< Security requirement for writing the characteristic's CCCD.*/
+    bool                        is_value_user;            /**< Indicate if the content of the characteristic is to be stored in the application (user) or in the stack.*/
+    ble_add_char_user_desc_t    *p_user_descr;            /**< Pointer to user descriptor if needed*/
+    ble_gatts_char_pf_t         *p_presentation_format;   /**< Pointer to characteristic format if needed*/
+} ble_add_char_params_t;
+
+
+/**@brief Add descriptor parameters structure.
+ * @details This structure contains the parameters needed to use the @ref descriptor_add function.
+ */
+typedef struct
+{
+    uint16_t       uuid;                     /**< descriptor UUID (16 bits UUIDs).*/
+    uint8_t        uuid_type;                /**< Base UUID. If 0, the Bluetooth SIG UUID will be used. Otherwise, this should be a value returned by @ref sd_ble_uuid_vs_add when adding the base UUID.*/
+    bool           is_defered_read;          /**< Indicate if deferred read operations are supported.*/
+    bool           is_defered_write;         /**< Indicate if deferred write operations are supported.*/
+    bool           is_var_len;               /**< Indicates if the descriptor value has variable length.*/
+    security_req_t read_access;              /**< Security requirement for reading the descriptor value.*/
+    security_req_t write_access;             /**< Security requirement for writing the descriptor value.*/
+    bool           is_value_user;            /**< Indicate if the content of the characteristic is to be stored in the application (user) or in the stack.*/
+    uint16_t       init_len;                 /**< Initial descriptor value length in bytes. */
+    uint16_t       init_offs;                /**< Initial descriptor value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */
+    uint16_t       max_len;                  /**< Maximum descriptor value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */
+    uint8_t*       p_value;                  /**< Pointer to the value of the descriptor*/
+} ble_add_descr_params_t;
+
+
+/**@brief Function for adding a characteristic to a given service. 
+ *
+ * If no pointer is given for the initial value,
+ * the initial length parameter will be ignored and the initial length will be 0.
+ *
+ * @param[in]  service_handle Handle of the service to which the characteristic is to be added.
+ * @param[in]  p_char_props   Information needed to add the characteristic.
+ * @param[out] p_char_handle  Handle of the added characteristic.
+ *
+ * @retval      NRF_SUCCESS If the characteristic was added successfully. Otherwise, an error code is returned.
+ */
+uint32_t characteristic_add(uint16_t                   service_handle,
+                            ble_add_char_params_t *    p_char_props,
+                            ble_gatts_char_handles_t * p_char_handle);
+
+
+/**@brief Function for adding a characteristic's descriptor to a given characteristic.
+ *
+ * @param[in]  char_handle    Handle of the characteristic to which the descriptor is to be added, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
+ * @param[in]  p_descr_props  Information needed to add the descriptor.
+ * @param[out] p_descr_handle Handle of the added descriptor.
+ *
+ * @retval      NRF_SUCCESS If the characteristic was added successfully. Otherwise, an error code is returned.
+ */
+uint32_t descriptor_add(uint16_t                   char_handle,
+                        ble_add_descr_params_t *   p_descr_props,
+                        uint16_t *                 p_descr_handle);
+
+
+#endif // BLE_SRV_COMMON_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/device_manager/config/device_manager_cnfg.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/device_manager/config/device_manager_cnfg.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+ /**
+ * @file device_manager_cnfg.h
+ *
+ * @cond
+ * @defgroup device_manager_cnfg Device Manager Configuration 
+ * @ingroup device_manager
+ * @{
+ *
+ * @brief Defines application specific configuration for Device Manager.
+ *
+ * @details All configurations that are specific to application have been defined
+ *          here. Application should configuration that best suits its requirements.
+ */
+ 
+#ifndef DEVICE_MANAGER_CNFG_H__
+#define DEVICE_MANAGER_CNFG_H__
+
+/**
+ * @defgroup device_manager_inst Device Manager Instances
+ * @{
+ */
+/**
+ * @brief Maximum applications that Device Manager can support.
+ *
+ * @details Maximum application that the Device Manager can support.
+ *          Currently only one application can be supported.
+ *          Minimum value : 1
+ *          Maximum value : 1
+ *          Dependencies  : None.
+ */
+#define DEVICE_MANAGER_MAX_APPLICATIONS  1
+
+/**
+ * @brief Maximum connections that Device Manager should simultaneously manage.
+ *
+ * @details Maximum connections that Device Manager should simultaneously manage.
+ *          Minimum value : 1
+ *          Maximum value : Maximum links supported by SoftDevice.
+ *          Dependencies  : None.
+ */
+#define DEVICE_MANAGER_MAX_CONNECTIONS   1
+
+
+/**
+ * @brief Maximum bonds that Device Manager should manage.
+ *
+ * @details Maximum bonds that Device Manager should manage.
+ *          Minimum value : 1
+ *          Maximum value : 254.
+ *          Dependencies  : None.
+ * @note In case of GAP Peripheral role, the Device Manager will accept bonding procedure 
+ *       requests from peers even if this limit is reached, but bonding information will not 
+ *       be stored. In such cases, application will be notified with DM_DEVICE_CONTEXT_FULL 
+ *       as event result at the completion of the security procedure.
+ */
+#define DEVICE_MANAGER_MAX_BONDS         2
+
+
+/**
+ * @brief Maximum Characteristic Client Descriptors used for GATT Server.
+ *
+ * @details Maximum Characteristic Client Descriptors used for GATT Server.
+ *          Minimum value : 1
+ *          Maximum value : 254.
+ *          Dependencies  : None.
+ */
+#define DM_GATT_CCCD_COUNT               2
+
+
+/**
+ * @brief Size of application context.
+ *
+ * @details Size of application context that Device Manager should manage for each bonded device.
+ *          Size had to be a multiple of word size.
+ *          Minimum value : 4.
+ *          Maximum value : 256. 
+ *          Dependencies  : Needed only if Application Context saving is used by the application.
+ * @note If set to zero, its an indication that application context is not required to be managed
+ *       by the module.
+ */
+#define DEVICE_MANAGER_APP_CONTEXT_SIZE    0
+
+/* @} */
+/* @} */
+/** @endcond */
+#endif // DEVICE_MANAGER_CNFG_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,909 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * @file device_manager.h
+ *
+ * @defgroup device_manager Device Manager
+ * @ingroup ble_sdk_lib
+ * @{
+ * @brief Device Manager Application Interface Abstraction.
+ *
+ * @details The Device Manager module manages Active and Bonded Peers. Management of peer includes
+ *          book keeping of contextual information like the Security Keys, GATT
+ *          configuration and any application specific information.
+ *
+ *          Active Peers are devices which are connected, and may or may not be bonded.
+ *          Bonded Peers are devices which are bonded, and may or may not be Active (Connected).
+ *          Active Bonded Peer refers to a device which is connected and bonded.
+ *
+ *          Paired Devices refers to peer devices that are connected and have necessary context
+ *          establishment/exchange for the current connection session. On disconnect,
+ *          all contextual information is flushed. For example, SMP Information Exchanged during
+ *          pairing and GATT Configuration is not retained on disconnection.
+ *
+ *          Note that this module allows management of contextual information but 
+ *          does not provide an interface for connection management. Therefore, entering connectible
+ *          mode, connection establishment, or disconnection of a link with peer is not in scope
+ *          of this module.
+ *
+ *          For bonded peers, the contextual information is required to be retained on disconnection
+ *          and power cycling. Persistent storage of contextual information is handled by the
+ *          module. This module categorizes the contextual information into 3 categories:
+ *             - <b>Bonding Information</b>
+ *               Bond information is the information exchanged between local and peer device to
+ *               establish a bond. It also includes peer identification information,
+ *               like the peer address or the IRK or both. From here on this category of information
+ *               is referred to as Device Context.
+ *             - <b>Service/Protocol Information</b>
+ *               Service/Protocol information is the information retained for the peer to save on one-time
+ *               procedures like the GATT Service Discovery procedures and Service Configurations.
+ *               It allows devices to resume data exchange on subsequent reconnection without having
+ *               to perform initial set-up procedures each time. From here on this category is
+ *               referred to as Service Context.
+ *             - <b>Application Information</b>
+ *               Application information is the context that the application would like to associate with
+ *               each of the bonded device. For example, if the application chooses to rank its peers
+ *               in order to manage them better, the rank information could be treated as
+ *               Application Information. This storage space is provided to save the application from
+ *               maintaining a mapping table with each Device Instance and Application Information.
+ *               However, if the application have no use for this, it is possible to not
+ *               use or employ this at compile time. From here on this category of information is
+ *               referred to as Application Context.
+ */
+
+
+#ifndef DEVICE_MANAGER_H__
+#define DEVICE_MANAGER_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "sdk_common.h"
+#include "nrf_ble.h"
+#include "ble_gap.h"
+#include "device_manager_cnfg.h"
+
+/**
+ * @defgroup dm_service_cntext_types Service/Protocol Types
+ *
+ * @brief Describes the possible types of Service/Protocol Contexts for a bonded/peer device.
+ *
+ * @details Possible Service/Protocol context per peer device. The Device Manager provides the
+ *          functionality of persistently storing the Service/Protocol context and can automatically
+ *          load them when needed.
+ *          For example system attributes for a GATT Server. Based on the nature of the application, 
+ *          not all service types may be needed. The application can specify
+ *          only the service/protocol context it wants to use at the time of registration.
+ * @{
+ */
+#define DM_PROTOCOL_CNTXT_NONE         0x00  /**< No Service Context, this implies the application does not want to associate any service/protocol context with the peer device */
+#define DM_PROTOCOL_CNTXT_GATT_SRVR_ID 0x01  /**< GATT Server Service Context, this implies the application does associate GATT Server with the peer device and this information will be loaded when needed for a bonded device */
+#define DM_PROTOCOL_CNTXT_GATT_CLI_ID  0x02  /**< GATT Client Service Context, this implies the application does associate GATT Client with the peer device and this information will be loaded when needed for a bonded device */
+#define DM_PROTOCOL_CNTXT_ALL                                                                     \
+        (DM_PROTOCOL_CNTXT_GATT_SRVR_ID | DM_PROTOCOL_CNTXT_GATT_CLI_ID) /**< All Service/Protocol Context, this implies that the application wants to associate all Service/Protocol Information with the bonded device. This is configurable based on system requirements. If the application has only one type of service, this define could be altered to reflect the same.  */
+/** @} */
+
+
+/**
+ * @defgroup dm_events Device Manager Events
+ *
+ * @brief This section describes the device manager events that are notified to the application.
+ *
+ * @details The Device Manager notifies the application of various asynchronous events using the
+ *          asynchronous event notification callback. All events has been categorized into:
+ *          a. General.
+ *          b. Link Status.
+ *          c. Context Management.
+ *
+ *          In the callback, these events are notified along with handle that uniquely identifies:
+ *          application instance, active instance (if applicable), device instance
+ *          bonding instance, (if applicable) and service instance.
+ *          Not all events are pertaining to an active connection, for example a context deletion event could occur even if the peer
+ *          is not connected. Also, general category of events may not be pertaining to any specific peer.
+ *          See also \ref dm_event_cb_t and \ref dm_register.
+ * @{
+ */
+/**
+ * @defgroup general_events General Events
+ *
+ * @brief General or miscellaneous events.
+ *
+ * @details This category of events are general events not pertaining to a peer or context.
+ *
+ * @{
+ */
+#define DM_EVT_RFU   0x00 /**< Reserved for future use, is never notified. */
+#define DM_EVT_ERROR 0x01 /**< Device Manager Event Error. */
+/** @} */
+
+/**
+ * @defgroup link_status_events Link Status Events
+ *
+ * @brief Link Status Events.
+ *
+ * @details This category of events notify the application of the link status. Event result associated
+ *          with the event is provided along with the event in the callback to provide more details of
+ *          whether a procedure succeeded or failed and assist the application in decision making of
+ *          how to proceed. For example if a DM_DEVICE_CONNECT_IND is indicated with NRF_SUCCESS
+ *          result, the application may want to proceed with discovering and association with
+ *          service of the peer. However, if indicated with a failure result, the application may
+ *          want to take an alternate action such as reattempting to connect or go into a
+ *          sleep mode.
+ *
+ * @{
+ */
+#define DM_EVT_CONNECTION              0x11 /**< Indicates that link with the peer is established. */
+#define DM_EVT_DISCONNECTION           0x12 /**< Indicates that link with peer is torn down. */
+#define DM_EVT_SECURITY_SETUP          0x13 /**< Security procedure for link started indication */
+#define DM_EVT_SECURITY_SETUP_COMPLETE 0x14 /**< Security procedure for link completion indication. */
+#define DM_EVT_LINK_SECURED            0x15 /**< Indicates that link with the peer is secured. For bonded devices, subsequent reconnections with bonded peer will result only in this event when the link is secured and setup procedures will not occur unless the bonding information is either lost or deleted on either or both sides.  */
+#define DM_EVT_SECURITY_SETUP_REFRESH  0x16 /**< Indicates that the security on the link was re-established. */
+/** @} */
+
+/**
+ * @defgroup context_mgmt_events Context Management Events
+ *
+ * @brief Context Management Events.
+ *
+ * @details These events notify the application of the status of context loading and storing.
+ *
+ * @{
+ */
+#define DM_EVT_DEVICE_CONTEXT_LOADED   0x21 /**< Indicates that device context for a peer is loaded. */
+#define DM_EVT_DEVICE_CONTEXT_STORED   0x22 /**< Indicates that device context is stored persistently. */
+#define DM_EVT_DEVICE_CONTEXT_DELETED  0x23 /**< Indicates that device context is deleted. */
+#define DM_EVT_SERVICE_CONTEXT_LOADED  0x31 /**< Indicates that service context for a peer is loaded. */
+#define DM_EVT_SERVICE_CONTEXT_STORED  0x32 /**< Indicates that service context is stored persistently. */
+#define DM_EVT_SERVICE_CONTEXT_DELETED 0x33 /**< Indicates that service context is deleted. */
+#define DM_EVT_APPL_CONTEXT_LOADED     0x41 /**< Indicates that application context for a peer is loaded. */
+#define DM_EVT_APPL_CONTEXT_STORED     0x42 /**< Indicates that application context is stored persistently. */
+#define DM_EVT_APPL_CONTEXT_DELETED    0x43 /**< Indicates that application context is deleted. */
+/** @} */
+/** @} */
+
+#define DM_INVALID_ID 0xFF /**< Invalid instance idenitifer. */
+
+/**
+ * @defgroup dm_data_structure Device Manager Data Types
+ *
+ * @brief This section describes all the data types exposed by the module to the application.
+ * @{
+ */
+
+/**
+ * @brief Application Instance.
+ *
+ * @details Application instance uniquely identifies an application. The identifier is allocated by
+ *          the device manager when application registers with the module. The application is
+ *          expected to identify itself with this instance identifier when initiating subsequent
+ *          requests. Application should use the utility API \ref dm_application_instance_set in
+ *          order to set its application instance in dm_handle_t needed for all subsequent APIs.
+ *          See also \ref dm_register.
+ */
+typedef uint8_t dm_application_instance_t;
+
+/**
+ * @brief Connection Instance.
+ *
+ * @details Identifies connection instance for an active device. This instance is allocated by the 
+ *          device manager when a connection is established and is notified with DM_EVT_CONNECTION
+ *          with the event result NRF_SUCCESS.
+ */
+typedef uint8_t dm_connection_instance_t;
+
+/**
+ * @brief Device Instance.
+ *
+ * @details Uniquely identifies a bonded peer device. The peer device may or may not be connected.
+ *          In case of the central: The bonded device instance to identify the peer is allocated when bonding procedure is initiated by the central using dm_security_setup_req.
+ *          In case of the peripheral: When the bonding procedure is successful, the DM_EVT_SECURITY_SETUP_COMPLETE event with success event result, is received.
+ *          In case the module cannot add more bonded devices, no instance is allocated, this is indicated by an appropriate error code for the API/event as the case may be. Application can choose to disconnect the link.
+ */
+typedef uint8_t dm_device_instance_t;
+
+/**
+ * @brief Service Instance.
+ *
+ * @details Uniquely identifies a peer device. The peer device may or may not be connected. This
+ *          instance is allocated by the device manager when a device is bonded and is notified
+ *          when security procedures have been initiated.
+ *          Security Procedures initiation is notified with DM_SECURITY_SETUP_IND with
+ *          success event result. In case the event result indicates that the module cannot add more
+ *          bonded devices, no instance is allocated. Application can chose to disconnect the link.
+ */
+typedef uint8_t dm_service_instance_t;
+
+/**
+ * @brief Service/Protocol Type Identifier.
+ *
+ * @details Uniquely identifies a service or a protocol type. Service/Protocol Type identification
+ *          is needed as each service/protocol can have its own contextual data.
+ *          This allows the peer to access more than one service at a time. \ref dm_service_cntext_types describes the
+ *          list of services/protocols supported.
+ */
+typedef uint8_t service_type_t;
+
+/**@brief Device Manager Master identification and encryption information. */
+typedef struct dm_enc_key
+{
+    ble_gap_enc_info_t  enc_info;  /**< GAP encryption information. */
+    ble_gap_master_id_t master_id; /**< Master identification. */
+} dm_enc_key_t;
+
+/** @brief Device Manager identity and address information. */
+typedef struct dm_id_key
+{
+  ble_gap_irk_t  id_info;      /**< Identity information. */
+  ble_gap_addr_t id_addr_info; /**< Identity address information. */
+} dm_id_key_t;
+
+/** @brief Device Manager signing information. */
+typedef struct dm_sign_key
+{
+    ble_gap_sign_info_t sign_key; /**< GAP signing information. */
+} dm_sign_key_t;
+
+/** @brief Security keys. */
+typedef struct dm_sec_keyset
+{
+    union 
+    {
+        dm_enc_key_t       * p_enc_key;  /**< Pointer to Device Manager encryption information structure. */
+    } enc_key;
+    dm_id_key_t   * p_id_key;            /**< Identity key, or NULL. */
+    dm_sign_key_t * p_sign_key;          /**< Signing key, or NULL. */
+} dm_sec_keys_t;
+
+/** @brief Device Manager security key set. */
+typedef struct
+{
+  dm_sec_keys_t keys_periph;  /**< Keys distributed by the device in the Peripheral role. */
+  dm_sec_keys_t keys_central; /**< Keys distributed by the device in the Central role. */
+} dm_sec_keyset_t;
+
+/**
+ * @brief Device Handle used for unique identification of each peer.
+ *
+ * @details This data type is used to uniquely identify each peer device. A peer device could be
+ *          active and/or bonded. Therefore an instance for active and bonded is provided.
+ *          However, the application is expected to treat this is an opaque structure and use this for
+ *          all API interactions once stored on appropriate events.
+ *          See \ref dm_events.
+ */
+typedef struct device_handle
+{
+    dm_application_instance_t    appl_id;       /**< Identifies the application instances for the device that is being managed. */
+    dm_connection_instance_t     connection_id; /**< Identifies the active connection instance. */
+    dm_device_instance_t         device_id;     /**< Identifies peer instance in the data base. */
+    dm_service_instance_t        service_id;    /**< Service instance identifier. */
+} dm_handle_t;
+
+/**
+ * @brief Definition of Data Context.
+ *
+ * @details Defines contextual data format, it consists of context data length and pointer to data.
+ */
+typedef struct
+{
+    uint32_t  flags;  /**< Additional flags identifying data. */
+    uint32_t  len;    /**< Length of data. */
+    uint8_t * p_data; /**< Pointer to contextual data, a copy is made of the data. */
+} dm_context_t;
+
+
+/**
+ * @brief Device Context.
+ *
+ * @details Defines "device context" type for a device managed by device manager.
+ */
+typedef dm_context_t dm_device_context_t;
+
+/**
+ * @brief Service Context.
+ *
+ * @details Service context data for a service identified by the 'service_type' field.
+ */
+typedef struct
+{
+    service_type_t service_type; /**< Identifies the service/protocol to which the context data is related. */
+    dm_context_t   context_data; /**< Contains length and pointer to context data */
+} dm_service_context_t;
+
+/**
+ * @brief Application context.
+ *
+ * @details The application context can be used by the application to map any application level
+ *          information that is to be mapped with a particular peer.
+ *          For bonded peers, this information will be stored by the bond manager persistently.
+ *          Note that the device manager treats this information as an
+ *          opaque block of bytes.
+ *          Necessary APIs to get and set this context for a peer have been provided.
+ */
+typedef dm_context_t dm_application_context_t;
+
+/**
+ * @brief Event parameters.
+ *
+ * @details Defines event parameters for each of the events notified by the module.
+ */
+typedef union
+{
+    ble_gap_evt_t            * p_gap_param;       /**< All events that are triggered in device manager as a result of GAP events, like connection, disconnection and security procedures are accompanied with GAP parameters. */
+    dm_application_context_t * p_app_context;     /**< All events that are associated with application context procedures of store, load, and deletion have this as event parameter. */
+    dm_service_context_t     * p_service_context; /**< All events that are associated with service context procedures of store, load and deletion have this as event parameter. */
+    dm_device_context_t      * p_device_context;  /**< All events that are associated with device context procedures of store, load and deletion have this as event parameter. */
+} dm_event_param_t;
+
+/**
+ * @brief Asynchronous events details notified to the application by the module.
+ *
+ * @details Defines event type along with event parameters notified to the application by the
+ *          module.
+ */
+typedef struct
+{
+    uint8_t          event_id;       /**< Identifies the event. See \ref dm_events for details on event types and their significance. */
+    dm_event_param_t event_param;    /**< Event parameters. Can be NULL if the event does not have any parameters. */
+    uint16_t         event_paramlen; /**< Length of the event parameters, is zero if the event does not have any parameters. */
+} dm_event_t;
+
+/**
+ * @brief Event notification callback registered by application with the module.
+ *
+ * @details Event notification callback registered by application with the module when registering
+ *          the module using \ref dm_register API.
+ *
+ * @param[in] p_handle   Identifies the peer for which the event is being notified.
+ * @param[in] p_event    Identifies the event, any associated parameters and parameter length.
+ *                       See \ref dm_events for details on event types and their significance.
+ * @param[in,out] event_result   Provide additional information on the event. 
+ *                      In addition to SDK error codes there is also a return value
+ *                      indicating if maximum number of connections has been reached when connecting or bonding.
+ *
+ * @retval NRF_SUCCESS on success, or a failure to indicate if it could handle the event
+ *         successfully. There is no action taken in case application returns a failure.
+ */
+typedef ret_code_t (*dm_event_cb_t)(dm_handle_t const * p_handle,
+                                    dm_event_t const  * p_event,
+                                    ret_code_t        event_result);
+
+/**
+ * @brief Initialization Parameters.
+ *
+ * @details Indicates the application parameters. Currently this only encompasses clearing
+ *          all persistent data.
+ */
+typedef struct
+{
+    bool clear_persistent_data; /**< Set to true in case the module should clear all persistent data. */
+} dm_init_param_t;
+
+/**
+ * @brief Application Registration Parameters.
+ *
+ * @details Parameters needed by the module when registering with it.
+ */
+typedef struct
+{
+    dm_event_cb_t        evt_handler;  /**< Event Handler to be registered. It will receive asynchronous notification from the module, see \ref dm_events for asynchronous events. */
+    uint8_t              service_type; /**< Bit mask identifying services that the application intends to support for all peers. */
+    ble_gap_sec_params_t sec_param;    /**< Security parameters to be used for the application. */
+} dm_application_param_t;
+
+/**
+ * @brief Defines possible security status/states.
+ *
+ * @details Defines possible security status/states of a link when requested by application using
+ *          the \ref dm_security_status_req.
+ */
+typedef enum
+{
+    NOT_ENCRYPTED,          /**< The link is not secured. */
+    ENCRYPTION_IN_PROGRESS, /**< Link security is being established.*/
+    ENCRYPTED               /**< The link is secure.*/
+} dm_security_status_t;
+/** @} */
+
+/**
+ * @defgroup dm_api Device Module APIs
+ *
+ * @brief This section describes APIs exposed by the module.
+ *
+ * @details This section describes APIs exposed by the module. The APIs have been categorized to provide
+ *          better and specific look up for developers. Categories are:
+ *          - Set up APIs.
+ *          - Context Management APIs.
+ *          - Utility APIs.
+ *
+ *          MSCs describe usage of these APIs.  
+ *          See @ref dm_msc.
+ * @{
+ */
+/**
+ * @defgroup dm_setup_api Device Module Set-up APIs
+ *
+ * @brief Initialization & registration APIs that are pre-requisite for all other module procedures.
+ * @details This section describes the Module Initialization and Registration APIs needed to be set up by
+ *          the application before device manager can start managing devices and device contexts
+ *          for the application.
+ *
+ * @{
+ */
+
+/**
+ * @brief Module Initialization Routine.
+ *
+ * @details Function for initializing the module. Must called before any other APIs of the module are used.
+ *
+ * @param[in] p_init_param Initialization parameters.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ *
+ * @note It is mandatory that pstorage is initialized before initializing this module.
+ */
+ret_code_t dm_init(dm_init_param_t const * p_init_param);
+
+/**
+ * @brief Function for registering the application.
+ *
+ * @details This routine is used by the application to register for asynchronous events with the
+ *          device manager. During registration the application also indicates the services that it
+ *          intends to support on this instance. It is possible to register multiple times with the
+ *          device manager. At least one instance shall be registered with the device manager after
+ *          the module has been initialized.
+ *          Maximum number of application instances device manager can support is determined
+ *          by DM_MAX_APPLICATIONS.
+ *
+ *          All applications must be registered before initiating or accepting connections from the peer.     
+ *
+ * @param[in]  p_appl_param    Application parameters.
+ * @param[out] p_appl_instance Application Instance Identifier in case registration is successful.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization.
+ * @retval NRF_ERROR_NO_MEM        If module cannot support more applications.
+ *
+ * @note Currently only one application instance is supported by the module.
+ */
+ret_code_t dm_register(dm_application_instance_t    * p_appl_instance,
+                       dm_application_param_t const * p_appl_param);
+
+/**
+ * @brief Function for handling BLE events.
+ *
+ * @details BLE Event Handler for the module. This routine should be called from BLE stack event
+ *          dispatcher for the module to work as expected.
+ *
+ * @param[in] p_ble_evt BLE stack event being dispatched to the function.
+ *
+ */
+void dm_ble_evt_handler(ble_evt_t * p_ble_evt);
+
+/** @} */
+
+
+/**
+ * @defgroup dm_security_api APIs to set up or read status of security on a link.
+ *
+ * @brief This section describes APIs to set up Security. These APIs require that the peer is
+ *        connected before the procedures can be requested.
+ *
+ * @details This group allows application to request security procedures
+ *          or get the status of the security on a link.
+ * @{
+ */
+/**
+ * @brief Function for requesting setting up security on a link.
+ *
+ * @details This API initiates security procedures with a peer device.
+ *          @note For the GAP Central role, in case peer is not bonded, request to bond/pair is
+ *          initiated. If it is bonded, the link is re-encrypted using the existing bond information.
+ *          For the GAP peripheral role, a Slave security request is sent.
+ * @details If a pairing procedure is initiated successfully, application is notified of
+ *          @ref DM_EVT_SECURITY_SETUP_COMPLETE. A result indicating success or failure is notified along with the event.
+ *          In case the link is re-encrypted using existing bond information, @ref DM_EVT_LINK_SECURED is
+ *          notified to the application.
+ *
+ * @param[in] p_handle Identifies the link on which security is desired.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application
+ *                                 or if the peer is not connected when this procedure is requested.
+ */
+ret_code_t dm_security_setup_req(dm_handle_t * p_handle);
+
+/**
+ * @brief Function for reading the status of the security on a link.
+ *
+ * @details This API allows application to query status of security on a link.
+ *
+ * @param[in]  p_handle  Identifies the link on which security is desired.
+ * @param[out] p_status  Pointer where security status is provided to the application.
+ *                       See \ref dm_security_status_t for possible statuses that can be expected.
+ *
+ * @retval NRF_SUCCESS             Or appropriate error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle or p_status is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If peer is not identified by the handle provided by the application
+ *                                 or if peer is not connected when this procedure is requested.
+ */
+ret_code_t dm_security_status_req(dm_handle_t const * p_handle, dm_security_status_t * p_status);
+
+/**
+ * @brief Function for creating the whitelist.
+ *
+ * @details This API allows application to create whitelist based on bonded peer devices in module
+ *          data base.
+ *
+ * @param[in]  p_handle       Identifies the application requesting whitelist creation.
+ * @param[in,out] p_whitelist Pointer where created whitelist is provided to the application.
+ *
+ * @note 'addr_count' and 'irk_count' fields of the structure should be populated with the maximum
+ *       number of devices that the application wishes to request in the whitelist. 
+ *       If the number of bonded devices is less than requested, the fields are updated with that number of devices.
+ *       If the number of devices are more than requested, the module will populate the list
+ *       with devices in the order the bond was established with the peer devices. Also, if this routine is
+ *       called when a connection exists with one or more peer devices,
+ *       those connected devices are not added to the whitelist.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle or p_whitelist is NULL.
+ */
+ret_code_t dm_whitelist_create(dm_application_instance_t const * p_handle,
+                               ble_gap_whitelist_t             * p_whitelist);
+
+/** @} */
+
+
+/**
+ * @defgroup dm_cntxt_mgmt_api Context Management APIs
+ *
+ * @brief Utility APIs offered by the device manager to get information about the peer if and
+ *        when needed.
+ *
+ * @details This group of API allow the application to access information that is not required to be
+ *          maintained by the application but may be needed. Hence it is possible to get the
+ *          information from the module instead of mapping all the information with a device
+ *          context.
+ * @{
+ */
+
+ret_code_t dm_device_add(dm_handle_t               * p_handle,
+                         dm_device_context_t const * p_context);
+
+/**
+ * @brief Function for deleting a peer device context and all related information from the database.
+ *
+ * @details Delete peer device context and all related information from database. If
+ *          this API returns NRF_SUCCESS, DM_EVT_DEVICE_CONTEXT_DELETED event is notified to the
+ *          application. Event result notified along with the event indicates success or failure
+ *          of this procedure.
+ *
+ * @param[in] p_handle Identifies the peer device to be deleted.
+ *
+ * @retval NRF_SUCCESS             on success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE In the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If peer is not identified the handle provided by the application.
+ *
+ * @note Deleting device context results in deleting service and application context for the
+ *       bonded device. The respective events DM_EVT_SERVICE_CONTEXT_DELETED and
+ *       DM_EVT_APPL_CONTEXT_DELETED are not notified to the application.
+ */
+ret_code_t dm_device_delete(dm_handle_t const * p_handle);
+
+/**
+ * @brief Function for deleting all peer device context and all related information from the database.
+ *
+ * @details Delete peer device context and all related information from database. If
+ *          this API returns NRF_SUCCESS, DM_EVT_DEVICE_CONTEXT_DELETED event is notified to the
+ *          application for each device that is deleted from the data base. Event result
+ *          notified along with the event indicates success or failure of this procedure.
+ *
+ * @param[in] p_handle Identifies application instance that is requesting
+ *                     the deletion of all bonded devices.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If peer is not identified the handle provided by the application.
+ *
+ * @note Deleting device context results in deleting both service and application context for the
+ *       bonded device. The respective events DM_EVT_SERVICE_CONTEXT_DELETED and
+ *       DM_EVT_APPL_CONTEXT_DELETED are not notified to the application.
+ */
+ret_code_t dm_device_delete_all(dm_application_instance_t const * p_handle);
+
+/**
+ * @brief Function for setting Service Context for a peer device identified by 'p_handle' parameter.
+ *
+ * @details This API allows application to Set Service Context for a peer device identified by the
+ *          'p_handle' parameter. This API is useful when the Service Context cannot be requested
+ *          from the SoftDevice, but needs to be assembled by the application or an another module.
+ *          (or when service context is exchanged in an out of band way.)
+ *          This API could also be used to trigger a storing of service context into persistent
+ *          memory. If this is desired, a NULL pointer could be passed to the p_context.
+ *
+ * @param[in] p_handle  Identifies peer device for which the procedure is requested.
+ * @param[in] p_context Service context being set. The context information includes length of
+ *                      data and pointer to the contextual data being set. The memory pointed to by
+ *                      the pointer to data is assumed to be resident when API is being called and
+ *                      can be freed or reused once the set procedure is complete. Set procedure
+ *                      completion is indicated by the event \ref DM_EVT_SERVICE_CONTEXT_STORED.
+ *                      The Event result is notified along with the event and indicates success or failure of
+ *                      this procedure.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ */
+ret_code_t dm_service_context_set(dm_handle_t const          * p_handle,
+                                  dm_service_context_t const * p_context);
+
+/**
+ * @brief Function for getting Service Context for a peer device identified by 'p_handle' parameter.
+ *
+ * @details Get Service Context for a peer device identified by the 'p_handle' parameter. If
+ *          this API returns NRF_SUCCESS, DM_EVT_SERVICE_CONTEXT_LOADED event is notified to the
+ *          application. The event result is notified along with the event indicates success or failure
+ *          of this procedure.
+ *
+ * @param[in] p_handle  Identifies peer device for which procedure is requested.
+ * @param[in] p_context Application context being requested. The context information includes length
+ *                      of the data and a pointer to the data. Note that requesting a 'get'
+ *                      of application does not need to provide memory, the pointer to data will be
+ *                      pointing to service data and hence no data movement is involved.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE In case API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ */
+ret_code_t dm_service_context_get(dm_handle_t const    * p_handle,
+                                  dm_service_context_t * p_context);
+
+/**
+ * @brief Function for deleting a Service Context for a peer device identified by the 'p_handle' parameter.
+ *
+ * @details This API allows application to delete a Service Context identified for a peer device
+ *          identified by the 'p_handle' parameter. If this API returns NRF_SUCCESS,
+ *          DM_EVT_SERVICE_CONTEXT_DELETED event is notified to the application. 
+ *          Event result is notified along with the event and indicates success or failure of this
+ *          procedure.
+ *
+ * @param[in] p_handle Identifies peer device for which procedure is requested.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ */
+ret_code_t dm_service_context_delete(dm_handle_t const * p_handle);
+
+/**
+ * @brief Function for setting Application Context for a peer device identified by the 'p_handle' parameter.
+ *
+ * @details This application allows the setting of the application context for the peer device identified by
+ *          the 'p_handle'. Application context is stored persistently by the module and can be
+ *          requested by the application at any time using the \ref dm_application_context_get
+ *          API. Note that this procedure is permitted only for bonded devices. If the
+ *          device is not bonded, application context cannot be set. However, it is not mandatory
+ *          that the bonded device is connected when requesting this procedure.
+ *
+ * @param[in] p_handle  Identifies peer device for which procedure is requested.
+ *
+ * @param[in] p_context Application context being set. The context information includes length of the
+ *                      data and pointer to the contextual data being set. The memory pointed to by
+ *                      the data pointer is assumed to be resident when API is being called and
+ *                      can be freed or reused once the set procedure is complete. Set procedure
+ *                      completion is notified by the event \ref DM_EVT_APPL_CONTEXT_STORED.
+ *                      The event result is notified along with the event and indicates success or
+ *                      failure of this procedure.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle and/or p_context is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If peer is not identified the handle provided by the application.
+ *
+ * @note The API returns FEATURE_NOT_ENABLED in case DEVICE_MANAGER_APP_CONTEXT_SIZE is set to zero.
+ */
+ret_code_t dm_application_context_set(dm_handle_t const              * p_handle,
+                                      dm_application_context_t const * p_context);
+
+/**
+ * @brief Function for getting Application Context for a peer device identified by the 'p_handle' parameter.
+ *
+ * @details Get Application Context for a peer device identified by the 'p_handle' parameter. If
+ *          this API returns NRF_SUCCESS, DM_EVT_APPL_CONTEXT_LOADED event is notified to the
+ *          application. Event result notified along with the event indicates success or failure
+ *          of this procedure.
+ *
+ * @param[in] p_handle  Identifies peer device for which procedure is requested.
+ * @param[in] p_context Application context being requested. The context information includes
+ *                      length of data and pointer to the contextual data is provided.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle and/or p_context is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ * @retval DM_NO_APP_CONTEXT       If no application context was set that can be fetched.
+ *
+ * @note The API returns FEATURE_NOT_ENABLED in case DEVICE_MANAGER_APP_CONTEXT_SIZE is set to
+ *       zero.
+ */
+ret_code_t dm_application_context_get(dm_handle_t const        * p_handle,
+                                      dm_application_context_t * p_context);
+
+/**
+ * @brief Function for deleting Application Context for a peer device identified by the 'p_handle' parameter.
+ *
+ * @details Delete Application Context for a peer device identified by the 'p_handle' parameter. If
+ *          this API returns NRF_SUCCESS, DM_EVT_APPL_CONTEXT_DELETED event is notified to the
+ *          application. The event result notified along with the event and indicates success or failure
+ *          of this procedure.
+ *
+ * @param[in] p_handle Identifies peer device for which procedure is requested.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If the p_handle is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If peer is not identified the handle provided by the application.
+ * @retval DM_NO_APP_CONTEXT       If no application context was set that can be deleted.
+ *
+ * @note The API returns FEATURE_NOT_ENABLED if the DEVICE_MANAGER_APP_CONTEXT_SIZE is set to zero.
+ */
+ret_code_t dm_application_context_delete(dm_handle_t const * p_handle);
+
+/** @} */
+
+
+/**
+ * @defgroup utility_api Utility APIs
+ * @{
+ * @brief This section describes the utility APIs offered by the module.
+ *
+ * @details APIs defined in this section are utility or assisting/helper APIs.
+ */
+/**
+ * @brief Function for Setting/Copying Application instance to Device Manager handle.
+ *
+ * @param[in]  p_appl_instance Application instance to be set.
+ * @param[out] p_handle        Device Manager handle for which the instance is to be copied.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle and/or p_addr is NULL.
+ */
+ret_code_t dm_application_instance_set(dm_application_instance_t const * p_appl_instance,
+                                       dm_handle_t                     * p_handle);
+
+/**
+ * @brief Function for getting a peer's device address.
+ *
+ * @param[in]  p_handle Identifies the peer device whose address is requested. Can not be NULL.
+ * @param[out] p_addr   Pointer where address is to be copied. Can not be NULL.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle and/or p_addr is NULL.
+ * @retval NRF_ERROR_NOT_FOUND     If the peer could not be identified.
+ */
+ret_code_t dm_peer_addr_get(dm_handle_t const * p_handle,
+                            ble_gap_addr_t    * p_addr);
+
+/**
+ * @brief Function for setting/updating a peer's device address.
+ *
+ * @param[in]  p_handle Identifies the peer device whose address is requested to be set/updated.
+ * @param[out] p_addr   Address to be set/updated.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If p_handle and/or p_addr is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ * @retval NRF_ERROR_INVALID_PARAM If this procedure is requested while connected to the peer or if the address
+ *                                 type was set to BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE.
+ *
+ * @note Setting or updating a peer's device address is permitted 
+ *       only for a peer that is bonded and disconnected.
+ * @note Updated address is reflected only after DM_EVT_DEVICE_CONTEXT_STORED is notified to the
+ *       application for this bonded device instance. In order to avoid abnormal behaviour, it is
+ *       recommended to not invite/initiate connections on the updated address unless this event
+ *       has been notified.
+ */
+ret_code_t dm_peer_addr_set(dm_handle_t const    * p_handle,
+                            ble_gap_addr_t const * p_addr);
+
+/**
+ * @brief Function for initializing Device Manager handle.
+ *
+ * @param[in] p_handle Device Manager handle to be initialized.
+ *
+ * @retval NRF_SUCCESS    On success.
+ * @retval NRF_ERROR_NULL If p_handle is NULL.
+ *
+ * @note This routine is permitted before initialization of the module.
+ */
+ret_code_t dm_handle_initialize(dm_handle_t * p_handle);
+
+/**
+ * @brief Function for getting distributed keys for a device.
+ *
+ * @param[in]  p_handle   Device Manager handle identifying the peer.
+ * @param[out] p_key_dist Pointer to distributed keys.
+ *
+ * @retval NRF_SUCCESS             On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_INVALID_STATE If the API is called without module initialization and/or
+ *                                 application registration.
+ * @retval NRF_ERROR_NULL          If the p_handle and/or p_key_dist pointer is NULL.
+ * @retval NRF_ERROR_INVALID_ADDR  If the peer is not identified by the handle provided by the application.
+ */
+ret_code_t dm_distributed_keys_get(dm_handle_t const * p_handle,
+                                   dm_sec_keyset_t   * p_key_dist);
+
+/**
+ * @brief Function for getting the corresponding dm_handle_t based on the connection handle.
+ *
+ * @param[in]     conn_handle Connection handle as provided by the SoftDevice.
+ * @param[in,out] p_handle    Pointer to the p_handle containg the application instance for the 
+ *                            registered application. If the application instance is valid then 
+ *                            the p_handle will be filled with requested data.
+ *
+ * @retval NRF_SUCCESS          On success, else an error code indicating reason for failure.
+ * @retval NRF_ERROR_NULL       If the p_handle pointer is NULL.
+ * @retval NRF_ERROR_NOT_FOUND  If no p_handle is found for the provided connection handle.
+ */
+ret_code_t dm_handle_get(uint16_t conn_handle, dm_handle_t * p_handle);
+
+/** @} */
+/** @} */
+/** @} */
+#endif // DEVICE_MANAGER_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager_peripheral.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/device_manager/device_manager_peripheral.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,2934 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "device_manager.h"
+#include "pstorage.h"
+#include "ble_hci.h"
+#include "app_error.h"
+
+#if defined ( __CC_ARM )
+    #ifndef __ALIGN
+        #define __ALIGN(x)      __align(x)                  /**< Forced aligment keyword for ARM Compiler */
+    #endif
+#elif defined ( __ICCARM__ )
+    #ifndef __ALIGN
+        #define __ALIGN(x)                                  /**< Forced aligment keyword for IAR Compiler */
+    #endif
+#elif defined   ( __GNUC__ )
+    #ifndef __ALIGN
+        #define __ALIGN(x)      __attribute__((aligned(x))) /**< Forced aligment keyword for GNU Compiler */
+    #endif
+#endif
+
+#define INVALID_ADDR_TYPE 0xFF   /**< Identifier for an invalid address type. */
+#define EDIV_INIT_VAL     0xFFFF /**< Initial value for diversifier. */
+
+/**
+ * @defgroup device_manager_app_states Connection Manager Application States
+ * @{
+ */
+#define STATE_CONTROL_PROCEDURE_IN_PROGRESS 0x01 /**< State where a security procedure is ongoing. */
+#define STATE_QUEUED_CONTROL_REQUEST        0x02 /**< State where it is known if there is any queued security request or not. */
+/** @} */
+
+/**
+ * @defgroup device_manager_conn_inst_states Connection Manager Connection Instances States.
+ * @{
+ */
+#define STATE_IDLE             0x01 /**< State where connection instance is free. */
+#define STATE_CONNECTED        0x02 /**< State where connection is successfully established. */
+#define STATE_PAIRING          0x04 /**< State where pairing procedure is in progress. This state is used for pairing and bonding, as pairing is needed for both. */
+#define STATE_BONDED           0x08 /**< State where device is bonded. */
+#define STATE_DISCONNECTING    0x10 /**< State where disconnection is in progress, application will be notified first, but no further active procedures on the link. */
+#define STATE_PAIRING_PENDING  0x20 /**< State where pairing request is pending on the link. */
+#define STATE_BOND_INFO_UPDATE 0x40 /**< State where information has been updated, update the flash. */
+#define STATE_LINK_ENCRYPTED   0x80 /**< State where link is encrypted. */
+/** @} */
+
+/**
+ * @defgroup device_manager_peer_id_defines Peer Identification Information Defines.
+ *
+ * @brief These defines are used to know which of the peer identification is applicable for a peer.
+ *
+ * @details These defines are used for peer identification. Here, bit map is used because it is
+ *          possible that the application has both IRK and address for identification.
+ * @{
+ */
+#define UNASSIGNED            0xFF /**< Peer instance is unassigned/unused. */
+#define IRK_ENTRY             0x01 /**< Peer instance has IRK as identification information. */
+#define ADDR_ENTRY            0x02 /**< Peer instance has address as identification information. */
+#define SERVICE_CONTEXT_ENTRY 0x04 /**< Peer instance has service context set. */
+#define APP_CONTEXT_ENTRY     0x08 /**< Peer instance has an application context set. */
+/** @} */
+
+/**@brief Device store state identifiers. */
+typedef enum
+{
+    STORE_ALL_CONTEXT, /**< Store all context. */
+    FIRST_BOND_STORE,  /**< Store bond. */
+    UPDATE_PEER_ADDR   /**< Update peer address. */
+} device_store_state_t;
+
+/**
+ * @defgroup device_manager_context_offsets Context Offsets
+ * @{
+ *
+ * @brief Context offsets each of the context information in persistent memory.
+ *
+ * @details Below is a layout showing how each how the context information is stored in persistent
+ *          memory.
+ *
+ * All Device context is stored in the flash as follows:
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ * | Block / Device ID + Layout of stored information in storage block                    |
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ * | Block 0 | Device 0| Peer Id | Bond Information | Service Context| Application Context|
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ * | Block 1 | Device 1| Peer Id | Bond Information | Service Context| Application Context|
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ * |  ...              | ....                                                             |
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ * | Block N | Device N| Peer Id | Bond Information | Service Context| Application Context|
+ * +---------+---------+---------+------------------+----------------+--------------------+
+ *
+ * The following defines are used to get offset of each of the components within a block.
+ */
+
+#define PEER_ID_STORAGE_OFFSET     0                                               /**< Offset at which peer id is stored in the block. */
+#define BOND_STORAGE_OFFSET        PEER_ID_SIZE                                    /**< Offset at which bond information is stored in the block. */
+#define SERVICE_STORAGE_OFFSET     (BOND_STORAGE_OFFSET + BOND_SIZE)               /**< Offset at which service context is stored in the block. */
+#define APP_CONTEXT_STORAGE_OFFSET (SERVICE_STORAGE_OFFSET + SERVICE_CONTEXT_SIZE) /**< Offset at which application context is stored in the block. */
+/** @} */
+
+/**
+ * @defgroup device_manager_context_size Context size.
+ * @{
+ *
+ * @brief This group defines the size of each of the context information.
+ */
+#define PEER_ID_SIZE               (sizeof(peer_id_t))                                             /**< Size of peer identification information. */
+#define BOND_SIZE                  (sizeof(bond_context_t))                                        /**< Size of bond information. */
+#define DEVICE_CONTEXT_SIZE        (PEER_ID_SIZE + BOND_SIZE)                                      /**< Size of Device context, include peer identification and bond information. */
+#define GATTS_SERVICE_CONTEXT_SIZE (sizeof(dm_gatts_context_t))                                    /**< Size of GATTS service context. */
+#define GATTC_SERVICE_CONTEXT_SIZE (sizeof(dm_gatt_client_context_t))                              /**< Size of GATTC service context. */
+#define SERVICE_CONTEXT_SIZE       (GATTS_SERVICE_CONTEXT_SIZE + GATTC_SERVICE_CONTEXT_SIZE)       /**< Combined size of GATTS and GATTC service contexts. */
+#define APP_CONTEXT_MIN_SIZE       4                                                               /**< Minimum size for application context data. */
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+#define APP_CONTEXT_SIZE           (sizeof(uint32_t) + DEVICE_MANAGER_APP_CONTEXT_SIZE)            /**< Size of application context including length field. */
+#else //DEVICE_MANAGER_APP_CONTEXT_SIZE
+#define APP_CONTEXT_SIZE           0                                                               /**< Size of application context. */
+#endif // DEVICE_MANAGER_APP_CONTEXT_SIZE
+#define ALL_CONTEXT_SIZE           (DEVICE_CONTEXT_SIZE + SERVICE_CONTEXT_SIZE + APP_CONTEXT_SIZE) /**< Size of all contexts. */
+/** @} */
+
+
+/**
+ * @defgroup device_manager_log Module's Log Macros
+ *
+ * @details Macros used for creating module logs which can be useful in understanding handling
+ *          of events or actions on API requests. These are intended for debugging purposes and
+ *          can be disabled by defining the DM_DISABLE_LOGS.
+ *
+ * @note That if ENABLE_DEBUG_LOG_SUPPORT is disabled, having DM_DISABLE_LOGS has no effect.
+ * @{
+ */
+#define DM_DISABLE_LOGS        /**< Enable this macro to disable any logs from this module. */
+
+#ifndef DM_DISABLE_LOGS
+#define DM_LOG  app_trace_log  /**< Used for logging details. */
+#define DM_ERR  app_trace_log  /**< Used for logging errors in the module. */
+#define DM_TRC  app_trace_log  /**< Used for getting trace of execution in the module. */
+#define DM_DUMP app_trace_dump /**< Used for dumping octet information to get details of bond information etc. */
+#else //DM_DISABLE_LOGS
+#define DM_DUMP(...)           /**< Disables dumping of octet streams. */
+#define DM_LOG(...)            /**< Disables detailed logs. */
+#define DM_ERR(...)            /**< Disables error logs. */
+#define DM_TRC(...)            /**< Disables traces. */
+#endif //DM_DISABLE_LOGS
+/** @} */
+
+/**
+ * @defgroup device_manager_mutex_lock_unlock Module's Mutex Lock/Unlock Macros.
+ *
+ * @details Macros used to lock and unlock modules. Currently the SDK does not use mutexes but
+ *          framework is provided in case need arises to use an alternative architecture.
+ * @{
+ */
+#define DM_MUTEX_LOCK()   SDK_MUTEX_LOCK(m_dm_mutex)   /**< Lock module using mutex. */
+#define DM_MUTEX_UNLOCK() SDK_MUTEX_UNLOCK(m_dm_mutex) /**< Unlock module using mutex. */
+/** @} */
+
+
+/**
+ * @defgroup device_manager_misc_defines Miscellaneous defines used across the module.
+ * @{
+ */
+#define DM_GATT_ATTR_SIZE            6                                                   /**< Size of each GATT attribute to be stored persistently. */
+#define DM_GATT_SERVER_ATTR_MAX_SIZE ((DM_GATT_ATTR_SIZE * DM_GATT_CCCD_COUNT) + 2) /**< Maximum size of GATT attributes to be stored.*/
+#define DM_SERVICE_CONTEXT_COUNT     (DM_PROTOCOL_CNTXT_ALL + 1)                         /**< Maximum number of service contexts. */
+#define DM_EVT_DEVICE_CONTEXT_BASE   0x20                                                /**< Base for device context base. */
+#define DM_EVT_SERVICE_CONTEXT_BASE  0x30                                                /**< Base for service context base. */
+#define DM_EVT_APP_CONTEXT_BASE      0x40                                                /**< Base for application context base. */
+#define DM_LOAD_OPERATION_ID         0x01                                                /**< Load operation identifier. */
+#define DM_STORE_OPERATION_ID        0x02                                                /**< Store operation identifier. */
+#define DM_CLEAR_OPERATION_ID        0x03                                                /**< Clear operation identifier. */
+/** @} */
+
+#define DM_GATTS_INVALID_SIZE        0xFFFFFFFF                                     /**< Identifer for GATTS invalid size. */
+
+/**
+ * @defgroup api_param_check API Parameters check macros.
+ *
+ * @details Macros for verifying parameters passed to the module in the APIs. These macros
+ *          could be mapped to nothing in the final version of the code in order to save execution 
+ *          time and program size.
+ * @{
+ */
+
+//#define DM_DISABLE_API_PARAM_CHECK /**< Macro to disable API parameters check. */
+
+#ifndef DM_DISABLE_API_PARAM_CHECK
+
+/**@brief Macro for verifying NULL parameters are not passed to API.
+ *
+ * @param[in] PARAM Parameter checked for NULL.
+ *
+ * @retval (NRF_ERROR_NULL | DEVICE_MANAGER_ERR_BASE) when @ref PARAM is NULL.
+ */
+#define NULL_PARAM_CHECK(PARAM)                            \
+    if ((PARAM) == NULL)                                   \
+    {                                                      \
+        return (NRF_ERROR_NULL | DEVICE_MANAGER_ERR_BASE); \
+    }
+/**@} */
+
+
+/**@brief Macro for verifying module's initialization status.
+ *
+ * @retval (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE) when module is not initialized.
+ */
+#define VERIFY_MODULE_INITIALIZED()                                     \
+    do                                                                  \
+    {                                                                   \
+        if (!m_module_initialized)                                      \
+        {                                                               \
+            return (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE); \
+        }                                                               \
+    } while (0)
+
+
+/**@brief Macro for verifying module's initialization status. Returns in case it is not initialized.
+ */
+#define VERIFY_MODULE_INITIALIZED_VOID() \
+    do                                   \
+    {                                    \
+        if (!m_module_initialized)       \
+        {                                \
+            return;                      \
+        }                                \
+    } while (0)
+
+
+/**@brief Macro for verifying that the application is registered.
+ *
+ * @param[in] X Application instance identifier.
+ *
+ * @retval (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE) when module API is called without
+ *         registering an application with the module.
+ */
+#define VERIFY_APP_REGISTERED(X)                                        \
+    do                                                                  \
+    {                                                                   \
+        if (((X) >= DEVICE_MANAGER_MAX_APPLICATIONS) ||                 \
+            (m_application_table[(X)].ntf_cb == NULL))                  \
+        {                                                               \
+            return (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE); \
+        }                                                               \
+    } while (0)
+
+
+/**@brief Macro for verifying that the application is registered. Returns in case it is not
+ *        registered.
+ *
+ * @param[in] X Application instance identifier.
+ */
+#define VERIFY_APP_REGISTERED_VOID(X)                   \
+    do                                                  \
+    {                                                   \
+        if (((X) >= DEVICE_MANAGER_MAX_APPLICATIONS) || \
+            (m_application_table[(X)].ntf_cb == NULL))  \
+        {                                               \
+            return;                                     \
+        }                                               \
+    } while (0)
+
+
+/**@brief Macro for verifying connection instance is allocated.
+ *
+ * @param[in] X Connection instance identifier.
+ *
+ * @retval (NRF_ERROR_INVALID_ADDR | DEVICE_MANAGER_ERR_BASE) when connection instance is not
+ *         allocated.
+ */
+#define VERIFY_CONNECTION_INSTANCE(X)                                  \
+    do                                                                 \
+    {                                                                  \
+        if (((X) >= DEVICE_MANAGER_MAX_CONNECTIONS) ||                 \
+            (m_connection_table[(X)].state == STATE_IDLE))             \
+        {                                                              \
+            return (NRF_ERROR_INVALID_ADDR | DEVICE_MANAGER_ERR_BASE); \
+        }                                                              \
+    } while (0)
+
+
+/**@brief Macro for verifying if device instance is allocated.
+ *
+ * @param[in] X Device instance identifier.
+ *
+ * @retval (NRF_ERROR_INVALID_ADDR | DEVICE_MANAGER_ERR_BASE) when device instance is not allocated.
+ */
+#define VERIFY_DEVICE_INSTANCE(X)                                      \
+    do                                                                 \
+    {                                                                  \
+        if (((X) >= DEVICE_MANAGER_MAX_BONDS) ||                       \
+            (m_peer_table[(X)].id_bitmap == UNASSIGNED))               \
+        {                                                              \
+            return (NRF_ERROR_INVALID_ADDR | DEVICE_MANAGER_ERR_BASE); \
+        }                                                              \
+    } while (0)
+
+/**@brief Macro for verifying if device is bonded and thus can store data persistantly.
+ *
+ * @param[in] X Connection instance identifier.
+ *
+ * @retval (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE) when device is not bonded.
+ */
+#define VERIFY_DEVICE_BOND(X)                                              \
+    do                                                                     \
+    {                                                                      \
+        if ((m_connection_table[(X)].state & STATE_BONDED) != STATE_BONDED)\
+        {                                                                  \
+            return (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE);    \
+        }                                                                  \
+    } while (0)
+#else
+#define NULL_PARAM_CHECK(X)
+#define VERIFY_MODULE_INITIALIZED()
+#define VERIFY_MODULE_INITIALIZED_VOID()
+#define VERIFY_APP_REGISTERED(X)
+#define VERIFY_APP_REGISTERED_VOID(X)
+#define VERIFY_CONNECTION_INSTANCE(X)
+#define VERIFY_DEVICE_INSTANCE(X)
+#endif //DM_DISABLE_API_PARAM_CHECK
+/** @} */
+
+#define INVALID_CONTEXT_LEN 0xFFFFFFFF /**< Identifier for invalid context length. */
+/**@brief Macro for checking that application context size is greater that minimal size.
+ *
+ * @param[in] X Size of application context.
+ *
+ * @retval (NRF_ERROR_INVALID_PARAM) when size is smaller than minimun required size.
+ */
+#define SIZE_CHECK_APP_CONTEXT(X)                                      \
+    if ((X) < (APP_CONTEXT_MIN_SIZE))                                  \
+    {                                                                  \
+        return NRF_ERROR_INVALID_PARAM;                                \
+    }
+
+
+/**
+ * @defgroup dm_data_types Module's internal data types.
+ *
+ * @brief This section describes a module's internal data structures.
+ * @{
+ */
+/**@brief Peer identification information.
+ */
+typedef struct
+{ 
+    ble_gap_id_key_t peer_id;   /**< IRK and/or address of peer. */
+    uint16_t         ediv;      /**< Peer's encrypted diversifier. */
+    uint8_t          id_bitmap; /**< Contains information if above field is valid. */
+} peer_id_t;
+
+STATIC_ASSERT(sizeof(peer_id_t) % 4 == 0); /**< Check to ensure Peer identification information is a multiple of 4. */
+
+/**@brief Portion of bonding information exchanged by a device during bond creation that needs to
+ *        be stored persistently.
+ *
+ * @note  An entry is not made in this table unless device is bonded.
+ */
+typedef struct
+{
+    ble_gap_enc_key_t peer_enc_key; /**< Local LTK info, central IRK and address */
+} bond_context_t;
+
+STATIC_ASSERT(sizeof(bond_context_t) % 4 == 0); /**< Check to ensure bond information is a multiple of 4. */
+
+/**@brief GATT Server Attributes size and data.
+ */
+typedef struct
+{
+    uint32_t flags;                                    /**< Flags identifying the stored attributes. */
+    uint32_t size;                                     /**< Size of stored attributes. */
+    uint8_t  attributes[DM_GATT_SERVER_ATTR_MAX_SIZE]; /**< Array to hold the server attributes. */
+} dm_gatts_context_t;
+
+STATIC_ASSERT(sizeof(dm_gatts_context_t) % 4 == 0); /**< Check to ensure GATT Server Attributes size and data information is a multiple of 4. */
+
+/**@brief GATT Client context information. Placeholder for now.
+ */
+typedef struct
+{
+    void * p_dummy; /**< Placeholder, currently unused. */
+} dm_gatt_client_context_t;
+
+STATIC_ASSERT(sizeof(dm_gatt_client_context_t) % 4 == 0);  /**< Check to ensure GATT Client context information is a multiple of 4. */
+STATIC_ASSERT((DEVICE_MANAGER_APP_CONTEXT_SIZE % 4) == 0); /**< Check to ensure device manager application context information is a multiple of 4. */
+
+/**@brief Connection instance definition. Maintains information with respect to an active peer.
+ */
+typedef struct
+{
+    ble_gap_addr_t peer_addr;     /**< Peer identification information. This information is retained as long as the connection session exists, once disconnected, for non-bonded devices this information is not stored persistently. */
+    uint16_t       conn_handle;   /**< Connection handle for the device. */
+    uint8_t        state;         /**< Link state. */
+    uint8_t        bonded_dev_id; /**< In case the device is bonded, this points to the corresponding bonded device. This index can be used to index service and bond context as well. */
+} connection_instance_t;
+
+/**@brief Application instance definition. Maintains information with respect to a registered
+ *        application.
+ */
+typedef struct
+{
+    dm_event_cb_t        ntf_cb;    /**< Callback registered with the application. */
+    ble_gap_sec_params_t sec_param; /**< Local security parameters registered by the application. */
+    uint8_t              state;     /**< Application state. Currently this is used only for knowing if any security procedure is in progress and/or a security procedure is pending to be requested. */
+    uint8_t              service;   /**< Service registered by the application. */
+} application_instance_t;
+
+/**@brief Function for performing necessary action of storing each of the service context as
+ *        registered by the application.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is stored.
+ *
+ * @retval Operation result code.
+ */
+typedef ret_code_t (* service_context_access_t)(pstorage_handle_t const * p_block_handle,
+                                                dm_handle_t const       * p_handle);
+
+/**@brief Function for performing necessary action of applying the context information.
+ *
+ * @param[in] p_handle Device handle identifying device that is stored.
+ *
+ * @retval Operation result code.
+ */
+typedef ret_code_t (* service_context_apply_t)(dm_handle_t * p_handle);
+
+/**@brief Function for performing necessary functions of storing or updating.
+ *
+ * @param[in] p_dest Destination address where data is stored persistently.
+ * @param[in] p_src  Source address containing data to be stored.
+ * @param[in] size   Size of data to be stored expressed in bytes. Must be word aligned.
+ * @param[in] offset Offset in bytes to be applied when writing to the block.
+ *
+ * @retval Operation result code.
+ */
+typedef uint32_t (* storage_operation)(pstorage_handle_t * p_dest,
+                                       uint8_t           * p_src,
+                                       pstorage_size_t     size,
+                                       pstorage_size_t     offset);
+/** @} */
+
+/**
+ * @defgroup dm_tables Module's internal tables.
+ *
+ * @brief This section describes the module's internal tables and the static global variables
+ *        needed for its functionality.
+ * @{
+ */
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+static uint8_t * m_app_context_table[DEVICE_MANAGER_MAX_BONDS];                     /**< Table to remember application contexts of bonded devices. */
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+__ALIGN(sizeof(uint32_t))
+static peer_id_t              m_peer_table[DEVICE_MANAGER_MAX_BONDS] ;              /**< Table to maintain bonded devices' identification information, an instance is allocated in the table when a device is bonded and freed when bond information is deleted. */
+__ALIGN(sizeof(uint32_t))
+static bond_context_t         m_bond_table[DEVICE_MANAGER_MAX_CONNECTIONS];         /**< Table to maintain bond information for active peers. */
+static dm_gatts_context_t     m_gatts_table[DEVICE_MANAGER_MAX_CONNECTIONS];        /**< Table for service information for active connection instances. */
+static connection_instance_t  m_connection_table[DEVICE_MANAGER_MAX_CONNECTIONS];   /**< Table to maintain active peer information. An instance is allocated in the table when a new connection is established and freed on disconnection. */
+static application_instance_t m_application_table[DEVICE_MANAGER_MAX_APPLICATIONS]; /**< Table to maintain application instances. */
+static pstorage_handle_t      m_storage_handle;                                     /**< Persistent storage handle for blocks requested by the module. */
+static uint32_t               m_peer_addr_update;                                   /**< 32-bit bitmap to remember peer device address update. */
+static ble_gap_id_key_t       m_local_id_info;                                      /**< ID information of central in case resolvable address is used. */
+static bool                   m_module_initialized = false;                         /**< State indicating if module is initialized or not. */
+static uint8_t                m_irk_index_table[DEVICE_MANAGER_MAX_BONDS];          /**< List maintaining IRK index list. */
+
+SDK_MUTEX_DEFINE(m_dm_mutex) /**< Mutex variable. Currently unused, this declaration does not occupy any space in RAM. */
+/** @} */
+
+static __INLINE ret_code_t no_service_context_store(pstorage_handle_t const * p_block_handle,
+                                                    dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gatts_context_store(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gattc_context_store(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gattsc_context_store(pstorage_handle_t const * p_block_handle,
+                                                dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t no_service_context_load(pstorage_handle_t const * p_block_handle,
+                                                   dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gatts_context_load(pstorage_handle_t const * p_block_handle,
+                                              dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gattc_context_load(pstorage_handle_t const * p_block_handle,
+                                              dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t gattsc_context_load(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle);
+
+static __INLINE ret_code_t no_service_context_apply(dm_handle_t * p_handle);
+
+static __INLINE ret_code_t gatts_context_apply(dm_handle_t * p_handle);
+
+static __INLINE ret_code_t gattc_context_apply(dm_handle_t * p_handle);
+
+static __INLINE ret_code_t gattsc_context_apply(dm_handle_t * p_handle);
+
+
+/**< Array of function pointers based on the types of service registered. */
+const service_context_access_t m_service_context_store[DM_SERVICE_CONTEXT_COUNT] =
+{
+    no_service_context_store, /**< Dummy function, when there is no service context registered. */
+    gatts_context_store,      /**< GATT Server context store function. */
+    gattc_context_store,      /**< GATT Client context store function. */
+    gattsc_context_store      /**< GATT Server & Client context store function. */
+};
+
+
+/**< Array of function pointers based on the types of service registered. */
+const service_context_access_t m_service_context_load[DM_SERVICE_CONTEXT_COUNT] =
+{
+    no_service_context_load,  /**< Dummy function, when there is no service context registered. */
+    gatts_context_load,       /**< GATT Server context load function. */
+    gattc_context_load,       /**< GATT Client context load function. */
+    gattsc_context_load       /**< GATT Server & Client context load function. */
+};
+
+
+/**< Array of function pointers based on the types of service registered. */
+const service_context_apply_t m_service_context_apply[DM_SERVICE_CONTEXT_COUNT] =
+{
+    no_service_context_apply, /**< Dummy function, when there is no service context registered. */
+    gatts_context_apply,      /**< GATT Server context apply function. */
+    gattc_context_apply,      /**< GATT Client context apply function. */
+    gattsc_context_apply      /**< GATT Server & Client context apply function. */
+};
+
+
+const uint32_t m_context_init_len = 0xFFFFFFFF; /**< Constant used to update the initial value for context in the flash. */
+
+/**@brief Function for setting update status for the device identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ */
+static __INLINE void update_status_bit_set(uint32_t index)
+{
+    m_peer_addr_update |= (BIT_0 << index);
+}
+
+
+/**@brief Function for resetting update status for device identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ */
+static __INLINE void update_status_bit_reset(uint32_t index)
+{
+    m_peer_addr_update &= (~((uint32_t)BIT_0 << index));
+}
+
+
+/**@brief Function for providing update status for the device identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ *
+ * @retval true if the bit is set, false otherwise.
+ */
+static __INLINE bool update_status_bit_is_set(uint32_t index)
+{
+    return ((m_peer_addr_update & (BIT_0 << index)) ? true : false);
+}
+
+
+/**@brief Function for initialiasing the application instance identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ */
+static __INLINE void application_instance_init(uint32_t index)
+{
+    DM_TRC("[DM]: Initializing Application Instance 0x%08X.\r\n", index);
+
+    m_application_table[index].ntf_cb  = NULL;
+    m_application_table[index].state   = 0x00;
+    m_application_table[index].service = 0x00;
+}
+
+
+/**@brief Function for initialiasing the connection instance identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ */
+static __INLINE void connection_instance_init(uint32_t index)
+{
+    DM_TRC("[DM]: Initializing Connection Instance 0x%08X.\r\n", index);
+    
+    m_connection_table[index].state         = STATE_IDLE;
+    m_connection_table[index].conn_handle   = BLE_CONN_HANDLE_INVALID;
+    m_connection_table[index].bonded_dev_id = DM_INVALID_ID;
+    
+    memset(&m_connection_table[index].peer_addr, 0, sizeof (ble_gap_addr_t));
+}
+
+
+/**@brief Function for initialiasing the peer device instance identified by 'index'.
+ *
+ * @param[in] index Device identifier.
+ */
+static __INLINE void peer_instance_init(uint32_t index)
+{
+    DM_TRC("[DM]: Initializing Peer Instance 0x%08X.\r\n", index);
+    
+    memset(m_peer_table[index].peer_id.id_addr_info.addr, 0, BLE_GAP_ADDR_LEN);
+    memset(m_peer_table[index].peer_id.id_info.irk, 0, BLE_GAP_SEC_KEY_LEN);
+
+    //Initialize the address type to invalid.
+    m_peer_table[index].peer_id.id_addr_info.addr_type = INVALID_ADDR_TYPE;
+
+    //Initialize the identification bit map to unassigned.
+    m_peer_table[index].id_bitmap = UNASSIGNED;
+
+    // Initialize diversifier.
+    m_peer_table[index].ediv      = EDIV_INIT_VAL;
+
+
+    //Reset the status bit.
+    update_status_bit_reset(index);
+
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+    //Initialize the application context for bond device.
+    m_app_context_table[index] = NULL;
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+}
+
+
+/**@brief Function for searching connection instance matching the connection handle and the state
+ *        requested.
+ *
+ * @details Connection handle and state information is used to get a connection instance, it
+ *          is possible to ignore the connection handle by using BLE_CONN_HANDLE_INVALID.
+ *
+ * @param[in]  conn_handle Connection handle.
+ * @param[in]  state       Connection instance state.
+ * @param[out] p_instance  Connection instance.
+ *
+ * @retval NRF_SUCCESS             Operation success.
+ * @retval NRF_ERROR_INVALID_STATE Operation failure. Invalid state
+ * @retval NRF_ERROR_NOT_FOUND     Operation failure. Not found
+ */
+static ret_code_t connection_instance_find(uint16_t   conn_handle,
+                                           uint8_t    state,
+                                           uint32_t * p_instance)
+{
+    ret_code_t err_code;
+    uint32_t   index;
+
+    err_code = NRF_ERROR_INVALID_STATE;
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_CONNECTIONS; index++)
+    {
+        //Search only based on the state.
+        if (state & m_connection_table[index].state)
+        {
+            //Ignore the connection handle.
+            if ((conn_handle == BLE_CONN_HANDLE_INVALID) ||
+                (conn_handle == m_connection_table[index].conn_handle))
+            {
+                //Search for matching connection handle.
+                (*p_instance) = index;
+                err_code      = NRF_SUCCESS;
+
+                break;
+            }
+            else
+            {
+                err_code = NRF_ERROR_NOT_FOUND;
+            }
+        }
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for allocating device instance for a bonded device.
+ *
+ * @param[out] p_device_index Device index.
+ * @param[in]  p_addr         Peer identification information.
+ *
+ * @retval NRF_SUCCESS            Operation success.
+ * @retval DM_DEVICE_CONTEXT_FULL Operation failure.
+ */
+static __INLINE ret_code_t device_instance_allocate(uint8_t *              p_device_index,
+                                                    ble_gap_addr_t const * p_addr)
+{
+    ret_code_t err_code;
+    uint32_t   index;
+
+    err_code = DM_DEVICE_CONTEXT_FULL;
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        DM_TRC("[DM]:[DI 0x%02X]: Device type 0x%02X.\r\n",
+               index, m_peer_table[index].peer_id.id_addr_info.addr_type);
+        DM_TRC("[DM]: Device Addr 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X.\r\n",
+               m_peer_table[index].peer_id.id_addr_info.addr[0],
+               m_peer_table[index].peer_id.id_addr_info.addr[1],
+               m_peer_table[index].peer_id.id_addr_info.addr[2],
+               m_peer_table[index].peer_id.id_addr_info.addr[3],
+               m_peer_table[index].peer_id.id_addr_info.addr[4],
+               m_peer_table[index].peer_id.id_addr_info.addr[5]);
+
+        if (m_peer_table[index].id_bitmap == UNASSIGNED)
+        {
+            if (p_addr->addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE)
+            {
+                m_peer_table[index].id_bitmap            &= (~ADDR_ENTRY);
+                m_peer_table[index].peer_id.id_addr_info  = (*p_addr);
+            }
+            else
+            {
+                m_peer_table[index].id_bitmap &= (~IRK_ENTRY);
+            }
+
+            (*p_device_index) = index;
+            err_code          = NRF_SUCCESS;
+
+            DM_LOG("[DM]: Allocated device instance 0x%02X\r\n", index);
+            
+            break;
+        }
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for freeing a device instance allocated for bonded device.
+ *
+ * @param[in] device_index Device index.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ */
+static __INLINE ret_code_t device_instance_free(uint32_t device_index)
+{
+    ret_code_t        err_code;
+    pstorage_handle_t block_handle;
+
+    //Get the block handle.
+    err_code = pstorage_block_identifier_get(&m_storage_handle, device_index, &block_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        DM_TRC("[DM]:[DI 0x%02X]: Freeing Instance.\r\n", device_index);
+
+        //Request clearing of the block.
+        err_code = pstorage_clear(&block_handle, ALL_CONTEXT_SIZE);
+
+        if (err_code == NRF_SUCCESS)
+        {
+            peer_instance_init(device_index);
+        }
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for searching for the device in the bonded device list.
+ *
+ * @param[in]  p_addr         Peer identification information.
+ * @param[out] p_device_index Device index.
+ *
+ * @retval NRF_SUCCESS         Operation success.
+ * @retval NRF_ERROR_NOT_FOUND Operation failure.
+ */
+static ret_code_t device_instance_find(ble_gap_addr_t const * p_addr, uint32_t * p_device_index, uint16_t ediv)
+{
+    ret_code_t err_code;
+    uint32_t   index;
+
+    err_code = NRF_ERROR_NOT_FOUND;
+    
+    if (NULL != p_addr)
+    {
+        DM_TRC("[DM]: Searching for device 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X.\r\n",
+               p_addr->addr[0],
+               p_addr->addr[1],
+               p_addr->addr[2],
+               p_addr->addr[3],
+               p_addr->addr[4],
+               p_addr->addr[5]);
+    }
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        DM_TRC("[DM]:[DI 0x%02X]: Device type 0x%02X.\r\n",
+               index, m_peer_table[index].peer_id.id_addr_info.addr_type);
+        DM_TRC("[DM]: Device Addr 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X.\r\n",
+               m_peer_table[index].peer_id.id_addr_info.addr[0],
+               m_peer_table[index].peer_id.id_addr_info.addr[1],
+               m_peer_table[index].peer_id.id_addr_info.addr[2],
+               m_peer_table[index].peer_id.id_addr_info.addr[3],
+               m_peer_table[index].peer_id.id_addr_info.addr[4],
+               m_peer_table[index].peer_id.id_addr_info.addr[5]);
+
+        if (((NULL == p_addr) && (ediv == m_peer_table[index].ediv)) ||
+            ((NULL != p_addr) && (memcmp(&m_peer_table[index].peer_id.id_addr_info, p_addr, sizeof(ble_gap_addr_t)) == 0)))
+        {
+            DM_LOG("[DM]: Found device at instance 0x%02X\r\n", index);
+
+            (*p_device_index) = index;
+            err_code          = NRF_SUCCESS;
+
+            break;
+        }
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for notifying connection manager event to the application.
+ *
+ * @param[in] p_handle     Device handle identifying device.
+ * @param[in] p_event      Connection manager event details.
+ * @param[in] event_result Event result code.
+ */
+static __INLINE void app_evt_notify(dm_handle_t const * const p_handle,
+                                    dm_event_t const * const  p_event,
+                                    uint32_t                  event_result)
+{
+    dm_event_cb_t app_cb = m_application_table[0].ntf_cb;
+
+    DM_MUTEX_UNLOCK();
+
+    DM_TRC("[DM]: Notifying application of event 0x%02X\r\n", p_event->event_id);
+
+    //No need to do any kind of return value processing thus can be supressed.
+    UNUSED_VARIABLE(app_cb(p_handle, p_event, event_result));
+
+    DM_MUTEX_LOCK();
+}
+
+
+/**@brief Function for allocating instance.
+ *
+ * @details The instance identifier is provided in the 'p_instance' parameter if the routine
+ *          succeeds.
+ *
+ * @param[out] p_instance Connection instance.
+ *
+ * @retval NRF_SUCCESS      Operation success.
+ * @retval NRF_ERROR_NO_MEM Operation failure. No memory.
+ */
+static __INLINE uint32_t connection_instance_allocate(uint32_t * p_instance)
+{
+    uint32_t err_code;
+
+    DM_TRC("[DM]: Request to allocation connection instance\r\n");
+
+    err_code = connection_instance_find(BLE_CONN_HANDLE_INVALID, STATE_IDLE, p_instance);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        DM_LOG("[DM]:[%02X]: Connection Instance Allocated.\r\n", (*p_instance));        
+        m_connection_table[*p_instance].state = STATE_CONNECTED;
+    }
+    else
+    {
+        DM_LOG("[DM]: No free connection instances available\r\n");        
+        err_code = NRF_ERROR_NO_MEM;
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for freeing instance. Instance identifier is provided in the parameter
+ *        'p_instance' in case the routine succeeds.
+ *
+ * @param[in] p_instance Connection instance.
+ */
+static __INLINE void connection_instance_free(uint32_t const * p_instance)
+{
+    DM_TRC("[DM]:[CI 0x%02X]: Freeing connection instance\r\n", (*p_instance));
+
+    if (m_connection_table[*p_instance].state != STATE_IDLE)
+    {
+        DM_LOG("[DM]:[%02X]: Freed connection instance.\r\n", (*p_instance));
+        connection_instance_init(*p_instance);
+    }
+}
+
+
+/**@brief Function for storage operation dummy handler.
+ *
+ * @param[in] p_dest Destination address where data is to be stored persistently.
+ * @param[in] p_src  Source address containing data to be stored. API assumes this to be resident
+ *                   memory and no intermediate copy of data is made by the API.
+ * @param[in] size   Size of data to be stored expressed in bytes. Should be word aligned.
+ * @param[in] offset Offset in bytes to be applied when writing to the block.
+ *                   For example, if within a block of 100 bytes, application wishes to
+ *                   write 20 bytes at offset of 12, then this field should be set to 12.
+ *                   Should be word aligned.
+ *
+ * @retval NRF_SUCCESS Operation success.
+ */
+static uint32_t storage_operation_dummy_handler(pstorage_handle_t * p_dest,
+                                                uint8_t           * p_src,
+                                                pstorage_size_t     size,
+                                                pstorage_size_t     offset)
+{
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for saving the device context persistently.
+ *
+ * @param[in] p_handle Device handle identifying device.
+ * @param[in] state    Device store state.
+ */
+static __INLINE void device_context_store(dm_handle_t const * p_handle, device_store_state_t state)
+{
+    pstorage_handle_t block_handle;
+    storage_operation store_fn;
+    ret_code_t        err_code;
+
+    DM_LOG("[DM]: --> device_context_store\r\n");
+
+    err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                             p_handle->device_id,
+                                             &block_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        if ((STATE_BOND_INFO_UPDATE ==
+             (m_connection_table[p_handle->connection_id].state & STATE_BOND_INFO_UPDATE)) ||
+            (state == UPDATE_PEER_ADDR))
+        {
+            DM_LOG("[DM]:[DI %02X]:[CI %02X]: -> Updating bonding information.\r\n",
+                   p_handle->device_id, p_handle->connection_id);
+
+            store_fn = pstorage_update;
+        }
+        else if (state == FIRST_BOND_STORE)
+        {
+            DM_LOG("[DM]:[DI %02X]:[CI %02X]: -> Storing bonding information.\r\n",
+                   p_handle->device_id, p_handle->connection_id);
+
+            store_fn = pstorage_store;
+        }
+        else
+        {
+            DM_LOG("[DM]:[DI %02X]:[CI %02X]: -> No update in bonding information.\r\n",
+                   p_handle->device_id, p_handle->connection_id);
+
+            //No operation needed.
+            store_fn = storage_operation_dummy_handler;
+        }
+
+        //Store the peer id.
+        err_code = store_fn(&block_handle,
+                            (uint8_t *)&m_peer_table[p_handle->device_id],
+                            PEER_ID_SIZE,
+                            PEER_ID_STORAGE_OFFSET);
+
+        if ((err_code == NRF_SUCCESS) && (state != UPDATE_PEER_ADDR))
+        {
+            m_connection_table[p_handle->connection_id].state &= (~STATE_BOND_INFO_UPDATE);
+
+            //Store the bond information.
+            err_code = store_fn(&block_handle,
+                                (uint8_t *)&m_bond_table[p_handle->connection_id],
+                                BOND_SIZE,
+                                BOND_STORAGE_OFFSET);
+
+            if (err_code != NRF_SUCCESS)
+            {
+                DM_ERR("[DM]:[0x%02X]:Failed to store bond information, reason 0x%08X\r\n",
+                       p_handle->device_id, err_code);
+            }
+        }
+
+        if (state != UPDATE_PEER_ADDR)
+        {
+            //Store the service information
+            err_code = m_service_context_store[m_application_table[p_handle->appl_id].service]
+                    (
+                        &block_handle,
+                        p_handle
+                    );
+
+            if (err_code != NRF_SUCCESS)
+            {
+                //Notify application of an error event.
+                DM_ERR("[DM]: Failed to store service context, reason %08X\r\n", err_code);
+            }
+        }
+    }
+
+    if (err_code != NRF_SUCCESS)
+    {
+        //Notify application of an error event.
+        DM_ERR("[DM]: Failed to store device context, reason %08X\r\n", err_code);
+    }
+}
+
+
+/**@brief Function for storing when there is no service registered.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is loaded.
+ *
+ * @retval NRF_SUCCESS
+ */
+static __INLINE ret_code_t no_service_context_store(pstorage_handle_t const * p_block_handle,
+                                                    dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> no_service_context_store\r\n");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for storing GATT Server context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is stored.
+ *
+ * @retval NRF_SUCCESS Operation success.
+ */
+static __INLINE ret_code_t gatts_context_store(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle)
+{
+    storage_operation store_fn;
+    uint32_t          attr_flags = BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS;
+    uint16_t          attr_len   = DM_GATT_SERVER_ATTR_MAX_SIZE;
+    uint8_t           sys_data[DM_GATT_SERVER_ATTR_MAX_SIZE];
+
+    DM_LOG("[DM]: --> gatts_context_store\r\n");
+
+    uint32_t err_code = sd_ble_gatts_sys_attr_get(
+        m_connection_table[p_handle->connection_id].conn_handle,
+        sys_data,
+        &attr_len,
+        attr_flags);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        if (memcmp(m_gatts_table[p_handle->connection_id].attributes, sys_data, attr_len) == 0)
+        {
+            //No store operation is needed.
+            DM_LOG("[DM]:[0x%02X]: No change in GATTS Context information.\r\n",
+                   p_handle->device_id);
+
+            if ((m_connection_table[p_handle->connection_id].state & STATE_CONNECTED) !=
+                STATE_CONNECTED)
+            {
+                DM_LOG("[DM]:[0x%02X]: Resetting GATTS for active instance.\r\n",
+                       p_handle->connection_id);
+
+                //Reset GATTS information for the current context.
+                memset(&m_gatts_table[p_handle->connection_id], 0, sizeof(dm_gatts_context_t));
+            }
+        }
+        else
+        {
+            if (m_gatts_table[p_handle->connection_id].size != 0)
+            {
+                //There is data already stored in persistent memory, therefore an update is needed.
+                DM_LOG("[DM]:[0x%02X]: Updating stored service context\r\n", p_handle->device_id);
+
+                store_fn = pstorage_update;
+            }
+            else
+            {
+                //Fresh write, a store is needed.
+                DM_LOG("[DM]:[0x%02X]: Storing service context\r\n", p_handle->device_id);
+
+                store_fn = pstorage_store;
+            }
+
+            m_gatts_table[p_handle->connection_id].flags = attr_flags;
+            m_gatts_table[p_handle->connection_id].size  = attr_len;
+            memcpy(m_gatts_table[p_handle->connection_id].attributes, sys_data, attr_len);
+
+            DM_DUMP((uint8_t *)&m_gatts_table[p_handle->connection_id], sizeof(dm_gatts_context_t));
+
+            DM_LOG("[DM]:[0x%02X]: GATTS Data size 0x%08X\r\n",
+                   p_handle->device_id,
+                   m_gatts_table[p_handle->connection_id].size);
+
+            //Store GATTS information.
+            err_code = store_fn((pstorage_handle_t *)p_block_handle,
+                                (uint8_t *)&m_gatts_table[p_handle->connection_id],
+                                GATTS_SERVICE_CONTEXT_SIZE,
+                                SERVICE_STORAGE_OFFSET);
+
+            if (err_code != NRF_SUCCESS)
+            {
+                DM_ERR("[DM]:[0x%02X]:Failed to store service context, reason 0x%08X\r\n",
+                       p_handle->device_id,
+                       err_code);
+            }
+            else
+            {
+                DM_LOG("[DM]: Service context successfully stored.\r\n");
+            }
+        }
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for storing GATT Client context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is stored.
+ *
+ * @retval NRF_SUCCESS Operation success.
+ */
+static __INLINE ret_code_t gattc_context_store(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> gattc_context_store\r\n");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for storing GATT Server & Client context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is stored.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ */
+static __INLINE ret_code_t gattsc_context_store(pstorage_handle_t const * p_block_handle,
+                                                dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> gattsc_context_store\r\n");
+
+    ret_code_t err_code = gatts_context_store(p_block_handle, p_handle);
+
+    if (NRF_SUCCESS == err_code)
+    {
+        err_code = gattc_context_store(p_block_handle, p_handle);
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for loading when there is no service registered.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is loaded.
+ *
+ * @retval NRF_SUCCESS
+ */
+static __INLINE ret_code_t no_service_context_load(pstorage_handle_t const * p_block_handle,
+                                                   dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> no_service_context_load\r\n");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for loading GATT Server context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is loaded.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ */
+static __INLINE ret_code_t gatts_context_load(pstorage_handle_t const * p_block_handle,
+                                              dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]:[CI 0x%02X]:[DI 0x%02X]: --> gatts_context_load\r\n",
+           p_handle->connection_id,
+           p_handle->device_id);
+
+    ret_code_t err_code = pstorage_load((uint8_t *)&m_gatts_table[p_handle->connection_id],
+                                        (pstorage_handle_t *)p_block_handle,
+                                        GATTS_SERVICE_CONTEXT_SIZE,
+                                        SERVICE_STORAGE_OFFSET);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        DM_LOG("[DM]:[%02X]:[Block ID 0x%08X]: Service context loaded, size 0x%08X\r\n",
+               p_handle->connection_id,
+               p_block_handle->block_id,
+               m_gatts_table[p_handle->connection_id].size);
+        DM_DUMP((uint8_t *)&m_gatts_table[p_handle->connection_id], sizeof(dm_gatts_context_t));
+
+        if (m_gatts_table[p_handle->connection_id].size == DM_GATTS_INVALID_SIZE)
+        {
+            m_gatts_table[p_handle->connection_id].size = 0;
+        }
+    }
+    else
+    {
+        DM_ERR("[DM]:[%02X]: Failed to load Service context, reason %08X\r\n",
+               p_handle->connection_id,
+               err_code);
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for loading GATT Client context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is loaded.
+ *
+ * @retval NRF_SUCCESS
+ */
+static __INLINE ret_code_t gattc_context_load(pstorage_handle_t const * p_block_handle,
+                                              dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> gattc_context_load\r\n");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for loading GATT Server & Client context.
+ *
+ * @param[in] p_block_handle Storage block identifier.
+ * @param[in] p_handle       Device handle identifying device that is loaded.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ */
+static __INLINE ret_code_t gattsc_context_load(pstorage_handle_t const * p_block_handle,
+                                               dm_handle_t const       * p_handle)
+{
+    DM_LOG("[DM]: --> gattsc_context_load\r\n");
+
+    ret_code_t err_code = gatts_context_load(p_block_handle, p_handle);
+
+    if (NRF_SUCCESS == err_code)
+    {
+        err_code = gattc_context_load(p_block_handle, p_handle);
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for applying when there is no service registered.
+ *
+ * @param[in] p_handle Device handle identifying device that is applied.
+ *
+ * @retval NRF_SUCCESS
+ */
+static __INLINE ret_code_t no_service_context_apply(dm_handle_t * p_handle)
+{
+    DM_LOG("[DM]: --> no_service_context_apply\r\n");
+    DM_LOG("[DM]:[CI 0x%02X]: No Service context\r\n", p_handle->connection_id);
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for applying GATT Server context.
+ *
+ * @param[in] p_handle Device handle identifying device that is applied.
+ *
+ * @retval NRF_SUCCESS                    On success.
+ * @retval DM_SERVICE_CONTEXT_NOT_APPLIED On failure.
+ */
+static __INLINE ret_code_t gatts_context_apply(dm_handle_t * p_handle)
+{
+    uint32_t err_code;
+
+    uint8_t * p_gatts_context = NULL;
+    uint16_t  context_len     = 0;
+    uint32_t  context_flags   = 0;
+
+    DM_LOG("[DM]: --> gatts_context_apply\r\n");
+    DM_LOG("[DM]:[CI 0x%02X]: State 0x%02X, Size 0x%08X\r\n",
+           p_handle->connection_id,
+           m_connection_table[p_handle->connection_id].state,
+           m_gatts_table[p_handle->connection_id].size);
+
+    if ((m_gatts_table[p_handle->connection_id].size != 0) &&
+        (
+            ((m_connection_table[p_handle->connection_id].state & STATE_LINK_ENCRYPTED) == STATE_LINK_ENCRYPTED) &&
+            ((m_connection_table[p_handle->connection_id].state & STATE_BOND_INFO_UPDATE)
+             != STATE_BOND_INFO_UPDATE)
+        )
+       )
+    {
+        DM_LOG("[DM]: Setting stored context.\r\n");
+
+        p_gatts_context = &m_gatts_table[p_handle->connection_id].attributes[0];
+        context_len     = m_gatts_table[p_handle->connection_id].size;
+        context_flags   = m_gatts_table[p_handle->connection_id].flags;
+    }
+
+    err_code = sd_ble_gatts_sys_attr_set(m_connection_table[p_handle->connection_id].conn_handle,
+                                         p_gatts_context,
+                                         context_len,
+                                         context_flags);
+
+    if (err_code == NRF_ERROR_INVALID_DATA)
+    {
+        // Indication that the ATT table has changed. Restore the system attributes to system
+        // services only and send a service changed indication if possible.
+        context_flags = BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS;
+        err_code      = sd_ble_gatts_sys_attr_set(m_connection_table[p_handle->connection_id].conn_handle,
+                                                  p_gatts_context,
+                                                  context_len,
+                                                  context_flags);
+    }
+
+    if (err_code != NRF_SUCCESS)
+    {
+        DM_LOG("[DM]: Failed to set system attributes, reason 0x%08X.\r\n", err_code);
+
+        err_code = DM_SERVICE_CONTEXT_NOT_APPLIED;
+    }
+
+    if (context_flags == BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS)
+    {
+        err_code = sd_ble_gatts_service_changed(m_connection_table[p_handle->connection_id].conn_handle,
+                                                0x000C,
+                                                0xFFFF);
+        if (err_code != NRF_SUCCESS)
+        {
+            DM_LOG("[DM]: Failed to send Service Changed indication, reason 0x%08X.\r\n", err_code);
+            if ((err_code != BLE_ERROR_INVALID_CONN_HANDLE) &&
+                (err_code != NRF_ERROR_INVALID_STATE) &&
+                (err_code != BLE_ERROR_NO_TX_BUFFERS) &&
+                (err_code != NRF_ERROR_BUSY))
+            {
+                // Those errors can be expected when sending trying to send Service Changed
+                // Indication if the CCCD is not set to indicate. Thus set the returning error
+                //  code to success.
+                err_code = NRF_SUCCESS;
+            }
+            else
+            {
+                err_code = DM_SERVICE_CONTEXT_NOT_APPLIED;
+            }
+        }
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for applying GATT Client context.
+ *
+ * @param[in] p_handle Device handle identifying device that is applied.
+ *
+ * @retval NRF_SUCCESS On success.
+ */
+static __INLINE ret_code_t gattc_context_apply(dm_handle_t * p_handle)
+{
+    DM_LOG("[DM]: --> gattc_context_apply\r\n");
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Function for applying GATT Server & Client context.
+ *
+ * @param[in] p_handle Device handle identifying device that is applied.
+ *
+ * @retval NRF_SUCCESS On success, else an error code indicating reason for failure.
+ */
+static __INLINE ret_code_t gattsc_context_apply(dm_handle_t * p_handle)
+{
+    uint32_t err_code;
+
+    DM_LOG("[DM]: --> gattsc_context_apply\r\n");
+
+    err_code = gatts_context_apply(p_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        err_code = gattc_context_apply(p_handle);
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for pstorage module callback.
+ *
+ * @param[in] p_handle Identifies module and block for which callback is received.
+ * @param[in] op_code  Identifies the operation for which the event is notified.
+ * @param[in] result   Identifies the result of flash access operation.
+ *                     NRF_SUCCESS implies, operation succeeded.
+ * @param[in] p_data   Identifies the application data pointer. In case of store operation, this
+ *                     points to the resident source of application memory that application can now
+ *                     free or reuse. In case of clear, this is NULL as no application pointer is
+ *                     needed for this operation.
+ * @param[in] data_len Length of data provided by the application for the operation.
+ */
+static void dm_pstorage_cb_handler(pstorage_handle_t * p_handle,
+                                   uint8_t             op_code,
+                                   uint32_t            result,
+                                   uint8_t           * p_data,
+                                   uint32_t            data_len)
+{
+    VERIFY_APP_REGISTERED_VOID(0);
+
+    if (data_len > ALL_CONTEXT_SIZE)
+    {
+        //Clearing of all bonds at initialization, no event is generated.
+        return;
+    }
+
+    DM_MUTEX_LOCK();
+
+    dm_event_t        dm_event;
+    dm_handle_t       dm_handle;
+    dm_context_t      context_data;
+    pstorage_handle_t block_handle;
+    uint32_t          index_count;
+    uint32_t          err_code;
+
+    bool app_notify = true;
+
+    err_code = dm_handle_initialize(&dm_handle);
+    APP_ERROR_CHECK(err_code);
+
+    dm_handle.appl_id = 0;
+    dm_event.event_id = 0x00;
+
+    //Construct the event which it is related to.
+
+    //Initialize context data information and length.
+    context_data.p_data = p_data;
+    context_data.len    = data_len;
+
+    for (uint32_t index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        err_code = pstorage_block_identifier_get(&m_storage_handle, index, &block_handle);
+        if ((err_code == NRF_SUCCESS) &&
+            (
+                (memcmp(p_handle, &block_handle, sizeof(pstorage_handle_t)) == 0)
+            )
+           )
+        {
+            dm_handle.device_id = index;
+            break;
+        }
+    }
+
+    if (dm_handle.device_id != DM_INVALID_ID)
+    {
+        if (op_code == PSTORAGE_CLEAR_OP_CODE)
+        {
+            if (data_len == ALL_CONTEXT_SIZE)
+            {
+                dm_event.event_id = DM_EVT_DEVICE_CONTEXT_BASE;
+            }
+            else
+            {
+                dm_event.event_id = DM_EVT_APP_CONTEXT_BASE;
+            }
+        }
+        else
+        {
+            //Update or store operation.
+            //Context is identified based on the pointer value. Device context, application context
+            //and service context all have their own value range.
+            index_count = ((uint32_t)(p_data - (uint8_t *)m_peer_table)) / PEER_ID_SIZE;
+
+            if (index_count < DEVICE_MANAGER_MAX_BONDS)
+            {
+                dm_event.event_param.p_device_context = &context_data;
+
+                //Only the peer identification is stored, not bond information. Hence do not notify
+                //the application yet, unless the store operation resulted in a failure.
+                if ((result == NRF_SUCCESS) &&
+                    (
+                        (update_status_bit_is_set(dm_handle.device_id) == false)
+                    )
+                   )
+                {
+                    app_notify = false;
+                }
+                else
+                {
+                    //Reset update status since update is complete.
+                    update_status_bit_reset(dm_handle.device_id);
+
+                    //Notify application of error in storing the context.
+                    dm_event.event_id = DM_EVT_DEVICE_CONTEXT_BASE;
+                }
+            }
+            else
+            {
+                index_count = ((uint32_t)(p_data - (uint8_t *)m_bond_table)) / BOND_SIZE;
+
+                if (index_count < DEVICE_MANAGER_MAX_CONNECTIONS)
+                {
+                    DM_LOG("[DM]:[0x%02X]:[0x%02X]: Bond context Event\r\n",
+                           dm_handle.device_id,
+                           dm_handle.connection_id);
+
+                    dm_event.event_param.p_device_context = &context_data;
+                    dm_event.event_id                     = DM_EVT_DEVICE_CONTEXT_BASE;
+                    dm_handle.connection_id               = index_count;
+
+                    ble_gap_sec_keyset_t keys_exchanged;
+                    keys_exchanged.keys_central.p_enc_key = NULL;
+                    keys_exchanged.keys_central.p_id_key  = &m_local_id_info;
+                    keys_exchanged.keys_periph.p_enc_key  = &m_bond_table[index_count].peer_enc_key;
+                    keys_exchanged.keys_periph.p_id_key   =
+                        &m_peer_table[dm_handle.device_id].peer_id;
+
+                    //Context information updated to provide the keys.
+                    context_data.p_data = (uint8_t *)&keys_exchanged;
+                    context_data.len    = sizeof(ble_gap_sec_keyset_t);
+                }
+                else
+                {
+                    index_count = ((uint32_t)(p_data - (uint8_t *)m_gatts_table)) /
+                                  GATTS_SERVICE_CONTEXT_SIZE;
+
+                    if (index_count < DEVICE_MANAGER_MAX_CONNECTIONS)
+                    {
+                        DM_LOG("[DM]:[0x%02X]:[0x%02X]: Service context Event\r\n",
+                               dm_handle.device_id,
+                               dm_handle.connection_id);
+
+                        //Notify application.
+                        dm_event.event_id       = DM_EVT_SERVICE_CONTEXT_BASE;
+                        dm_handle.connection_id = index_count;
+                        dm_handle.service_id    = DM_PROTOCOL_CNTXT_GATT_SRVR_ID;
+
+                        //Reset the service context now that it was successfully written to the
+                        //application and the link is disconnected.
+                        if ((m_connection_table[index_count].state & STATE_CONNECTED) !=
+                            STATE_CONNECTED)
+                        {
+                            DM_LOG("[DM]:[0x%02X]:[0x%02X]: Resetting bond information for "
+                                   "active instance.\r\n",
+                                   dm_handle.device_id,
+                                   dm_handle.connection_id);
+
+                            memset(&m_gatts_table[dm_handle.connection_id],
+                                   0,
+                                   sizeof(dm_gatts_context_t));
+                        }
+                    }
+                    else
+                    {
+                        DM_LOG("[DM]:[0x%02X]:[0x%02X]: App context Event\r\n",
+                               dm_handle.device_id,
+                               dm_handle.connection_id);
+
+                        app_notify        = false;
+                        dm_event.event_id = DM_EVT_APP_CONTEXT_BASE;
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+
+                        if (p_data == (uint8_t *)(&m_context_init_len))
+                        {
+                            //Context data is deleted.
+                            //This is a workaround to get the right event as on delete operation
+                            //update operation is used instead of clear.
+                            op_code    = PSTORAGE_CLEAR_OP_CODE;
+                            app_notify = true;
+                        }
+                        else if (m_app_context_table[dm_handle.device_id] == p_data)
+                        {
+                            app_notify                         = true;
+                            dm_event.event_param.p_app_context = &context_data;
+
+                            //Verify if the device is connected, if yes set connection instance.
+                            for (uint32_t index = 0;
+                                 index < DEVICE_MANAGER_MAX_CONNECTIONS;
+                                 index++)
+                            {
+                                if (dm_handle.device_id == m_connection_table[index].bonded_dev_id)
+                                {
+                                    dm_handle.connection_id = index;
+                                    break;
+                                }
+                            }
+                        }
+                        else
+                        {
+                            //No implementation needed.
+                        }
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+                    }
+                }
+            }
+        }
+
+        if (app_notify == true)
+        {
+            if (op_code == PSTORAGE_CLEAR_OP_CODE)
+            {
+                dm_event.event_id |= DM_CLEAR_OPERATION_ID;
+            }
+            else if (op_code == PSTORAGE_LOAD_OP_CODE)
+            {
+                dm_event.event_id |= DM_LOAD_OPERATION_ID;
+            }
+            else
+            {
+                dm_event.event_id |= DM_STORE_OPERATION_ID;
+            }
+
+            dm_event.event_param.p_app_context = &context_data;
+            app_evt_notify(&dm_handle, &dm_event, result);
+        }
+    }
+
+    DM_MUTEX_UNLOCK();
+}
+
+
+ret_code_t dm_init(dm_init_param_t const * const p_init_param)
+{
+    pstorage_module_param_t param;
+    pstorage_handle_t       block_handle;
+    ret_code_t              err_code;
+    uint32_t                index;
+
+    DM_LOG("[DM]: >> dm_init.\r\n");
+
+    NULL_PARAM_CHECK(p_init_param);
+
+    SDK_MUTEX_INIT(m_dm_mutex);
+
+    DM_MUTEX_LOCK();
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_APPLICATIONS; index++)
+    {
+        application_instance_init(index);
+    }
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_CONNECTIONS; index++)
+    {
+        connection_instance_init(index);
+    }
+
+    memset(m_gatts_table, 0, sizeof(m_gatts_table));
+
+    //Initialization of all device instances.
+    for (index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        peer_instance_init(index);
+        m_irk_index_table[index] = DM_INVALID_ID;
+    }
+
+    //All context with respect to a particular device is stored contiguously.
+    param.block_size  = ALL_CONTEXT_SIZE;
+    param.block_count = DEVICE_MANAGER_MAX_BONDS;
+    param.cb          = dm_pstorage_cb_handler;
+
+    err_code = pstorage_register(&param, &m_storage_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        m_module_initialized = true;
+
+        if (p_init_param->clear_persistent_data == false)
+        {
+            DM_LOG("[DM]: Storage handle 0x%08X.\r\n", m_storage_handle.block_id);
+
+            //Copy bonded peer device address and IRK to RAM table.
+
+            //Bonded devices are stored in range (0,DEVICE_MANAGER_MAX_BONDS-1). The remaining
+            //range is for active connections that may or may not be bonded.
+            for (index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+            {
+                err_code = pstorage_block_identifier_get(&m_storage_handle, index, &block_handle);
+
+                //Issue read request if you successfully get the block identifier.
+                if (err_code == NRF_SUCCESS)
+                {
+                    DM_TRC("[DM]:[0x%02X]: Block handle 0x%08X.\r\n", index, block_handle.block_id);
+
+                    err_code = pstorage_load((uint8_t *)&m_peer_table[index],
+                                             &block_handle,
+                                             sizeof(peer_id_t),
+                                             0);
+
+                    if (err_code != NRF_SUCCESS)
+                    {
+                        // In case a peer device could not be loaded successfully, rest of the
+                        // initialization procedure are skipped and an error is sent to the
+                        // application.
+                        DM_ERR(
+                            "[DM]: Failed to load peer device %08X from storage, reason %08X.\r\n",
+                            index,
+                            err_code);
+
+                        m_module_initialized = false;
+                        break;
+                    }
+                    else
+                    {
+                        DM_TRC("[DM]:[DI 0x%02X]: Device type 0x%02X.\r\n",
+                               index,
+                               m_peer_table[index].peer_id.id_addr_info.addr_type);
+                        DM_TRC("[DM]: Device Addr 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X.\r\n",
+                               m_peer_table[index].peer_id.id_addr_info.addr[0],
+                               m_peer_table[index].peer_id.id_addr_info.addr[1],
+                               m_peer_table[index].peer_id.id_addr_info.addr[2],
+                               m_peer_table[index].peer_id.id_addr_info.addr[3],
+                               m_peer_table[index].peer_id.id_addr_info.addr[4],
+                               m_peer_table[index].peer_id.id_addr_info.addr[5]);
+                    }
+                }
+                else
+                {
+                    //In case a peer device could not be loaded successfully, rest of the
+                    //initialization procedure are skipped and an error is sent to the application.
+                    DM_LOG("[DM]: Failed to get block handle for instance %08X, reason %08X.\r\n",
+                           index,
+                           err_code);
+
+                    m_module_initialized = false;
+                    break;
+                }
+            }
+        }
+        else
+        {
+            err_code = pstorage_clear(&m_storage_handle, (param.block_size * param.block_count));
+            DM_ERR("[DM]: Successfully requested clear of persistent data.\r\n");
+        }
+    }
+    else
+    {
+        DM_ERR("[DM]: Failed to register with storage module, reason 0x%08X.\r\n", err_code);
+    }
+
+    DM_MUTEX_UNLOCK();
+
+    DM_TRC("[DM]: << dm_init.\r\n");
+
+    return err_code;
+}
+
+
+ret_code_t dm_register(dm_application_instance_t    * p_appl_instance,
+                       dm_application_param_t const * p_appl_param)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_appl_instance);
+    NULL_PARAM_CHECK(p_appl_param);
+    NULL_PARAM_CHECK(p_appl_param->evt_handler);
+
+    DM_MUTEX_LOCK();
+
+    DM_LOG("[DM]: >> dm_register.\r\n");
+
+    uint32_t err_code;
+
+    //Verify if an application instance is available. Currently only one instance is supported.
+    if (m_application_table[0].ntf_cb == NULL)
+    {
+        DM_LOG("[DM]: Application Instance allocated.\r\n");
+
+        //Mark instance as allocated.
+        m_application_table[0].ntf_cb    = p_appl_param->evt_handler;
+        m_application_table[0].sec_param = p_appl_param->sec_param;
+        m_application_table[0].service   = p_appl_param->service_type;
+
+        m_application_table[0].sec_param.kdist_central.enc  = 0;
+        m_application_table[0].sec_param.kdist_central.id   = 1;
+        m_application_table[0].sec_param.kdist_central.sign = 0;
+        m_application_table[0].sec_param.kdist_periph.enc   = 1;
+        m_application_table[0].sec_param.kdist_periph.id    = 1;
+        m_application_table[0].sec_param.kdist_periph.sign  = 0;
+        //Populate application's instance variable with the assigned allocation instance.
+        *p_appl_instance = 0;
+        err_code         = NRF_SUCCESS;
+    }
+    else
+    {
+        err_code = (NRF_ERROR_NO_MEM | DEVICE_MANAGER_ERR_BASE);
+    }
+
+    DM_MUTEX_UNLOCK();
+
+    DM_TRC("[DM]: << dm_register.\r\n");
+
+    return err_code;
+}
+
+
+ret_code_t dm_security_setup_req(dm_handle_t * p_handle)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_CONNECTION_INSTANCE(p_handle->connection_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_LOG("[DM]: >> dm_security_setup_req\r\n");
+
+    uint32_t err_code = (NRF_ERROR_INVALID_STATE | DEVICE_MANAGER_ERR_BASE);
+
+    if ((m_connection_table[p_handle->connection_id].state & STATE_CONNECTED) == STATE_CONNECTED)
+    {
+        err_code = sd_ble_gap_authenticate(m_connection_table[p_handle->connection_id].conn_handle,
+                                           &m_application_table[0].sec_param);
+    }
+
+    DM_TRC("[DM]: << dm_security_setup_req, 0x%08X\r\n", err_code);
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_security_status_req(dm_handle_t const    * p_handle,
+                                  dm_security_status_t * p_status)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_status);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_CONNECTION_INSTANCE(p_handle->connection_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_LOG("[DM]: >> dm_security_status_req\r\n");
+
+    if ((m_connection_table[p_handle->connection_id].state & STATE_PAIRING) ||
+        (m_connection_table[p_handle->connection_id].state & STATE_PAIRING_PENDING))
+    {
+        (*p_status) = ENCRYPTION_IN_PROGRESS;
+    }
+    else if (m_connection_table[p_handle->connection_id].state & STATE_LINK_ENCRYPTED)
+    {
+        (*p_status) = ENCRYPTED;
+    }
+    else
+    {
+        (*p_status) = NOT_ENCRYPTED;
+    }
+
+    DM_TRC("[DM]: << dm_security_status_req\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t dm_whitelist_create(dm_application_instance_t const * p_handle,
+                               ble_gap_whitelist_t             * p_whitelist)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_whitelist);
+    NULL_PARAM_CHECK(p_whitelist->pp_addrs);
+    NULL_PARAM_CHECK(p_whitelist->pp_irks);
+    VERIFY_APP_REGISTERED(*p_handle);
+
+    DM_MUTEX_LOCK();
+
+    DM_LOG("[DM]: >> dm_whitelist_create\r\n");
+
+    uint32_t addr_count = 0;
+    uint32_t irk_count  = 0;
+    bool     connected  = false;
+
+    for (uint32_t index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        connected = false;
+
+        for (uint32_t c_index = 0; c_index < DEVICE_MANAGER_MAX_CONNECTIONS; c_index++)
+        {
+            if ((index == m_connection_table[c_index].bonded_dev_id) &&
+                ((m_connection_table[c_index].state & STATE_CONNECTED) == STATE_CONNECTED))
+            {
+                connected = true;
+                break;
+            }
+        }
+
+        if (connected == false)
+        {
+            if ((irk_count < p_whitelist->irk_count) &&
+                ((m_peer_table[index].id_bitmap & IRK_ENTRY) == 0))
+            {
+                p_whitelist->pp_irks[irk_count] = &m_peer_table[index].peer_id.id_info;
+                m_irk_index_table[irk_count]    = index;
+                irk_count++;
+            }
+
+            if ((addr_count < p_whitelist->addr_count) &&
+                (m_peer_table[index].id_bitmap & ADDR_ENTRY) == 0)
+            {
+                p_whitelist->pp_addrs[addr_count] = &m_peer_table[index].peer_id.id_addr_info;
+                addr_count++;
+            }
+        }
+    }
+
+    p_whitelist->addr_count = addr_count;
+    p_whitelist->irk_count  = irk_count;
+
+    DM_LOG("[DM]: Created whitelist, number of IRK = 0x%02X, number of addr = 0x%02X\r\n",
+           irk_count,
+           addr_count);
+
+    DM_TRC("[DM]: << dm_whitelist_create\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t dm_device_add(dm_handle_t               * p_handle,
+                         dm_device_context_t const * p_context)
+{
+    return (API_NOT_IMPLEMENTED | DEVICE_MANAGER_ERR_BASE);
+}
+
+
+ret_code_t dm_device_delete(dm_handle_t const * p_handle)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_device_delete\r\n");
+
+    uint32_t err_code = device_instance_free(p_handle->device_id);
+
+    DM_TRC("[DM]: << dm_device_delete\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_device_delete_all(dm_application_instance_t const * p_handle)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED((*p_handle));
+
+    DM_MUTEX_LOCK();
+
+    uint32_t err_code = NRF_SUCCESS;
+
+    DM_TRC("[DM]: >> dm_device_delete_all\r\n");
+
+    for (uint32_t index = 0; index < DEVICE_MANAGER_MAX_BONDS; index++)
+    {
+        if (m_peer_table[index].id_bitmap != UNASSIGNED)
+        {
+            err_code = device_instance_free(index);
+        }
+    }
+
+    DM_TRC("[DM]: << dm_device_delete_all\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_service_context_set(dm_handle_t const          * p_handle,
+                                  dm_service_context_t const * p_context)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_context);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_CONNECTION_INSTANCE(p_handle->connection_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_service_context_set\r\n");
+
+    if ((p_context->context_data.p_data != NULL) &&
+        (
+            (p_context->context_data.len != 0) &&
+            (p_context->context_data.len < DM_GATT_SERVER_ATTR_MAX_SIZE)
+        )
+       )
+    {
+        if (p_context->service_type == DM_PROTOCOL_CNTXT_GATT_SRVR_ID)
+        {
+            memcpy(m_gatts_table[p_handle->connection_id].attributes,
+                   p_context->context_data.p_data,
+                   p_context->context_data.len);
+        }
+    }
+
+    pstorage_handle_t block_handle;
+    uint32_t          err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                                               p_handle->device_id,
+                                                               &block_handle);
+
+    err_code = m_service_context_store[p_context->service_type](&block_handle, p_handle);
+
+    DM_TRC("[DM]: << dm_service_context_set\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_service_context_get(dm_handle_t const    * p_handle,
+                                  dm_service_context_t * p_context)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_context);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    if ((m_connection_table[p_handle->connection_id].state & STATE_CONNECTED) != STATE_CONNECTED)
+    {
+        DM_TRC("[DM]: Device must be connected to get context. \r\n");
+
+        return (FEATURE_NOT_ENABLED | DEVICE_MANAGER_ERR_BASE);
+    }
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_service_context_get\r\n");
+
+    if ((p_context->context_data.p_data == NULL) &&
+        (p_context->context_data.len < DM_GATT_SERVER_ATTR_MAX_SIZE))
+    {
+        if (p_context->service_type == DM_PROTOCOL_CNTXT_GATT_SRVR_ID)
+        {
+            p_context->context_data.p_data = m_gatts_table[p_handle->connection_id].attributes;
+            p_context->context_data.len    = m_gatts_table[p_handle->connection_id].size;
+        }
+    }
+
+    pstorage_handle_t block_handle;
+    uint32_t          err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                                               p_handle->device_id,
+                                                               &block_handle);
+
+    err_code = m_service_context_load[p_context->service_type](&block_handle, p_handle);
+
+    DM_TRC("[DM]: << dm_service_context_get\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_service_context_delete(dm_handle_t const * p_handle)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_LOG("[DM]: Context delete is not supported yet.\r\n");
+
+    return (API_NOT_IMPLEMENTED | DEVICE_MANAGER_ERR_BASE);
+}
+
+
+ret_code_t dm_application_context_set(dm_handle_t const              * p_handle,
+                                      dm_application_context_t const * p_context)
+{
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_context);
+    NULL_PARAM_CHECK(p_context->p_data);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+    VERIFY_DEVICE_BOND(p_handle->connection_id);
+    SIZE_CHECK_APP_CONTEXT(p_context->len);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_application_context_set\r\n");
+
+    uint32_t          err_code;
+    uint32_t          context_len;
+    pstorage_handle_t block_handle;
+
+    storage_operation store_fn = pstorage_store;
+
+    err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                             p_handle->device_id,
+                                             &block_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        err_code = pstorage_load((uint8_t *)&context_len,
+                                 &block_handle,
+                                 sizeof(uint32_t),
+                                 APP_CONTEXT_STORAGE_OFFSET);
+
+        if ((err_code == NRF_SUCCESS) && (context_len != INVALID_CONTEXT_LEN))
+        {
+            //Data already exists. Need an update.
+            store_fn = pstorage_update;
+
+            DM_LOG("[DM]:[DI 0x%02X]: Updating existing application context, existing len 0x%08X, "
+                   "new length 0x%08X.\r\n",
+                   p_handle->device_id,
+                   context_len,
+                   p_context->len);
+        }
+        else
+        {
+            DM_LOG("[DM]: Storing application context.\r\n");
+        }
+
+        //Store/update context length.
+        err_code = store_fn(&block_handle,
+                            (uint8_t *)(&p_context->len),
+                            sizeof(uint32_t),
+                            APP_CONTEXT_STORAGE_OFFSET);
+
+        if (err_code == NRF_SUCCESS)
+        {
+            //Update context data is used for application context as flash is never
+            //cleared if a delete of application context is called.
+            err_code = pstorage_update(&block_handle,
+                                       p_context->p_data,
+                                       DEVICE_MANAGER_APP_CONTEXT_SIZE,
+                                       (APP_CONTEXT_STORAGE_OFFSET + sizeof(uint32_t)));
+            if (err_code == NRF_SUCCESS)
+            {
+                m_app_context_table[p_handle->device_id] = p_context->p_data;
+            }
+        }
+    }
+
+    DM_TRC("[DM]: << dm_application_context_set\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+
+#else //DEVICE_MANAGER_APP_CONTEXT_SIZE
+    return (FEATURE_NOT_ENABLED | DEVICE_MANAGER_ERR_BASE);
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+}
+
+
+ret_code_t dm_application_context_get(dm_handle_t const        * p_handle,
+                                      dm_application_context_t * p_context)
+{
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_context);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_application_context_get\r\n");
+
+    uint32_t          context_len;
+    uint32_t          err_code;
+    pstorage_handle_t block_handle;
+
+    //Check if the context exists.
+    if (NULL == p_context->p_data)
+    {
+        p_context->p_data = m_app_context_table[p_handle->device_id];
+    }
+    else
+    {
+        m_app_context_table[p_handle->device_id] = p_context->p_data;
+    }
+
+    err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                             p_handle->device_id,
+                                             &block_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        err_code = pstorage_load((uint8_t *)&context_len,
+                                 &block_handle,
+                                 sizeof(uint32_t),
+                                 APP_CONTEXT_STORAGE_OFFSET);
+
+        if ((err_code == NRF_SUCCESS) && (context_len != INVALID_CONTEXT_LEN))
+        {
+            err_code = pstorage_load(p_context->p_data,
+                                     &block_handle,
+                                     DEVICE_MANAGER_APP_CONTEXT_SIZE,
+                                     (APP_CONTEXT_STORAGE_OFFSET + sizeof(uint32_t)));
+            if (err_code == NRF_SUCCESS)
+            {
+                p_context->len = context_len;
+            }
+        }
+        else
+        {
+            err_code = DM_NO_APP_CONTEXT;
+        }
+    }
+
+    DM_TRC("[DM]: << dm_application_context_get\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+
+#else //DEVICE_MANAGER_APP_CONTEXT_SIZE
+    return (FEATURE_NOT_ENABLED | DEVICE_MANAGER_ERR_BASE);
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+}
+
+
+ret_code_t dm_application_context_delete(const dm_handle_t * p_handle)
+{
+#if (DEVICE_MANAGER_APP_CONTEXT_SIZE != 0)
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_application_context_delete\r\n");
+
+    uint32_t          err_code;
+    uint32_t          context_len;
+    pstorage_handle_t block_handle;
+
+    err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                             p_handle->device_id,
+                                             &block_handle);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        err_code = pstorage_load((uint8_t *)&context_len,
+                                 &block_handle,
+                                 sizeof(uint32_t),
+                                 APP_CONTEXT_STORAGE_OFFSET);
+
+        if (context_len != m_context_init_len)
+        {
+            err_code = pstorage_update(&block_handle,
+                                       (uint8_t *)&m_context_init_len,
+                                       sizeof(uint32_t),
+                                       APP_CONTEXT_STORAGE_OFFSET);
+
+            if (err_code != NRF_SUCCESS)
+            {
+                DM_ERR("[DM]: Failed to delete application context, reason 0x%08X\r\n", err_code);
+            }
+            else
+            {
+                m_app_context_table[p_handle->device_id] = NULL;
+            }
+        }
+    }
+
+    DM_TRC("[DM]: << dm_application_context_delete\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+#else //DEVICE_MANAGER_APP_CONTEXT_SIZE
+    return (FEATURE_NOT_ENABLED | DEVICE_MANAGER_ERR_BASE);
+#endif //DEVICE_MANAGER_APP_CONTEXT_SIZE
+}
+
+
+ret_code_t dm_application_instance_set(dm_application_instance_t const * p_appl_instance,
+                                       dm_handle_t                     * p_handle)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_appl_instance);
+    VERIFY_APP_REGISTERED((*p_appl_instance));
+
+    p_handle->appl_id = (*p_appl_instance);
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t dm_handle_initialize(dm_handle_t * p_handle)
+{
+    NULL_PARAM_CHECK(p_handle);
+
+    p_handle->appl_id       = DM_INVALID_ID;
+    p_handle->connection_id = DM_INVALID_ID;
+    p_handle->device_id     = DM_INVALID_ID;
+    p_handle->service_id    = DM_INVALID_ID;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t dm_peer_addr_set(dm_handle_t const    * p_handle,
+                            ble_gap_addr_t const * p_addr)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_addr);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_peer_addr_set\r\n");
+
+    ret_code_t err_code;
+
+    if ((p_handle->connection_id == DM_INVALID_ID) &&
+        (p_addr->addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE))
+    {
+        m_peer_table[p_handle->device_id].peer_id.id_addr_info = (*p_addr);
+        update_status_bit_set(p_handle->device_id);
+        device_context_store(p_handle, UPDATE_PEER_ADDR);
+        err_code = NRF_SUCCESS;
+    }
+    else
+    {
+        err_code = (NRF_ERROR_INVALID_PARAM | DEVICE_MANAGER_ERR_BASE);
+    }
+
+    DM_TRC("[DM]: << dm_peer_addr_set\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_peer_addr_get(dm_handle_t const * p_handle,
+                            ble_gap_addr_t    * p_addr)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_addr);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_peer_addr_get\r\n");
+
+    ret_code_t err_code;
+
+    err_code = (NRF_ERROR_NOT_FOUND | DEVICE_MANAGER_ERR_BASE);
+
+    if (p_handle->device_id == DM_INVALID_ID)
+    {
+        if ((p_handle->connection_id != DM_INVALID_ID) &&
+            ((m_connection_table[p_handle->connection_id].state & STATE_CONNECTED) ==
+             STATE_CONNECTED))
+        {
+            DM_TRC("[DM]:[CI 0x%02X]: Address get for non bonded active connection.\r\n",
+                   p_handle->connection_id);
+
+            (*p_addr) = m_connection_table[p_handle->connection_id].peer_addr;
+            err_code  = NRF_SUCCESS;
+        }
+    }
+    else
+    {
+        if ((m_peer_table[p_handle->device_id].id_bitmap & ADDR_ENTRY) == 0)
+        {
+            DM_TRC("[DM]:[DI 0x%02X]: Address get for bonded device.\r\n",
+                   p_handle->device_id);
+
+            (*p_addr) = m_peer_table[p_handle->device_id].peer_id.id_addr_info;
+            err_code  = NRF_SUCCESS;
+        }
+    }
+
+    DM_TRC("[DM]: << dm_peer_addr_get\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+ret_code_t dm_distributed_keys_get(dm_handle_t const * p_handle,
+                                   dm_sec_keyset_t   * p_key_dist)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_handle);
+    NULL_PARAM_CHECK(p_key_dist);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+    VERIFY_DEVICE_INSTANCE(p_handle->device_id);
+
+    DM_MUTEX_LOCK();
+
+    DM_TRC("[DM]: >> dm_distributed_keys_get\r\n");
+
+    ret_code_t        err_code;
+    ble_gap_enc_key_t peer_enc_key;
+    pstorage_handle_t block_handle;
+
+    err_code                                   = NRF_ERROR_NOT_FOUND;
+    p_key_dist->keys_central.enc_key.p_enc_key = NULL;
+    p_key_dist->keys_central.p_id_key          = (dm_id_key_t *)&m_peer_table[p_handle->device_id].peer_id;
+    p_key_dist->keys_central.p_sign_key        = NULL;
+    p_key_dist->keys_periph.p_id_key           = (dm_id_key_t *)&m_local_id_info;
+    p_key_dist->keys_periph.p_sign_key         = NULL;
+    p_key_dist->keys_periph.enc_key.p_enc_key  = (dm_enc_key_t *)&peer_enc_key;
+
+    if ((m_peer_table[p_handle->device_id].id_bitmap & IRK_ENTRY) == 0)
+    {
+//        p_key_dist->keys_periph.p_id_key->id_addr_info.addr_type = INVALID_ADDR_TYPE;
+    }
+
+    err_code = pstorage_block_identifier_get(&m_storage_handle, p_handle->device_id, &block_handle);
+    if (err_code == NRF_SUCCESS)
+    {
+
+        err_code = pstorage_load((uint8_t *)&peer_enc_key,
+                                 &block_handle,
+                                 BOND_SIZE,
+                                 BOND_STORAGE_OFFSET);
+
+        if (err_code == NRF_SUCCESS)
+        {
+            p_key_dist->keys_central.enc_key.p_enc_key = NULL;
+            p_key_dist->keys_central.p_id_key          = (dm_id_key_t *)&m_peer_table[p_handle->device_id].peer_id;
+            p_key_dist->keys_central.p_sign_key        = NULL;
+            p_key_dist->keys_periph.p_id_key           = (dm_id_key_t *)&m_local_id_info;
+            p_key_dist->keys_periph.p_sign_key         = NULL;
+            p_key_dist->keys_periph.enc_key.p_enc_key  = (dm_enc_key_t *)&peer_enc_key;
+        }
+    }
+
+    DM_TRC("[DM]: << dm_distributed_keys_get\r\n");
+
+    DM_MUTEX_UNLOCK();
+
+    return err_code;
+}
+
+
+/**@brief Function for loading bond information for a connection instance.
+ */
+void bond_data_load(dm_handle_t * p_handle)
+{
+    pstorage_handle_t block_handle;
+
+    uint32_t err_code = pstorage_block_identifier_get(&m_storage_handle,
+                                                       p_handle->device_id,
+                                                       &block_handle);
+    if (err_code == NRF_SUCCESS)
+    {
+        DM_LOG(
+            "[DM]:[%02X]:[Block ID 0x%08X]:Loading bond information at %p, size 0x%08X, offset 0x%08X.\r\n",
+            p_handle->connection_id,
+            block_handle.block_id,
+            &m_bond_table[p_handle->connection_id],
+            BOND_SIZE,
+            BOND_STORAGE_OFFSET);
+
+        err_code = pstorage_load((uint8_t *)&m_bond_table[p_handle->connection_id],
+                                 &block_handle,
+                                 BOND_SIZE,
+                                 BOND_STORAGE_OFFSET);
+
+        if (err_code != NRF_SUCCESS)
+        {
+            DM_ERR("[DM]:[%02X]: Failed to load Bond information, reason %08X\r\n",
+                   p_handle->connection_id,
+                   err_code);
+        }
+
+        DM_LOG(
+            "[DM]:[%02X]:Loading service context at %p, size 0x%08X, offset 0x%08X.\r\n",
+            p_handle->connection_id,
+            &m_gatts_table[p_handle->connection_id],
+            sizeof(dm_gatts_context_t),
+            SERVICE_STORAGE_OFFSET);
+
+        err_code = m_service_context_load[m_application_table[0].service](
+            &block_handle,
+            p_handle);
+
+        if (err_code != NRF_SUCCESS)
+        {
+            DM_ERR(
+                "[DM]:[%02X]: Failed to load service information, reason %08X\r\n",
+                p_handle->connection_id,
+                err_code);
+        }
+    }
+    else
+    {
+        DM_ERR("[DM]:[%02X]: Failed to get block identifier for "
+               "device %08X, reason %08X.\r\n", p_handle->connection_id, p_handle->device_id, err_code);
+    }
+}
+
+
+void dm_ble_evt_handler(ble_evt_t * p_ble_evt)
+{
+    uint32_t    err_code;
+    uint32_t    index;
+    uint32_t    device_index        = DM_INVALID_ID;
+    bool        notify_app          = false;
+    dm_handle_t handle;
+    dm_event_t  event;
+    uint32_t    event_result;
+    ble_gap_enc_info_t * p_enc_info = NULL;
+
+    VERIFY_MODULE_INITIALIZED_VOID();
+    VERIFY_APP_REGISTERED_VOID(0);
+    DM_MUTEX_LOCK();
+
+    err_code = dm_handle_initialize(&handle);
+    APP_ERROR_CHECK(err_code);
+
+    event_result                    = NRF_SUCCESS;
+    err_code                        = NRF_SUCCESS;
+    event.event_param.p_gap_param   = &p_ble_evt->evt.gap_evt;
+    event.event_paramlen            = sizeof(ble_gap_evt_t);
+    handle.device_id                = DM_INVALID_ID;
+    handle.appl_id                  = 0;
+    index                           = 0x00;
+
+    if (p_ble_evt->header.evt_id != BLE_GAP_EVT_CONNECTED)
+    {
+        err_code = connection_instance_find(p_ble_evt->evt.gap_evt.conn_handle,
+                                            STATE_CONNECTED,
+                                            &index);
+
+        if (err_code == NRF_SUCCESS)
+        {
+            handle.device_id     = m_connection_table[index].bonded_dev_id;
+            handle.connection_id = index;
+        }
+    }
+
+    switch (p_ble_evt->header.evt_id)
+    {
+        case BLE_GAP_EVT_CONNECTED:
+            //Allocate connection instance for a new connection.
+            err_code = connection_instance_allocate(&index);
+
+            //Connection instance is successfully allocated.
+            if (err_code == NRF_SUCCESS)
+            {
+                //Application notification related information.
+                notify_app           = true;
+                event.event_id       = DM_EVT_CONNECTION;
+                handle.connection_id = index;
+
+                m_connection_table[index].conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
+                m_connection_table[index].state       = STATE_CONNECTED;
+                m_connection_table[index].peer_addr   =
+                    p_ble_evt->evt.gap_evt.params.connected.peer_addr;
+
+                if (p_ble_evt->evt.gap_evt.params.connected.irk_match == 1)
+                {
+                    if (m_irk_index_table[p_ble_evt->evt.gap_evt.params.connected.irk_match_idx] != DM_INVALID_ID)
+                    {
+                        device_index = m_irk_index_table[p_ble_evt->evt.gap_evt.params.connected.irk_match_idx];
+                        err_code = NRF_SUCCESS;
+                    }
+                }
+                else
+                {
+                    //Use the device address to check if the device exists in the bonded device list.
+                    err_code = device_instance_find(&p_ble_evt->evt.gap_evt.params.connected.peer_addr,
+                                                    &device_index, EDIV_INIT_VAL);
+                }
+
+                if (err_code == NRF_SUCCESS)
+                {
+                    m_connection_table[index].bonded_dev_id = device_index;
+                    m_connection_table[index].state        |= STATE_BONDED;
+                    handle.device_id                        = device_index;
+
+                    bond_data_load(&handle);
+                }
+            }
+            break;
+
+        case BLE_GAP_EVT_DISCONNECTED:
+            //Disconnection could be peer or self initiated hence disconnecting and connecting
+            //both states are permitted, however, connection handle must be known.
+            DM_LOG("[DM]: Disconnect Reason 0x%04X\r\n",
+                   p_ble_evt->evt.gap_evt.params.disconnected.reason);
+
+            m_connection_table[index].state &= (~STATE_CONNECTED);
+
+            if ((m_connection_table[index].state & STATE_BONDED) == STATE_BONDED)
+            {
+                if ((m_connection_table[index].state & STATE_LINK_ENCRYPTED) == STATE_LINK_ENCRYPTED)
+                {
+                    //Write bond information persistently.
+                    device_context_store(&handle, STORE_ALL_CONTEXT);
+                }
+            }
+            else
+            {
+                //Free any allocated instances for devices that is not bonded.
+                if (handle.device_id != DM_INVALID_ID)
+                {
+                    peer_instance_init(handle.device_id);
+                    handle.device_id = DM_INVALID_ID;
+                }
+            }
+
+            m_connection_table[index].state = STATE_DISCONNECTING;
+            notify_app                      = true;
+            event.event_id                  = DM_EVT_DISCONNECTION;
+
+            break;
+
+        case BLE_GAP_EVT_SEC_INFO_REQUEST:
+            DM_LOG("[DM]: >> BLE_GAP_EVT_SEC_INFO_REQUEST\r\n");
+
+            //If the device is already bonded, respond with existing info, else NULL.
+            if (m_connection_table[index].bonded_dev_id == DM_INVALID_ID)
+            {
+                //Find device based on div.
+                err_code = device_instance_find(NULL,&device_index, p_ble_evt->evt.gap_evt.params.sec_info_request.master_id.ediv);
+                if (err_code == NRF_SUCCESS)
+                {
+                    //Load needed bonding information.
+                    m_connection_table[index].bonded_dev_id = device_index;
+                    m_connection_table[index].state        |= STATE_BONDED;
+                    handle.device_id                        = device_index;
+                    bond_data_load(&handle);
+                }
+            }
+
+            if (m_connection_table[index].bonded_dev_id != DM_INVALID_ID)
+            {
+                p_enc_info = &m_bond_table[index].peer_enc_key.enc_info;
+                DM_DUMP((uint8_t *)p_enc_info, sizeof(ble_gap_enc_info_t));
+            }
+
+            err_code = sd_ble_gap_sec_info_reply(p_ble_evt->evt.gap_evt.conn_handle,
+                                                 p_enc_info,
+                                                 &m_peer_table[index].peer_id.id_info,
+                                                 NULL);
+
+            if (err_code != NRF_SUCCESS)
+            {
+                DM_ERR("[DM]:[CI %02X]:[DI %02X]: Security information response failed, reason "
+                       "0x%08X\r\n", index, m_connection_table[index].bonded_dev_id, err_code);
+            }
+            break;
+
+        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
+            DM_LOG("[DM]: >> BLE_GAP_EVT_SEC_PARAMS_REQUEST\r\n");
+
+            event.event_id = DM_EVT_SECURITY_SETUP;
+
+            m_connection_table[index].state |= STATE_PAIRING;
+            notify_app                       = true;
+
+            if (m_connection_table[index].bonded_dev_id == DM_INVALID_ID)
+            {
+                //Assign a peer index as a new bond or update existing bonds.
+                err_code = device_instance_allocate((uint8_t *)&device_index,
+                                                    &m_connection_table[index].peer_addr);
+
+                //Allocation successful.
+                if (err_code == NRF_SUCCESS)
+                {
+                    DM_LOG("[DM]:[CI 0x%02X]:[DI 0x%02X]: Bonded!\r\n",index, device_index);
+
+                    handle.device_id                        = device_index;
+                    m_connection_table[index].bonded_dev_id = device_index;
+                }
+                else
+                {
+                    DM_LOG("[DM]: Security parameter request failed, reason 0x%08X.\r\n", err_code);
+                    event_result = err_code;
+                    notify_app   = true;
+                }
+            }
+            else
+            {
+                //Bond/key refresh.
+                event.event_id = DM_EVT_SECURITY_SETUP_REFRESH;
+                memset(m_gatts_table[index].attributes, 0, DM_GATT_SERVER_ATTR_MAX_SIZE);
+
+                //Set the update flag for bond data.
+                m_connection_table[index].state |= STATE_BOND_INFO_UPDATE;
+            }
+
+            ble_gap_sec_keyset_t keys_exchanged;
+
+            DM_LOG("[DM]: 0x%02X, 0x%02X, 0x%02X, 0x%02X\r\n",
+                   p_ble_evt->evt.gap_evt.params.sec_params_request.peer_params.kdist_periph.enc,
+                   p_ble_evt->evt.gap_evt.params.sec_params_request.peer_params.kdist_central.id,
+                   p_ble_evt->evt.gap_evt.params.sec_params_request.peer_params.kdist_periph.sign,
+                   p_ble_evt->evt.gap_evt.params.sec_params_request.peer_params.bond);
+
+            keys_exchanged.keys_central.p_enc_key  = NULL;
+            keys_exchanged.keys_central.p_id_key   = &m_peer_table[m_connection_table[index].bonded_dev_id].peer_id; 
+            keys_exchanged.keys_central.p_sign_key = NULL;
+            keys_exchanged.keys_periph.p_enc_key   = &m_bond_table[index].peer_enc_key;
+            keys_exchanged.keys_periph.p_id_key    = NULL;
+            keys_exchanged.keys_periph.p_sign_key  = NULL;
+
+            err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle,
+                                                   BLE_GAP_SEC_STATUS_SUCCESS,
+                                                   &m_application_table[0].sec_param, 
+                                                   &keys_exchanged);
+
+            if (err_code != NRF_SUCCESS)
+            {
+                DM_LOG("[DM]: Security parameter reply request failed, reason 0x%08X.\r\n", err_code);
+                event_result = err_code;
+                notify_app   = false;
+            }
+            break;
+
+        case BLE_GAP_EVT_AUTH_STATUS:
+        {
+            DM_LOG("[DM]: >> BLE_GAP_EVT_AUTH_STATUS, status %08X\r\n",
+                   p_ble_evt->evt.gap_evt.params.auth_status.auth_status);
+
+            m_application_table[0].state    &= (~STATE_CONTROL_PROCEDURE_IN_PROGRESS);
+            m_connection_table[index].state &= (~STATE_PAIRING);
+            event.event_id                   = DM_EVT_SECURITY_SETUP_COMPLETE;
+            notify_app                       = true;
+
+            if (p_ble_evt->evt.gap_evt.params.auth_status.auth_status != BLE_GAP_SEC_STATUS_SUCCESS)
+            {
+                // Free the allocation as bonding failed.
+                ret_code_t result = device_instance_free(m_connection_table[index].bonded_dev_id);
+                (void) result;
+                event_result = p_ble_evt->evt.gap_evt.params.auth_status.auth_status;
+            }
+            else
+            {
+                DM_DUMP((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status,
+                        sizeof(ble_gap_evt_auth_status_t));
+                DM_DUMP((uint8_t *)&m_bond_table[index], sizeof(bond_context_t));
+
+                if (p_ble_evt->evt.gap_evt.params.auth_status.bonded == 1)
+                {
+                    if (handle.device_id != DM_INVALID_ID)
+                    {
+                        m_connection_table[index].state |= STATE_BONDED;
+
+                        //IRK and/or public address is shared, update it.
+                        if (p_ble_evt->evt.gap_evt.params.auth_status.kdist_central.id == 1)
+                        {
+                            m_peer_table[handle.device_id].id_bitmap &= (~IRK_ENTRY);
+                        }
+
+                        if (m_connection_table[index].bonded_dev_id != DM_INVALID_ID)
+                        {
+                            DM_LOG("[DM]:[CI 0x%02X]:[DI 0x%02X]: Bonded!\r\n",
+                                   index,
+                                   handle.device_id);
+
+                            if (m_connection_table[index].peer_addr.addr_type !=
+                                BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE)
+                            {
+                               m_peer_table[handle.device_id].peer_id.id_addr_info =
+                                    m_connection_table[index].peer_addr;
+                               m_peer_table[handle.device_id].id_bitmap &= (~ADDR_ENTRY);
+
+                               DM_DUMP((uint8_t *)&m_peer_table[handle.device_id].peer_id.id_addr_info,
+                                       sizeof(m_peer_table[handle.device_id].peer_id.id_addr_info));
+                            }
+                            else
+                            {
+                                // Here we must fetch the keys from the keyset distributed.
+                                m_peer_table[handle.device_id].ediv       = m_bond_table[index].peer_enc_key.master_id.ediv;
+                                m_peer_table[handle.device_id].id_bitmap &= (~IRK_ENTRY);
+                            }
+
+                            device_context_store(&handle, FIRST_BOND_STORE);
+                        }
+                    }
+                }
+                else
+                {
+                    //Pairing request, no need to touch the bonding info.
+                }
+            }
+            break;
+        }
+
+        case BLE_GAP_EVT_CONN_SEC_UPDATE:
+            DM_LOG("[DM]: >> BLE_GAP_EVT_CONN_SEC_UPDATE, Mode 0x%02X, Level 0x%02X\r\n",
+                   p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.sm,
+                   p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv);
+
+            if ((p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.lv == 1) &&
+                (p_ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec.sec_mode.sm == 1) &&
+                ((m_connection_table[index].state & STATE_BONDED) == STATE_BONDED))
+            {
+                //Lost bond case, generate a security refresh event!
+                memset(m_gatts_table[index].attributes, 0, DM_GATT_SERVER_ATTR_MAX_SIZE);
+                
+                event.event_id                   = DM_EVT_SECURITY_SETUP_REFRESH;
+                m_connection_table[index].state |= STATE_PAIRING_PENDING;
+                m_connection_table[index].state |= STATE_BOND_INFO_UPDATE;
+                m_application_table[0].state    |= STATE_QUEUED_CONTROL_REQUEST;
+            }
+            else
+            {
+                m_connection_table[index].state |= STATE_LINK_ENCRYPTED;
+                event.event_id                   = DM_EVT_LINK_SECURED;
+
+                //Apply service context.
+                err_code = m_service_context_apply[m_application_table[0].service](&handle);
+
+                if (err_code != NRF_SUCCESS)
+                {
+                    DM_ERR("[DM]:[CI 0x%02X]:[DI 0x%02X]: Failed to apply service context\r\n",
+                            handle.connection_id, 
+                            handle.device_id);
+
+                    event_result = DM_SERVICE_CONTEXT_NOT_APPLIED;
+                }
+            }
+            event_result = NRF_SUCCESS;
+            notify_app   = true;
+            
+            break;
+
+        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
+            DM_LOG("[DM]: >> BLE_GATTS_EVT_SYS_ATTR_MISSING\r\n");
+
+            //Apply service context.
+            event_result = m_service_context_apply[m_application_table[0].service](&handle);
+            break;
+
+        case BLE_GAP_EVT_SEC_REQUEST:
+            DM_LOG("[DM]: >> BLE_GAP_EVT_SEC_REQUEST\r\n");
+            
+            //Verify if the device is already bonded, and if it is bonded, initiate encryption.
+            //If the device is not bonded, an instance needs to be allocated in order to initiate 
+            //bonding. The application have to initiate the procedure, the module will not do this 
+            //automatically.
+            event.event_id = DM_EVT_SECURITY_SETUP;
+            notify_app     = true;
+            
+            break;
+
+        default:
+            break;
+    }
+
+    if (notify_app)
+    {
+        app_evt_notify(&handle, &event, event_result);
+
+        //Freeing the instance after the event is notified so the application can get the context.
+        if (event.event_id == DM_EVT_DISCONNECTION)
+        {
+            //Free the instance.
+            connection_instance_free(&index);
+        }
+    }
+
+    UNUSED_VARIABLE(err_code);
+
+    DM_MUTEX_UNLOCK();
+}
+
+
+ret_code_t dm_handle_get(uint16_t conn_handle, dm_handle_t * p_handle)
+{
+    ret_code_t err_code;
+    uint32_t   index;
+
+    NULL_PARAM_CHECK(p_handle);
+    VERIFY_APP_REGISTERED(p_handle->appl_id);
+
+    p_handle->device_id  = DM_INVALID_ID;
+
+    err_code = NRF_ERROR_NOT_FOUND;
+
+    for (index = 0; index < DEVICE_MANAGER_MAX_CONNECTIONS; index++)
+    {
+        //Search for matching connection handle.
+        if (conn_handle == m_connection_table[index].conn_handle)
+        {
+            p_handle->connection_id = index;
+            p_handle->device_id     = m_connection_table[index].bonded_dev_id;
+
+            err_code = NRF_SUCCESS;
+            break;
+        }
+    }
+    return err_code;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,751 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "id_manager.h"
+
+#include <string.h>
+#include "nrf_soc.h"
+#include "ble_gap.h"
+#include "ble_conn_state.h"
+#include "peer_manager_types.h"
+#include "peer_database.h"
+#include "nordic_common.h"
+
+#define IM_MAX_CONN_HANDLES         8
+#define IM_NO_INVALID_CONN_HANDLES  0xFF
+#define MAX_REGISTRANTS             3
+#define WHITELIST_MAX_COUNT         MAX(BLE_GAP_WHITELIST_ADDR_MAX_COUNT, \
+                                        BLE_GAP_WHITELIST_IRK_MAX_COUNT)
+#define IM_ADDR_CLEARTEXT_LENGTH    3
+#define IM_ADDR_CIPHERTEXT_LENGTH   3
+
+#define MODULE_INITIALIZED (m_im.n_registrants > 0)
+
+#define VERIFY_MODULE_INITIALIZED()     \
+do                                      \
+{                                       \
+    if (!MODULE_INITIALIZED)            \
+    {                                   \
+        return NRF_ERROR_INVALID_STATE; \
+    }                                   \
+} while(0)
+
+#define VERIFY_PARAM_NOT_NULL(param)    \
+do                                      \
+{                                       \
+    if (param == NULL)                  \
+    {                                   \
+        return NRF_ERROR_NULL;          \
+    }                                   \
+} while(0)
+
+
+typedef struct
+{
+    pm_peer_id_t   peer_id;
+    uint16_t       conn_handle;
+    ble_gap_addr_t peer_address;
+} im_connection_t;
+
+typedef struct
+{
+    im_evt_handler_t              evt_handlers[MAX_REGISTRANTS];
+    uint8_t                       n_registrants;
+    im_connection_t               connections[8];
+    pm_peer_id_t                  whitelist_peer_ids[BLE_GAP_WHITELIST_IRK_MAX_COUNT];
+    ble_gap_irk_t                 whitelist_irks[BLE_GAP_WHITELIST_IRK_MAX_COUNT];
+    ble_gap_addr_t                whitelist_addrs[BLE_GAP_WHITELIST_ADDR_MAX_COUNT];
+    uint8_t                       n_whitelist_peer_ids;
+    ble_conn_state_user_flag_id_t conn_state_user_flag_id;
+} im_t;
+
+static im_t m_im = {.n_registrants = 0};
+
+static void internal_state_reset()
+{
+    memset(&m_im, 0, sizeof(im_t));
+    m_im.n_registrants = 0;
+    m_im.n_whitelist_peer_ids = 0;
+    m_im.conn_state_user_flag_id = BLE_CONN_STATE_USER_FLAG_INVALID;
+    for (uint32_t i = 0; i < IM_MAX_CONN_HANDLES; i++)
+    {
+        m_im.connections[i].conn_handle = BLE_CONN_HANDLE_INVALID;
+    }
+}
+
+
+/**@brief Function for sending an event to all registered event handlers.
+ *
+ * @param[in] p_event The event to distribute.
+ */
+static void evt_send(im_evt_t * p_event)
+{
+    for (uint32_t i = 0; i < m_im.n_registrants; i++)
+    {
+        m_im.evt_handlers[i](p_event);
+    }
+}
+
+/**@brief Function finding a free position in m_im.connections.
+ *
+ * @detail All connection handles in the m_im.connections array are checked against the connection
+ *         state module. The index of the first one that is not a connection handle for a current
+ *         connection is returned. This position in the array can safely be used for a new connection.
+ *
+ * @return Either the index of a free position in the array or IM_NO_INVALID_CONN_HANDLES if no free
+           position exists.
+ */
+uint8_t get_free_connection()
+{
+    for (uint32_t i = 0; i < IM_MAX_CONN_HANDLES; i++)
+    {
+        // Query the connection state module to check if the connection handle does not belong to a
+        // valid connection.
+        if (!ble_conn_state_user_flag_get(m_im.connections[i].conn_handle, m_im.conn_state_user_flag_id))
+        {
+            return i;
+        }
+    }
+    // If all connection handles belong to a valid connection, return IM_NO_INVALID_CONN_HANDLES.
+    return IM_NO_INVALID_CONN_HANDLES;
+}
+
+
+/**@brief Function finding a particular connection handle m_im.connections.
+ *
+ * @param[in]  conn_handle  The handle to find.
+ *
+ * @return Either the index of the conn_handle in the array or IM_NO_INVALID_CONN_HANDLES if the
+ *         handle was not found.
+ */
+uint8_t get_connection_by_conn_handle(uint16_t conn_handle)
+{
+    if (ble_conn_state_user_flag_get(conn_handle, m_im.conn_state_user_flag_id))
+    {
+        for (uint32_t i = 0; i < IM_MAX_CONN_HANDLES; i++)
+        {
+            if (m_im.connections[i].conn_handle == conn_handle)
+            {
+                return i;
+            }
+        }
+    }
+    // If all connection handles belong to a valid connection, return IM_NO_INVALID_CONN_HANDLES.
+    return IM_NO_INVALID_CONN_HANDLES;
+}
+
+
+/**@brief Function for registering a new connection instance.
+ *
+ * @param[in]  conn_handle  The handle of the new connection.
+ * @param[in]  p_ble_addr   The address used to connect.
+ *
+ * @return Either the index of the new connection in the array or IM_NO_INVALID_CONN_HANDLES if no
+ *         free position exists.
+ */
+uint8_t new_connection(uint16_t conn_handle, ble_gap_addr_t * p_ble_addr)
+{
+    uint8_t conn_index = IM_NO_INVALID_CONN_HANDLES;
+
+    if ((p_ble_addr != NULL) && (conn_handle != BLE_CONN_HANDLE_INVALID))
+    {
+        ble_conn_state_user_flag_set(conn_handle, m_im.conn_state_user_flag_id, true);
+
+        conn_index = get_connection_by_conn_handle(conn_handle);
+        if (conn_index == IM_NO_INVALID_CONN_HANDLES)
+        {
+            conn_index = get_free_connection();
+        }
+
+        if (conn_index != IM_NO_INVALID_CONN_HANDLES)
+        {
+            m_im.connections[conn_index].conn_handle  = conn_handle;
+            m_im.connections[conn_index].peer_id      = PM_PEER_ID_INVALID;
+            m_im.connections[conn_index].peer_address = *p_ble_addr;
+        }
+    }
+    return conn_index;
+}
+
+
+/**@brief Function checking the validity of an IRK
+ *
+ * @detail An all-zero IRK is not valid. This function will check if a given IRK is valid.
+ *
+ * @param[in] irk The IRK for which the validity is going to be checked.
+ *
+ * @retval true  The IRK is valid.
+ * @retval false The IRK is invalid.
+ */
+bool is_valid_irk(ble_gap_irk_t const * irk)
+{
+    for (uint32_t i = 0; i < BLE_GAP_SEC_KEY_LEN; i++)
+    {
+        if (irk->irk[i] != 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**@brief Function for comparing two addresses to determine if they are identical
+ *
+ * @note The address type need to be identical, as well as every bit in the address itself.
+ *
+ * @param[in] p_addr1 The first address to be compared.
+ * @param[in] p_addr2 The second address to be compared.
+ *
+ * @retval true  The addresses are identical.
+ * @retval false The addresses are not identical.
+ */
+bool addr_compare(ble_gap_addr_t const * p_addr1, ble_gap_addr_t const * p_addr2)
+{
+    if ((p_addr1 == NULL) || (p_addr2 == NULL))
+    {
+        return false;
+    }
+
+    // Check that the addr type is identical, return false if it is not
+    if (p_addr1->addr_type != p_addr2->addr_type)
+    {
+        return false;
+    }
+    // Check if the addr bytes are is identical
+    return (memcmp(p_addr1->addr, p_addr2->addr, BLE_GAP_ADDR_LEN) == 0);
+}
+
+
+void im_ble_evt_handler(ble_evt_t * ble_evt)
+{
+    ret_code_t err_code;
+    switch (ble_evt->header.evt_id)
+    {
+        case BLE_GAP_EVT_CONNECTED:
+        {
+            pm_peer_id_t bonded_matching_peer_id = PM_PEER_ID_INVALID;
+
+            if (ble_evt->evt.gap_evt.params.connected.irk_match == 1)
+            {
+                // The peer was matched using a whitelist.
+                bonded_matching_peer_id
+                        = m_im.whitelist_peer_ids[ble_evt->evt.gap_evt.params.connected.irk_match_idx];
+            }
+            else if (   ble_evt->evt.gap_evt.params.connected.peer_addr.addr_type
+                     != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE)
+            {
+                /* Search the database for bonding data matching the one that triggered the event.
+                 * Public and static addresses can be matched on address alone, while resolvable
+                 * random addresses can be resolved agains known IRKs. Non-resolvable random addresses
+                 * are never matching because they are not longterm form of identification.
+                 */
+                pm_peer_id_t compared_peer_id = pdb_next_peer_id_get(PM_PEER_ID_INVALID);
+                while (   (compared_peer_id        != PM_PEER_ID_INVALID)
+                       && (bonded_matching_peer_id == PM_PEER_ID_INVALID))
+                {
+                    pm_peer_data_flash_t compared_data;
+                    switch (ble_evt->evt.gap_evt.params.connected.peer_addr.addr_type)
+                    {
+                        case BLE_GAP_ADDR_TYPE_PUBLIC:
+                            /* fall-through */
+                        case BLE_GAP_ADDR_TYPE_RANDOM_STATIC:
+                            err_code = pdb_read_buf_get(compared_peer_id,
+                                                        PM_PEER_DATA_ID_BONDING,
+                                                        &compared_data,
+                                                        NULL);
+                            if ((err_code == NRF_SUCCESS) &&
+                                addr_compare(&ble_evt->evt.gap_evt.params.connected.peer_addr,
+                                             &compared_data.data.p_bonding_data->peer_id.id_addr_info)
+                            )
+                            {
+                                bonded_matching_peer_id = compared_peer_id;
+                            }
+                            break;
+
+                        case BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE:
+                            err_code = pdb_read_buf_get(compared_peer_id,
+                                                        PM_PEER_DATA_ID_BONDING,
+                                                        &compared_data,
+                                                        NULL);
+                            if (err_code == NRF_SUCCESS &&
+                                im_address_resolve(&ble_evt->evt.gap_evt.params.connected.peer_addr,
+                                                   &compared_data.data.p_bonding_data->peer_id.id_info)
+                            )
+                            {
+                                bonded_matching_peer_id = compared_peer_id;
+                            }
+                            break;
+
+                        case BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE:
+                            // Should not happen.
+                            break;
+
+                        default:
+                            break;
+                    }
+                    compared_peer_id = pdb_next_peer_id_get(compared_peer_id);
+                }
+            }
+            new_connection(ble_evt->evt.gap_evt.conn_handle, &ble_evt->evt.gap_evt.params.connected.peer_addr);
+
+            if (bonded_matching_peer_id != PM_PEER_ID_INVALID)
+            {
+                im_new_peer_id(ble_evt->evt.gap_evt.conn_handle, bonded_matching_peer_id);
+
+                // Send a bonded peer event
+                im_evt_t im_evt;
+                im_evt.conn_handle = ble_evt->evt.gap_evt.conn_handle;
+                im_evt.evt_id = IM_EVT_BONDED_PEER_CONNECTED;
+                evt_send(&im_evt);
+            }
+        }
+    }
+}
+
+
+/**@brief Function to compare two sets of bonding data to check if they belong to the same device.
+ * @note  Invalid irks will never match even though they are identical.
+ *
+ * @param[in]  p_bonding_data1 First bonding data for comparison
+ * @param[in]  p_bonding_data2 Second bonding data for comparison
+ *
+ * @return     True if the input matches, false if it does not.
+ */
+bool is_duplicate_bonding_data(pm_peer_data_bonding_t const * p_bonding_data1,
+                               pm_peer_data_bonding_t const * p_bonding_data2)
+{
+    bool valid_irk = is_valid_irk(&p_bonding_data1->peer_id.id_info);
+    bool duplicate_irk = valid_irk &&
+        (memcmp(p_bonding_data1->peer_id.id_info.irk,
+        p_bonding_data2->peer_id.id_info.irk,
+        BLE_GAP_SEC_KEY_LEN) == 0
+    );
+    bool duplicate_addr = addr_compare(&p_bonding_data1->peer_id.id_addr_info,
+                                       &p_bonding_data2->peer_id.id_addr_info
+    );
+    return duplicate_irk || duplicate_addr;
+}
+
+
+/**@brief Event handler for events from the peer_database module.
+ *
+ * @param[in]  p_event The event that has happend with peer id and flags.
+ */
+static void pdb_evt_handler(pdb_evt_t const * p_event)
+{
+    ret_code_t err_code;
+    if ((p_event != NULL) && (p_event->evt_id == PDB_EVT_WRITE_BUF_STORED))
+    {
+        // If new data about peer id has been stored it is compared to other peers peer ids in
+        // search of duplicates.
+        if (p_event->data_id == PM_PEER_DATA_ID_BONDING)
+        {
+            pm_peer_data_flash_t written_data;
+            err_code = pdb_read_buf_get(p_event->peer_id, PM_PEER_DATA_ID_BONDING, &written_data, NULL);
+            if (err_code == NRF_SUCCESS)
+            {
+                pm_peer_id_t compared_peer_id = pdb_next_peer_id_get(PM_PEER_ID_INVALID);
+                while (compared_peer_id != PM_PEER_ID_INVALID)
+                {
+                    pm_peer_data_flash_t compared_data;
+                    err_code = pdb_read_buf_get(compared_peer_id,
+                                                PM_PEER_DATA_ID_BONDING,
+                                                &compared_data,
+                                                NULL);
+                    if ( err_code == NRF_SUCCESS &&
+                        p_event->peer_id != compared_peer_id &&
+                        is_duplicate_bonding_data(written_data.data.p_bonding_data,
+                                                  compared_data.data.p_bonding_data)
+                    )
+                    {
+                        im_evt_t im_evt;
+                        im_evt.conn_handle = im_conn_handle_get(p_event->peer_id);
+                        im_evt.evt_id = IM_EVT_DUPLICATE_ID;
+                        im_evt.params.duplicate_id.peer_id_1 = p_event->peer_id;
+                        im_evt.params.duplicate_id.peer_id_2 = compared_peer_id;
+                        evt_send(&im_evt);
+                    }
+                    compared_peer_id = pdb_next_peer_id_get(compared_peer_id);
+                }
+            }
+        }
+    }
+}
+
+
+ret_code_t im_register(im_evt_handler_t evt_handler)
+{
+    VERIFY_PARAM_NOT_NULL(evt_handler);
+    ret_code_t err_code = NRF_SUCCESS;
+
+    if (!MODULE_INITIALIZED)
+    {
+        internal_state_reset();
+        m_im.conn_state_user_flag_id = ble_conn_state_user_flag_acquire();
+        if (m_im.conn_state_user_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
+        {
+            err_code = NRF_ERROR_NO_MEM;
+        }
+        else
+        {
+            err_code = pdb_register(pdb_evt_handler);
+        }
+    }
+    if (err_code == NRF_SUCCESS)
+    {
+        if ((m_im.n_registrants < MAX_REGISTRANTS))
+        {
+            m_im.evt_handlers[m_im.n_registrants++] = evt_handler;
+        }
+        else
+        {
+            err_code = NRF_ERROR_NO_MEM;
+        }
+    }
+    return err_code;
+}
+
+
+pm_peer_id_t im_peer_id_get_by_conn_handle(uint16_t conn_handle)
+{
+    uint8_t conn_index = get_connection_by_conn_handle(conn_handle);
+
+    if (MODULE_INITIALIZED && (conn_index != IM_NO_INVALID_CONN_HANDLES))
+    {
+        return m_im.connections[conn_index].peer_id;
+    }
+
+    return PM_PEER_ID_INVALID;
+}
+
+
+ret_code_t im_ble_addr_get(uint16_t conn_handle, ble_gap_addr_t * p_ble_addr)
+{
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_NULL(p_ble_addr);
+
+    uint8_t conn_index = get_connection_by_conn_handle(conn_handle);
+    if (conn_index != IM_NO_INVALID_CONN_HANDLES)
+    {
+        *p_ble_addr = m_im.connections[conn_index].peer_address;
+        return NRF_SUCCESS;
+    }
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+/**@brief Function for comparing two master ids
+ * @note  Two invalid master IDs will not match.
+ *
+ * @param[in]  p_master_id1 First master id for comparison
+ * @param[in]  p_master_id2 Second master id for comparison
+ *
+ * @return     True if the input matches, false if it does not.
+ */
+bool master_id_compare(ble_gap_master_id_t const * p_master_id1,
+                       ble_gap_master_id_t const * p_master_id2)
+{
+    if(!im_master_id_is_valid(p_master_id1))
+    {
+        return false;
+    }
+    if (p_master_id1->ediv != p_master_id2->ediv)
+    {
+        return false;
+    }
+    return (memcmp(p_master_id1->rand, p_master_id2->rand, BLE_GAP_SEC_RAND_LEN) == 0);
+}
+
+
+pm_peer_id_t im_peer_id_get_by_master_id(ble_gap_master_id_t * p_master_id)
+{
+    ret_code_t err_code;
+    // For each stored peer, check if the master_id match p_master_id
+    pm_peer_id_t compared_peer_id = pdb_next_peer_id_get(PM_PEER_ID_INVALID);
+    while (compared_peer_id != PM_PEER_ID_INVALID)
+    {
+        pm_peer_data_flash_t        compared_data;
+        ble_gap_master_id_t const * p_compared_master_id;
+
+        err_code = pdb_read_buf_get(compared_peer_id, PM_PEER_DATA_ID_BONDING, &compared_data, NULL);
+        if (err_code == NRF_SUCCESS)
+        {
+            p_compared_master_id = &compared_data.data.p_bonding_data->own_ltk.master_id;
+            if (compared_data.data.p_bonding_data->own_role == BLE_GAP_ROLE_CENTRAL)
+            {
+                p_compared_master_id = &compared_data.data.p_bonding_data->peer_ltk.master_id;
+            }
+            if (master_id_compare(p_master_id, p_compared_master_id))
+            {
+                // If a matching master_id is found return the peer_id
+                return compared_peer_id;
+            }
+        }
+        compared_peer_id = pdb_next_peer_id_get(compared_peer_id);
+    }
+    // If no matching master_id is found return the PM_PEER_ID_INVALID
+    return PM_PEER_ID_INVALID;
+}
+
+
+pm_peer_id_t im_peer_id_get_by_irk_match_idx(uint8_t irk_match_idx)
+{
+    // Verify that the requested idx is within the list
+    if (irk_match_idx < m_im.n_whitelist_peer_ids)
+    {
+        // Return the peer_id from the white list
+        return m_im.whitelist_peer_ids[irk_match_idx];
+    }
+    else
+    {
+        // Return PM_PEER_ID_INVALID to indicate that there was no peer with the requested idx
+        return PM_PEER_ID_INVALID;
+    }
+}
+
+
+uint16_t im_conn_handle_get(pm_peer_id_t peer_id)
+{
+    for (uint32_t i = 0; i < IM_MAX_CONN_HANDLES; i++)
+    {
+        if (peer_id == m_im.connections[i].peer_id)
+        {
+            return m_im.connections[i].conn_handle;
+        }
+    }
+    return BLE_CONN_HANDLE_INVALID;
+}
+
+
+bool im_master_id_is_valid(ble_gap_master_id_t const * p_master_id)
+{
+
+    if (p_master_id->ediv != 0)
+    {
+        return true;
+    }
+    for (uint32_t i = 0; i < BLE_GAP_SEC_RAND_LEN; i++)
+    {
+        if (p_master_id->rand[i] != 0)
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+void im_new_peer_id(uint16_t conn_handle, pm_peer_id_t peer_id)
+{
+    uint8_t conn_index = get_connection_by_conn_handle(conn_handle);
+    if (conn_index != IM_NO_INVALID_CONN_HANDLES)
+    {
+        m_im.connections[conn_index].peer_id = peer_id;
+    }
+}
+
+
+ret_code_t im_wlist_create(pm_peer_id_t *        p_peer_ids,
+                           uint8_t               n_peer_ids,
+                           ble_gap_whitelist_t * p_whitelist)
+{
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_NULL(p_whitelist);
+    ret_code_t err_code;
+    p_whitelist->addr_count = 0;
+    p_whitelist->irk_count = 0;
+    m_im.n_whitelist_peer_ids = 0;
+    for (uint32_t peer_index = 0; peer_index < n_peer_ids; peer_index++)
+    {
+        bool peer_connected = false;
+        for (uint32_t conn_index = 0; conn_index < IM_MAX_CONN_HANDLES; conn_index++)
+        {
+            if (p_peer_ids[peer_index] == m_im.connections[conn_index].peer_id &&
+                ble_conn_state_user_flag_get(m_im.connections[conn_index].conn_handle, m_im.conn_state_user_flag_id)
+            )
+            {
+                peer_connected = true;
+                break;
+            }
+        }
+        if (!peer_connected)
+        {
+            pm_peer_data_flash_t peer_data;
+            err_code = pdb_read_buf_get(p_peer_ids[peer_index], PM_PEER_DATA_ID_BONDING, &peer_data, NULL);
+            if (err_code == NRF_ERROR_INVALID_PARAM || err_code == NRF_ERROR_NOT_FOUND)
+            {
+                return NRF_ERROR_INVALID_PARAM;
+            }
+            if (p_whitelist->pp_addrs != NULL &&
+                peer_data.data.p_bonding_data->peer_id.id_addr_info.addr_type
+                        != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE &&
+                peer_data.data.p_bonding_data->peer_id.id_addr_info.addr_type
+                        != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE
+            )
+            {
+                memcpy(m_im.whitelist_addrs[peer_index].addr,
+                    peer_data.data.p_bonding_data->peer_id.id_addr_info.addr,
+                    BLE_GAP_ADDR_LEN
+                );
+                m_im.whitelist_addrs[peer_index].addr_type =
+                    peer_data.data.p_bonding_data->peer_id.id_addr_info.addr_type;
+                p_whitelist->pp_addrs[peer_index] = &m_im.whitelist_addrs[peer_index];
+                p_whitelist->addr_count++;
+            }
+            if (p_whitelist->pp_irks != NULL &&
+                is_valid_irk(&(peer_data.data.p_bonding_data->peer_id.id_info))
+            )
+            {
+                memcpy(m_im.whitelist_irks[peer_index].irk,
+                    peer_data.data.p_bonding_data->peer_id.id_info.irk,
+                    BLE_GAP_SEC_KEY_LEN
+                );
+                p_whitelist->pp_irks[peer_index] = &m_im.whitelist_irks[peer_index];
+                p_whitelist->irk_count++;
+                m_im.whitelist_peer_ids[peer_index] = p_peer_ids[peer_index];
+                m_im.n_whitelist_peer_ids++;
+            }
+        }
+    }
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t im_wlist_set(ble_gap_whitelist_t * p_whitelist)
+{
+    pm_peer_id_t new_whitelist_peer_ids[BLE_GAP_WHITELIST_IRK_MAX_COUNT];
+    uint32_t n_new_whitelist_peer_ids = 0;
+    VERIFY_PARAM_NOT_NULL(p_whitelist);
+    for (uint32_t i = 0; i < BLE_GAP_WHITELIST_IRK_MAX_COUNT; i++)
+    {
+        new_whitelist_peer_ids[i] = PM_PEER_ID_INVALID;
+    }
+    pm_peer_id_t compared_peer_id = pdb_next_peer_id_get(PM_PEER_ID_INVALID);
+    while (compared_peer_id != PM_PEER_ID_INVALID)
+    {
+        pm_peer_data_flash_t compared_data;
+        pdb_read_buf_get(compared_peer_id, PM_PEER_DATA_ID_BONDING, &compared_data, NULL);
+        for (uint32_t i = 0; i < p_whitelist->irk_count; i++)
+        {
+            bool valid_irk = is_valid_irk(&compared_data.data.p_bonding_data->peer_id.id_info);
+            bool duplicate_irk = valid_irk &&
+                (memcmp(p_whitelist->pp_irks[i]->irk,
+                compared_data.data.p_bonding_data->peer_id.id_info.irk,
+                BLE_GAP_SEC_KEY_LEN) == 0
+            );
+            if (duplicate_irk)
+            {
+                new_whitelist_peer_ids[i] = compared_peer_id;
+                n_new_whitelist_peer_ids++;
+            }
+        }
+        compared_peer_id = pdb_next_peer_id_get(compared_peer_id);
+    }
+    if (n_new_whitelist_peer_ids != p_whitelist->irk_count)
+    {
+        return NRF_ERROR_NOT_FOUND;
+    }
+    else
+    {
+        for (uint32_t i = 0; i < n_new_whitelist_peer_ids; i++)
+        {
+            m_im.whitelist_peer_ids[i] = new_whitelist_peer_ids[i];
+        }
+        m_im.n_whitelist_peer_ids = n_new_whitelist_peer_ids;
+        return NRF_SUCCESS;
+    }
+}
+
+
+/**@brief Function for calculating the ah() hash function described in Bluetooth core specification
+ *        4.2 section 3.H.2.2.2.
+ *
+ * @detail  BLE uses a hash function to calculate the first half of a resolvable address
+ *          from the second half of the address and an irk. This function will use the ECB
+ *          periferal to hash these data acording to the Bluetooth core specification.
+ *
+ * @note The ECB expect little endian input and output.
+ *       This function expect big endian and will reverse the data as necessary.
+ *
+ * @param[in]  p_k          The key used in the hash function.
+ *                          For address resolution this is should be the irk.
+ *                          The array must have a length of 16.
+ * @param[in]  p_r          The rand used in the hash function. For generating a new address
+ *                          this would be a random number. For resolving a resolvable address
+ *                          this would be the last half of the address being resolved.
+ *                          The array must have a length of 3.
+ * @param[out] p_local_hash The result of the hash operation. For address resolution this
+ *                          will match the first half of the address being resolved if and only
+ *                          if the irk used in the hash function is the same one used to generate
+ *                          the address.
+ *                          The array must have a length of 16.
+ */
+void ah(uint8_t const * p_k, uint8_t const * p_r, uint8_t * p_local_hash)
+{
+    nrf_ecb_hal_data_t ecb_hal_data;
+    for (uint32_t i = 0; i < SOC_ECB_KEY_LENGTH; i++)
+    {
+        ecb_hal_data.key[i] = p_k[SOC_ECB_KEY_LENGTH - 1 - i];
+    }
+    memset(ecb_hal_data.cleartext, 0, SOC_ECB_KEY_LENGTH - IM_ADDR_CLEARTEXT_LENGTH);
+
+    for (uint32_t i = 0; i < IM_ADDR_CLEARTEXT_LENGTH; i++)
+    {
+        ecb_hal_data.cleartext[SOC_ECB_KEY_LENGTH - 1 - i] = p_r[i];
+    }
+
+    sd_ecb_block_encrypt(&ecb_hal_data);
+
+    for (uint32_t i = 0; i < IM_ADDR_CIPHERTEXT_LENGTH; i++)
+    {
+        p_local_hash[i] = ecb_hal_data.ciphertext[SOC_ECB_KEY_LENGTH - 1 - i];
+    }
+}
+
+
+bool im_address_resolve(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk)
+{
+    if (p_addr->addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE)
+    {
+        return false;
+    }
+    uint8_t hash[IM_ADDR_CIPHERTEXT_LENGTH];
+    uint8_t local_hash[IM_ADDR_CIPHERTEXT_LENGTH];
+    uint8_t prand[IM_ADDR_CLEARTEXT_LENGTH];
+    memcpy(hash, p_addr->addr, IM_ADDR_CIPHERTEXT_LENGTH);
+    memcpy(prand, &p_addr->addr[IM_ADDR_CIPHERTEXT_LENGTH], IM_ADDR_CLEARTEXT_LENGTH);
+    ah(p_irk->irk, prand, local_hash);
+
+    return (memcmp(hash, local_hash, IM_ADDR_CIPHERTEXT_LENGTH) == 0);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/id_manager.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef PEER_ID_MANAGER_H__
+#define PEER_ID_MANAGER_H__
+
+#include "stdint.h"
+#include "sdk_errors.h"
+#include "nrf_ble.h"
+#include "ble_gap.h"
+#include "peer_manager_types.h"
+
+
+/**
+ * @defgroup id_manager ID Manager
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. A module for keeping track of peer identities
+ *       (IRK and peer address).
+ */
+
+
+/**@brief Events that can come from the ID Manager module.
+ */
+typedef enum
+{
+    IM_EVT_DUPLICATE_ID,          /**< The ID Manager module has detected that two stored peers represent the same peer. */
+    IM_EVT_BONDED_PEER_CONNECTED, /**< A connected peer has been identified as one of the bonded peers. This can happen immediately on connection, or at a later time. */
+} im_evt_id_t;
+
+
+typedef struct
+{
+    im_evt_id_t evt_id;
+    uint16_t    conn_handle;
+    union
+    {
+        struct
+        {
+            pm_peer_id_t peer_id_1;
+            pm_peer_id_t peer_id_2;
+        } duplicate_id;
+    } params;
+} im_evt_t;
+
+
+/**@brief Event handler for events from the ID Manager module.
+ *
+ * @param[in]  p_event   The event that has happened.
+ */
+typedef void (*im_evt_handler_t)(im_evt_t const * p_event);
+
+/**@brief Function for registering for events from the ID Manager module.
+ *
+ * @note This will also initialize the module if needed.
+ *
+ * @param[in]  evt_handler  Callback for events from the ID Manager module.
+ *
+ * @retval NRF_SUCCESS       Registration was successful.
+ * @retval NRF_ERROR_NO_MEM  No more registrations possible.
+ * @retval NRF_ERROR_NULL    evt_handler was NULL.
+ */
+ret_code_t im_register(im_evt_handler_t evt_handler);
+
+
+/**@brief Function for dispatching SoftDevice events to the ID Manager module.
+ *
+ * @param[in]  p_ble_evt  The SoftDevice event.
+ */
+void im_ble_evt_handler(ble_evt_t * p_ble_evt);
+
+
+/**@brief Function for getting the corresponding peer ID from a connection handle.
+ *
+ * @param[in]  conn_handle  The connection handle.
+ *
+ * @return The corresponding peer ID, or @ref PM_PEER_ID_INVALID if none could be resolved.
+ */
+pm_peer_id_t im_peer_id_get_by_conn_handle(uint16_t conn_handle);
+
+
+/**@brief Function for getting the corresponding peer ID from a master ID (EDIV and rand).
+ *
+ * @param[in]  p_master_id  The master ID.
+ *
+ * @return The corresponding peer ID, or @ref PM_PEER_ID_INVALID if none could be resolved.
+ */
+pm_peer_id_t im_peer_id_get_by_master_id(ble_gap_master_id_t * p_master_id);
+
+
+/**@brief Function for getting the corresponding peer ID from an IRK match index, see @ref
+ *        ble_gap_evt_connected_t.
+ *
+ * @param[in]  irk_match_idx  The IRK match index.
+ *
+ * @return The corresponding peer ID, or @ref PM_PEER_ID_INVALID if none could be resolved.
+ */
+pm_peer_id_t im_peer_id_get_by_irk_match_idx(uint8_t irk_match_idx);
+
+
+/**@brief Function for getting the corresponding connection handle from a peer ID.
+ *
+ * @param[in] peer_id  The peer ID.
+ *
+ * @return The corresponding connection handle, or @ref BLE_CONN_HANDLE_INVALID if none could be
+ *         resolved.
+ */
+uint16_t im_conn_handle_get(pm_peer_id_t peer_id);
+
+
+/**@brief Function for getting the BLE address used by the peer when connecting.
+ *
+ * @param[in]  conn_handle  The connection handle.
+ * @param[out] p_ble_addr   The BLE address used by the peer when the connection specified by
+ *                          conn_handle was established.
+ *
+ * @retval NRF_SUCCESS                   The address was found and copied.
+ * @retval NRF_ERROR_INVALID_STATE       Module not initialized.
+ * @retval BLE_ERROR_CONN_HANDLE_INVALID conn_handle does not refer to an active connection.
+ * @retval NRF_ERROR_NULL                p_ble_addr was NULL.
+ */
+ret_code_t im_ble_addr_get(uint16_t conn_handle, ble_gap_addr_t * p_ble_addr);
+
+
+/**@brief Function for checking whether a master ID is valid or invalid
+ *
+ * @param[in]  p_master_id  The master ID.
+ *
+ * @retval true   The master id is valid.
+ * @retval true   The master id is invalid (i.e. all zeros).
+ */
+bool im_master_id_is_valid(ble_gap_master_id_t const * p_master_id);
+
+
+/**@brief Function for reporting that a new peer ID has been allocated for a specified connection.
+ *
+ * @param[in]  conn_handle  The connection.
+ * @param[in]  peer_id      The new peer ID.
+ */
+void im_new_peer_id(uint16_t conn_handle, pm_peer_id_t peer_id);
+
+
+/**
+ * @brief Function for informing this module of what whitelist will be used.
+ *
+ * @details This function is meant to be used when the app wants to use a custom whitelist.
+ *          When using peer manager, this function must be used if a custom whitelist is used.
+ *
+ * @note When using a whitelist, always use the whitelist created/set by the most recent
+ *       call to @ref im_wlist_create or to this function, whichever happened most recently.
+ * @note Do not call this function while scanning with another whitelist.
+ * @note Do not add any irks to the whitelist that are not present in the bonding data of a peer in
+ *       the peer database.
+ *
+ * @param[in] p_whitelist  The whitelist.
+ *
+ * @retval NRF_SUCCESS         Whitelist successfully set.
+ * @retval NRF_ERROR_NULL      p_whitelist was NULL.
+ * @retval NRF_ERROR_NOT_FOUND One or more of the whitelists irks was not found in the peer_database.
+ */
+ret_code_t im_wlist_set(ble_gap_whitelist_t * p_whitelist);
+
+
+/**
+ * @brief Function for constructing a whitelist for use when advertising.
+ *
+ * @note When advertising with whitelist, always use the whitelist created/set by the most recent
+ *       call to this function or to @ref im_wlist_set, whichever happened most recently.
+ * @note Do not call this function while advertising with another whitelist.
+ *
+ * @param[in]     p_peer_ids   The ids of the peers to be added to the whitelist.
+ * @param[in]     n_peer_ids   The number of peer ids in p_peer_ids.
+ * @param[in,out] p_whitelist  The constructed whitelist. Note that p_adv_whitelist->pp_addrs
+ *                             must be NULL or point to an array with size @ref
+ *                             BLE_GAP_WHITELIST_ADDR_MAX_COUNT and p_adv_whitelist->pp_irks
+ *                             must be NULL or point to an array with size @ref
+ *                             BLE_GAP_WHITELIST_IRK_MAX_COUNT.
+ *
+ * @retval NRF_SUCCESS     Whitelist successfully created.
+ * @retval NRF_ERROR_NULL  p_whitelist was NULL.
+ */
+ret_code_t im_wlist_create(pm_peer_id_t        * p_peer_ids,
+                           uint8_t               n_peer_ids,
+                           ble_gap_whitelist_t * p_whitelist);
+
+/**
+ * @brief Function for resolving a resolvable address with an identity resolution key (IRK).
+ *
+ * @details This function will use the ECB peripheral to resolve a resolvable address.
+ *          This can be used to resolve the identity of a device distributing a random
+ *          resolvable address based on any IRKs you have received earlier. If an address is
+ *          resolved by an IRK, the device disributing the address must also know the IRK.
+ *
+ * @param[in] p_addr  A random resolvable address.
+ * @param[in] p_irk   An identity resolution key (IRK).
+ *
+ * @retval true   The irk used matched the one used to create the address.
+ * @retval false  The irk used did not match the one used to create the address, or an argument was
+ *                NULL.
+ */
+bool im_address_resolve(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk);
+
+/**@brief Function for calculating the ah() hash function described in Bluetooth core specification
+ *        4.2 section 3.H.2.2.2.
+ *
+ * @detail  BLE uses a hash function to calculate the first half of a resolvable address
+ *          from the second half of the address and an irk. This function will use the ECB
+ *          periferal to hash these data acording to the Bluetooth core specification.
+ *
+ * @note The ECB expect little endian input and output.
+ *       This function expect big endian and will reverse the data as necessary.
+ *
+ * @param[in]  p_k          The key used in the hash function.
+ *                          For address resolution this is should be the irk.
+ *                          The array must have a length of 16.
+ * @param[in]  p_r          The rand used in the hash function. For generating a new address
+ *                          this would be a random number. For resolving a resolvable address
+ *                          this would be the last half of the address being resolved.
+ *                          The array must have a length of 3.
+ * @param[out] p_local_hash The result of the hash operation. For address resolution this
+ *                          will match the first half of the address being resolved if and only
+ *                          if the irk used in the hash function is the same one used to generate
+ *                          the address.
+ *                          The array must have a length of 16.
+ *
+ * @note    ====IMPORTANT====
+ *          This is a special modification to the original nRF51 SDK required by the mbed BLE API
+ *          to be able to generate BLE private resolvable addresses. This function is used by
+ *          the BLE API implementation for nRF5xSecurityManager::getAddressFromBondTable() in the
+ *          ble-nrf51822 yotta module.
+ *          =================
+ */
+void ah(uint8_t const * p_k, uint8_t const * p_r, uint8_t * p_local_hash);
+
+/** @} */
+
+#endif /* PEER_ID_MANAGER_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "peer_data.h"
+
+#include <stdint.h>
+#include <string.h>
+#include "peer_manager_types.h"
+#include "fds.h"
+
+
+
+void peer_data_parts_get(pm_peer_data_const_t const * p_peer_data, fds_record_chunk_t * p_chunks, uint16_t * p_n_chunks)
+{
+    if (p_n_chunks == NULL)
+    {
+    }
+    else if ((p_peer_data == NULL) || (p_chunks == NULL))
+    {
+        *p_n_chunks = 0;
+    }
+    else
+    {
+        switch (p_peer_data->data_type)
+        {
+            case PM_PEER_DATA_ID_BONDING:
+                p_chunks[0].p_data       = p_peer_data->data.p_bonding_data;
+                p_chunks[0].length_words = p_peer_data->length_words;
+                *p_n_chunks = 1;
+                break;
+            case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
+                p_chunks[0].p_data       = p_peer_data->data.p_service_changed_pending;
+                p_chunks[0].length_words = p_peer_data->length_words;
+                *p_n_chunks = 1;
+                break;
+            case PM_PEER_DATA_ID_GATT_LOCAL:
+                p_chunks[0].p_data       = p_peer_data->data.p_local_gatt_db;
+                p_chunks[0].length_words = PM_N_WORDS(PM_LOCAL_DB_LEN_OVERHEAD_BYTES);
+                p_chunks[1].p_data       = p_peer_data->data.p_local_gatt_db->p_data;
+                p_chunks[1].length_words = p_peer_data->length_words - p_chunks[0].length_words;
+                *p_n_chunks = 2;
+                break;
+            case PM_PEER_DATA_ID_GATT_REMOTE:
+                p_chunks[0].p_data       = p_peer_data->data.p_remote_gatt_db;
+                p_chunks[0].length_words = PM_N_WORDS(PM_REMOTE_DB_LEN_OVERHEAD_BYTES);
+                p_chunks[1].p_data       = p_peer_data->data.p_remote_gatt_db->p_data;
+                p_chunks[1].length_words = p_peer_data->length_words - p_chunks[0].length_words;
+                *p_n_chunks = 2;
+                break;
+            case PM_PEER_DATA_ID_APPLICATION:
+                p_chunks[0].p_data       = p_peer_data->data.p_application_data;
+                p_chunks[0].length_words = p_peer_data->length_words;
+                *p_n_chunks = 1;
+                break;
+            default:
+                *p_n_chunks = 0;
+                break;
+        }
+    }
+}
+
+
+ret_code_t peer_data_deserialize(pm_peer_data_flash_t const * p_in_data, pm_peer_data_t * p_out_data)
+{
+    if ((p_in_data == NULL) || (p_out_data == NULL))
+    {
+        return NRF_ERROR_NULL;
+    }
+    else
+    {
+        if (p_out_data->length_words < p_in_data->length_words)
+        {
+            p_out_data->length_words = p_in_data->length_words;
+            return NRF_ERROR_NO_MEM;
+        }
+        p_out_data->length_words = p_in_data->length_words;
+        p_out_data->data_type    = p_in_data->data_type;
+
+        switch (p_in_data->data_type)
+        {
+            case PM_PEER_DATA_ID_BONDING:
+                *p_out_data->data.p_bonding_data = *p_in_data->data.p_bonding_data;
+                break;
+            case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
+                *p_out_data->data.p_service_changed_pending = *p_in_data->data.p_service_changed_pending;
+                break;
+            case PM_PEER_DATA_ID_GATT_LOCAL:
+                if (p_out_data->data.p_local_gatt_db->p_data == NULL)
+                {
+                    return NRF_ERROR_NULL;
+                }
+                if (p_out_data->data.p_local_gatt_db->len < p_in_data->data.p_local_gatt_db->len)
+                {
+                    p_out_data->data.p_local_gatt_db->len = p_in_data->data.p_local_gatt_db->len;
+                    return NRF_ERROR_NO_MEM;
+                }
+                else
+                {
+                    p_out_data->data.p_local_gatt_db->flags = p_in_data->data.p_local_gatt_db->flags;
+                    p_out_data->data.p_local_gatt_db->len   = p_in_data->data.p_local_gatt_db->len;
+                    memcpy(p_out_data->data.p_local_gatt_db->p_data,
+                           p_in_data->data.p_local_gatt_db->p_data,
+                           p_in_data->data.p_local_gatt_db->len);
+                }
+                break;
+            case PM_PEER_DATA_ID_GATT_REMOTE:
+                if (p_out_data->data.p_remote_gatt_db->p_data == NULL)
+                {
+                    return NRF_ERROR_NULL;
+                }
+                if (p_out_data->data.p_remote_gatt_db->service_count < p_in_data->data.p_remote_gatt_db->service_count)
+                {
+                    p_out_data->data.p_remote_gatt_db->service_count = p_in_data->data.p_remote_gatt_db->service_count;
+                    return NRF_ERROR_NO_MEM;
+                }
+                else
+                {
+                    p_out_data->data.p_remote_gatt_db->service_count = p_in_data->data.p_remote_gatt_db->service_count;
+                    memcpy(p_out_data->data.p_remote_gatt_db->p_data,
+                           p_in_data->data.p_remote_gatt_db->p_data,
+                           p_in_data->data.p_remote_gatt_db->service_count * sizeof(ble_gatt_db_srv_t));
+                }
+                break;
+            case PM_PEER_DATA_ID_APPLICATION:
+                memcpy(p_out_data->data.p_application_data,
+                       p_in_data->data.p_application_data,
+                       p_in_data->length_words * 4);
+                break;
+            default:
+                break;
+        }
+    }
+    return NRF_SUCCESS;
+}
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef PEER_DATA_H__
+#define PEER_DATA_H__
+
+#include <stdint.h>
+#include "peer_manager_types.h"
+#include "fds.h"
+
+
+/**
+ * @defgroup peer_data Peer Data
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. This module defines the structure of the data
+ *        that is managed by the @ref peer_manager. It also provides functions for parsing the data.
+ */
+
+
+/**@brief Function for enumerating the separate (non-contiguous) parts of the peer data.
+ *
+ * @param[in]  p_peer_data  The peer data to enumerate.
+ * @param[out] p_chunks      The resulting chunks. This must be an array of at least 2 elements.
+ * @param[out] p_n_chunks    The number of chunks. If this is 0, something went wrong.
+ */
+void peer_data_parts_get(pm_peer_data_const_t const * p_peer_data, fds_record_chunk_t * p_chunks, uint16_t * p_n_chunks);
+
+
+/**@brief Function for converting @ref pm_peer_data_flash_t into @ref pm_peer_data_t.
+ *
+ * @param[in]  p_in_data   The source data.
+ * @param[out] p_out_data  The target data structure.
+ *
+ * @retval NRF_SUCCESS       Successful conversion.
+ * @retval NRF_ERROR_NULL    A parameter was NULL.
+ * @retval NRF_ERROR_NO_MEM  A buffer was not large enough.
+ */
+ret_code_t peer_data_deserialize(pm_peer_data_flash_t const * p_in_data, pm_peer_data_t * p_out_data);
+
+/** @} */
+
+#endif /* PEER_DATA_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,688 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "peer_data_storage.h"
+
+#include <stdint.h>
+#include <string.h>
+#include "sdk_errors.h"
+#include "peer_manager_types.h"
+#include "peer_id.h"
+#include "peer_data.h"
+#include "fds.h"
+
+#define MAX_REGISTRANTS    6                         /**< The number of user that can register with the module. */
+
+#define MODULE_INITIALIZED (m_pds.n_registrants > 0) /**< Expression which is true when the module is initialized. */
+
+/**@brief Macro for verifying that the module is initialized. It will cause the function to return
+ *        @ref NRF_ERROR_INVALID_STATE if not.
+ */
+#define VERIFY_MODULE_INITIALIZED()         \
+do                                          \
+{                                           \
+    if (!MODULE_INITIALIZED)                \
+    {                                       \
+        return NRF_ERROR_INVALID_STATE;     \
+    }                                       \
+} while(0)
+
+
+/**@brief Macro for verifying that the module is initialized. It will cause the function to return
+ *        if not.
+ */
+#define VERIFY_MODULE_INITIALIZED_VOID()    \
+do                                          \
+{                                           \
+    if (!MODULE_INITIALIZED)                \
+    {                                       \
+        return;                             \
+    }                                       \
+} while(0)
+
+
+/**@brief Macro for verifying that the param is not NULL. It will cause the function to return
+ *        if not.
+ *
+ * @param[in] param  The variable to check if is NULL.
+ */
+#define VERIFY_PARAM_NOT_NULL(param)        \
+do                                          \
+{                                           \
+    if (param == NULL)                      \
+    {                                       \
+        return NRF_ERROR_NULL;              \
+    }                                       \
+} while(0)
+
+
+/**@brief Macro for verifying that param is not zero. It will cause the function to return
+ *        if not.
+ *
+ * @param[in] param  The variable to check if is zero.
+ */
+#define VERIFY_PARAM_NOT_ZERO(param)        \
+do                                          \
+{                                           \
+    if (param == 0)                         \
+    {                                       \
+        return NRF_ERROR_NULL;              \
+    }                                       \
+} while(0)
+
+
+/**@brief Macro for verifying that the peer id is within a valid range
+ *
+ * @param[in]   id      The peer data id to check.
+ */
+#define VERIFY_PEER_ID_IN_RANGE(id)         \
+do                                          \
+{                                           \
+    if ((id >= PM_PEER_ID_N_AVAILABLE_IDS)) \
+    {                                       \
+        return NRF_ERROR_INVALID_PARAM;     \
+    }                                       \
+} while (0)
+
+
+/**@brief Macro for verifying that the peer data id is withing a valid range
+ *
+ * @param[in]   id      The peer data id to check.
+ */
+#define VERIFY_PEER_DATA_ID_IN_RANGE(id)    \
+do                                          \
+{                                           \
+    if (!PM_PEER_DATA_ID_IS_VALID(id))      \
+    {                                       \
+        return NRF_ERROR_INVALID_PARAM;     \
+    }                                       \
+} while (0)
+
+
+#define PEER_IDS_INITIALIZE()               \
+do                                          \
+{                                           \
+    if (!m_pds.peer_ids_initialized)        \
+    {                                       \
+        peer_ids_init();                    \
+    }                                       \
+} while (0)
+
+
+typedef struct
+{
+    bool                peer_ids_initialized;
+    pds_evt_handler_t   evt_handlers[MAX_REGISTRANTS];
+    uint8_t             n_registrants;
+} pds_t;
+
+static pds_t m_pds = {.n_registrants = 0};
+
+static void internal_state_reset(pds_t * p_pds)
+{
+    memset(p_pds, 0, sizeof(pds_t));
+}
+
+/**@brief Function for dispatching outbound events to all registered event handlers.
+ *
+ * @param[in]  p_event  The event to dispatch.
+ */
+static void pds_evt_send(pds_evt_t * p_event)
+{
+    for (int i = 0; i < m_pds.n_registrants; i++)
+    {
+        m_pds.evt_handlers[i](p_event);
+    }
+}
+
+/**@brief Function to convert peer id to instance id
+ *
+ * @param[in] peer_id   Peer id to convert to instance id
+ *
+ * @return  Value as instance id
+ */
+static fds_instance_id_t convert_peer_id_to_instance_id(pm_peer_id_t peer_id)
+{
+    return (fds_instance_id_t)(peer_id + peer_id_to_instance_id);
+}
+
+/**@brief Function to convert peer data id to type id
+ *
+ * @param[in]   peer_data_id    Peer data id to convert to type_id
+ *
+ * @return Value as type id
+ */
+static fds_type_id_t convert_peer_data_id_to_type_id(pm_peer_data_id_t peer_data_id)
+{
+    return (fds_type_id_t)peer_data_id + (fds_type_id_t)peer_data_id_to_type_id;
+}
+
+
+/**@brief Function to convert peer data id to type id
+ *
+ * @param[in]   peer_data_id    Peer data id to convert to type_id
+ *
+ * @return Value as type id
+ */
+static pm_peer_id_t convert_instance_id_to_peer_id(fds_instance_id_t instance_id)
+{
+    return (pm_peer_id_t)(instance_id + instance_id_to_peer_id);
+}
+
+
+/**@brief Function to type id to peer data id
+ *
+ * @param[in]   type_id    Type id to convert to peer data id
+ *
+ * @return Value as peer data id
+ */
+static pm_peer_data_id_t convert_type_id_to_peer_data_id(fds_type_id_t type_id)
+{
+    return (pm_peer_data_id_t)(type_id + instance_id_to_peer_id);
+}
+
+
+static ret_code_t find_fds_item(pm_peer_id_t              peer_id,
+                                pm_peer_data_id_t         data_id,
+                                fds_record_desc_t * const p_desc)
+{
+    fds_find_token_t find_tok;
+
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(data_id);
+    // pp_record verified outside
+
+    fds_type_id_t       type_id     = convert_peer_data_id_to_type_id(data_id);
+    fds_instance_id_t   instance_id = convert_peer_id_to_instance_id(peer_id);
+
+    return fds_find(type_id, instance_id, p_desc, &find_tok);
+}
+
+
+static void peer_ids_init()
+{
+    fds_record_t            record;
+    fds_record_desc_t       record_desc;
+    fds_find_token_t        find_tok;
+    fds_type_id_t     const type_id = convert_peer_data_id_to_type_id(PM_PEER_DATA_ID_BONDING);
+    pm_peer_id_t            peer_id;
+
+    if (!m_pds.peer_ids_initialized)
+    {
+        while(fds_find_by_type(type_id, &record_desc, &find_tok) == NRF_SUCCESS)
+        {
+            fds_open(&record_desc, &record);
+            fds_close(&record_desc);
+            peer_id = convert_instance_id_to_peer_id(record.header.ic.instance);
+            peer_id_allocate(peer_id);
+        }
+
+        m_pds.peer_ids_initialized = true;
+    }
+}
+
+//uint32_t size_pad_to_mult_of_four(uint32_t unpadded_size)
+//{
+//    return (unpadded_size + 3) & 3;
+//}
+
+static void fds_evt_handler(ret_code_t          result,
+                            fds_cmd_id_t        cmd,
+                            fds_record_id_t     record_id,
+                            fds_record_key_t    record_key
+                            /*fds_record_t  const * const p_record*/)
+{
+    pds_evt_t evt;
+    switch(cmd)
+    {
+        case FDS_CMD_INIT:
+
+            break;
+
+        case FDS_CMD_UPDATE:
+        case FDS_CMD_WRITE:
+            evt.peer_id = convert_instance_id_to_peer_id(record_key.instance);
+            evt.evt_id = (result == NRF_SUCCESS) ? PDS_EVT_STORED : PDS_EVT_ERROR_STORE;
+            evt.data_id = convert_type_id_to_peer_data_id(record_key.type);
+            evt.store_token = record_id;
+            pds_evt_send(&evt);
+            break;
+
+        case FDS_CMD_CLEAR:
+            evt.peer_id = convert_instance_id_to_peer_id(record_key.instance);
+            evt.evt_id = (result == NRF_SUCCESS) ? PDS_EVT_CLEARED : PDS_EVT_ERROR_CLEAR;
+            evt.data_id = convert_type_id_to_peer_data_id(record_key.type);
+            evt.store_token = record_id;
+            pds_evt_send(&evt);
+            break;
+
+        case FDS_CMD_CLEAR_INST:
+            {
+                if ((record_key.type     == FDS_TYPE_ID_INVALID) &&
+                    (record_key.instance != FDS_TYPE_ID_INVALID))
+                {
+                    pm_peer_id_t peer_id = convert_instance_id_to_peer_id(record_key.instance);
+
+                    evt.peer_id = peer_id;
+                    evt.data_id = PM_PEER_DATA_ID_INVALID;
+                    if (result == NRF_SUCCESS)
+                    {
+                        evt.evt_id = PDS_EVT_PEER_ID_CLEAR;
+                        peer_id_free(peer_id);
+                    }
+                    else
+                    {
+                        evt.evt_id = PDS_EVT_ERROR_PEER_ID_CLEAR;
+                    }
+                }
+                else
+                {
+                    // TODO: Not supported yet (clear many without clearing peer_id)
+                }
+
+                pds_evt_send(&evt);
+            }
+            break;
+
+        case FDS_CMD_GC:
+            evt.peer_id = convert_instance_id_to_peer_id(record_key.instance);
+            evt.evt_id = PDS_EVT_COMPRESSED;
+            evt.data_id = convert_type_id_to_peer_data_id(record_key.type);
+            evt.store_token = record_id;
+            pds_evt_send(&evt);
+            break;
+
+        default:
+
+            break;
+    }
+}
+
+
+ret_code_t pds_register(pds_evt_handler_t evt_handler)
+{
+    if (m_pds.n_registrants >= MAX_REGISTRANTS)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    VERIFY_PARAM_NOT_NULL(evt_handler);
+
+    if (!MODULE_INITIALIZED)
+    {
+        ret_code_t retval;
+        internal_state_reset(&m_pds);
+        peer_id_init();
+
+        fds_cb_t cb = fds_evt_handler;
+        retval = fds_register(cb);
+        if(retval != NRF_SUCCESS)
+        {
+            return retval;
+        }
+
+        retval = fds_init();
+        if(retval != NRF_SUCCESS)
+        {
+            return retval;
+        }
+    }
+
+    m_pds.evt_handlers[m_pds.n_registrants] = evt_handler;
+    m_pds.n_registrants += 1;
+
+    return NRF_SUCCESS;
+
+}
+
+
+ret_code_t pds_peer_data_read_ptr_get(pm_peer_id_t            peer_id,
+                                      pm_peer_data_id_t       data_id,
+                                      pm_peer_data_flash_t  * p_data,
+                                      pm_store_token_t      * p_token)
+{
+    ret_code_t retval;
+
+    fds_record_t      record;
+    fds_record_desc_t record_desc;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(data_id);
+
+    retval = find_fds_item(peer_id, data_id, &record_desc);
+    if (retval != NRF_SUCCESS)
+    {
+        return retval;
+    }
+
+    // Shouldn't fail, unless record is cleared.
+    fds_open(&record_desc, &record);
+    // No need to keep it open, since we are not reading.
+    fds_close(&record_desc);
+
+    //NRF_LOG_PRINTF("Found item with peer_id: %d, data_id: %d, Address: %p\r\n", record.p_data);
+
+    if (p_data != NULL)
+    {
+        p_data->data_type    = data_id;
+        p_data->length_words = record.header.tl.length_words;
+
+        p_data->data.p_application_data = (uint8_t const*)record.p_data;
+    }
+
+    if (p_token != NULL)
+    {
+        *p_token = (uint32_t)record.header.id;
+    }
+
+    return retval;
+}
+
+
+ret_code_t pds_peer_data_lock(pm_store_token_t store_token)
+{
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_ZERO(store_token);
+
+    // TODO: Not implemented yet in fds
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t pds_peer_data_verify(pm_store_token_t store_token)
+{
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_ZERO(store_token);
+
+    // TODO: Not implemented yet in fds
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t pds_peer_data_read(pm_peer_id_t          peer_id,
+                              pm_peer_data_id_t     data_id,
+                              pm_peer_data_t      * p_data,
+                              fds_length_t        * p_len_words)
+{
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(data_id);
+    VERIFY_PARAM_NOT_NULL(p_len_words);
+    VERIFY_PARAM_NOT_NULL(p_data);
+
+    ret_code_t err_code;
+    pm_peer_data_flash_t peer_data_flash;
+
+    err_code = pds_peer_data_read_ptr_get(peer_id, data_id, &peer_data_flash, NULL);
+
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+
+    if ((*p_len_words) == 0)
+    {
+        (*p_len_words) = peer_data_flash.length_words;
+        return NRF_SUCCESS;
+    }
+    else if ((*p_len_words) < peer_data_flash.length_words)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    VERIFY_PARAM_NOT_NULL(p_data->data.p_application_data);
+
+    err_code = peer_data_deserialize(&peer_data_flash, p_data);
+
+    return err_code;
+}
+
+
+ret_code_t pds_peer_data_write_prepare(pm_peer_data_const_t const * p_peer_data,
+                                       pm_prepare_token_t         * p_prepare_token)
+{
+    ret_code_t retval;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_NULL(p_peer_data);
+    VERIFY_PARAM_NOT_NULL(p_prepare_token);
+    VERIFY_PEER_DATA_ID_IN_RANGE(p_peer_data->data_type);
+
+    retval = fds_reserve((fds_write_token_t*)p_prepare_token, p_peer_data->length_words);
+    return retval;
+}
+
+
+ret_code_t pds_peer_data_write_prepare_cancel(pm_prepare_token_t prepare_token)
+{
+    ret_code_t retval;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_ZERO(prepare_token);
+
+    retval = fds_reserve_cancel((fds_write_token_t*)&prepare_token);
+    return retval;
+}
+
+
+ret_code_t pds_peer_data_write_prepared(pm_peer_id_t                    peer_id,
+                                        pm_peer_data_const_t    const * p_peer_data,
+                                        pm_prepare_token_t              prepare_token,
+                                        pm_store_token_t              * p_store_token)
+{
+    ret_code_t         retval;
+    fds_record_desc_t  record_desc;
+    fds_record_key_t   record_key;
+    fds_record_chunk_t chunks[2];
+    uint16_t           n_chunks;
+
+    VERIFY_MODULE_INITIALIZED();
+    //VERIFY_PARAM_NOT_ZERO(prepare_token);
+    VERIFY_PARAM_NOT_NULL(p_peer_data);
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(p_peer_data->data_type);
+
+    // Fill in the keys.
+    record_key.type     = convert_peer_data_id_to_type_id(p_peer_data->data_type);
+    record_key.instance = convert_peer_id_to_instance_id(peer_id);
+
+    // Create chunks.
+    peer_data_parts_get(p_peer_data, chunks, &n_chunks);
+
+    retval = fds_write_reserved((fds_write_token_t*)&prepare_token, &record_desc,
+                                record_key, n_chunks, chunks);
+
+    if ((retval == NRF_SUCCESS) && (p_store_token != NULL))
+    {
+        fds_record_id_from_desc(&record_desc, (fds_record_id_t*)p_store_token);
+    }
+
+    return retval;
+}
+
+
+ret_code_t pds_peer_data_write(pm_peer_id_t                 peer_id,
+                               pm_peer_data_const_t const * p_peer_data,
+                               pm_store_token_t           * p_store_token)
+{
+    ret_code_t          retval;
+    fds_record_desc_t   record_desc;
+    fds_record_key_t    record_key;
+    fds_record_chunk_t  chunks[2];
+    uint16_t            n_chunks;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(p_peer_data->data_type);
+
+    // Fill in the keys.
+    record_key.type     = convert_peer_data_id_to_type_id(p_peer_data->data_type);
+    record_key.instance = convert_peer_id_to_instance_id(peer_id);
+
+    // Create chunks
+    peer_data_parts_get(p_peer_data, chunks, &n_chunks);
+
+    // Request write
+    retval = fds_write(&record_desc, record_key, n_chunks, chunks);
+
+    if ((retval == NRF_SUCCESS) && (p_store_token != NULL))
+    {
+        fds_record_id_from_desc(&record_desc, (fds_record_id_t*)p_store_token);
+    }
+
+    return retval;
+}
+
+
+ret_code_t pds_peer_data_update(pm_peer_id_t                 peer_id,
+                                pm_peer_data_const_t const * p_peer_data,
+                                pm_store_token_t             old_token,
+                                pm_store_token_t           * p_store_token)
+{
+    ret_code_t         retval;
+    fds_record_desc_t  record_desc;
+    fds_record_key_t   record_key;
+    fds_record_chunk_t chunks[2];
+    uint16_t           n_chunks;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PEER_DATA_ID_IN_RANGE(p_peer_data->data_type);
+    VERIFY_PARAM_NOT_NULL(p_peer_data);
+
+    record_key.type     = convert_peer_data_id_to_type_id(p_peer_data->data_type);
+    record_key.instance = convert_peer_id_to_instance_id(peer_id);
+
+    // Create chunks
+    peer_data_parts_get(p_peer_data, chunks, &n_chunks);
+
+    fds_descriptor_from_rec_id(&record_desc, (fds_record_id_t)old_token);
+
+    retval = fds_update(&record_desc, record_key, n_chunks, chunks);
+
+    if ((retval == NRF_SUCCESS) && (p_store_token != NULL))
+    {
+        fds_record_id_from_desc(&record_desc, (fds_record_id_t*)p_store_token);
+    }
+
+    return retval;
+}
+
+ret_code_t pds_peer_data_clear(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
+{
+    ret_code_t        retval;
+    fds_type_id_t     type_id;
+    fds_instance_id_t instance_id;
+    fds_record_desc_t record_desc;
+    fds_find_token_t  find_tok;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    VERIFY_PEER_DATA_ID_IN_RANGE(data_id);
+
+    type_id     = convert_peer_data_id_to_type_id(data_id);
+    instance_id = convert_peer_id_to_instance_id(peer_id);
+
+    retval = fds_find(type_id, instance_id, &record_desc, &find_tok);
+    if(retval != NRF_SUCCESS)
+    {
+        return retval;
+    }
+
+    retval = fds_clear(&record_desc);
+    return retval;
+}
+
+
+pm_peer_id_t pds_peer_id_allocate(void)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return PM_PEER_ID_INVALID;
+    }
+    PEER_IDS_INITIALIZE();
+    return peer_id_allocate(PM_PEER_ID_INVALID);
+}
+
+
+ret_code_t pds_peer_id_free(pm_peer_id_t peer_id)
+{
+    ret_code_t retval;
+    fds_instance_id_t instance_id;
+
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PEER_ID_IN_RANGE(peer_id);
+    PEER_IDS_INITIALIZE();
+
+    instance_id = convert_peer_id_to_instance_id(peer_id);
+
+    retval = fds_clear_by_instance(instance_id);
+    return retval;
+}
+
+
+bool pds_peer_id_is_allocated(pm_peer_id_t peer_id)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return false;
+    }
+    PEER_IDS_INITIALIZE();
+
+    return peer_id_is_allocated(peer_id);
+}
+
+
+pm_peer_id_t pds_next_peer_id_get(pm_peer_id_t prev_peer_id)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return PM_PEER_ID_INVALID;
+    }
+    PEER_IDS_INITIALIZE();
+
+    return peer_id_next_id_get(prev_peer_id);
+}
+
+
+uint32_t pds_n_peers(void)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return 0;
+    }
+    PEER_IDS_INITIALIZE();
+    return peer_id_n_ids();
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_data_storage.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,370 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef PEER_DATA_STORAGE_H__
+#define PEER_DATA_STORAGE_H__
+
+
+#include "stdint.h"
+#include "sdk_errors.h"
+#include "ble_gap.h"
+#include "peer_manager_types.h"
+#include "fds.h"
+
+
+/**
+ * @defgroup peer_data_storage Peer Data Storage
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. This module provides a Peer Manager-specific API
+ *        to the persistent storage.
+ */
+
+#define PDS_PREPARE_TOKEN_INVALID 0
+#define PDS_STORE_TOKEN_INVALID   0
+
+
+typedef enum
+{
+    peer_id_to_instance_id  = 16384,
+    instance_id_to_peer_id  = -peer_id_to_instance_id,
+    peer_data_id_to_type_id = 32768,
+    type_id_to_peer_data_id = -peer_data_id_to_type_id,
+} pds_convert_t;
+
+
+/**@brief The types of events that can come from the peer_data_storage module.
+ */
+typedef enum
+{
+    PDS_EVT_STORED,                 /**< The specified data has been successfully stored. */
+    PDS_EVT_CLEARED,                /**< The specified data has been successfully cleared. */
+    PDS_EVT_PEER_ID_CLEAR,          /**< The peer id has been successfully cleared. */
+    PDS_EVT_ERROR_STORE,            /**< The specified data could not be stored. */
+    PDS_EVT_ERROR_CLEAR,            /**< The specified data could not be cleared. */
+    PDS_EVT_ERROR_PEER_ID_CLEAR,    /**< The peer id has been successfully cleared. */
+    PDS_EVT_COMPRESSED,             /**< A compress procedure has finished successfully. */
+} pds_evt_id_t;
+
+
+/**@brief Events that can come from the peer_data_storage module.
+ */
+typedef struct
+{
+    pds_evt_id_t      evt_id;       /**< The type of event. */
+    pm_peer_id_t      peer_id;      /**< The peer the event pertains to. */
+    pm_peer_data_id_t data_id;      /**< The data the event pertains to. */
+    pm_store_token_t  store_token;
+} pds_evt_t;
+
+
+/**@brief Event handler for events from the peer_data_storage module.
+ *
+ * @param[in]  event    The event that has happened.
+ * @param[in]  peer_id  The id of the peer the event pertains to.
+ * @param[in]  flags    The data the event pertains to.
+ */
+typedef void (*pds_evt_handler_t)(pds_evt_t const * p_event);
+
+
+/**@brief Function for registering for events from the peer database.
+ *
+ * @note This function will initialize the module if it is not already initialized.
+ *
+ * @param[in]  evt_handler  Event handler to register.
+ *
+ * @retval NRF_SUCCESS              Registration successful.
+ * @retval NRF_ERROR_NO_MEM         No more event handlers can be registered.
+ * @retval NRF_ERROR_NULL           evt_handler was NULL.
+ * @retval NRF_ERROR_INVALID_PARAM  Unexpected return code from @ref pm_buffer_init.
+ * @retval NRF_ERROR_INVALID_STATE  FDS has not been initalized.
+ */
+ret_code_t pds_register(pds_evt_handler_t evt_handler);
+
+
+#if 0
+/**@brief Function for initializing Peer Data storage and registering a
+ * callback for its events.
+ *
+ * @param[in] evt_handler  Event handler to register.
+ *
+ * @retval NRF_SUCCESS              Registration successful.
+ * @retval NRF_ERROR_NO_MEM         No more event handlers can be registered.
+ * @retval NRF_ERROR_NULL           evt_handler was NULL.
+ * @retval NRF_ERROR_INVALID_STATE  FDS has not completed initialization.
+ */
+ret_code_t pds_init(pds_evt_handler_t evt_handler);
+#endif
+
+/**@brief Function for retrieving a direct pointer to peer data in persistent storage.
+ *
+ * @param[in]  peer_id      The id of the peer whose data to read.
+ * @param[in]  data_id      Which data to get.
+ * @param[out] p_data       The peer data pointer.
+ * @param[out] p_token      Token that can be used to lock data in flash and check data validity.
+ *
+ * @retval NRF_SUCCESS              The pointer was successfully retrieved.
+ * @retval NRF_ERROR_INVALID_PARAM  Invalid data_id.
+ * @retval NRF_ERROR_NULL           p_data was NULL.
+ * @retval NRF_ERROR_NOT_FOUND      The requested data was not found in persistent storage.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pds_peer_data_read_ptr_get(pm_peer_id_t            peer_id,
+                                      pm_peer_data_id_t       data_id,
+                                      pm_peer_data_flash_t  * p_data,
+                                      pm_store_token_t      * p_token);
+
+/**@brief Function to lock the flash data (to defer compression from invalidating data)
+ *
+ * @param[in]   store_token     The token representing the item to lock
+ *
+ */
+ret_code_t pds_peer_data_lock(pm_store_token_t store_token);
+
+
+/**@brief Function to verify flash data integrity
+ *
+ * @param[in]   store_token     The token representing the item to lock
+ *
+ * @retval NRF_SUCCESS              The data integrity is valid.
+ * @retval NRF_ERROR_NULL           The token is invalid.
+ * @retval NRF_ERROR_INVALID_DATA   The data integrity is not valid.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t  pds_peer_data_verify(pm_store_token_t store_token);
+
+
+/**@brief Function for retrieving peer data from persistent storage by making a copy
+ *
+ * @param[in]       peer_id     The id of the peer whose data to read.
+ * @param[in]       data_id     Which piece of data to read.
+ * @param[out]      p_data      Pointer to the peer data.
+ * @param[in,out]   p_len_words Length available to copy to (in words).
+ *                              If set to NULL, then no copy will be made and the
+ *                              length will be reflected in p_len_words after the call returns.
+ *
+ * @retval NRF_SUCCESS              The read was successful.
+ * @retval NRF_ERROR_INVALID_PARAM  Invalid data_id.
+ * @retval NRF_ERROR_NULL           data contained a NULL pointer.
+ * @retval NRF_ERROR_NOT_FOUND      The requested data was not found in persistent storage.
+ * @retval NRF_ERROR_NO_MEM         The length of stored data too large to copy out
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pds_peer_data_read(pm_peer_id_t          peer_id,
+                              pm_peer_data_id_t     data_id,
+                              pm_peer_data_t      * p_data,
+                              fds_length_t        * p_len_words);
+
+
+/**@brief Function for preparing persistent storage for a write.
+ *
+ * @details If this call succeeds, space is reserved in persistent storage, so the write will fit.
+ *
+ * @note If space has already been prepared for this peer_id/data_id pair, no new space will be
+ *       reserved, unless the previous reservation had too small size.
+ *
+ * @param[in]  p_peer_data      Data to prepare for. The data needs not be ready, but length and type
+ *                              values must.
+ * @param[out] p_prepare_token  A token identifying the prepared memory area.
+ *
+ * @retval NRF_SUCCESS               The call was successful.
+ * @retval NRF_ERROR_INVALID_PARAM   Invalid data ID.
+ * @retval NRF_ERROR_INVALID_LENGTH  Data length above the maximum allowed.
+ * @retval NRF_ERROR_NO_MEM          No space available in persistent storage.
+ * @retval NRF_ERROR_INVALID_STATE   Module is not initialized.
+ */
+ret_code_t pds_peer_data_write_prepare(pm_peer_data_const_t const * p_peer_data,
+                                       pm_prepare_token_t         * p_prepare_token);
+
+
+/**@brief Function for undoing a previous call to @ref pds_peer_data_write_prepare.
+ *
+ * @param[in]  prepare_token  A token identifying the prepared memory area to cancel.
+ *
+ * @retval NRF_SUCCESS               The call was successful.
+ * @retval NRF_ERROR_NOT_FOUND       Invalid peer ID and/or prepare token.
+ * @retval NRF_ERROR_INVALID_STATE   Module is not initialized.
+ */
+ret_code_t pds_peer_data_write_prepare_cancel(pm_prepare_token_t prepare_token);
+
+
+/**@brief Function for writing prepared (reserved) peer data to persistent storage.
+ *
+ * @details Writing happens asynchronously. Expect a @ref PDS_EVT_STORED or @ref PDS_EVT_ERROR_STORE
+ *          event.
+ *
+ * @param[in]  peer_id        The id of the peer the data pertains to.
+ * @param[in]  p_peer_data    The peer data.
+ * @param[in]  prepare_token  A token identifying the prepared memory area to write into. If
+ *                            the prepare token is invalid, e.g. PDS_PREPARE_TOKEN_INVALID, the
+ *                            prepare/write sequence will happen atomically.
+ * @param[out] p_store_token  A token identifying this particular store operation. The token can be
+ *                            used to identify events pertaining to this operation.
+ *
+ * @retval NRF_SUCCESS               The write was initiated successfully.
+ * @retval NRF_ERROR_INVALID_PARAM   Invalid data ID or store_flags.
+ * @retval NRF_ERROR_INVALID_LENGTH  Length of data longer than in prepare call.
+ * @retval NRF_ERROR_NULL            data contained a NULL pointer.
+ * @retval NRF_ERROR_NO_MEM          No space available in persistent storage. This can only happen
+ *                                   if p_prepare_token is NULL.
+ * @retval NRF_ERROR_BUSY            FDS or underlying modules are busy and can't take any
+ *                                   more requests
+ * @retval NRF_ERROR_INVALID_STATE   Module is not initialized.
+ */
+ret_code_t pds_peer_data_write_prepared(pm_peer_id_t                    peer_id,
+                                        pm_peer_data_const_t    const * p_peer_data,
+                                        pm_prepare_token_t              prepare_token,
+                                        pm_store_token_t              * p_store_token);
+
+
+/**@brief Function for writing peer data to persistent storage.
+ *
+ * @details Writing happens asynchronously. Expect a @ref PDS_EVT_STORED or @ref PDS_EVT_ERROR_STORE
+ *          event.
+ *
+ * @param[in]  peer_id        The id of the peer the data pertains to.
+ * @param[in]  p_peer_data    The peer data.
+ * @param[out] p_store_token  A token identifying this particular store operation. The token can be
+ *                            used to identify events pertaining to this operation.
+ *
+ * @retval NRF_SUCCESS               The write was initiated successfully.
+ * @retval NRF_ERROR_INVALID_PARAM   Invalid data ID or store_flags.
+ * @retval NRF_ERROR_NULL            Data contained a NULL pointer.
+ * @retval NRF_ERROR_NO_MEM          No space available in persistent storage. This can only happen
+ *                                   if p_prepare_token is NULL.
+ * @retval NRF_ERROR_BUSY            FDS or underlying modules are busy and can't take any
+ *                                   more requests
+ * @retval NRF_ERROR_INVALID_STATE   Module is not initialized.
+ */
+ret_code_t pds_peer_data_write(pm_peer_id_t                 peer_id,
+                               pm_peer_data_const_t const * p_peer_data,
+                               pm_store_token_t           * p_store_token);
+
+
+/**@brief Function for updating currently stored peer data to a new version
+ *
+ * @details Updating happens asynchronously.
+ *          Expect a @ref PDS_EVT_STORED or @ref PDS_EVT_ERROR_STORE for the store token
+ *          and a @ref PDS_EVT_ERROR_CLEAR or @ref PDS_EVT_ERROR_CLEAR for the old token
+ *
+ * @param[in]   peer_id             The peer which the data is associated to.
+ * @param[in]   peer_data           New data.
+ * @param[in]   old_token           Store token for the old data.
+ * @param[out]  p_store_token       Store token for the new data.
+ *
+ * @retval NRF_SUCESS               The update was initiated successfully
+ * @retval NRF_ERROR_NOT_FOUND      The old store token was invalid.
+ * @retval NRF_ERROR_NULL           Data contained a NULL pointer.
+ * @retval NRF_ERROR_NO_MEM         No space available in persistent storage.
+ * @retval NRF_ERROR_BUSY           FDS or underlying modules are busy and can't take any
+ *                                  more requests
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pds_peer_data_update(pm_peer_id_t                 peer_id,
+                                pm_peer_data_const_t const * peer_data,
+                                pm_store_token_t             old_token,
+                                pm_store_token_t           * p_store_token);
+
+
+/**@brief Function for clearing peer data from persistent storage.
+ *
+ * @details Clearing happens asynchronously. Expect a @ref PDS_EVT_CLEARED or @ref PDS_EVT_ERROR_CLEAR
+ *          event.
+ *
+ * @param[in]  peer_id  The id of the peer the data pertains to.
+ * @param[in]  data_id  Which data to clear.
+ *
+ * @retval NRF_SUCCESS              The clear was initiated successfully.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID or was invalid.
+ * @retval NRF_ERROR_NOT_FOUND      Nothing to clear for this peer ID.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pds_peer_data_clear(pm_peer_id_t peer_id, pm_peer_data_id_t data_id);
+
+
+/**@brief Function for claiming an unused peer ID.
+ *
+ * @return  The first unused peer ID.
+ * @retval  PM_PEER_ID_INVALID  If no peer ID is available or module is not initialized.
+ */
+pm_peer_id_t pds_peer_id_allocate(void);
+
+
+/**@brief Function for freeing a peer ID and clearing all data associated with it in persistent
+ *        storage.
+ *
+ * @param[in]  peer_id  Peer ID to free.
+ *
+ * @retval NRF_SUCCESS          The clear was initiated successfully
+ * @retval NRF_ERROR_BUSY       Another peer_id clear was already requested or fds queue full
+ */
+ret_code_t pds_peer_id_free(pm_peer_id_t peer_id);
+
+
+/**@brief Function for finding out whether a peer ID is in use.
+ *
+ * @param[in]  peer_id  The peer ID to inquire about.
+ *
+ * @retval  true   peer_id is in use.
+ * @retval  false  peer_id is free, or the module is not initialized.
+ */
+bool pds_peer_id_is_allocated(pm_peer_id_t peer_id);
+
+
+/**@brief Function for getting the next peer ID in the sequence of all used peer IDs. Can be
+ *        used to loop through all used peer IDs.
+ *
+ * @note @ref PM_PEER_ID_INVALID is considered to be before the first and after the last ordinary
+ *       peer ID.
+ *
+ * @param[in]  prev_peer_id  The previous peer ID.
+ *
+ * @return  The next peer ID.
+ * @return  The first ordinary peer ID  if prev_peer_id was @ref PM_PEER_ID_INVALID.
+ * @retval  PM_PEER_ID_INVALID          if prev_peer_id was the last ordinary peer ID or the module
+ *                                      is not initialized.
+ */
+pm_peer_id_t pds_next_peer_id_get(pm_peer_id_t prev_peer_id);
+
+
+/**@brief Function for querying the number of valid peer IDs available. I.E the number of peers
+ *        in persistent storage.
+ *
+ * @return  The number of valid peer IDs, or 0 if module is not initialized.
+ */
+uint32_t pds_n_peers(void);
+
+
+/** @} */
+
+#endif /* PEER_DATA_STORAGE_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,768 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "peer_database.h"
+
+#include <string.h>
+#include "peer_manager_types.h"
+#include "peer_data_storage.h"
+#include "pm_buffer.h"
+
+
+#define MAX_REGISTRANTS    6                         /**< The number of user that can register with the module. */
+
+#define MODULE_INITIALIZED (m_pdb.n_registrants > 0) /**< Expression which is true when the module is initialized. */
+
+#define N_WRITE_BUFFERS        8                     /**< The number of write buffers available. */
+#define N_WRITE_BUFFER_RECORDS (N_WRITE_BUFFERS)     /**< The number of write buffer records. */
+
+/**@brief Macro for verifying that the module is initialized. It will cause the function to return
+ *        @ref NRF_ERROR_INVALID_STATE if not.
+ */
+#define VERIFY_MODULE_INITIALIZED()     \
+do                                      \
+{                                       \
+    if (!MODULE_INITIALIZED)            \
+    {                                   \
+        return NRF_ERROR_INVALID_STATE; \
+    }                                   \
+} while(0)
+
+
+/**@brief Macro for verifying that the module is initialized. It will cause the function to return
+ *        if not.
+ */
+#define VERIFY_MODULE_INITIALIZED_VOID()\
+do                                      \
+{                                       \
+    if (!MODULE_INITIALIZED)            \
+    {                                   \
+        return;                         \
+    }                                   \
+} while(0)
+
+
+/**@brief Macro for verifying that the module is initialized. It will cause the function to return
+ *        if not.
+ *
+ * @param[in] param  The variable to check if is NULL.
+ */
+#define VERIFY_PARAM_NOT_NULL(param)    \
+do                                      \
+{                                       \
+    if (param == NULL)                  \
+    {                                   \
+        return NRF_ERROR_NULL;          \
+    }                                   \
+} while(0)
+
+
+typedef struct
+{
+    pm_peer_id_t        peer_id;
+    pm_peer_data_id_t   data_id;
+    uint8_t             buffer_block_id;
+    uint8_t             store_busy       : 1;
+    uint8_t             store_flash_full : 1;
+    uint8_t             store_requested  : 1;
+    uint32_t            n_bufs;
+    pm_prepare_token_t  prepare_token;
+    pm_store_token_t    store_token;
+} pdb_buffer_record_t;
+
+typedef struct
+{
+    pdb_evt_handler_t   evt_handlers[MAX_REGISTRANTS];
+    uint8_t             n_registrants;
+    pm_buffer_t         write_buffer;
+    pdb_buffer_record_t write_buffer_records[N_WRITE_BUFFER_RECORDS];
+    uint32_t            n_writes;
+} pdb_t;
+
+static pdb_t m_pdb = {.n_registrants = 0};
+
+
+/**@brief Function for invalidating a record of a write buffer allocation.
+ *
+ * @param[in]  p_record  The record to invalidate.
+ */
+static void write_buffer_record_invalidate(pdb_buffer_record_t * p_record)
+{
+    p_record->peer_id          = PM_PEER_ID_INVALID;
+    p_record->data_id          = PM_PEER_DATA_ID_INVALID;
+    p_record->buffer_block_id  = BUFFER_INVALID_ID;
+    p_record->store_busy       = false;
+    p_record->store_flash_full = false;
+    p_record->store_requested  = false;
+    p_record->n_bufs           = 0;
+    p_record->prepare_token    = PDS_PREPARE_TOKEN_INVALID;
+    p_record->store_token      = PDS_STORE_TOKEN_INVALID;
+}
+
+
+/**@brief Function for finding a record of a write buffer allocation.
+ *
+ * @param[in]  peer_id  The peer ID in the record.
+ * @param[in]  data_id  The data ID in the record.
+ *
+ * @return  A pointer to the matching record, or NULL if none was found.
+ */
+static pdb_buffer_record_t * write_buffer_record_find(pm_peer_id_t      peer_id,
+                                                      pm_peer_data_id_t data_id)
+{
+    for (int i = 0; i < N_WRITE_BUFFER_RECORDS; i++)
+    {
+        if   ((m_pdb.write_buffer_records[i].peer_id == peer_id)
+           && (m_pdb.write_buffer_records[i].data_id == data_id))
+        {
+            return &m_pdb.write_buffer_records[i];
+        }
+    }
+    return NULL;
+}
+
+
+/**@brief Function for finding an available record for write buffer allocation.
+ *
+ * @return  A pointer to the available record, or NULL if none was found.
+ */
+static pdb_buffer_record_t * write_buffer_record_find_unused(void)
+{
+    return write_buffer_record_find(PM_PEER_ID_INVALID, PM_PEER_DATA_ID_INVALID);
+}
+
+
+/**@brief Function for gracefully deactivating a write buffer record.
+ *
+ * @details This function will first release any buffers, then invalidate the record.
+ *
+ * @param[inout] p_write_buffer_record  The record to release.
+ *
+ * @return  A pointer to the matching record, or NULL if none was found.
+ */
+static void write_buffer_record_release(pdb_buffer_record_t * p_write_buffer_record)
+{
+    for (int i = 0; i < p_write_buffer_record->n_bufs; i++)
+    {
+        pm_buffer_release(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id + i);
+    }
+
+    write_buffer_record_invalidate(p_write_buffer_record);
+}
+
+
+static void write_buffer_record_get(pdb_buffer_record_t ** pp_write_buffer_record, pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
+{
+    if (pp_write_buffer_record == NULL)
+    {
+        return;
+    }
+    *pp_write_buffer_record = write_buffer_record_find_unused();
+    if (*pp_write_buffer_record == NULL)
+    {
+        // This also means the buffer is full.
+        return;
+    }
+    (*pp_write_buffer_record)->peer_id = peer_id;
+    (*pp_write_buffer_record)->data_id = data_id;
+}
+
+
+/**@brief Function for dispatching outbound events to all registered event handlers.
+ *
+ * @param[in]  p_event  The event to dispatch.
+ */
+static void pdb_evt_send(pdb_evt_t * p_event)
+{
+    for (int i = 0; i < m_pdb.n_registrants; i++)
+    {
+        m_pdb.evt_handlers[i](p_event);
+    }
+}
+
+
+/**@brief Function for resetting the internal state of the Peer Database module.
+ *
+ * @param[out] p_event  The event to dispatch.
+ */
+static void internal_state_reset(pdb_t * pdb)
+{
+    memset(pdb, 0, sizeof(pdb_t));
+    for (int i = 0; i < N_WRITE_BUFFER_RECORDS; i++)
+    {
+        write_buffer_record_invalidate(&pdb->write_buffer_records[i]);
+    }
+}
+
+
+/**@brief Function for handling events from the Peer Data Storage module.
+ *
+ * @param[in]  p_event  The event to handle.
+ */
+static void pds_evt_handler(pds_evt_t const * p_event)
+{
+    ret_code_t            err_code;
+    pdb_buffer_record_t * p_write_buffer_record;
+    bool                  retry_flash_full = false;
+    pdb_evt_t             event =
+    {
+        .peer_id = p_event->peer_id,
+        .data_id = p_event->data_id,
+    };
+
+    p_write_buffer_record = write_buffer_record_find(p_event->peer_id, p_event->data_id);
+
+    switch (p_event->evt_id)
+    {
+        case PDS_EVT_STORED:
+            if (   (p_write_buffer_record != NULL)
+                //&& (p_write_buffer_record->store_token == p_event->store_token)
+                && (p_write_buffer_record->store_requested))
+            {
+                write_buffer_record_release(p_write_buffer_record);
+                event.evt_id = PDB_EVT_WRITE_BUF_STORED;
+                pdb_evt_send(&event);
+            }
+            else
+            {
+                event.evt_id = PDB_EVT_RAW_STORED;
+                pdb_evt_send(&event);
+            }
+            break;
+        case PDS_EVT_ERROR_STORE:
+            if (   (p_write_buffer_record != NULL)
+                && (p_write_buffer_record->store_token == p_event->store_token)
+                && (p_write_buffer_record->store_requested))
+            {
+                // Retry if internal buffer.
+                m_pdb.n_writes++;
+                p_write_buffer_record->store_requested = false;
+                p_write_buffer_record->store_busy      = true;
+            }
+            else
+            {
+                event.evt_id = PDB_EVT_RAW_STORE_FAILED;
+                pdb_evt_send(&event);
+            }
+            break;
+        case PDS_EVT_CLEARED:
+            event.evt_id = PDB_EVT_CLEARED;
+            pdb_evt_send(&event);
+            break;
+        case PDS_EVT_ERROR_CLEAR:
+            event.evt_id = PDB_EVT_CLEAR_FAILED;
+            pdb_evt_send(&event);
+            break;
+        case PDS_EVT_COMPRESSED:
+            retry_flash_full = true;
+            event.evt_id = PDB_EVT_COMPRESSED;
+            pdb_evt_send(&event);
+            break;
+        default:
+            break;
+    }
+
+    if (m_pdb.n_writes > 0)
+    {
+        for (int i = 0; i < N_WRITE_BUFFER_RECORDS; i++)
+        {
+            if  ((m_pdb.write_buffer_records[i].store_busy)
+              || (m_pdb.write_buffer_records[i].store_flash_full && retry_flash_full))
+            {
+                err_code = pdb_write_buf_store(m_pdb.write_buffer_records[i].peer_id,
+                                               m_pdb.write_buffer_records[i].data_id);
+                if (err_code != NRF_SUCCESS)
+                {
+                    event.peer_id = m_pdb.write_buffer_records[i].peer_id;
+                    event.data_id = m_pdb.write_buffer_records[i].data_id;
+                    if (err_code == NRF_ERROR_NO_MEM)
+                    {
+                        event.evt_id = PDB_EVT_ERROR_NO_MEM;
+                    }
+                    else
+                    {
+                        event.evt_id = PDB_EVT_ERROR_UNEXPECTED;
+                    }
+
+                    pdb_evt_send(&event);
+                    break;
+                }
+            }
+        }
+    }
+}
+
+
+ret_code_t pdb_register(pdb_evt_handler_t evt_handler)
+{
+    if (m_pdb.n_registrants >= MAX_REGISTRANTS)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    VERIFY_PARAM_NOT_NULL(evt_handler);
+
+    if (!MODULE_INITIALIZED)
+    {
+        ret_code_t err_code;
+
+        internal_state_reset(&m_pdb);
+        err_code = pds_register(pds_evt_handler);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+        PM_BUFFER_INIT(&m_pdb.write_buffer, N_WRITE_BUFFERS, PDB_WRITE_BUF_SIZE, err_code);
+        if (err_code != NRF_SUCCESS)
+        {
+            return err_code;
+        }
+    }
+
+    m_pdb.evt_handlers[m_pdb.n_registrants] = evt_handler;
+    m_pdb.n_registrants += 1;
+
+    return NRF_SUCCESS;
+}
+
+
+pm_peer_id_t pdb_peer_allocate(void)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return PM_PEER_ID_INVALID;
+    }
+
+    return pds_peer_id_allocate();
+}
+
+
+ret_code_t pdb_peer_free(pm_peer_id_t peer_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    return pds_peer_id_free(peer_id);
+}
+
+
+ret_code_t pdb_read_buf_get(pm_peer_id_t           peer_id,
+                            pm_peer_data_id_t      data_id,
+                            pm_peer_data_flash_t * p_peer_data,
+                            pm_store_token_t     * p_token)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    return pds_peer_data_read_ptr_get(peer_id, data_id, p_peer_data, p_token);
+}
+
+
+static void peer_data_point_to_buffer(pm_peer_data_t * p_peer_data, pm_peer_data_id_t data_id, uint8_t * p_buffer_memory, uint16_t n_bufs)
+{
+    uint16_t n_bytes = n_bufs * PDB_WRITE_BUF_SIZE;
+    p_peer_data->data_type    = data_id;
+
+    switch(p_peer_data->data_type)
+    {
+        case PM_PEER_DATA_ID_BONDING:
+            p_peer_data->data.p_bonding_data = (pm_peer_data_bonding_t *)p_buffer_memory;
+            p_peer_data->length_words = PM_BONDING_DATA_N_WORDS();
+            break;
+        case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
+            p_peer_data->data.p_service_changed_pending = (bool *)p_buffer_memory;
+            p_peer_data->length_words = PM_SC_STATE_N_WORDS();
+            break;
+        case PM_PEER_DATA_ID_GATT_LOCAL:
+            p_peer_data->data.p_local_gatt_db = (pm_peer_data_local_gatt_db_t *)p_buffer_memory;
+            p_peer_data->length_words = PM_LOCAL_DB_N_WORDS(n_bytes);
+            break;
+        case PM_PEER_DATA_ID_GATT_REMOTE:
+            p_peer_data->data.p_remote_gatt_db = (pm_peer_data_remote_gatt_db_t *)p_buffer_memory;
+            p_peer_data->length_words = PM_REMOTE_DB_N_WORDS(n_bytes / sizeof(ble_gatt_db_srv_t));
+            break;
+        case PM_PEER_DATA_ID_APPLICATION:
+            p_peer_data->data.p_application_data = p_buffer_memory;
+            p_peer_data->length_words = PM_N_WORDS(n_bytes);
+            break;
+        default:
+            p_peer_data->length_words = 0;
+            break;
+    }
+}
+
+
+static void peer_data_const_point_to_buffer(pm_peer_data_const_t * p_peer_data, pm_peer_data_id_t data_id,  uint8_t * p_buffer_memory, uint32_t n_bufs)
+{
+    peer_data_point_to_buffer((pm_peer_data_t*)p_peer_data, data_id, p_buffer_memory, n_bufs);
+}
+
+
+ret_code_t pdb_write_buf_get(pm_peer_id_t       peer_id,
+                             pm_peer_data_id_t  data_id,
+                             uint32_t           n_bufs,
+                             pm_peer_data_t   * p_peer_data)
+{
+    VERIFY_MODULE_INITIALIZED();
+    VERIFY_PARAM_NOT_NULL(p_peer_data);
+    if (   !PM_PEER_DATA_ID_IS_VALID(data_id)
+        || (n_bufs == 0)
+        || (n_bufs > N_WRITE_BUFFERS)
+        || !pds_peer_id_is_allocated(peer_id))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    pdb_buffer_record_t * write_buffer_record;
+    uint8_t             * p_buffer_memory;
+
+    write_buffer_record = write_buffer_record_find(peer_id, data_id);
+
+    if ((write_buffer_record != NULL) && (write_buffer_record->n_bufs < n_bufs))
+    {
+        // @TODO: Copy?
+        // Existing buffer is too small.
+        for (uint8_t i = 0; i < write_buffer_record->n_bufs; i++)
+        {
+            pm_buffer_release(&m_pdb.write_buffer, write_buffer_record->buffer_block_id + i);
+        }
+        write_buffer_record_invalidate(write_buffer_record);
+        write_buffer_record = NULL;
+    }
+    else if ((write_buffer_record != NULL) && write_buffer_record->n_bufs > n_bufs)
+    {
+        // Release excess blocks.
+        for (uint8_t i = n_bufs; i < write_buffer_record->n_bufs; i++)
+        {
+            pm_buffer_release(&m_pdb.write_buffer, write_buffer_record->buffer_block_id + i);
+        }
+    }
+
+    if (write_buffer_record == NULL)
+    {
+        write_buffer_record_get(&write_buffer_record, peer_id, data_id);
+        if (write_buffer_record == NULL)
+        {
+            return NRF_ERROR_BUSY;
+        }
+    }
+
+    if (write_buffer_record->buffer_block_id == BUFFER_INVALID_ID)
+    {
+        write_buffer_record->buffer_block_id = pm_buffer_block_acquire(&m_pdb.write_buffer, n_bufs);
+
+        if (write_buffer_record->buffer_block_id == BUFFER_INVALID_ID)
+        {
+            write_buffer_record_invalidate(write_buffer_record);
+            return NRF_ERROR_BUSY;
+        }
+    }
+
+    write_buffer_record->n_bufs = n_bufs;
+
+    p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, write_buffer_record->buffer_block_id);
+
+    if (p_buffer_memory == NULL)
+    {
+        return NRF_ERROR_INTERNAL;
+    }
+
+    peer_data_point_to_buffer(p_peer_data, data_id, p_buffer_memory, n_bufs);
+    switch(data_id)
+    {
+        case PM_PEER_DATA_ID_BONDING:
+            /* No action needed. */
+            break;
+        case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
+            /* No action needed. */
+            break;
+        case PM_PEER_DATA_ID_GATT_LOCAL:
+        {
+            uint32_t size_offset = sizeof(pm_peer_data_local_gatt_db_t);
+            p_peer_data->data.p_local_gatt_db->p_data = &p_buffer_memory[size_offset];
+            p_peer_data->data.p_local_gatt_db->len    = (PDB_WRITE_BUF_SIZE*n_bufs)-size_offset;
+        }
+            break;
+        case PM_PEER_DATA_ID_GATT_REMOTE:
+        {
+            uint32_t size_offset = sizeof(pm_peer_data_remote_gatt_db_t);
+            p_peer_data->data.p_remote_gatt_db->p_data = (ble_gatt_db_srv_t*)&(p_buffer_memory[size_offset]);
+            p_peer_data->data.p_remote_gatt_db->service_count
+                            = ((PDB_WRITE_BUF_SIZE*n_bufs)-size_offset)/sizeof(ble_gatt_db_srv_t);
+        }
+            break;
+        case PM_PEER_DATA_ID_APPLICATION:
+        {
+            p_peer_data->data.p_application_data = p_buffer_memory;
+        }
+            break;
+        default:
+            // Invalid data_id. This should have been picked up earlier.
+            return NRF_ERROR_INTERNAL;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t pdb_write_buf_release(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    ret_code_t            err_code = NRF_SUCCESS;
+    pdb_buffer_record_t * p_write_buffer_record;
+    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);
+
+    if (p_write_buffer_record == NULL)
+    {
+        return NRF_ERROR_NOT_FOUND;
+    }
+
+    if (p_write_buffer_record->prepare_token != PDS_PREPARE_TOKEN_INVALID)
+    {
+        err_code = pds_peer_data_write_prepare_cancel(p_write_buffer_record->prepare_token);
+        if (err_code != NRF_SUCCESS)
+        {
+            err_code = NRF_ERROR_INTERNAL;
+        }
+    }
+
+    write_buffer_record_release(p_write_buffer_record);
+
+    return err_code;
+}
+
+
+ret_code_t pdb_write_buf_store_prepare(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    ret_code_t            err_code = NRF_SUCCESS;
+    pdb_buffer_record_t * p_write_buffer_record;
+    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);
+
+    if (p_write_buffer_record == NULL)
+    {
+        return NRF_ERROR_NOT_FOUND;
+    }
+
+    if (p_write_buffer_record->prepare_token == PDS_PREPARE_TOKEN_INVALID)
+    {
+        uint8_t * p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id);
+        pm_peer_data_const_t peer_data = {.data_type = data_id};
+
+        if (p_buffer_memory == NULL)
+        {
+            return NRF_ERROR_INTERNAL;
+        }
+
+        peer_data_const_point_to_buffer(&peer_data, data_id, p_buffer_memory, p_write_buffer_record->n_bufs);
+
+        err_code = pds_peer_data_write_prepare(&peer_data, &p_write_buffer_record->prepare_token);
+        if (err_code == NRF_ERROR_INVALID_LENGTH)
+        {
+            return NRF_ERROR_INTERNAL;
+        }
+    }
+
+    return err_code;
+}
+
+
+static ret_code_t write_or_update(pm_peer_id_t           peer_id,
+                                  pm_peer_data_id_t      data_id,
+                                  pm_peer_data_const_t * p_peer_data,
+                                  pm_store_token_t     * p_store_token,
+                                  pm_prepare_token_t     prepare_token)
+{
+    pm_peer_data_flash_t old_peer_data;
+    pm_store_token_t     old_store_token;
+    ret_code_t err_code = pds_peer_data_read_ptr_get(peer_id, data_id, &old_peer_data, &old_store_token);
+
+    if (err_code == NRF_SUCCESS)
+    {
+        pds_peer_data_write_prepare_cancel(prepare_token);
+        err_code = pds_peer_data_update(peer_id, p_peer_data, old_store_token, p_store_token);
+    }
+    else if (err_code == NRF_ERROR_NOT_FOUND)
+    {
+        if (prepare_token == PDS_PREPARE_TOKEN_INVALID)
+        {
+            err_code = pds_peer_data_write(peer_id, p_peer_data, p_store_token);
+        }
+        else
+        {
+            err_code = pds_peer_data_write_prepared(peer_id, p_peer_data, prepare_token, p_store_token);
+        }
+    }
+    return err_code;
+}
+
+
+ret_code_t pdb_write_buf_store(pm_peer_id_t      peer_id,
+                               pm_peer_data_id_t data_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    ret_code_t            err_code = NRF_SUCCESS;
+    pdb_buffer_record_t * p_write_buffer_record;
+    uint8_t             * p_buffer_memory;
+    pm_peer_data_const_t  peer_data = {.data_type = data_id};
+
+
+    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);
+
+    if (p_write_buffer_record == NULL)
+    {
+        return NRF_ERROR_NOT_FOUND;
+    }
+
+    if (p_write_buffer_record->store_requested)
+    {
+        return NRF_SUCCESS;
+    }
+
+    p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id);
+
+    if (p_buffer_memory == NULL)
+    {
+        return NRF_ERROR_INTERNAL;
+    }
+
+    peer_data_const_point_to_buffer(&peer_data, data_id, p_buffer_memory, p_write_buffer_record->n_bufs);
+
+    switch (data_id)
+    {
+        case PM_PEER_DATA_ID_BONDING:
+            peer_data.length_words = PM_BONDING_DATA_N_WORDS();
+            break;
+        case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
+            peer_data.length_words = PM_SC_STATE_N_WORDS();
+            break;
+        case PM_PEER_DATA_ID_GATT_LOCAL:
+            peer_data.length_words = PM_LOCAL_DB_N_WORDS(peer_data.data.p_local_gatt_db->len);
+            break;
+        case PM_PEER_DATA_ID_GATT_REMOTE:
+            peer_data.length_words = PM_REMOTE_DB_N_WORDS(peer_data.data.p_remote_gatt_db->service_count);
+            break;
+        case PM_PEER_DATA_ID_APPLICATION:
+            peer_data.length_words = PM_N_WORDS(p_write_buffer_record->n_bufs * PDB_WRITE_BUF_SIZE);
+            break;
+        default:
+            return NRF_ERROR_INVALID_PARAM;
+    }
+
+    err_code = write_or_update(peer_id, data_id, &peer_data, &p_write_buffer_record->store_token, p_write_buffer_record->prepare_token);
+
+    if (p_write_buffer_record->store_busy && p_write_buffer_record->store_flash_full)
+    {
+        m_pdb.n_writes--;
+    }
+
+    if (err_code == NRF_SUCCESS)
+    {
+        p_write_buffer_record->store_requested  = true;
+        p_write_buffer_record->store_busy       = false;
+        p_write_buffer_record->store_flash_full = false;
+    }
+    else
+    {
+        if (err_code == NRF_ERROR_BUSY)
+        {
+            m_pdb.n_writes++;
+            p_write_buffer_record->store_busy       = true;
+            p_write_buffer_record->store_flash_full = false;
+            err_code = NRF_SUCCESS;
+        }
+        else if (err_code == NRF_ERROR_NO_MEM)
+        {
+            m_pdb.n_writes++;
+            p_write_buffer_record->store_busy       = false;
+            p_write_buffer_record->store_flash_full = true;
+        }
+        else if ((err_code != NRF_ERROR_NO_MEM) && (err_code != NRF_ERROR_INVALID_PARAM))
+        {
+            err_code = NRF_ERROR_INTERNAL;
+        }
+    }
+
+    return err_code;
+}
+
+
+ret_code_t pdb_clear(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+
+    return pds_peer_data_clear(peer_id, data_id);
+}
+
+
+uint32_t pdb_n_peers(void)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return 0;
+    }
+
+    return pds_n_peers();
+}
+
+
+pm_peer_id_t pdb_next_peer_id_get(pm_peer_id_t prev_peer_id)
+{
+    if (!MODULE_INITIALIZED)
+    {
+        return PM_PEER_ID_INVALID;
+    }
+
+    return pds_next_peer_id_get(prev_peer_id);
+}
+
+
+ret_code_t pdb_raw_read(pm_peer_id_t      peer_id,
+                        pm_peer_data_id_t data_id,
+                        pm_peer_data_t  * p_peer_data)
+{
+    VERIFY_MODULE_INITIALIZED();
+    return pds_peer_data_read(peer_id, data_id, p_peer_data, &p_peer_data->length_words);
+}
+
+
+ret_code_t pdb_raw_store(pm_peer_id_t           peer_id,
+                         pm_peer_data_const_t * p_peer_data,
+                         pm_store_token_t     * p_store_token)
+{
+    VERIFY_MODULE_INITIALIZED();
+    
+    return write_or_update(peer_id, p_peer_data->data_type, p_peer_data, p_store_token, PDS_PREPARE_TOKEN_INVALID);
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_database.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef PEER_DATABASE_H__
+#define PEER_DATABASE_H__
+
+#include <stdint.h>
+#include "peer_manager_types.h"
+#include "sdk_errors.h"
+
+/**
+ * @defgroup peer_database Peer Database
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. A module for simple management of reading and
+ *        writing of peer data into persistent storage.
+ *
+ */
+
+#define PDB_WRITE_BUF_SIZE (sizeof(pm_peer_data_bonding_t))
+
+/**@brief Events that can come from the peer_database module.
+ */
+typedef enum
+{
+    PDB_EVT_WRITE_BUF_STORED,   /**< A pdb_write_buf_store operation has completed successfully. */
+    PDB_EVT_RAW_STORED,         /**< A pdb_raw_store operation has completed successfully. */
+    PDB_EVT_RAW_STORE_FAILED,   /**< A pdb_raw_store operation has failed. */
+    PDB_EVT_CLEARED,            /**< A pdb_clear operation has completed successfully. */
+    PDB_EVT_CLEAR_FAILED,       /**< A pdb_clear operation has failed. */
+    PDB_EVT_COMPRESSED,         /**< A compress procedure has completed. */
+    PDB_EVT_ERROR_NO_MEM,       /**< An operation is blocked because the flash is full. It will be reattempted automatically after the next compress procedure. */
+    PDB_EVT_ERROR_UNEXPECTED,   /**< An unexpected error occurred. This is a fatal error. */
+} pdb_evt_id_t;
+
+/**@brief Events that can come from the peer_database module.
+ */
+typedef struct
+{
+    pdb_evt_id_t      evt_id;  /**< The event that has happened. */
+    pm_peer_id_t      peer_id; /**< The id of the peer the event pertains to. */
+    pm_peer_data_id_t data_id; /**< The data the event pertains to. */
+    union
+    {
+        struct
+        {
+            pm_store_token_t store_token;  /**< A token identifying the store operation this event pertains to. */
+        } raw_stored_evt;
+        struct
+        {
+            pm_store_token_t store_token;  /**< A token identifying the store operation this event pertains to. */
+        } error_raw_store_evt;
+    } params;
+} pdb_evt_t;
+
+/**@brief Event handler for events from the peer_data_storage module.
+ *
+ * @param[in]  p_event   The event that has happened.
+ */
+typedef void (*pdb_evt_handler_t)(pdb_evt_t const * p_event);
+
+
+/**@brief Function for registering for events from the peer database.
+ *
+ * @note This function will initialize the module if it is not already initialized.
+ *
+ * @param[in]  evt_handler  Event handler to register.
+ *
+ * @retval NRF_SUCCESS              Registration successful.
+ * @retval NRF_ERROR_NO_MEM         No more event handlers can be registered.
+ * @retval NRF_ERROR_NULL           evt_handler was NULL.
+ * @retval NRF_ERROR_INVALID_PARAM  Unexpected return code from @ref pm_buffer_init.
+ * @retval NRF_ERROR_INVALID_STATE  FDS has not been initalized.
+ */
+ret_code_t pdb_register(pdb_evt_handler_t evt_handler);
+
+
+/**@brief Function for allocating persistent bond storage for a peer.
+ *
+ * @return  The ID of the newly allocated storage.
+ * @retval  PM_PEER_ID_INVALID  If no peer ID is available.
+ */
+pm_peer_id_t pdb_peer_allocate(void);
+
+
+/**@brief Function for freeing a peer's persistent bond storage.
+ *
+ * @note This function will call @ref pdb_write_buf_release on the data for this peer.
+ *
+ * @param[in] peer_id  ID to be freed.
+ *
+ * @retval NRF_SUCCESS              Peer ID was released and clear operation was initiated successfully.
+ * @retval NRF_ERROR_BUSY           Another peer_id clear was already requested or could not be started.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_peer_free(pm_peer_id_t peer_id);
+
+
+/**@brief Function for retrieving pointers to read-only peer data.
+ *
+ * @note  Reading this pointer is not safe in the strictest sense. If a safe read is required:
+ *          - Disable interrupts
+ *          - Call this function. If the return code is @ref NRF_SUCCESS, the following read is safe.
+ *          - Read memory.
+ *          - Enable interrupts.
+ * @note  This buffer does not need to be released. It is a pointer directly to flash.
+ *
+ * @param[in]  peer_id      ID of peer to retrieve data for.
+ * @param[in]  data_id      Which piece of data to get.
+ * @param[out] p_peer_data  Pointer to immutable peer data.
+ * @param[out] p_token      Token that can be used to lock data in flash and check data validity.
+ *
+ * @retval NRF_SUCCESS              Data retrieved successfully.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID or Peer ID was invalid or unallocated.
+ * @retval NRF_ERROR_NULL           p_peer_data was NULL.
+ * @retval NRF_ERROR_NOT_FOUND      This data was not found for this peer ID.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_read_buf_get(pm_peer_id_t           peer_id,
+                            pm_peer_data_id_t      data_id,
+                            pm_peer_data_flash_t * p_peer_data,
+                            pm_store_token_t     * p_token);
+
+
+/**@brief Function for retrieving pointers to a write buffer for peer data.
+ *
+ * @details This function will provide pointers to a buffer of the data. The data buffer will not be
+ *          written to persistent storage until @ref pdb_write_buf_store is called. The buffer is
+ *          released by calling either @ref pdb_write_buf_release, @ref pdb_write_buf_store, or
+ *          @ref pdb_peer_free.
+ *
+ *          When the data_id refers to a variable length data type, the available size is written
+ *          to the data, both the top-level, and any internal length fields.
+ *
+ * @note Calling this function on a peer_id/data_id pair that already has a buffer created will
+ *       give the same buffer, not create a new one. If n_bufs was increased since last time, the
+ *       buffer might be relocated to be able to provide additional room. In this case, the data
+ *       will be copied. If n_bufs was increased since last time, this function might return @ref
+ *       NRF_ERROR_BUSY. In that case, the buffer is automatically released.
+ *
+ * @param[in]  peer_id      ID of peer to get a write buffer for.
+ * @param[in]  data_id      Which piece of data to get.
+ * @param[in]  n_bufs       The number of contiguous buffers needed.
+ * @param[out] p_peer_data  Pointers to mutable peer data.
+ *
+ * @retval NRF_SUCCESS              Data retrieved successfully.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID or Peer ID was invalid or unallocated, or n_bufs was 0
+ *                                  or more than the total available buffers.
+ * @retval NRF_ERROR_NULL           p_peer_data was NULL.
+ * @retval NRF_ERROR_BUSY           Not enough buffer(s) available.
+ * @retval NRF_ERROR_INTERNAL       Unexpected internal error.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_write_buf_get(pm_peer_id_t      peer_id,
+                             pm_peer_data_id_t data_id,
+                             uint32_t          n_bufs,
+                             pm_peer_data_t  * p_peer_data);
+
+
+/**@brief Function for freeing a write buffer allocated with @ref pdb_write_buf_get.
+ *
+ * @note This function will not write peer data to persistent memory. Data in released buffer will
+ *       be lost.
+ *
+ * @note This function will undo any previous call to @ref pdb_write_buf_store_prepare for this
+ *       piece of data.
+ *
+ * @param[in]  peer_id  ID of peer to release buffer for.
+ * @param[in]  data_id  Which piece of data to release buffer for.
+ *
+ * @retval NRF_SUCCESS              Successfully released buffer.
+ * @retval NRF_ERROR_NOT_FOUND      No buffer was allocated for this peer ID/data ID pair.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ * @retval NRF_ERROR_INTERNAL       Unexpected internal error.
+ */
+ret_code_t pdb_write_buf_release(pm_peer_id_t peer_id, pm_peer_data_id_t data_id);
+
+
+/**@brief Function for reserving space in persistent storage for data in a buffer.
+ *
+ * @note This function only works for data which has a write buffer allocated. If the write buffer
+ *       is released, this prepare is undone.
+ *
+ * @note If space has already been reserved for this data, nothing is done.
+ *
+ * @param[in]  peer_id  The peer whose data to reserve space for.
+ * @param[in]  data_id  The type of data to reserve space for.
+ *
+ * @retval NRF_SUCCESS              Successfully reserved space in persistent storage.
+ * @retval NRF_ERROR_NO_MEM         Not enough room in persistent storage.
+ * @retval NRF_ERROR_BUSY           Could not process request at this time. Reattempt later.
+ * @retval NRF_ERROR_NOT_FOUND      No buffer has been allocated for this peer ID/data ID pair.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID or Peer ID was invalid or unallocated.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_write_buf_store_prepare(pm_peer_id_t peer_id, pm_peer_data_id_t data_id);
+
+
+/**@brief Function for writing data into persistent storage. Writing happens asynchronously.
+ *
+ * @note This will unlock the data after it has been written.
+ *
+ * @param[in]  peer_id      ID of peer to store data for.
+ * @param[in]  data_id      Which piece of data to store.
+ *
+ * @retval NRF_SUCCESS              Data storing was successfully started.
+ * @retval NRF_ERROR_NO_MEM         No space available in persistent storage. Please clear some
+ *                                  space, the operation will be reattempted after the next compress
+ *                                  procedure. This error will not happen if
+ *                                  @ref pdb_write_buf_store_prepare is called beforehand.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID was invalid.
+ * @retval NRF_ERROR_NOT_FOUND      No buffer has been allocated for this peer ID/data ID pair.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ * @retval NRF_ERROR_INTERNAL       Unexpected internal error.
+ */
+ret_code_t pdb_write_buf_store(pm_peer_id_t      peer_id,
+                               pm_peer_data_id_t data_id);
+
+
+/**@brief Function for clearing data from persistent storage.
+ *
+ * @param[in]  peer_id  ID of peer to clear data for.
+ * @param[in]  data_id  Which piece of data to clear.
+ *
+ * @retval NRF_SUCCESS              Data clear was successfully started.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID was invalid.
+ * @retval NRF_ERROR_NOT_FOUND      Nothing to clear for this data for this peer ID.
+ * @retval NRF_ERROR_BUSY           Could not process request at this time. Reattempt later.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_clear(pm_peer_id_t peer_id, pm_peer_data_id_t data_id);
+
+
+/**@brief Function for querying the number of valid peer IDs available. I.E the number of peers
+ *        in persistent storage.
+ *
+ * @return  The number of valid peer IDs.
+ */
+uint32_t pdb_n_peers(void);
+
+
+/**@brief Function for getting the next peer ID in the sequence of all used peer IDs. Can be
+ *        used to loop through all used peer IDs.
+ *
+ * @note @ref PM_PEER_ID_INVALID is considered to be before the first and after the last ordinary
+ *       peer ID.
+ *
+ * @param[in]  prev_peer_id  The previous peer ID.
+ *
+ * @return  The next peer ID.
+ * @return  The first ordinary peer ID  if prev_peer_id was @ref PM_PEER_ID_INVALID.
+ * @retval  PM_PEER_ID_INVALID          if prev_peer_id was the last ordinary peer ID.
+ */
+pm_peer_id_t pdb_next_peer_id_get(pm_peer_id_t prev_peer_id);
+
+
+/**@brief Function for updating currently stored peer data to a new version
+ *
+ * @details Updating happens asynchronously. 
+ *          Expect a @ref PDS_EVT_STORED or @ref PDS_EVT_ERROR_STORE for the store token
+ *          and a @ref PDS_EVT_ERROR_CLEAR or @ref PDS_EVT_ERROR_CLEAR for the old token 
+ *      
+ * @param[in]   peer_data           New data
+ * @param[in]   old_token           Store token for the old data
+ * @param[out]  p_store_token       Store token for the new data
+ *
+ * @retval NRF_SUCESS               The update was initiated successfully
+ * @retval NRF_ERROR_NOT_FOUND      The old store token was invalid.
+ * @retval NRF_ERROR_NULL           Data contained a NULL pointer.
+ * @retval NRF_ERROR_NO_MEM         No space available in persistent storage.
+ * @retval NRF_ERROR_BUSY           FDS or underlying modules are busy and can't take any 
+ *                                  more requests
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_peer_data_update(pm_peer_data_const_t        peer_data,
+                                pm_store_token_t            old_token,
+                                pm_store_token_t          * p_store_token);
+
+
+/**@brief Function for reading data directly from persistent storage to external memory.
+ *
+ * @param[in]    peer_id      ID of peer to read data for.
+ * @param[in]    data_id      Which piece of data to read.
+ * @param[inout] p_peer_data  Where to store the data. If the data to be read has variable length,
+ *                            the appropriate length field needs to reflect the available buffer
+ *                            space. On a successful read, the length field is updated to match the
+ *                            length of the read data.
+ *
+ * @retval NRF_SUCCESS              Data successfully read.
+ * @retval NRF_ERROR_INVALID_PARAM  Data ID or Peer ID was invalid or unallocated.
+ * @retval NRF_ERROR_NULL           p_peer_data contained a NULL pointer.
+ * @retval NRF_ERROR_NOT_FOUND      This data was not found for this peer ID.
+ * @retval NRF_ERROR_DATA_SIZE      The provided buffer was not large enough.
+ * @retval NRF_ERROR_INVALID_STATE  Module is not initialized.
+ */
+ret_code_t pdb_raw_read(pm_peer_id_t      peer_id,
+                        pm_peer_data_id_t data_id,
+                        pm_peer_data_t  * p_peer_data);
+
+
+/**@brief Function for writing data directly to persistent storage from external memory.
+ *
+ * @param[in]  peer_id        ID of peer to write data for.
+ * @param[in]  p_peer_data    Data to store.
+ * @param[out] p_store_token  A token identifying this particular store operation. The token can be
+ *                            used to identify events pertaining to this operation.
+ *
+ * @retval NRF_SUCCESS               Data successfully written.
+ * @retval NRF_ERROR_INVALID_PARAM   Data ID or Peer ID was invalid or unallocated.
+ * @retval NRF_ERROR_NULL            p_peer_data contained a NULL pointer.
+ * @retval NRF_ERROR_NO_MEM          No space available in persistent storage.
+ * @retval NRF_ERROR_INVALID_LENGTH  Data length above the maximum allowed.
+ * @retval NRF_ERROR_INVALID_STATE   Module is not initialized.
+ */
+ret_code_t pdb_raw_store(pm_peer_id_t           peer_id,
+                         pm_peer_data_const_t * p_peer_data,
+                         pm_store_token_t     * p_store_token);
+
+
+/** @} */
+
+#endif /* PEER_DATABASE_H__ */
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "peer_id.h"
+
+#include <stdint.h>
+#include <string.h>
+#include "sdk_errors.h"
+#include "peer_manager_types.h"
+#include "pm_mutex.h"
+
+
+typedef struct
+{
+    uint8_t peer_ids[MUTEX_STORAGE_SIZE(PM_PEER_ID_N_AVAILABLE_IDS)]; /*< bitmap. */
+} pi_t;
+
+
+static pi_t m_pi = {.peer_ids = {0}};
+
+
+static void internal_state_reset(pi_t * p_pi)
+{
+    memset(p_pi, 0, sizeof(pi_t));
+}
+
+
+void peer_id_init(void)
+{
+    internal_state_reset(&m_pi);
+    pm_mutex_init(m_pi.peer_ids, PM_PEER_ID_N_AVAILABLE_IDS);
+}
+
+
+pm_peer_id_t peer_id_allocate(pm_peer_id_t peer_id)
+{
+    pm_peer_id_t allocated_peer_id = PM_PEER_ID_INVALID;
+    if (peer_id == PM_PEER_ID_INVALID)
+    {
+        allocated_peer_id = pm_mutex_lock_first_available(m_pi.peer_ids, PM_PEER_ID_N_AVAILABLE_IDS);
+        if (allocated_peer_id == PM_PEER_ID_N_AVAILABLE_IDS)
+        {
+            allocated_peer_id = PM_PEER_ID_INVALID;
+        }
+    }
+    else if (peer_id < PM_PEER_ID_N_AVAILABLE_IDS)
+    {
+        bool lock_success = pm_mutex_lock(m_pi.peer_ids, peer_id);
+        allocated_peer_id = lock_success ? peer_id : PM_PEER_ID_INVALID;
+    }
+    return allocated_peer_id;
+}
+
+
+void peer_id_free(pm_peer_id_t peer_id)
+{
+    if (peer_id < PM_PEER_ID_N_AVAILABLE_IDS)
+    {
+        pm_mutex_unlock(m_pi.peer_ids, peer_id);
+    }
+}
+
+
+bool peer_id_is_allocated(pm_peer_id_t peer_id)
+{
+    if (peer_id < PM_PEER_ID_N_AVAILABLE_IDS)
+    {
+        return pm_mutex_lock_status_get(m_pi.peer_ids, peer_id);
+    }
+    return false;
+}
+
+
+pm_peer_id_t peer_id_next_id_get(pm_peer_id_t prev_peer_id)
+{
+    pm_peer_id_t i = (prev_peer_id == PM_PEER_ID_INVALID) ? 0 : (prev_peer_id + 1);
+    for (; i < PM_PEER_ID_N_AVAILABLE_IDS; i++)
+    {
+        if (pm_mutex_lock_status_get(m_pi.peer_ids, i))
+        {
+            return i;
+        }
+    }
+
+    return PM_PEER_ID_INVALID;
+}
+
+
+uint32_t peer_id_n_ids(void)
+{
+    uint32_t n_ids = 0;
+
+    for (pm_peer_id_t i = 0; i < PM_PEER_ID_N_AVAILABLE_IDS; i++)
+    {
+        n_ids += pm_mutex_lock_status_get(m_pi.peer_ids, i);
+    }
+
+    return n_ids;
+}
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_id.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef PEER_ID_H__
+#define PEER_ID_H__
+
+
+#include "stdint.h"
+#include "sdk_errors.h"
+#include "ble_gap.h"
+#include "peer_manager_types.h"
+
+
+/**
+ * @defgroup peer_id Peer IDs
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. This module keeps track of which peer IDs are in
+ *        use and which are free.
+ */
+
+
+/**@brief Function for initializing the module.
+ */
+void peer_id_init(void);
+
+
+/**@brief Function for claiming an unused peer ID.
+ *
+ * @param peer_id  The peer ID to allocate. If this is @ref PM_PEER_ID_INVALID, the first available
+ *                 will be allocated.
+ *
+ * @return  The allocated peer ID.
+ * @retval  PM_PEER_ID_INVALID  If no peer ID could be allocated or module is not initialized.
+ */
+pm_peer_id_t peer_id_allocate(pm_peer_id_t peer_id);
+
+
+/**@brief Function for freeing a peer ID and clearing all data associated with it in persistent
+ *        storage.
+ *
+ * @param[in]  peer_id  Peer ID to free.
+ */
+void peer_id_free(pm_peer_id_t peer_id);
+
+
+/**@brief Function for finding out whether a peer ID is in use.
+ *
+ * @param[in]  peer_id  The peer ID to inquire about.
+ *
+ * @retval  true   peer_id is in use.
+ * @retval  false  peer_id is free, or the module is not initialized.
+ */
+bool peer_id_is_allocated(pm_peer_id_t peer_id);
+
+
+/**@brief Function for getting the next peer ID in the sequence of all used peer IDs. Can be
+ *        used to loop through all used peer IDs.
+ *
+ * @note @ref PM_PEER_ID_INVALID is considered to be before the first and after the last ordinary
+ *       peer ID.
+ *
+ * @param[in]  prev_peer_id  The previous peer ID.
+ *
+ * @return  The next peer ID.
+ * @return  The first used peer ID  if prev_peer_id was @ref PM_PEER_ID_INVALID.
+ * @retval  PM_PEER_ID_INVALID      if prev_peer_id was the last ordinary peer ID or the module is
+ *                                  not initialized.
+ */
+pm_peer_id_t peer_id_next_id_get(pm_peer_id_t prev_peer_id);
+
+
+/**@brief Function for querying the number of valid peer IDs available. I.E the number of peers
+ *        in persistent storage.
+ *
+ * @return  The number of valid peer IDs, or 0 if module is not initialized.
+ */
+uint32_t peer_id_n_ids(void);
+
+/** @} */
+
+#endif /* PEER_ID_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_manager_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/peer_manager_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+
+#ifndef PEER_MANAGER_TYPES_H__
+#define PEER_MANAGER_TYPES_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+
+
+/**
+ * @file peer_manager_types.h
+ *
+ * @addtogroup peer_manager
+ * @{
+ */
+
+
+#include <stdint.h>
+#include <stddef.h>
+#include "ble_gap.h"
+#include "ble_hci.h"
+#include "ble_gatt_db.h"
+#include "compiler_abstraction.h"
+
+
+/**@brief Handle to uniquely identify a peer for which we have persistently stored data.
+ */
+typedef uint16_t pm_peer_id_t;
+
+#define PM_PEER_ID_INVALID              0xFFFF /**< Invalid value for @ref pm_peer_id_t. */
+#define PM_PEER_ID_N_AVAILABLE_IDS      256    /**< The number of available peer IDs. */
+#define PM_LOCAL_DB_LEN_OVERHEAD_BYTES  offsetof(pm_peer_data_local_gatt_db_flash_t, p_data)
+#define PM_REMOTE_DB_LEN_OVERHEAD_BYTES offsetof(pm_peer_data_remote_gatt_db_flash_t, p_data)
+
+static __INLINE uint16_t PM_N_WORDS(uint16_t n_bytes)
+{
+    return ((n_bytes + 3) >> 2);
+}
+
+/**@brief Errors originating from the Peer Manager module.
+ */
+typedef enum
+{
+    PM_SEC_ERROR_CODE_PIN_OR_KEY_MISSING = BLE_HCI_STATUS_CODE_PIN_OR_KEY_MISSING,  /**< Encryption failed because the peripheral has lost the LTK for this bond. */
+    PM_SEC_ERROR_CODE_MIC_FAILURE = BLE_HCI_CONN_TERMINATED_DUE_TO_MIC_FAILURE,     /**< Pairing ended with disconnection because of mismatching keys. */
+    PM_SEC_ERROR_SMP_TIMEOUT,                                                       /**< Pairing/bonding could not start because an SMP timeout has already happened on this link. This means that no more pairing or bonding can happen on this link. To be able to pair or bond, the link must be disconnected and then reconnected. See Bluetooth specification 4.2 section 3.H.3.4 */
+} pm_sec_error_code_t;
+
+
+/**@brief Enumeration describing the different procedures that can lead to an encrypted link.
+ */
+typedef enum
+{
+    PM_LINK_SECURED_PROCEDURE_ENCRYPTION, /**< Using an LTK shared during a previous bonding procedure to encrypt the link. */
+    PM_LINK_SECURED_PROCEDURE_BONDING,    /**< A pairing procedure, followed by a bonding procedure. */
+    PM_LINK_SECURED_PROCEDURE_PAIRING,    /**< A pairing procedure with no bonding. */
+} pm_sec_procedure_t;
+
+
+/**@brief Data associated with a bond to a peer.
+ */
+typedef struct
+{
+    uint8_t           own_role; /**< The role of the local device during bonding. */
+    ble_gap_id_key_t  peer_id;  /**< The peer's peer address and identity resolution key. */
+    ble_gap_enc_key_t peer_ltk; /**< The peer's long term encryption key. */
+    ble_gap_enc_key_t own_ltk;  /**< Locally generated long term encryption key, distributed to the peer. */
+} pm_peer_data_bonding_t;
+
+
+/**@brief Function for calculating the flash size of bonding data.
+ *
+ * @return The number of words the data will take in flash.
+ */
+static __INLINE uint16_t PM_BONDING_DATA_N_WORDS(void)
+{
+    return PM_N_WORDS(sizeof(pm_peer_data_bonding_t));
+}
+
+
+/**@brief Function for calculating the flash size of service changed pending state.
+ *
+ * @return The number of words the data will take in flash.
+ */
+static __INLINE uint16_t PM_SC_STATE_N_WORDS(void)
+{
+    return PM_N_WORDS(sizeof(bool));
+}
+
+
+/**@brief Data on a local GATT database.
+ */
+typedef struct
+{
+    uint32_t  flags;   /**< Flags describing the database attributes. */
+    uint16_t  len;     /**< Size of attribute array. */
+    uint8_t * p_data;  /**< Array to hold the database attributes. */
+} pm_peer_data_local_gatt_db_t;
+
+
+/**@brief Data on a local GATT database, as formatted in flash.
+ */
+typedef struct
+{
+    uint32_t flags;
+    uint16_t len;
+    uint16_t _padding;
+    uint8_t  p_data[];
+} pm_peer_data_local_gatt_db_flash_t;
+
+
+/**@brief Function for calculating the flash size of local GATT database data.
+ *
+ * @param[in]  local_db_len  The length of the database as reported by the SoftDevice.
+ *
+ * @return The number of words the data will take in flash.
+ */
+static __INLINE uint16_t PM_LOCAL_DB_N_WORDS(uint16_t local_db_len)
+{
+    return PM_N_WORDS(local_db_len + PM_LOCAL_DB_LEN_OVERHEAD_BYTES);
+}
+
+
+/**@brief Function for calculating the length of a local GATT database attribute array.
+ *
+ * @param[in]  n_words  The number of words the data takes in flash.
+ *
+ * @return The length of the database attribute array.
+ */
+static __INLINE uint16_t PM_LOCAL_DB_LEN(uint16_t n_words)
+{
+    return ((n_words * 4) - PM_LOCAL_DB_LEN_OVERHEAD_BYTES);
+}
+
+
+/**@brief Data on a remote GATT database.
+ */
+typedef struct
+{
+    uint32_t            service_count; /**< Number of stored services. */
+    ble_gatt_db_srv_t * p_data;        /**< Array to hold the database attributes. */
+} pm_peer_data_remote_gatt_db_t;
+
+
+/**@brief Data on a remote GATT database, as formatted in flash.
+ */
+typedef struct
+{
+    uint32_t          service_count;
+    ble_gatt_db_srv_t p_data[];
+} pm_peer_data_remote_gatt_db_flash_t;
+
+
+
+/**@brief Function for calculating the flash size of remote GATT database data.
+ *
+ * @param[in]  service_count  The number of services in the service array.
+ *
+ * @return The number of words the data will take in flash.
+ */
+static __INLINE uint16_t PM_REMOTE_DB_N_WORDS(uint16_t service_count)
+{
+    return PM_N_WORDS((sizeof(ble_gatt_db_srv_t) * service_count) + PM_REMOTE_DB_LEN_OVERHEAD_BYTES);
+}
+
+
+/**@brief Union of all data associated with one peer.
+ */
+typedef union
+{
+    pm_peer_data_bonding_t        * p_bonding_data;            /**< The exchanged bond information in addition to metadata of the bonding. */
+    bool                          * p_service_changed_pending; /**< Whether a service changed indication should be sent to the peer. */
+    pm_peer_data_local_gatt_db_t  * p_local_gatt_db;           /**< Persistent information pertaining to a peer GATT client. */
+    pm_peer_data_remote_gatt_db_t * p_remote_gatt_db;          /**< Persistent information pertaining to a peer GATT server. */
+    uint8_t                       * p_application_data;        /**< Arbitrary data to associate with the peer. This data can be freely used by the application. */
+} pm_peer_data_unit_t;
+
+
+/**@brief Immutable version of @ref pm_peer_data_unit_t.
+ */
+typedef union
+{
+    pm_peer_data_bonding_t        const * p_bonding_data;
+    bool                          const * p_service_changed_pending;
+    pm_peer_data_local_gatt_db_t  const * p_local_gatt_db;
+    pm_peer_data_remote_gatt_db_t const * p_remote_gatt_db;
+    uint8_t                       const * p_application_data;
+} pm_peer_data_unit_const_t;
+
+
+/**@brief Data from @ref pm_peer_data_unit_t, as mapped in flash.
+ */
+typedef union
+{
+    pm_peer_data_bonding_t              const * p_bonding_data;
+    bool                                const * p_service_changed_pending;
+    pm_peer_data_local_gatt_db_flash_t  const * p_local_gatt_db;
+    pm_peer_data_remote_gatt_db_flash_t const * p_remote_gatt_db;
+    uint8_t                             const * p_application_data;
+} pm_peer_data_unit_flash_t;
+
+
+/**@brief The different types of data associated with a peer.
+ */
+typedef enum
+{
+    PM_PEER_DATA_ID_BONDING,
+    PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING,
+    PM_PEER_DATA_ID_GATT_LOCAL,
+    PM_PEER_DATA_ID_GATT_REMOTE,
+    PM_PEER_DATA_ID_APPLICATION,
+    PM_PEER_DATA_ID_INVALID,
+} pm_peer_data_id_t;
+
+
+//STATIC_ASSERT_MSG(sizeof(pm_peer_data_t) == sizeof(pm_peer_data_const_t), "Size of pm_peer_data_t different from immutable version.");
+
+
+/**@brief Macro saying whether a data_id is valid, i.e. one of the valid enum values.
+ *
+ * @param[in] data_id  The data_id to check.
+ */
+static __INLINE bool PM_PEER_DATA_ID_IS_VALID(pm_peer_data_id_t data_id)
+{
+    return ((data_id - PM_PEER_DATA_ID_BONDING) < (PM_PEER_DATA_ID_INVALID - PM_PEER_DATA_ID_BONDING));
+}
+
+
+/**@brief One piece of data associated with a peer, together with the type.
+ */
+typedef struct
+{
+    uint16_t            length_words;
+    pm_peer_data_id_t   data_type;
+    pm_peer_data_unit_t data;
+} pm_peer_data_t;
+
+/**@brief Immutable version of @ref pm_peer_data_t.
+ */
+typedef struct
+{
+    uint16_t                    length_words;
+    pm_peer_data_id_t           data_type;
+    pm_peer_data_unit_const_t   data;
+} pm_peer_data_const_t;
+
+/**@brief Data from @ref pm_peer_data_t, as mapped in flash.
+ */
+typedef struct
+{
+    uint16_t                  length_words;
+    pm_peer_data_id_t         data_type;
+    pm_peer_data_unit_flash_t data;
+} pm_peer_data_flash_t;
+
+
+/**@brief Typedef for type used for write prepares. Used to reserve space in flash
+ */
+typedef uint32_t pm_prepare_token_t;
+
+
+/**@brief Typedef for type used to hold reference to stored item in flash.
+ *        this token can be used for locking and validity check
+ */
+typedef uint32_t pm_store_token_t;
+
+ /** @} */
+
+#endif /* PEER_MANAGER_TYPES_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "pm_buffer.h"
+
+#include <stdbool.h>
+#include <string.h>
+#include "nrf_error.h"
+#include "pm_mutex.h"
+
+
+#define BUFFER_IS_VALID(p_buffer) ((p_buffer != NULL)             \
+                                && (p_buffer->p_memory != NULL)   \
+                                && (p_buffer->p_mutex  != NULL))
+
+
+
+ret_code_t pm_buffer_init(pm_buffer_t * p_buffer,
+                          uint8_t     * p_buffer_memory,
+                          uint32_t      buffer_memory_size,
+                          uint8_t     * p_mutex_memory,
+                          uint32_t      mutex_memory_size,
+                          uint32_t      n_blocks,
+                          uint32_t      block_size)
+{
+    if (   (p_buffer           != NULL)
+        && (p_buffer_memory    != NULL)
+        && (p_mutex_memory     != NULL)
+        && (buffer_memory_size >= (n_blocks*block_size))
+        && (mutex_memory_size  >= MUTEX_STORAGE_SIZE(n_blocks))
+        && (n_blocks           != 0)
+        && (block_size         != 0))
+    {
+        p_buffer->p_memory   = p_buffer_memory;
+        p_buffer->p_mutex    = p_mutex_memory;
+        p_buffer->n_blocks   = n_blocks;
+        p_buffer->block_size = block_size;
+        pm_mutex_init(p_buffer->p_mutex, n_blocks);
+
+        return NRF_SUCCESS;
+    }
+    else
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+}
+
+
+uint8_t pm_buffer_block_acquire(pm_buffer_t * p_buffer, uint32_t n_blocks)
+{
+    if (!BUFFER_IS_VALID(p_buffer))
+    {
+        return ( BUFFER_INVALID_ID );
+    }
+
+    uint8_t first_locked_mutex = BUFFER_INVALID_ID;
+
+    for (uint8_t i = 0; i < p_buffer->n_blocks; i++)
+    {
+        if (pm_mutex_lock(p_buffer->p_mutex, i))
+        {
+            if (first_locked_mutex == BUFFER_INVALID_ID)
+            {
+                first_locked_mutex = i;
+            }
+            if ((i - first_locked_mutex + 1) == n_blocks)
+            {
+                return first_locked_mutex;
+            }
+        }
+        else if (first_locked_mutex != BUFFER_INVALID_ID)
+        {
+            for (uint8_t j = first_locked_mutex; j < i; j++)
+            {
+                pm_buffer_release(p_buffer, j);
+            }
+            first_locked_mutex = BUFFER_INVALID_ID;
+        }
+    }
+
+    return ( BUFFER_INVALID_ID );
+}
+
+
+uint8_t * pm_buffer_ptr_get(pm_buffer_t * p_buffer, uint8_t id)
+{
+    if (!BUFFER_IS_VALID(p_buffer))
+    {
+        return ( NULL );
+    }
+
+    if ( (id != BUFFER_INVALID_ID)
+    &&   pm_mutex_lock_status_get(p_buffer->p_mutex, id) )
+    {
+        return ( &p_buffer->p_memory[id*p_buffer->block_size] );
+    }
+    else
+    {
+        return ( NULL );
+    }
+}
+
+
+void pm_buffer_release(pm_buffer_t * p_buffer, uint8_t id)
+{
+    if (    BUFFER_IS_VALID(p_buffer)
+       &&  (id != BUFFER_INVALID_ID)
+       &&   pm_mutex_lock_status_get(p_buffer->p_mutex, id))
+    {
+        pm_mutex_unlock(p_buffer->p_mutex, id);
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_buffer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef BUFFER_H__
+#define BUFFER_H__
+
+#include <stdint.h>
+#include "sdk_errors.h"
+#include "pm_mutex.h"
+
+
+/**
+ * @defgroup pm_buffer Buffer
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. This module provides a simple buffer.
+ */
+
+
+#define BUFFER_INVALID_ID 0xFF
+
+#define PM_BUFFER_INIT(p_buffer, n_blocks, block_size, err_code)    \
+do                                                                  \
+{                                                                   \
+    static uint8_t buffer_memory[(n_blocks) * (block_size)];        \
+    static uint8_t mutex_memory[MUTEX_STORAGE_SIZE(n_blocks)];      \
+    err_code = pm_buffer_init((p_buffer),                           \
+                               buffer_memory,                       \
+                              (n_blocks) * (block_size),            \
+                               mutex_memory,                        \
+                               MUTEX_STORAGE_SIZE(n_blocks),        \
+                              (n_blocks),                           \
+                              (block_size));                        \
+} while(0)
+
+
+typedef struct
+{
+    uint8_t * p_memory;   /**< The storage for all buffer entries. The size of the buffer must be n_blocks*block_size. */
+    uint8_t * p_mutex;    /**< A mutex group with one mutex for each buffer entry. */
+    uint32_t  n_blocks;   /**< The number of allocatable blocks in the buffer. */
+    uint32_t  block_size; /**< The size of each block in the buffer. */
+} pm_buffer_t;
+
+/**@brief Function for initializing a buffer instance.
+ *
+ * @param[out] p_buffer            The buffer instance to initialize.
+ * @param[in]  p_buffer_memory     The memory this buffer will use.
+ * @param[in]  buffer_memory_size  The size of p_buffer_memory. This must be at least
+ *                                 n_blocks*block_size.
+ * @param[in]  p_mutex_memory      The memory for the mutexes. This must be at least
+ *                                 @ref MUTEX_STORAGE_SIZE(n_blocks).
+ * @param[in]  mutex_memory_size   The size of p_mutex_memory.
+ * @param[in]  n_blocks            The number of blocks in the buffer.
+ * @param[in]  block_size          The size of each block.
+ *
+ * @retval NRF_SUCCESS              Successfully initialized buffer instance.
+ * @retval NRF_ERROR_INVALID_PARAM  A parameter was 0 or NULL or a size was too small.
+ */
+ret_code_t pm_buffer_init(pm_buffer_t * p_buffer,
+                          uint8_t     * p_buffer_memory,
+                          uint32_t      buffer_memory_size,
+                          uint8_t     * p_mutex_memory,
+                          uint32_t      mutex_memory_size,
+                          uint32_t      n_blocks,
+                          uint32_t      block_size);
+
+
+/**@brief Function for acquiring a buffer block in a buffer.
+ *
+ * @param[in]  p_buffer  The buffer instance acquire from.
+ * @param[in]  n_blocks  The number of contiguous blocks to acquire.
+ *
+ * @return The id of the acquired block, if successful.
+ * @retval BUFFER_INVALID_ID  If unsuccessful.
+ */
+uint8_t pm_buffer_block_acquire(pm_buffer_t * p_buffer, uint32_t n_blocks);
+
+
+/**@brief Function for getting a pointer to a specific buffer block.
+ *
+ * @param[in]  p_buffer  The buffer instance get from.
+ * @param[in]  id        The id of the buffer to get the pointer for.
+ *
+ * @return A pointer to the buffer for the specified id, if the id is valid.
+ * @retval NULL  If the id is invalid.
+ */
+uint8_t * pm_buffer_ptr_get(pm_buffer_t * p_buffer, uint8_t id);
+
+
+/**@brief Function for releasing a buffer block.
+ *
+ * @param[in]  p_buffer  The buffer instance containing the block to release.
+ * @param[in]  id        The id of the block to release.
+ */
+void pm_buffer_release(pm_buffer_t * p_buffer, uint8_t id);
+
+
+#endif // BUFFER_H__
+
+/**
+ * @}
+ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#include "pm_mutex.h"
+
+#include <stdbool.h>
+#include <string.h>
+#include "nrf_error.h"
+#include "app_util_platform.h"
+
+
+
+/**@brief Locks the mutex defined by the mask.
+ *
+ * @param p_mutex pointer to the mutex storage.
+ * @param mutex_mask the mask identifying the mutex position.
+ *
+ * @retval true if the mutex could be locked.
+ * @retval false if the mutex was already locked.
+ */
+static bool lock_by_mask(uint8_t * p_mutex, uint8_t mutex_mask)
+{
+    bool success = false;
+
+    if ( (*p_mutex & mutex_mask) == 0 )
+    {
+        CRITICAL_REGION_ENTER();
+        if ( (*p_mutex & mutex_mask) == 0 )
+        {
+            *p_mutex |= mutex_mask;
+
+            success = true;
+        }
+        CRITICAL_REGION_EXIT();
+    }
+
+    return ( success );
+}
+
+
+void pm_mutex_init(uint8_t * p_mutex, uint16_t mutex_size)
+{
+    if (p_mutex != NULL)
+    {
+        memset(&p_mutex[0], 0, MUTEX_STORAGE_SIZE(mutex_size));
+    }
+}
+
+
+bool pm_mutex_lock(uint8_t * p_mutex, uint16_t mutex_id)
+{
+    if (p_mutex != NULL)
+    {
+        return ( lock_by_mask(&(p_mutex[mutex_id >> 3]), (1 << (mutex_id & 0x07))) );
+    }
+    else
+    {
+        return false;
+    }
+}
+
+
+void pm_mutex_unlock(uint8_t * p_mutex, uint16_t mutex_id)
+{
+    uint8_t mutex_base = mutex_id >> 3;
+    uint8_t mutex_mask = (1 << (mutex_id & 0x07));
+
+    if   ((p_mutex != NULL)
+       && (p_mutex[mutex_base] & mutex_mask))
+    {
+        CRITICAL_REGION_ENTER();
+        p_mutex[mutex_base] &= ~mutex_mask;
+        CRITICAL_REGION_EXIT();
+    }
+}
+
+
+uint16_t pm_mutex_lock_first_available(uint8_t * p_mutex, uint16_t mutex_size)
+{
+    if (p_mutex != NULL)
+    {
+        for ( uint16_t i = 0; i < mutex_size; i++ )
+        {
+            if ( lock_by_mask(&(p_mutex[i >> 3]), 1 << (i & 0x07)) )
+            {
+                return ( i );
+            }
+        }
+    }
+
+    return ( mutex_size );
+}
+
+
+bool pm_mutex_lock_status_get(uint8_t * p_mutex, uint16_t mutex_id)
+{
+    if (p_mutex != NULL)
+    {
+        return ( (p_mutex[mutex_id >> 3] & (1 << (mutex_id & 0x07))) );
+    }
+    else
+    {
+        return true;
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/ble/peer_manager/pm_mutex.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+
+#ifndef MUTEX_H__
+#define MUTEX_H__
+
+
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @defgroup pm_mutex Mutex
+ * @ingroup peer_manager
+ * @{
+ * @brief An internal module of @ref peer_manager. This module provides thread-safe mutexes.
+ */
+
+
+/**@brief Defines the storage size of a specified mutex group.
+ *
+ * @param number_of_mutexes the number of mutexes in the group.
+ */
+#define MUTEX_STORAGE_SIZE(number_of_mutexes) ((7 + (number_of_mutexes)) >> 3)
+
+
+/**@brief Initializes a mutex group.
+ *
+ * @param[in] p_mutex     Pointer to the mutex group. See @ref MUTEX_STORAGE_SIZE().
+ * @param[in] mutex_size  The size of the mutex group in number of mutexes.
+ */
+void pm_mutex_init(uint8_t * p_mutex, uint16_t mutex_size);
+
+
+/**@brief Locks the mutex specified by the bit id.
+ *
+ * @param[inout] p_mutex       Pointer to the mutex group.
+ * @param[in]    mutex_bit_id  The bit id of the mutex.
+ *
+ * @retval true   if it was possible to lock the mutex.
+ * @retval false  otherwise.
+ */
+bool pm_mutex_lock(uint8_t * p_mutex, uint16_t mutex_bit_id);
+
+
+/**@brief Locks the first unlocked mutex within the mutex group.
+ *
+ * @param[in, out] p_mutex     Pointer to the mutex group.
+ * @param[in]      mutex_size  The size of the mutex group.
+ *
+ * @return The first unlocked mutex id in the group.
+ * @retval group-size  if there was no unlocked mutex available.
+ */
+uint16_t pm_mutex_lock_first_available(uint8_t * p_mutex, uint16_t mutex_size);
+
+
+/**@brief Unlocks the mutex specified by the bit id.
+ *
+ * @param[in, out] p_mutex       Pointer to the mutex group.
+ * @param[in]      mutex_bit_id  The bit id of the mutex.
+ */
+void pm_mutex_unlock(uint8_t * p_mutex, uint16_t mutex_bit_id);
+
+
+/**@brief Gets the locking status of the specified mutex.
+ *
+ * @param[in, out] p_mutex      Pointer to the mutex group.
+ * @param[in]      mutex_bit_id The bit id of the mutex.
+ *
+ * @retval true   if the mutex was locked.
+ * @retval false  otherwise.
+ */
+bool pm_mutex_lock_status_get(uint8_t * p_mutex, uint16_t mutex_bit_id);
+
+
+#endif // MUTEX_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/device/compiler_abstraction.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/device/compiler_abstraction.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef _COMPILER_ABSTRACTION_H
+#define _COMPILER_ABSTRACTION_H
+
+/*lint ++flb "Enter library region" */
+
+#if defined ( __CC_ARM )
+    
+    #ifndef __ASM
+        #define __ASM               __asm                       
+    #endif
+    
+    #ifndef __INLINE
+        #define __INLINE            __inline                    
+    #endif
+    
+    #ifndef __WEAK
+        #define __WEAK              __weak                      
+    #endif
+    
+    #ifndef __ALIGN
+        #define __ALIGN(n)          __align(n)                  
+    #endif
+    
+    #define GET_SP()                __current_sp()              
+  
+#elif defined ( __ICCARM__ )
+    
+    #ifndef __ASM
+        #define __ASM               __asm                       
+    #endif
+    
+    #ifndef __INLINE
+        #define __INLINE            inline                      
+    #endif
+    
+    #ifndef __WEAK
+        #define __WEAK              __weak                      
+    #endif
+
+    /* Not defined for IAR since it requires a new line to work, and C preprocessor does not allow that. */
+    #ifndef __ALIGN
+        #define __ALIGN(n)          
+    #endif
+    
+    #define GET_SP()                __get_SP()                  
+    
+#elif defined   ( __GNUC__ )
+    
+    #ifndef __ASM
+        #define __ASM               __asm                       
+    #endif
+    
+    #ifndef __INLINE
+        #define __INLINE            inline                      
+    #endif
+    
+    #ifndef __WEAK
+        #define __WEAK              __attribute__((weak))       
+    #endif
+    
+    #ifndef __ALIGN
+        #define __ALIGN(n)          __attribute__((aligned(n))) 
+    #endif
+    
+    #define GET_SP()                gcc_current_sp()            
+
+    static inline unsigned int gcc_current_sp(void)
+    {
+        register unsigned sp __ASM("sp");
+        return sp;
+    }
+    
+#elif defined   ( __TASKING__ )
+        
+    #ifndef __ASM        
+        #define __ASM               __asm                      
+    #endif
+    
+    #ifndef __INLINE
+        #define __INLINE            inline                     
+    #endif
+    
+    #ifndef __WEAK
+        #define __WEAK              __attribute__((weak))      
+    #endif
+    
+    #ifndef __ALIGN
+        #define __ALIGN(n)          __align(n)                  
+    #endif
+    
+    #define GET_SP()                __get_MSP()                
+    
+#endif
+
+/*lint --flb "Leave library region" */
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/device/nrf.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/device/nrf.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef NRF_H
+#define NRF_H
+
+#if defined(_WIN32)         
+    /* Do not include nrf51 specific files when building for PC host */
+#elif defined(__unix)       
+    /* Do not include nrf51 specific files when building for PC host */
+#elif defined(__APPLE__)    
+    /* Do not include nrf51 specific files when building for PC host */
+#else
+
+    /* Family selection for family includes. */
+    #if defined (NRF51)
+        #include "nrf51.h"
+        #include "nrf51_bitfields.h"
+        #include "nrf51_deprecated.h"
+    #elif defined (NRF52)
+        #include "nrf52.h"
+        #include "nrf52_bitfields.h"
+        #include "nrf51_to_nrf52.h"
+    #else
+        #error "Device family must be defined. See nrf.h."
+    #endif /* NRF51, NRF52 */
+
+    #include "compiler_abstraction.h"
+
+#endif /* _WIN32 || __unix || __APPLE__ */
+
+#endif /* NRF_H */
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/device/nrf51.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/device/nrf51.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,1263 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef NRF51_H
+#define NRF51_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* -------------------------  Interrupt Number Definition  ------------------------ */
+
+typedef enum {
+/* -------------------  Cortex-M0 Processor Exceptions Numbers  ------------------- */
+  Reset_IRQn                    = -15,              /*!<   1  Reset Vector, invoked on Power up and warm reset                 */
+  NonMaskableInt_IRQn           = -14,              /*!<   2  Non maskable Interrupt, cannot be stopped or preempted           */
+  HardFault_IRQn                = -13,              /*!<   3  Hard Fault, all classes of Fault                                 */
+  SVCall_IRQn                   =  -5,              /*!<  11  System Service Call via SVC instruction                          */
+  DebugMonitor_IRQn             =  -4,              /*!<  12  Debug Monitor                                                    */
+  PendSV_IRQn                   =  -2,              /*!<  14  Pendable request for system service                              */
+  SysTick_IRQn                  =  -1,              /*!<  15  System Tick Timer                                                */
+/* ----------------------  nrf51 Specific Interrupt Numbers  ---------------------- */
+  POWER_CLOCK_IRQn              =   0,              /*!<   0  POWER_CLOCK                                                      */
+  RADIO_IRQn                    =   1,              /*!<   1  RADIO                                                            */
+  UART0_IRQn                    =   2,              /*!<   2  UART0                                                            */
+  SPI0_TWI0_IRQn                =   3,              /*!<   3  SPI0_TWI0                                                        */
+  SPI1_TWI1_IRQn                =   4,              /*!<   4  SPI1_TWI1                                                        */
+  GPIOTE_IRQn                   =   6,              /*!<   6  GPIOTE                                                           */
+  ADC_IRQn                      =   7,              /*!<   7  ADC                                                              */
+  TIMER0_IRQn                   =   8,              /*!<   8  TIMER0                                                           */
+  TIMER1_IRQn                   =   9,              /*!<   9  TIMER1                                                           */
+  TIMER2_IRQn                   =  10,              /*!<  10  TIMER2                                                           */
+  RTC0_IRQn                     =  11,              /*!<  11  RTC0                                                             */
+  TEMP_IRQn                     =  12,              /*!<  12  TEMP                                                             */
+  RNG_IRQn                      =  13,              /*!<  13  RNG                                                              */
+  ECB_IRQn                      =  14,              /*!<  14  ECB                                                              */
+  CCM_AAR_IRQn                  =  15,              /*!<  15  CCM_AAR                                                          */
+  WDT_IRQn                      =  16,              /*!<  16  WDT                                                              */
+  RTC1_IRQn                     =  17,              /*!<  17  RTC1                                                             */
+  QDEC_IRQn                     =  18,              /*!<  18  QDEC                                                             */
+  LPCOMP_IRQn                   =  19,              /*!<  19  LPCOMP                                                           */
+  SWI0_IRQn                     =  20,              /*!<  20  SWI0                                                             */
+  SWI1_IRQn                     =  21,              /*!<  21  SWI1                                                             */
+  SWI2_IRQn                     =  22,              /*!<  22  SWI2                                                             */
+  SWI3_IRQn                     =  23,              /*!<  23  SWI3                                                             */
+  SWI4_IRQn                     =  24,              /*!<  24  SWI4                                                             */
+  SWI5_IRQn                     =  25               /*!<  25  SWI5                                                             */
+} IRQn_Type;
+
+
+/** @addtogroup Configuration_of_CMSIS
+  * @{
+  */
+
+
+/* ================================================================================ */
+/* ================      Processor and Core Peripheral Section     ================ */
+/* ================================================================================ */
+
+/* ----------------Configuration of the Cortex-M0 Processor and Core Peripherals---------------- */
+#define __CM0_REV                 0x0301            /*!< Cortex-M0 Core Revision                                               */
+#define __MPU_PRESENT                  0            /*!< MPU present or not                                                    */
+#define __NVIC_PRIO_BITS               2            /*!< Number of Bits used for Priority Levels                               */
+#define __Vendor_SysTickConfig         0            /*!< Set to 1 if different SysTick Config is used                          */
+/** @} */ /* End of group Configuration_of_CMSIS */
+
+#include "core_cm0.h"                               /*!< Cortex-M0 processor and core peripherals                              */
+#include "system_nrf51.h"                           /*!< nrf51 System                                                          */
+
+
+/* ================================================================================ */
+/* ================       Device Specific Peripheral Section       ================ */
+/* ================================================================================ */
+
+
+/** @addtogroup Device_Peripheral_Registers
+  * @{
+  */
+
+
+/* -------------------  Start of section using anonymous unions  ------------------ */
+#if defined(__CC_ARM)
+  #pragma push
+  #pragma anon_unions
+#elif defined(__ICCARM__)
+  #pragma language=extended
+#elif defined(__GNUC__)
+  /* anonymous unions are enabled by default */
+#elif defined(__TMS470__)
+/* anonymous unions are enabled by default */
+#elif defined(__TASKING__)
+  #pragma warning 586
+#else
+  #warning Not supported compiler type
+#endif
+
+
+typedef struct {
+  __IO uint32_t  CPU0;                              /*!< Configurable priority configuration register for CPU0.                */
+  __IO uint32_t  SPIS1;                             /*!< Configurable priority configuration register for SPIS1.               */
+  __IO uint32_t  RADIO;                             /*!< Configurable priority configuration register for RADIO.               */
+  __IO uint32_t  ECB;                               /*!< Configurable priority configuration register for ECB.                 */
+  __IO uint32_t  CCM;                               /*!< Configurable priority configuration register for CCM.                 */
+  __IO uint32_t  AAR;                               /*!< Configurable priority configuration register for AAR.                 */
+} AMLI_RAMPRI_Type;
+
+typedef struct {
+  __IO uint32_t  SCK;                               /*!< Pin select for SCK.                                                   */
+  __IO uint32_t  MOSI;                              /*!< Pin select for MOSI.                                                  */
+  __IO uint32_t  MISO;                              /*!< Pin select for MISO.                                                  */
+} SPIM_PSEL_Type;
+
+typedef struct {
+  __IO uint32_t  PTR;                               /*!< Data pointer.                                                         */
+  __IO uint32_t  MAXCNT;                            /*!< Maximum number of buffer bytes to receive.                            */
+  __I  uint32_t  AMOUNT;                            /*!< Number of bytes received in the last transaction.                     */
+} SPIM_RXD_Type;
+
+typedef struct {
+  __IO uint32_t  PTR;                               /*!< Data pointer.                                                         */
+  __IO uint32_t  MAXCNT;                            /*!< Maximum number of buffer bytes to send.                               */
+  __I  uint32_t  AMOUNT;                            /*!< Number of bytes sent in the last transaction.                         */
+} SPIM_TXD_Type;
+
+typedef struct {
+  __O  uint32_t  EN;                                /*!< Enable channel group.                                                 */
+  __O  uint32_t  DIS;                               /*!< Disable channel group.                                                */
+} PPI_TASKS_CHG_Type;
+
+typedef struct {
+  __IO uint32_t  EEP;                               /*!< Channel event end-point.                                              */
+  __IO uint32_t  TEP;                               /*!< Channel task end-point.                                               */
+} PPI_CH_Type;
+
+
+/* ================================================================================ */
+/* ================                      POWER                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Power Control. (POWER)
+  */
+
+typedef struct {                                    /*!< POWER Structure                                                       */
+  __I  uint32_t  RESERVED0[30];
+  __O  uint32_t  TASKS_CONSTLAT;                    /*!< Enable constant latency mode.                                         */
+  __O  uint32_t  TASKS_LOWPWR;                      /*!< Enable low power mode (variable latency).                             */
+  __I  uint32_t  RESERVED1[34];
+  __IO uint32_t  EVENTS_POFWARN;                    /*!< Power failure warning.                                                */
+  __I  uint32_t  RESERVED2[126];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[61];
+  __IO uint32_t  RESETREAS;                         /*!< Reset reason.                                                         */
+  __I  uint32_t  RESERVED4[9];
+  __I  uint32_t  RAMSTATUS;                         /*!< Ram status register.                                                  */
+  __I  uint32_t  RESERVED5[53];
+  __O  uint32_t  SYSTEMOFF;                         /*!< System off register.                                                  */
+  __I  uint32_t  RESERVED6[3];
+  __IO uint32_t  POFCON;                            /*!< Power failure configuration.                                          */
+  __I  uint32_t  RESERVED7[2];
+  __IO uint32_t  GPREGRET;                          /*!< General purpose retention register. This register is a retained
+                                                         register.                                                             */
+  __I  uint32_t  RESERVED8;
+  __IO uint32_t  RAMON;                             /*!< Ram on/off.                                                           */
+  __I  uint32_t  RESERVED9[7];
+  __IO uint32_t  RESET;                             /*!< Pin reset functionality configuration register. This register
+                                                         is a retained register.                                               */
+  __I  uint32_t  RESERVED10[3];
+  __IO uint32_t  RAMONB;                            /*!< Ram on/off.                                                           */
+  __I  uint32_t  RESERVED11[8];
+  __IO uint32_t  DCDCEN;                            /*!< DCDC converter enable configuration register.                         */
+  __I  uint32_t  RESERVED12[291];
+  __IO uint32_t  DCDCFORCE;                         /*!< DCDC power-up force register.                                         */
+} NRF_POWER_Type;
+
+
+/* ================================================================================ */
+/* ================                      CLOCK                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Clock control. (CLOCK)
+  */
+
+typedef struct {                                    /*!< CLOCK Structure                                                       */
+  __O  uint32_t  TASKS_HFCLKSTART;                  /*!< Start HFCLK clock source.                                             */
+  __O  uint32_t  TASKS_HFCLKSTOP;                   /*!< Stop HFCLK clock source.                                              */
+  __O  uint32_t  TASKS_LFCLKSTART;                  /*!< Start LFCLK clock source.                                             */
+  __O  uint32_t  TASKS_LFCLKSTOP;                   /*!< Stop LFCLK clock source.                                              */
+  __O  uint32_t  TASKS_CAL;                         /*!< Start calibration of LFCLK RC oscillator.                             */
+  __O  uint32_t  TASKS_CTSTART;                     /*!< Start calibration timer.                                              */
+  __O  uint32_t  TASKS_CTSTOP;                      /*!< Stop calibration timer.                                               */
+  __I  uint32_t  RESERVED0[57];
+  __IO uint32_t  EVENTS_HFCLKSTARTED;               /*!< HFCLK oscillator started.                                             */
+  __IO uint32_t  EVENTS_LFCLKSTARTED;               /*!< LFCLK oscillator started.                                             */
+  __I  uint32_t  RESERVED1;
+  __IO uint32_t  EVENTS_DONE;                       /*!< Calibration of LFCLK RC oscillator completed.                         */
+  __IO uint32_t  EVENTS_CTTO;                       /*!< Calibration timer timeout.                                            */
+  __I  uint32_t  RESERVED2[124];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[63];
+  __I  uint32_t  HFCLKRUN;                          /*!< Task HFCLKSTART trigger status.                                       */
+  __I  uint32_t  HFCLKSTAT;                         /*!< High frequency clock status.                                          */
+  __I  uint32_t  RESERVED4;
+  __I  uint32_t  LFCLKRUN;                          /*!< Task LFCLKSTART triggered status.                                     */
+  __I  uint32_t  LFCLKSTAT;                         /*!< Low frequency clock status.                                           */
+  __I  uint32_t  LFCLKSRCCOPY;                      /*!< Clock source for the LFCLK clock, set when task LKCLKSTART is
+                                                         triggered.                                                            */
+  __I  uint32_t  RESERVED5[62];
+  __IO uint32_t  LFCLKSRC;                          /*!< Clock source for the LFCLK clock.                                     */
+  __I  uint32_t  RESERVED6[7];
+  __IO uint32_t  CTIV;                              /*!< Calibration timer interval.                                           */
+  __I  uint32_t  RESERVED7[5];
+  __IO uint32_t  XTALFREQ;                          /*!< Crystal frequency.                                                    */
+} NRF_CLOCK_Type;
+
+
+/* ================================================================================ */
+/* ================                       MPU                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Memory Protection Unit. (MPU)
+  */
+
+typedef struct {                                    /*!< MPU Structure                                                         */
+  __I  uint32_t  RESERVED0[330];
+  __IO uint32_t  PERR0;                             /*!< Configuration of peripherals in mpu regions.                          */
+  __IO uint32_t  RLENR0;                            /*!< Length of RAM region 0.                                               */
+  __I  uint32_t  RESERVED1[52];
+  __IO uint32_t  PROTENSET0;                        /*!< Erase and write protection bit enable set register.                   */
+  __IO uint32_t  PROTENSET1;                        /*!< Erase and write protection bit enable set register.                   */
+  __IO uint32_t  DISABLEINDEBUG;                    /*!< Disable erase and write protection mechanism in debug mode.           */
+  __IO uint32_t  PROTBLOCKSIZE;                     /*!< Erase and write protection block size.                                */
+} NRF_MPU_Type;
+
+
+/* ================================================================================ */
+/* ================                      AMLI                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief AHB Multi-Layer Interface. (AMLI)
+  */
+
+typedef struct {                                    /*!< AMLI Structure                                                        */
+  __I  uint32_t  RESERVED0[896];
+  AMLI_RAMPRI_Type RAMPRI;                          /*!< RAM configurable priority configuration structure.                    */
+} NRF_AMLI_Type;
+
+
+/* ================================================================================ */
+/* ================                      RADIO                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief The radio. (RADIO)
+  */
+
+typedef struct {                                    /*!< RADIO Structure                                                       */
+  __O  uint32_t  TASKS_TXEN;                        /*!< Enable radio in TX mode.                                              */
+  __O  uint32_t  TASKS_RXEN;                        /*!< Enable radio in RX mode.                                              */
+  __O  uint32_t  TASKS_START;                       /*!< Start radio.                                                          */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop radio.                                                           */
+  __O  uint32_t  TASKS_DISABLE;                     /*!< Disable radio.                                                        */
+  __O  uint32_t  TASKS_RSSISTART;                   /*!< Start the RSSI and take one sample of the receive signal strength.    */
+  __O  uint32_t  TASKS_RSSISTOP;                    /*!< Stop the RSSI measurement.                                            */
+  __O  uint32_t  TASKS_BCSTART;                     /*!< Start the bit counter.                                                */
+  __O  uint32_t  TASKS_BCSTOP;                      /*!< Stop the bit counter.                                                 */
+  __I  uint32_t  RESERVED0[55];
+  __IO uint32_t  EVENTS_READY;                      /*!< Ready event.                                                          */
+  __IO uint32_t  EVENTS_ADDRESS;                    /*!< Address event.                                                        */
+  __IO uint32_t  EVENTS_PAYLOAD;                    /*!< Payload event.                                                        */
+  __IO uint32_t  EVENTS_END;                        /*!< End event.                                                            */
+  __IO uint32_t  EVENTS_DISABLED;                   /*!< Disable event.                                                        */
+  __IO uint32_t  EVENTS_DEVMATCH;                   /*!< A device address match occurred on the last received packet.          */
+  __IO uint32_t  EVENTS_DEVMISS;                    /*!< No device address match occurred on the last received packet.         */
+  __IO uint32_t  EVENTS_RSSIEND;                    /*!< Sampling of the receive signal strength complete. A new RSSI
+                                                         sample is ready for readout at the RSSISAMPLE register.               */
+  __I  uint32_t  RESERVED1[2];
+  __IO uint32_t  EVENTS_BCMATCH;                    /*!< Bit counter reached bit count value specified in BCC register.        */
+  __I  uint32_t  RESERVED2[53];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for the radio.                                              */
+  __I  uint32_t  RESERVED3[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED4[61];
+  __I  uint32_t  CRCSTATUS;                         /*!< CRC status of received packet.                                        */
+  __I  uint32_t  RESERVED5;
+  __I  uint32_t  RXMATCH;                           /*!< Received address.                                                     */
+  __I  uint32_t  RXCRC;                             /*!< Received CRC.                                                         */
+  __I  uint32_t  DAI;                               /*!< Device address match index.                                           */
+  __I  uint32_t  RESERVED6[60];
+  __IO uint32_t  PACKETPTR;                         /*!< Packet pointer. Decision point: START task.                           */
+  __IO uint32_t  FREQUENCY;                         /*!< Frequency.                                                            */
+  __IO uint32_t  TXPOWER;                           /*!< Output power.                                                         */
+  __IO uint32_t  MODE;                              /*!< Data rate and modulation.                                             */
+  __IO uint32_t  PCNF0;                             /*!< Packet configuration 0.                                               */
+  __IO uint32_t  PCNF1;                             /*!< Packet configuration 1.                                               */
+  __IO uint32_t  BASE0;                             /*!< Radio base address 0. Decision point: START task.                     */
+  __IO uint32_t  BASE1;                             /*!< Radio base address 1. Decision point: START task.                     */
+  __IO uint32_t  PREFIX0;                           /*!< Prefixes bytes for logical addresses 0 to 3.                          */
+  __IO uint32_t  PREFIX1;                           /*!< Prefixes bytes for logical addresses 4 to 7.                          */
+  __IO uint32_t  TXADDRESS;                         /*!< Transmit address select.                                              */
+  __IO uint32_t  RXADDRESSES;                       /*!< Receive address select.                                               */
+  __IO uint32_t  CRCCNF;                            /*!< CRC configuration.                                                    */
+  __IO uint32_t  CRCPOLY;                           /*!< CRC polynomial.                                                       */
+  __IO uint32_t  CRCINIT;                           /*!< CRC initial value.                                                    */
+  __IO uint32_t  TEST;                              /*!< Test features enable register.                                        */
+  __IO uint32_t  TIFS;                              /*!< Inter Frame Spacing in microseconds.                                  */
+  __I  uint32_t  RSSISAMPLE;                        /*!< RSSI sample.                                                          */
+  __I  uint32_t  RESERVED7;
+  __I  uint32_t  STATE;                             /*!< Current radio state.                                                  */
+  __IO uint32_t  DATAWHITEIV;                       /*!< Data whitening initial value.                                         */
+  __I  uint32_t  RESERVED8[2];
+  __IO uint32_t  BCC;                               /*!< Bit counter compare.                                                  */
+  __I  uint32_t  RESERVED9[39];
+  __IO uint32_t  DAB[8];                            /*!< Device address base segment.                                          */
+  __IO uint32_t  DAP[8];                            /*!< Device address prefix.                                                */
+  __IO uint32_t  DACNF;                             /*!< Device address match configuration.                                   */
+  __I  uint32_t  RESERVED10[56];
+  __IO uint32_t  OVERRIDE0;                         /*!< Trim value override register 0.                                       */
+  __IO uint32_t  OVERRIDE1;                         /*!< Trim value override register 1.                                       */
+  __IO uint32_t  OVERRIDE2;                         /*!< Trim value override register 2.                                       */
+  __IO uint32_t  OVERRIDE3;                         /*!< Trim value override register 3.                                       */
+  __IO uint32_t  OVERRIDE4;                         /*!< Trim value override register 4.                                       */
+  __I  uint32_t  RESERVED11[561];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_RADIO_Type;
+
+
+/* ================================================================================ */
+/* ================                      UART                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Universal Asynchronous Receiver/Transmitter. (UART)
+  */
+
+typedef struct {                                    /*!< UART Structure                                                        */
+  __O  uint32_t  TASKS_STARTRX;                     /*!< Start UART receiver.                                                  */
+  __O  uint32_t  TASKS_STOPRX;                      /*!< Stop UART receiver.                                                   */
+  __O  uint32_t  TASKS_STARTTX;                     /*!< Start UART transmitter.                                               */
+  __O  uint32_t  TASKS_STOPTX;                      /*!< Stop UART transmitter.                                                */
+  __I  uint32_t  RESERVED0[3];
+  __O  uint32_t  TASKS_SUSPEND;                     /*!< Suspend UART.                                                         */
+  __I  uint32_t  RESERVED1[56];
+  __IO uint32_t  EVENTS_CTS;                        /*!< CTS activated.                                                        */
+  __IO uint32_t  EVENTS_NCTS;                       /*!< CTS deactivated.                                                      */
+  __IO uint32_t  EVENTS_RXDRDY;                     /*!< Data received in RXD.                                                 */
+  __I  uint32_t  RESERVED2[4];
+  __IO uint32_t  EVENTS_TXDRDY;                     /*!< Data sent from TXD.                                                   */
+  __I  uint32_t  RESERVED3;
+  __IO uint32_t  EVENTS_ERROR;                      /*!< Error detected.                                                       */
+  __I  uint32_t  RESERVED4[7];
+  __IO uint32_t  EVENTS_RXTO;                       /*!< Receiver timeout.                                                     */
+  __I  uint32_t  RESERVED5[46];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for UART.                                                   */
+  __I  uint32_t  RESERVED6[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED7[93];
+  __IO uint32_t  ERRORSRC;                          /*!< Error source. Write error field to 1 to clear error.                  */
+  __I  uint32_t  RESERVED8[31];
+  __IO uint32_t  ENABLE;                            /*!< Enable UART and acquire IOs.                                          */
+  __I  uint32_t  RESERVED9;
+  __IO uint32_t  PSELRTS;                           /*!< Pin select for RTS.                                                   */
+  __IO uint32_t  PSELTXD;                           /*!< Pin select for TXD.                                                   */
+  __IO uint32_t  PSELCTS;                           /*!< Pin select for CTS.                                                   */
+  __IO uint32_t  PSELRXD;                           /*!< Pin select for RXD.                                                   */
+  __I  uint32_t  RXD;                               /*!< RXD register. On read action the buffer pointer is displaced.
+                                                         Once read the character is consumed. If read when no character
+                                                          available, the UART will stop working.                               */
+  __O  uint32_t  TXD;                               /*!< TXD register.                                                         */
+  __I  uint32_t  RESERVED10;
+  __IO uint32_t  BAUDRATE;                          /*!< UART Baudrate.                                                        */
+  __I  uint32_t  RESERVED11[17];
+  __IO uint32_t  CONFIG;                            /*!< Configuration of parity and hardware flow control register.           */
+  __I  uint32_t  RESERVED12[675];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_UART_Type;
+
+
+/* ================================================================================ */
+/* ================                       SPI                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief SPI master 0. (SPI)
+  */
+
+typedef struct {                                    /*!< SPI Structure                                                         */
+  __I  uint32_t  RESERVED0[66];
+  __IO uint32_t  EVENTS_READY;                      /*!< TXD byte sent and RXD byte received.                                  */
+  __I  uint32_t  RESERVED1[126];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED2[125];
+  __IO uint32_t  ENABLE;                            /*!< Enable SPI.                                                           */
+  __I  uint32_t  RESERVED3;
+  __IO uint32_t  PSELSCK;                           /*!< Pin select for SCK.                                                   */
+  __IO uint32_t  PSELMOSI;                          /*!< Pin select for MOSI.                                                  */
+  __IO uint32_t  PSELMISO;                          /*!< Pin select for MISO.                                                  */
+  __I  uint32_t  RESERVED4;
+  __I  uint32_t  RXD;                               /*!< RX data.                                                              */
+  __IO uint32_t  TXD;                               /*!< TX data.                                                              */
+  __I  uint32_t  RESERVED5;
+  __IO uint32_t  FREQUENCY;                         /*!< SPI frequency                                                         */
+  __I  uint32_t  RESERVED6[11];
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  __I  uint32_t  RESERVED7[681];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_SPI_Type;
+
+
+/* ================================================================================ */
+/* ================                       TWI                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Two-wire interface master 0. (TWI)
+  */
+
+typedef struct {                                    /*!< TWI Structure                                                         */
+  __O  uint32_t  TASKS_STARTRX;                     /*!< Start 2-Wire master receive sequence.                                 */
+  __I  uint32_t  RESERVED0;
+  __O  uint32_t  TASKS_STARTTX;                     /*!< Start 2-Wire master transmit sequence.                                */
+  __I  uint32_t  RESERVED1[2];
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop 2-Wire transaction.                                              */
+  __I  uint32_t  RESERVED2;
+  __O  uint32_t  TASKS_SUSPEND;                     /*!< Suspend 2-Wire transaction.                                           */
+  __O  uint32_t  TASKS_RESUME;                      /*!< Resume 2-Wire transaction.                                            */
+  __I  uint32_t  RESERVED3[56];
+  __IO uint32_t  EVENTS_STOPPED;                    /*!< Two-wire stopped.                                                     */
+  __IO uint32_t  EVENTS_RXDREADY;                   /*!< Two-wire ready to deliver new RXD byte received.                      */
+  __I  uint32_t  RESERVED4[4];
+  __IO uint32_t  EVENTS_TXDSENT;                    /*!< Two-wire finished sending last TXD byte.                              */
+  __I  uint32_t  RESERVED5;
+  __IO uint32_t  EVENTS_ERROR;                      /*!< Two-wire error detected.                                              */
+  __I  uint32_t  RESERVED6[4];
+  __IO uint32_t  EVENTS_BB;                         /*!< Two-wire byte boundary.                                               */
+  __I  uint32_t  RESERVED7[3];
+  __IO uint32_t  EVENTS_SUSPENDED;                  /*!< Two-wire suspended.                                                   */
+  __I  uint32_t  RESERVED8[45];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for TWI.                                                    */
+  __I  uint32_t  RESERVED9[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED10[110];
+  __IO uint32_t  ERRORSRC;                          /*!< Two-wire error source. Write error field to 1 to clear error.         */
+  __I  uint32_t  RESERVED11[14];
+  __IO uint32_t  ENABLE;                            /*!< Enable two-wire master.                                               */
+  __I  uint32_t  RESERVED12;
+  __IO uint32_t  PSELSCL;                           /*!< Pin select for SCL.                                                   */
+  __IO uint32_t  PSELSDA;                           /*!< Pin select for SDA.                                                   */
+  __I  uint32_t  RESERVED13[2];
+  __I  uint32_t  RXD;                               /*!< RX data register.                                                     */
+  __IO uint32_t  TXD;                               /*!< TX data register.                                                     */
+  __I  uint32_t  RESERVED14;
+  __IO uint32_t  FREQUENCY;                         /*!< Two-wire frequency.                                                   */
+  __I  uint32_t  RESERVED15[24];
+  __IO uint32_t  ADDRESS;                           /*!< Address used in the two-wire transfer.                                */
+  __I  uint32_t  RESERVED16[668];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_TWI_Type;
+
+
+/* ================================================================================ */
+/* ================                      SPIS                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief SPI slave 1. (SPIS)
+  */
+
+typedef struct {                                    /*!< SPIS Structure                                                        */
+  __I  uint32_t  RESERVED0[9];
+  __O  uint32_t  TASKS_ACQUIRE;                     /*!< Acquire SPI semaphore.                                                */
+  __O  uint32_t  TASKS_RELEASE;                     /*!< Release SPI semaphore.                                                */
+  __I  uint32_t  RESERVED1[54];
+  __IO uint32_t  EVENTS_END;                        /*!< Granted transaction completed.                                        */
+  __I  uint32_t  RESERVED2[2];
+  __IO uint32_t  EVENTS_ENDRX;                      /*!< End of RXD buffer reached                                             */
+  __I  uint32_t  RESERVED3[5];
+  __IO uint32_t  EVENTS_ACQUIRED;                   /*!< Semaphore acquired.                                                   */
+  __I  uint32_t  RESERVED4[53];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for SPIS.                                                   */
+  __I  uint32_t  RESERVED5[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED6[61];
+  __I  uint32_t  SEMSTAT;                           /*!< Semaphore status.                                                     */
+  __I  uint32_t  RESERVED7[15];
+  __IO uint32_t  STATUS;                            /*!< Status from last transaction.                                         */
+  __I  uint32_t  RESERVED8[47];
+  __IO uint32_t  ENABLE;                            /*!< Enable SPIS.                                                          */
+  __I  uint32_t  RESERVED9;
+  __IO uint32_t  PSELSCK;                           /*!< Pin select for SCK.                                                   */
+  __IO uint32_t  PSELMISO;                          /*!< Pin select for MISO.                                                  */
+  __IO uint32_t  PSELMOSI;                          /*!< Pin select for MOSI.                                                  */
+  __IO uint32_t  PSELCSN;                           /*!< Pin select for CSN.                                                   */
+  __I  uint32_t  RESERVED10[7];
+  __IO uint32_t  RXDPTR;                            /*!< RX data pointer.                                                      */
+  __IO uint32_t  MAXRX;                             /*!< Maximum number of bytes in the receive buffer.                        */
+  __I  uint32_t  AMOUNTRX;                          /*!< Number of bytes received in last granted transaction.                 */
+  __I  uint32_t  RESERVED11;
+  __IO uint32_t  TXDPTR;                            /*!< TX data pointer.                                                      */
+  __IO uint32_t  MAXTX;                             /*!< Maximum number of bytes in the transmit buffer.                       */
+  __I  uint32_t  AMOUNTTX;                          /*!< Number of bytes transmitted in last granted transaction.              */
+  __I  uint32_t  RESERVED12;
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  __I  uint32_t  RESERVED13;
+  __IO uint32_t  DEF;                               /*!< Default character.                                                    */
+  __I  uint32_t  RESERVED14[24];
+  __IO uint32_t  ORC;                               /*!< Over-read character.                                                  */
+  __I  uint32_t  RESERVED15[654];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_SPIS_Type;
+
+
+/* ================================================================================ */
+/* ================                      SPIM                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief SPI master with easyDMA 1. (SPIM)
+  */
+
+typedef struct {                                    /*!< SPIM Structure                                                        */
+  __I  uint32_t  RESERVED0[4];
+  __O  uint32_t  TASKS_START;                       /*!< Start SPI transaction.                                                */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop SPI transaction.                                                 */
+  __I  uint32_t  RESERVED1;
+  __O  uint32_t  TASKS_SUSPEND;                     /*!< Suspend SPI transaction.                                              */
+  __O  uint32_t  TASKS_RESUME;                      /*!< Resume SPI transaction.                                               */
+  __I  uint32_t  RESERVED2[56];
+  __IO uint32_t  EVENTS_STOPPED;                    /*!< SPI transaction has stopped.                                          */
+  __I  uint32_t  RESERVED3[2];
+  __IO uint32_t  EVENTS_ENDRX;                      /*!< End of RXD buffer reached.                                            */
+  __I  uint32_t  RESERVED4[3];
+  __IO uint32_t  EVENTS_ENDTX;                      /*!< End of TXD buffer reached.                                            */
+  __I  uint32_t  RESERVED5[10];
+  __IO uint32_t  EVENTS_STARTED;                    /*!< Transaction started.                                                  */
+  __I  uint32_t  RESERVED6[109];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED7[125];
+  __IO uint32_t  ENABLE;                            /*!< Enable SPIM.                                                          */
+  __I  uint32_t  RESERVED8;
+  SPIM_PSEL_Type PSEL;                              /*!< Pin select configuration.                                             */
+  __I  uint32_t  RESERVED9[4];
+  __IO uint32_t  FREQUENCY;                         /*!< SPI frequency.                                                        */
+  __I  uint32_t  RESERVED10[3];
+  SPIM_RXD_Type RXD;                                /*!< RXD EasyDMA configuration and status.                                 */
+  __I  uint32_t  RESERVED11;
+  SPIM_TXD_Type TXD;                                /*!< TXD EasyDMA configuration and status.                                 */
+  __I  uint32_t  RESERVED12;
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  __I  uint32_t  RESERVED13[26];
+  __IO uint32_t  ORC;                               /*!< Over-read character.                                                  */
+  __I  uint32_t  RESERVED14[654];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_SPIM_Type;
+
+
+/* ================================================================================ */
+/* ================                     GPIOTE                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief GPIO tasks and events. (GPIOTE)
+  */
+
+typedef struct {                                    /*!< GPIOTE Structure                                                      */
+  __O  uint32_t  TASKS_OUT[4];                      /*!< Tasks asssociated with GPIOTE channels.                               */
+  __I  uint32_t  RESERVED0[60];
+  __IO uint32_t  EVENTS_IN[4];                      /*!< Tasks asssociated with GPIOTE channels.                               */
+  __I  uint32_t  RESERVED1[27];
+  __IO uint32_t  EVENTS_PORT;                       /*!< Event generated from multiple pins.                                   */
+  __I  uint32_t  RESERVED2[97];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[129];
+  __IO uint32_t  CONFIG[4];                         /*!< Channel configuration registers.                                      */
+  __I  uint32_t  RESERVED4[695];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_GPIOTE_Type;
+
+
+/* ================================================================================ */
+/* ================                       ADC                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Analog to digital converter. (ADC)
+  */
+
+typedef struct {                                    /*!< ADC Structure                                                         */
+  __O  uint32_t  TASKS_START;                       /*!< Start an ADC conversion.                                              */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop ADC.                                                             */
+  __I  uint32_t  RESERVED0[62];
+  __IO uint32_t  EVENTS_END;                        /*!< ADC conversion complete.                                              */
+  __I  uint32_t  RESERVED1[128];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED2[61];
+  __I  uint32_t  BUSY;                              /*!< ADC busy register.                                                    */
+  __I  uint32_t  RESERVED3[63];
+  __IO uint32_t  ENABLE;                            /*!< ADC enable.                                                           */
+  __IO uint32_t  CONFIG;                            /*!< ADC configuration register.                                           */
+  __I  uint32_t  RESULT;                            /*!< Result of ADC conversion.                                             */
+  __I  uint32_t  RESERVED4[700];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_ADC_Type;
+
+
+/* ================================================================================ */
+/* ================                      TIMER                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Timer 0. (TIMER)
+  */
+
+typedef struct {                                    /*!< TIMER Structure                                                       */
+  __O  uint32_t  TASKS_START;                       /*!< Start Timer.                                                          */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop Timer.                                                           */
+  __O  uint32_t  TASKS_COUNT;                       /*!< Increment Timer (In counter mode).                                    */
+  __O  uint32_t  TASKS_CLEAR;                       /*!< Clear timer.                                                          */
+  __O  uint32_t  TASKS_SHUTDOWN;                    /*!< Shutdown timer.                                                       */
+  __I  uint32_t  RESERVED0[11];
+  __O  uint32_t  TASKS_CAPTURE[4];                  /*!< Capture Timer value to CC[n] registers.                               */
+  __I  uint32_t  RESERVED1[60];
+  __IO uint32_t  EVENTS_COMPARE[4];                 /*!< Compare event on CC[n] match.                                         */
+  __I  uint32_t  RESERVED2[44];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for Timer.                                                  */
+  __I  uint32_t  RESERVED3[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED4[126];
+  __IO uint32_t  MODE;                              /*!< Timer Mode selection.                                                 */
+  __IO uint32_t  BITMODE;                           /*!< Sets timer behaviour.                                                 */
+  __I  uint32_t  RESERVED5;
+  __IO uint32_t  PRESCALER;                         /*!< 4-bit prescaler to source clock frequency (max value 9). Source
+                                                         clock frequency is divided by 2^SCALE.                                */
+  __I  uint32_t  RESERVED6[11];
+  __IO uint32_t  CC[4];                             /*!< Capture/compare registers.                                            */
+  __I  uint32_t  RESERVED7[683];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_TIMER_Type;
+
+
+/* ================================================================================ */
+/* ================                       RTC                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Real time counter 0. (RTC)
+  */
+
+typedef struct {                                    /*!< RTC Structure                                                         */
+  __O  uint32_t  TASKS_START;                       /*!< Start RTC Counter.                                                    */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop RTC Counter.                                                     */
+  __O  uint32_t  TASKS_CLEAR;                       /*!< Clear RTC Counter.                                                    */
+  __O  uint32_t  TASKS_TRIGOVRFLW;                  /*!< Set COUNTER to 0xFFFFFFF0.                                            */
+  __I  uint32_t  RESERVED0[60];
+  __IO uint32_t  EVENTS_TICK;                       /*!< Event on COUNTER increment.                                           */
+  __IO uint32_t  EVENTS_OVRFLW;                     /*!< Event on COUNTER overflow.                                            */
+  __I  uint32_t  RESERVED1[14];
+  __IO uint32_t  EVENTS_COMPARE[4];                 /*!< Compare event on CC[n] match.                                         */
+  __I  uint32_t  RESERVED2[109];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[13];
+  __IO uint32_t  EVTEN;                             /*!< Configures event enable routing to PPI for each RTC event.            */
+  __IO uint32_t  EVTENSET;                          /*!< Enable events routing to PPI. The reading of this register gives
+                                                         the value of EVTEN.                                                   */
+  __IO uint32_t  EVTENCLR;                          /*!< Disable events routing to PPI. The reading of this register
+                                                         gives the value of EVTEN.                                             */
+  __I  uint32_t  RESERVED4[110];
+  __I  uint32_t  COUNTER;                           /*!< Current COUNTER value.                                                */
+  __IO uint32_t  PRESCALER;                         /*!< 12-bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).
+                                                         Must be written when RTC is STOPed.                                   */
+  __I  uint32_t  RESERVED5[13];
+  __IO uint32_t  CC[4];                             /*!< Capture/compare registers.                                            */
+  __I  uint32_t  RESERVED6[683];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_RTC_Type;
+
+
+/* ================================================================================ */
+/* ================                      TEMP                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Temperature Sensor. (TEMP)
+  */
+
+typedef struct {                                    /*!< TEMP Structure                                                        */
+  __O  uint32_t  TASKS_START;                       /*!< Start temperature measurement.                                        */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop temperature measurement.                                         */
+  __I  uint32_t  RESERVED0[62];
+  __IO uint32_t  EVENTS_DATARDY;                    /*!< Temperature measurement complete, data ready event.                   */
+  __I  uint32_t  RESERVED1[128];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED2[127];
+  __I  int32_t   TEMP;                              /*!< Die temperature in degC, 2's complement format, 0.25 degC pecision.   */
+  __I  uint32_t  RESERVED3[700];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_TEMP_Type;
+
+
+/* ================================================================================ */
+/* ================                       RNG                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Random Number Generator. (RNG)
+  */
+
+typedef struct {                                    /*!< RNG Structure                                                         */
+  __O  uint32_t  TASKS_START;                       /*!< Start the random number generator.                                    */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop the random number generator.                                     */
+  __I  uint32_t  RESERVED0[62];
+  __IO uint32_t  EVENTS_VALRDY;                     /*!< New random number generated and written to VALUE register.            */
+  __I  uint32_t  RESERVED1[63];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for the RNG.                                                */
+  __I  uint32_t  RESERVED2[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register                                         */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register                                       */
+  __I  uint32_t  RESERVED3[126];
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  __I  uint32_t  VALUE;                             /*!< RNG random number.                                                    */
+  __I  uint32_t  RESERVED4[700];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_RNG_Type;
+
+
+/* ================================================================================ */
+/* ================                       ECB                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief AES ECB Mode Encryption. (ECB)
+  */
+
+typedef struct {                                    /*!< ECB Structure                                                         */
+  __O  uint32_t  TASKS_STARTECB;                    /*!< Start ECB block encrypt. If a crypto operation is running, this
+                                                         will not initiate a new encryption and the ERRORECB event will
+                                                          be triggered.                                                        */
+  __O  uint32_t  TASKS_STOPECB;                     /*!< Stop current ECB encryption. If a crypto operation is running,
+                                                         this will will trigger the ERRORECB event.                            */
+  __I  uint32_t  RESERVED0[62];
+  __IO uint32_t  EVENTS_ENDECB;                     /*!< ECB block encrypt complete.                                           */
+  __IO uint32_t  EVENTS_ERRORECB;                   /*!< ECB block encrypt aborted due to a STOPECB task or due to an
+                                                         error.                                                                */
+  __I  uint32_t  RESERVED1[127];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED2[126];
+  __IO uint32_t  ECBDATAPTR;                        /*!< ECB block encrypt memory pointer.                                     */
+  __I  uint32_t  RESERVED3[701];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_ECB_Type;
+
+
+/* ================================================================================ */
+/* ================                       AAR                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Accelerated Address Resolver. (AAR)
+  */
+
+typedef struct {                                    /*!< AAR Structure                                                         */
+  __O  uint32_t  TASKS_START;                       /*!< Start resolving addresses based on IRKs specified in the IRK
+                                                         data structure.                                                       */
+  __I  uint32_t  RESERVED0;
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop resolving addresses.                                             */
+  __I  uint32_t  RESERVED1[61];
+  __IO uint32_t  EVENTS_END;                        /*!< Address resolution procedure completed.                               */
+  __IO uint32_t  EVENTS_RESOLVED;                   /*!< Address resolved.                                                     */
+  __IO uint32_t  EVENTS_NOTRESOLVED;                /*!< Address not resolved.                                                 */
+  __I  uint32_t  RESERVED2[126];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[61];
+  __I  uint32_t  STATUS;                            /*!< Resolution status.                                                    */
+  __I  uint32_t  RESERVED4[63];
+  __IO uint32_t  ENABLE;                            /*!< Enable AAR.                                                           */
+  __IO uint32_t  NIRK;                              /*!< Number of Identity root Keys in the IRK data structure.               */
+  __IO uint32_t  IRKPTR;                            /*!< Pointer to the IRK data structure.                                    */
+  __I  uint32_t  RESERVED5;
+  __IO uint32_t  ADDRPTR;                           /*!< Pointer to the resolvable address (6 bytes).                          */
+  __IO uint32_t  SCRATCHPTR;                        /*!< Pointer to a "scratch" data area used for temporary storage
+                                                         during resolution. A minimum of 3 bytes must be reserved.             */
+  __I  uint32_t  RESERVED6[697];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_AAR_Type;
+
+
+/* ================================================================================ */
+/* ================                       CCM                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief AES CCM Mode Encryption. (CCM)
+  */
+
+typedef struct {                                    /*!< CCM Structure                                                         */
+  __O  uint32_t  TASKS_KSGEN;                       /*!< Start generation of key-stream. This operation will stop by
+                                                         itself when completed.                                                */
+  __O  uint32_t  TASKS_CRYPT;                       /*!< Start encrypt/decrypt. This operation will stop by itself when
+                                                         completed.                                                            */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop encrypt/decrypt.                                                 */
+  __I  uint32_t  RESERVED0[61];
+  __IO uint32_t  EVENTS_ENDKSGEN;                   /*!< Keystream generation completed.                                       */
+  __IO uint32_t  EVENTS_ENDCRYPT;                   /*!< Encrypt/decrypt completed.                                            */
+  __IO uint32_t  EVENTS_ERROR;                      /*!< Error happened.                                                       */
+  __I  uint32_t  RESERVED1[61];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for the CCM.                                                */
+  __I  uint32_t  RESERVED2[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[61];
+  __I  uint32_t  MICSTATUS;                         /*!< CCM RX MIC check result.                                              */
+  __I  uint32_t  RESERVED4[63];
+  __IO uint32_t  ENABLE;                            /*!< CCM enable.                                                           */
+  __IO uint32_t  MODE;                              /*!< Operation mode.                                                       */
+  __IO uint32_t  CNFPTR;                            /*!< Pointer to a data structure holding AES key and NONCE vector.         */
+  __IO uint32_t  INPTR;                             /*!< Pointer to the input packet.                                          */
+  __IO uint32_t  OUTPTR;                            /*!< Pointer to the output packet.                                         */
+  __IO uint32_t  SCRATCHPTR;                        /*!< Pointer to a "scratch" data area used for temporary storage
+                                                         during resolution. A minimum of 43 bytes must be reserved.            */
+  __I  uint32_t  RESERVED5[697];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_CCM_Type;
+
+
+/* ================================================================================ */
+/* ================                       WDT                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Watchdog Timer. (WDT)
+  */
+
+typedef struct {                                    /*!< WDT Structure                                                         */
+  __O  uint32_t  TASKS_START;                       /*!< Start the watchdog.                                                   */
+  __I  uint32_t  RESERVED0[63];
+  __IO uint32_t  EVENTS_TIMEOUT;                    /*!< Watchdog timeout.                                                     */
+  __I  uint32_t  RESERVED1[128];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED2[61];
+  __I  uint32_t  RUNSTATUS;                         /*!< Watchdog running status.                                              */
+  __I  uint32_t  REQSTATUS;                         /*!< Request status.                                                       */
+  __I  uint32_t  RESERVED3[63];
+  __IO uint32_t  CRV;                               /*!< Counter reload value in number of 32kiHz clock cycles.                */
+  __IO uint32_t  RREN;                              /*!< Reload request enable.                                                */
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  __I  uint32_t  RESERVED4[60];
+  __O  uint32_t  RR[8];                             /*!< Reload requests registers.                                            */
+  __I  uint32_t  RESERVED5[631];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_WDT_Type;
+
+
+/* ================================================================================ */
+/* ================                      QDEC                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Rotary decoder. (QDEC)
+  */
+
+typedef struct {                                    /*!< QDEC Structure                                                        */
+  __O  uint32_t  TASKS_START;                       /*!< Start the quadrature decoder.                                         */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop the quadrature decoder.                                          */
+  __O  uint32_t  TASKS_READCLRACC;                  /*!< Transfers the content from ACC registers to ACCREAD registers,
+                                                         and clears the ACC registers.                                         */
+  __I  uint32_t  RESERVED0[61];
+  __IO uint32_t  EVENTS_SAMPLERDY;                  /*!< A new sample is written to the sample register.                       */
+  __IO uint32_t  EVENTS_REPORTRDY;                  /*!< REPORTPER number of samples accumulated in ACC register, and
+                                                         ACC register different than zero.                                     */
+  __IO uint32_t  EVENTS_ACCOF;                      /*!< ACC or ACCDBL register overflow.                                      */
+  __I  uint32_t  RESERVED1[61];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for the QDEC.                                               */
+  __I  uint32_t  RESERVED2[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[125];
+  __IO uint32_t  ENABLE;                            /*!< Enable the QDEC.                                                      */
+  __IO uint32_t  LEDPOL;                            /*!< LED output pin polarity.                                              */
+  __IO uint32_t  SAMPLEPER;                         /*!< Sample period.                                                        */
+  __I  int32_t   SAMPLE;                            /*!< Motion sample value.                                                  */
+  __IO uint32_t  REPORTPER;                         /*!< Number of samples to generate an EVENT_REPORTRDY.                     */
+  __I  int32_t   ACC;                               /*!< Accumulated valid transitions register.                               */
+  __I  int32_t   ACCREAD;                           /*!< Snapshot of ACC register. Value generated by the TASKS_READCLEACC
+                                                         task.                                                                 */
+  __IO uint32_t  PSELLED;                           /*!< Pin select for LED output.                                            */
+  __IO uint32_t  PSELA;                             /*!< Pin select for phase A input.                                         */
+  __IO uint32_t  PSELB;                             /*!< Pin select for phase B input.                                         */
+  __IO uint32_t  DBFEN;                             /*!< Enable debouncer input filters.                                       */
+  __I  uint32_t  RESERVED4[5];
+  __IO uint32_t  LEDPRE;                            /*!< Time LED is switched ON before the sample.                            */
+  __I  uint32_t  ACCDBL;                            /*!< Accumulated double (error) transitions register.                      */
+  __I  uint32_t  ACCDBLREAD;                        /*!< Snapshot of ACCDBL register. Value generated by the TASKS_READCLEACC
+                                                         task.                                                                 */
+  __I  uint32_t  RESERVED5[684];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_QDEC_Type;
+
+
+/* ================================================================================ */
+/* ================                     LPCOMP                     ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Low power comparator. (LPCOMP)
+  */
+
+typedef struct {                                    /*!< LPCOMP Structure                                                      */
+  __O  uint32_t  TASKS_START;                       /*!< Start the comparator.                                                 */
+  __O  uint32_t  TASKS_STOP;                        /*!< Stop the comparator.                                                  */
+  __O  uint32_t  TASKS_SAMPLE;                      /*!< Sample comparator value.                                              */
+  __I  uint32_t  RESERVED0[61];
+  __IO uint32_t  EVENTS_READY;                      /*!< LPCOMP is ready and output is valid.                                  */
+  __IO uint32_t  EVENTS_DOWN;                       /*!< Input voltage crossed the threshold going down.                       */
+  __IO uint32_t  EVENTS_UP;                         /*!< Input voltage crossed the threshold going up.                         */
+  __IO uint32_t  EVENTS_CROSS;                      /*!< Input voltage crossed the threshold in any direction.                 */
+  __I  uint32_t  RESERVED1[60];
+  __IO uint32_t  SHORTS;                            /*!< Shortcuts for the LPCOMP.                                             */
+  __I  uint32_t  RESERVED2[64];
+  __IO uint32_t  INTENSET;                          /*!< Interrupt enable set register.                                        */
+  __IO uint32_t  INTENCLR;                          /*!< Interrupt enable clear register.                                      */
+  __I  uint32_t  RESERVED3[61];
+  __I  uint32_t  RESULT;                            /*!< Result of last compare.                                               */
+  __I  uint32_t  RESERVED4[63];
+  __IO uint32_t  ENABLE;                            /*!< Enable the LPCOMP.                                                    */
+  __IO uint32_t  PSEL;                              /*!< Input pin select.                                                     */
+  __IO uint32_t  REFSEL;                            /*!< Reference select.                                                     */
+  __IO uint32_t  EXTREFSEL;                         /*!< External reference select.                                            */
+  __I  uint32_t  RESERVED5[4];
+  __IO uint32_t  ANADETECT;                         /*!< Analog detect configuration.                                          */
+  __I  uint32_t  RESERVED6[694];
+  __IO uint32_t  POWER;                             /*!< Peripheral power control.                                             */
+} NRF_LPCOMP_Type;
+
+
+/* ================================================================================ */
+/* ================                       SWI                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief SW Interrupts. (SWI)
+  */
+
+typedef struct {                                    /*!< SWI Structure                                                         */
+  __I  uint32_t  UNUSED;                            /*!< Unused.                                                               */
+} NRF_SWI_Type;
+
+
+/* ================================================================================ */
+/* ================                      NVMC                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Non Volatile Memory Controller. (NVMC)
+  */
+
+typedef struct {                                    /*!< NVMC Structure                                                        */
+  __I  uint32_t  RESERVED0[256];
+  __I  uint32_t  READY;                             /*!< Ready flag.                                                           */
+  __I  uint32_t  RESERVED1[64];
+  __IO uint32_t  CONFIG;                            /*!< Configuration register.                                               */
+  
+  union {
+    __IO uint32_t  ERASEPCR1;                       /*!< Register for erasing a non-protected non-volatile memory page.        */
+    __IO uint32_t  ERASEPAGE;                       /*!< Register for erasing a non-protected non-volatile memory page.        */
+  };
+  __IO uint32_t  ERASEALL;                          /*!< Register for erasing all non-volatile user memory.                    */
+  __IO uint32_t  ERASEPCR0;                         /*!< Register for erasing a protected non-volatile memory page.            */
+  __IO uint32_t  ERASEUICR;                         /*!< Register for start erasing User Information Congfiguration Registers. */
+} NRF_NVMC_Type;
+
+
+/* ================================================================================ */
+/* ================                       PPI                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief PPI controller. (PPI)
+  */
+
+typedef struct {                                    /*!< PPI Structure                                                         */
+  PPI_TASKS_CHG_Type TASKS_CHG[4];                  /*!< Channel group tasks.                                                  */
+  __I  uint32_t  RESERVED0[312];
+  __IO uint32_t  CHEN;                              /*!< Channel enable.                                                       */
+  __IO uint32_t  CHENSET;                           /*!< Channel enable set.                                                   */
+  __IO uint32_t  CHENCLR;                           /*!< Channel enable clear.                                                 */
+  __I  uint32_t  RESERVED1;
+  PPI_CH_Type CH[16];                               /*!< PPI Channel.                                                          */
+  __I  uint32_t  RESERVED2[156];
+  __IO uint32_t  CHG[4];                            /*!< Channel group configuration.                                          */
+} NRF_PPI_Type;
+
+
+/* ================================================================================ */
+/* ================                      FICR                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief Factory Information Configuration. (FICR)
+  */
+
+typedef struct {                                    /*!< FICR Structure                                                        */
+  __I  uint32_t  RESERVED0[4];
+  __I  uint32_t  CODEPAGESIZE;                      /*!< Code memory page size in bytes.                                       */
+  __I  uint32_t  CODESIZE;                          /*!< Code memory size in pages.                                            */
+  __I  uint32_t  RESERVED1[4];
+  __I  uint32_t  CLENR0;                            /*!< Length of code region 0 in bytes.                                     */
+  __I  uint32_t  PPFC;                              /*!< Pre-programmed factory code present.                                  */
+  __I  uint32_t  RESERVED2;
+  __I  uint32_t  NUMRAMBLOCK;                       /*!< Number of individualy controllable RAM blocks.                        */
+  
+  union {
+    __I  uint32_t  SIZERAMBLOCK[4];                 /*!< Deprecated array of size of RAM block in bytes. This name is
+                                                         kept for backward compatinility purposes. Use SIZERAMBLOCKS
+                                                          instead.                                                             */
+    __I  uint32_t  SIZERAMBLOCKS;                   /*!< Size of RAM blocks in bytes.                                          */
+  };
+  __I  uint32_t  RESERVED3[5];
+  __I  uint32_t  CONFIGID;                          /*!< Configuration identifier.                                             */
+  __I  uint32_t  DEVICEID[2];                       /*!< Device identifier.                                                    */
+  __I  uint32_t  RESERVED4[6];
+  __I  uint32_t  ER[4];                             /*!< Encryption root.                                                      */
+  __I  uint32_t  IR[4];                             /*!< Identity root.                                                        */
+  __I  uint32_t  DEVICEADDRTYPE;                    /*!< Device address type.                                                  */
+  __I  uint32_t  DEVICEADDR[2];                     /*!< Device address.                                                       */
+  __I  uint32_t  OVERRIDEEN;                        /*!< Radio calibration override enable.                                    */
+  __I  uint32_t  NRF_1MBIT[5];                      /*!< Override values for the OVERRIDEn registers in RADIO for NRF_1Mbit
+                                                         mode.                                                                 */
+  __I  uint32_t  RESERVED5[10];
+  __I  uint32_t  BLE_1MBIT[5];                      /*!< Override values for the OVERRIDEn registers in RADIO for BLE_1Mbit
+                                                         mode.                                                                 */
+} NRF_FICR_Type;
+
+
+/* ================================================================================ */
+/* ================                      UICR                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief User Information Configuration. (UICR)
+  */
+
+typedef struct {                                    /*!< UICR Structure                                                        */
+  __IO uint32_t  CLENR0;                            /*!< Length of code region 0.                                              */
+  __IO uint32_t  RBPCONF;                           /*!< Readback protection configuration.                                    */
+  __IO uint32_t  XTALFREQ;                          /*!< Reset value for CLOCK XTALFREQ register.                              */
+  __I  uint32_t  RESERVED0;
+  __I  uint32_t  FWID;                              /*!< Firmware ID.                                                          */
+  
+  union {
+    __IO uint32_t  NRFFW[15];                       /*!< Reserved for Nordic firmware design.                                  */
+    __IO uint32_t  BOOTLOADERADDR;                  /*!< Bootloader start address.                                             */
+  };
+  __IO uint32_t  NRFHW[12];                         /*!< Reserved for Nordic hardware design.                                  */
+  __IO uint32_t  CUSTOMER[32];                      /*!< Reserved for customer.                                                */
+} NRF_UICR_Type;
+
+
+/* ================================================================================ */
+/* ================                      GPIO                      ================ */
+/* ================================================================================ */
+
+
+/**
+  * @brief General purpose input and output. (GPIO)
+  */
+
+typedef struct {                                    /*!< GPIO Structure                                                        */
+  __I  uint32_t  RESERVED0[321];
+  __IO uint32_t  OUT;                               /*!< Write GPIO port.                                                      */
+  __IO uint32_t  OUTSET;                            /*!< Set individual bits in GPIO port.                                     */
+  __IO uint32_t  OUTCLR;                            /*!< Clear individual bits in GPIO port.                                   */
+  __I  uint32_t  IN;                                /*!< Read GPIO port.                                                       */
+  __IO uint32_t  DIR;                               /*!< Direction of GPIO pins.                                               */
+  __IO uint32_t  DIRSET;                            /*!< DIR set register.                                                     */
+  __IO uint32_t  DIRCLR;                            /*!< DIR clear register.                                                   */
+  __I  uint32_t  RESERVED1[120];
+  __IO uint32_t  PIN_CNF[32];                       /*!< Configuration of GPIO pins.                                           */
+} NRF_GPIO_Type;
+
+
+/* --------------------  End of section using anonymous unions  ------------------- */
+#if defined(__CC_ARM)
+  #pragma pop
+#elif defined(__ICCARM__)
+  /* leave anonymous unions enabled */
+#elif defined(__GNUC__)
+  /* anonymous unions are enabled by default */
+#elif defined(__TMS470__)
+  /* anonymous unions are enabled by default */
+#elif defined(__TASKING__)
+  #pragma warning restore
+#else
+  #warning Not supported compiler type
+#endif
+
+
+
+
+/* ================================================================================ */
+/* ================              Peripheral memory map             ================ */
+/* ================================================================================ */
+
+#define NRF_POWER_BASE                  0x40000000UL
+#define NRF_CLOCK_BASE                  0x40000000UL
+#define NRF_MPU_BASE                    0x40000000UL
+#define NRF_AMLI_BASE                   0x40000000UL
+#define NRF_RADIO_BASE                  0x40001000UL
+#define NRF_UART0_BASE                  0x40002000UL
+#define NRF_SPI0_BASE                   0x40003000UL
+#define NRF_TWI0_BASE                   0x40003000UL
+#define NRF_SPI1_BASE                   0x40004000UL
+#define NRF_TWI1_BASE                   0x40004000UL
+#define NRF_SPIS1_BASE                  0x40004000UL
+#define NRF_SPIM1_BASE                  0x40004000UL
+#define NRF_GPIOTE_BASE                 0x40006000UL
+#define NRF_ADC_BASE                    0x40007000UL
+#define NRF_TIMER0_BASE                 0x40008000UL
+#define NRF_TIMER1_BASE                 0x40009000UL
+#define NRF_TIMER2_BASE                 0x4000A000UL
+#define NRF_RTC0_BASE                   0x4000B000UL
+#define NRF_TEMP_BASE                   0x4000C000UL
+#define NRF_RNG_BASE                    0x4000D000UL
+#define NRF_ECB_BASE                    0x4000E000UL
+#define NRF_AAR_BASE                    0x4000F000UL
+#define NRF_CCM_BASE                    0x4000F000UL
+#define NRF_WDT_BASE                    0x40010000UL
+#define NRF_RTC1_BASE                   0x40011000UL
+#define NRF_QDEC_BASE                   0x40012000UL
+#define NRF_LPCOMP_BASE                 0x40013000UL
+#define NRF_SWI_BASE                    0x40014000UL
+#define NRF_NVMC_BASE                   0x4001E000UL
+#define NRF_PPI_BASE                    0x4001F000UL
+#define NRF_FICR_BASE                   0x10000000UL
+#define NRF_UICR_BASE                   0x10001000UL
+#define NRF_GPIO_BASE                   0x50000000UL
+
+
+/* ================================================================================ */
+/* ================             Peripheral declaration             ================ */
+/* ================================================================================ */
+
+#define NRF_POWER                       ((NRF_POWER_Type          *) NRF_POWER_BASE)
+#define NRF_CLOCK                       ((NRF_CLOCK_Type          *) NRF_CLOCK_BASE)
+#define NRF_MPU                         ((NRF_MPU_Type            *) NRF_MPU_BASE)
+#define NRF_AMLI                        ((NRF_AMLI_Type           *) NRF_AMLI_BASE)
+#define NRF_RADIO                       ((NRF_RADIO_Type          *) NRF_RADIO_BASE)
+#define NRF_UART0                       ((NRF_UART_Type           *) NRF_UART0_BASE)
+#define NRF_SPI0                        ((NRF_SPI_Type            *) NRF_SPI0_BASE)
+#define NRF_TWI0                        ((NRF_TWI_Type            *) NRF_TWI0_BASE)
+#define NRF_SPI1                        ((NRF_SPI_Type            *) NRF_SPI1_BASE)
+#define NRF_TWI1                        ((NRF_TWI_Type            *) NRF_TWI1_BASE)
+#define NRF_SPIS1                       ((NRF_SPIS_Type           *) NRF_SPIS1_BASE)
+#define NRF_SPIM1                       ((NRF_SPIM_Type           *) NRF_SPIM1_BASE)
+#define NRF_GPIOTE                      ((NRF_GPIOTE_Type         *) NRF_GPIOTE_BASE)
+#define NRF_ADC                         ((NRF_ADC_Type            *) NRF_ADC_BASE)
+#define NRF_TIMER0                      ((NRF_TIMER_Type          *) NRF_TIMER0_BASE)
+#define NRF_TIMER1                      ((NRF_TIMER_Type          *) NRF_TIMER1_BASE)
+#define NRF_TIMER2                      ((NRF_TIMER_Type          *) NRF_TIMER2_BASE)
+#define NRF_RTC0                        ((NRF_RTC_Type            *) NRF_RTC0_BASE)
+#define NRF_TEMP                        ((NRF_TEMP_Type           *) NRF_TEMP_BASE)
+#define NRF_RNG                         ((NRF_RNG_Type            *) NRF_RNG_BASE)
+#define NRF_ECB                         ((NRF_ECB_Type            *) NRF_ECB_BASE)
+#define NRF_AAR                         ((NRF_AAR_Type            *) NRF_AAR_BASE)
+#define NRF_CCM                         ((NRF_CCM_Type            *) NRF_CCM_BASE)
+#define NRF_WDT                         ((NRF_WDT_Type            *) NRF_WDT_BASE)
+#define NRF_RTC1                        ((NRF_RTC_Type            *) NRF_RTC1_BASE)
+#define NRF_QDEC                        ((NRF_QDEC_Type           *) NRF_QDEC_BASE)
+#define NRF_LPCOMP                      ((NRF_LPCOMP_Type         *) NRF_LPCOMP_BASE)
+#define NRF_SWI                         ((NRF_SWI_Type            *) NRF_SWI_BASE)
+#define NRF_NVMC                        ((NRF_NVMC_Type           *) NRF_NVMC_BASE)
+#define NRF_PPI                         ((NRF_PPI_Type            *) NRF_PPI_BASE)
+#define NRF_FICR                        ((NRF_FICR_Type           *) NRF_FICR_BASE)
+#define NRF_UICR                        ((NRF_UICR_Type           *) NRF_UICR_BASE)
+#define NRF_GPIO                        ((NRF_GPIO_Type           *) NRF_GPIO_BASE)
+
+
+/** @} */ /* End of group Device_Peripheral_Registers */
+/** @} */ /* End of group nrf51 */
+/** @} */ /* End of group Nordic Semiconductor */
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* nrf51_H */
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/device/nrf51_bitfields.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/device/nrf51_bitfields.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,6894 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef __NRF51_BITS_H
+#define __NRF51_BITS_H
+
+/*lint ++flb "Enter library region" */
+
+/* Peripheral: AAR */
+/* Description: Accelerated Address Resolver. */
+
+/* Register: AAR_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 2 : Enable interrupt on NOTRESOLVED event. */
+#define AAR_INTENSET_NOTRESOLVED_Pos (2UL) /*!< Position of NOTRESOLVED field. */
+#define AAR_INTENSET_NOTRESOLVED_Msk (0x1UL << AAR_INTENSET_NOTRESOLVED_Pos) /*!< Bit mask of NOTRESOLVED field. */
+#define AAR_INTENSET_NOTRESOLVED_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENSET_NOTRESOLVED_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENSET_NOTRESOLVED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on RESOLVED event. */
+#define AAR_INTENSET_RESOLVED_Pos (1UL) /*!< Position of RESOLVED field. */
+#define AAR_INTENSET_RESOLVED_Msk (0x1UL << AAR_INTENSET_RESOLVED_Pos) /*!< Bit mask of RESOLVED field. */
+#define AAR_INTENSET_RESOLVED_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENSET_RESOLVED_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENSET_RESOLVED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on END event. */
+#define AAR_INTENSET_END_Pos (0UL) /*!< Position of END field. */
+#define AAR_INTENSET_END_Msk (0x1UL << AAR_INTENSET_END_Pos) /*!< Bit mask of END field. */
+#define AAR_INTENSET_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENSET_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENSET_END_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: AAR_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 2 : Disable interrupt on NOTRESOLVED event. */
+#define AAR_INTENCLR_NOTRESOLVED_Pos (2UL) /*!< Position of NOTRESOLVED field. */
+#define AAR_INTENCLR_NOTRESOLVED_Msk (0x1UL << AAR_INTENCLR_NOTRESOLVED_Pos) /*!< Bit mask of NOTRESOLVED field. */
+#define AAR_INTENCLR_NOTRESOLVED_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENCLR_NOTRESOLVED_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENCLR_NOTRESOLVED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on RESOLVED event. */
+#define AAR_INTENCLR_RESOLVED_Pos (1UL) /*!< Position of RESOLVED field. */
+#define AAR_INTENCLR_RESOLVED_Msk (0x1UL << AAR_INTENCLR_RESOLVED_Pos) /*!< Bit mask of RESOLVED field. */
+#define AAR_INTENCLR_RESOLVED_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENCLR_RESOLVED_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENCLR_RESOLVED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on ENDKSGEN event. */
+#define AAR_INTENCLR_END_Pos (0UL) /*!< Position of END field. */
+#define AAR_INTENCLR_END_Msk (0x1UL << AAR_INTENCLR_END_Pos) /*!< Bit mask of END field. */
+#define AAR_INTENCLR_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define AAR_INTENCLR_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define AAR_INTENCLR_END_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: AAR_STATUS */
+/* Description: Resolution status. */
+
+/* Bits 3..0 : The IRK used last time an address was resolved. */
+#define AAR_STATUS_STATUS_Pos (0UL) /*!< Position of STATUS field. */
+#define AAR_STATUS_STATUS_Msk (0xFUL << AAR_STATUS_STATUS_Pos) /*!< Bit mask of STATUS field. */
+
+/* Register: AAR_ENABLE */
+/* Description: Enable AAR. */
+
+/* Bits 1..0 : Enable AAR. */
+#define AAR_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define AAR_ENABLE_ENABLE_Msk (0x3UL << AAR_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define AAR_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled AAR. */
+#define AAR_ENABLE_ENABLE_Enabled (0x03UL) /*!< Enable AAR. */
+
+/* Register: AAR_NIRK */
+/* Description: Number of Identity root Keys in the IRK data structure. */
+
+/* Bits 4..0 : Number of Identity root Keys in the IRK data structure. */
+#define AAR_NIRK_NIRK_Pos (0UL) /*!< Position of NIRK field. */
+#define AAR_NIRK_NIRK_Msk (0x1FUL << AAR_NIRK_NIRK_Pos) /*!< Bit mask of NIRK field. */
+
+/* Register: AAR_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define AAR_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define AAR_POWER_POWER_Msk (0x1UL << AAR_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define AAR_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define AAR_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: ADC */
+/* Description: Analog to digital converter. */
+
+/* Register: ADC_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 0 : Enable interrupt on END event. */
+#define ADC_INTENSET_END_Pos (0UL) /*!< Position of END field. */
+#define ADC_INTENSET_END_Msk (0x1UL << ADC_INTENSET_END_Pos) /*!< Bit mask of END field. */
+#define ADC_INTENSET_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define ADC_INTENSET_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define ADC_INTENSET_END_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: ADC_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 0 : Disable interrupt on END event. */
+#define ADC_INTENCLR_END_Pos (0UL) /*!< Position of END field. */
+#define ADC_INTENCLR_END_Msk (0x1UL << ADC_INTENCLR_END_Pos) /*!< Bit mask of END field. */
+#define ADC_INTENCLR_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define ADC_INTENCLR_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define ADC_INTENCLR_END_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: ADC_BUSY */
+/* Description: ADC busy register. */
+
+/* Bit 0 : ADC busy register. */
+#define ADC_BUSY_BUSY_Pos (0UL) /*!< Position of BUSY field. */
+#define ADC_BUSY_BUSY_Msk (0x1UL << ADC_BUSY_BUSY_Pos) /*!< Bit mask of BUSY field. */
+#define ADC_BUSY_BUSY_Ready (0UL) /*!< No ongoing ADC conversion is taking place. ADC is ready. */
+#define ADC_BUSY_BUSY_Busy (1UL) /*!< An ADC conversion is taking place. ADC is busy. */
+
+/* Register: ADC_ENABLE */
+/* Description: ADC enable. */
+
+/* Bits 1..0 : ADC enable. */
+#define ADC_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define ADC_ENABLE_ENABLE_Msk (0x3UL << ADC_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define ADC_ENABLE_ENABLE_Disabled (0x00UL) /*!< ADC is disabled. */
+#define ADC_ENABLE_ENABLE_Enabled (0x01UL) /*!< ADC is enabled. If an analog input pin is selected as source of the conversion, the selected pin is configured as an analog input. */
+
+/* Register: ADC_CONFIG */
+/* Description: ADC configuration register. */
+
+/* Bits 17..16 : ADC external reference pin selection. */
+#define ADC_CONFIG_EXTREFSEL_Pos (16UL) /*!< Position of EXTREFSEL field. */
+#define ADC_CONFIG_EXTREFSEL_Msk (0x3UL << ADC_CONFIG_EXTREFSEL_Pos) /*!< Bit mask of EXTREFSEL field. */
+#define ADC_CONFIG_EXTREFSEL_None (0UL) /*!< Analog external reference inputs disabled. */
+#define ADC_CONFIG_EXTREFSEL_AnalogReference0 (1UL) /*!< Use analog reference 0 as reference. */
+#define ADC_CONFIG_EXTREFSEL_AnalogReference1 (2UL) /*!< Use analog reference 1 as reference. */
+
+/* Bits 15..8 : ADC analog pin selection. */
+#define ADC_CONFIG_PSEL_Pos (8UL) /*!< Position of PSEL field. */
+#define ADC_CONFIG_PSEL_Msk (0xFFUL << ADC_CONFIG_PSEL_Pos) /*!< Bit mask of PSEL field. */
+#define ADC_CONFIG_PSEL_Disabled (0UL) /*!< Analog input pins disabled. */
+#define ADC_CONFIG_PSEL_AnalogInput0 (1UL) /*!< Use analog input 0 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput1 (2UL) /*!< Use analog input 1 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput2 (4UL) /*!< Use analog input 2 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput3 (8UL) /*!< Use analog input 3 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput4 (16UL) /*!< Use analog input 4 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput5 (32UL) /*!< Use analog input 5 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput6 (64UL) /*!< Use analog input 6 as analog input. */
+#define ADC_CONFIG_PSEL_AnalogInput7 (128UL) /*!< Use analog input 7 as analog input. */
+
+/* Bits 6..5 : ADC reference selection. */
+#define ADC_CONFIG_REFSEL_Pos (5UL) /*!< Position of REFSEL field. */
+#define ADC_CONFIG_REFSEL_Msk (0x3UL << ADC_CONFIG_REFSEL_Pos) /*!< Bit mask of REFSEL field. */
+#define ADC_CONFIG_REFSEL_VBG (0x00UL) /*!< Use internal 1.2V bandgap voltage as reference for conversion. */
+#define ADC_CONFIG_REFSEL_External (0x01UL) /*!< Use external source configured by EXTREFSEL as reference for conversion. */
+#define ADC_CONFIG_REFSEL_SupplyOneHalfPrescaling (0x02UL) /*!< Use supply voltage with 1/2 prescaling as reference for conversion. Only usable when supply voltage is between 1.7V and 2.6V. */
+#define ADC_CONFIG_REFSEL_SupplyOneThirdPrescaling (0x03UL) /*!< Use supply voltage with 1/3 prescaling as reference for conversion. Only usable when supply voltage is between 2.5V and 3.6V. */
+
+/* Bits 4..2 : ADC input selection. */
+#define ADC_CONFIG_INPSEL_Pos (2UL) /*!< Position of INPSEL field. */
+#define ADC_CONFIG_INPSEL_Msk (0x7UL << ADC_CONFIG_INPSEL_Pos) /*!< Bit mask of INPSEL field. */
+#define ADC_CONFIG_INPSEL_AnalogInputNoPrescaling (0x00UL) /*!< Analog input specified by PSEL with no prescaling used as input for the conversion. */
+#define ADC_CONFIG_INPSEL_AnalogInputTwoThirdsPrescaling (0x01UL) /*!< Analog input specified by PSEL with 2/3 prescaling used as input for the conversion. */
+#define ADC_CONFIG_INPSEL_AnalogInputOneThirdPrescaling (0x02UL) /*!< Analog input specified by PSEL with 1/3 prescaling used as input for the conversion. */
+#define ADC_CONFIG_INPSEL_SupplyTwoThirdsPrescaling (0x05UL) /*!< Supply voltage with 2/3 prescaling used as input for the conversion. */
+#define ADC_CONFIG_INPSEL_SupplyOneThirdPrescaling (0x06UL) /*!< Supply voltage with 1/3 prescaling used as input for the conversion. */
+
+/* Bits 1..0 : ADC resolution. */
+#define ADC_CONFIG_RES_Pos (0UL) /*!< Position of RES field. */
+#define ADC_CONFIG_RES_Msk (0x3UL << ADC_CONFIG_RES_Pos) /*!< Bit mask of RES field. */
+#define ADC_CONFIG_RES_8bit (0x00UL) /*!< 8bit ADC resolution. */
+#define ADC_CONFIG_RES_9bit (0x01UL) /*!< 9bit ADC resolution. */
+#define ADC_CONFIG_RES_10bit (0x02UL) /*!< 10bit ADC resolution. */
+
+/* Register: ADC_RESULT */
+/* Description: Result of ADC conversion. */
+
+/* Bits 9..0 : Result of ADC conversion. */
+#define ADC_RESULT_RESULT_Pos (0UL) /*!< Position of RESULT field. */
+#define ADC_RESULT_RESULT_Msk (0x3FFUL << ADC_RESULT_RESULT_Pos) /*!< Bit mask of RESULT field. */
+
+/* Register: ADC_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define ADC_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define ADC_POWER_POWER_Msk (0x1UL << ADC_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define ADC_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define ADC_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: AMLI */
+/* Description: AHB Multi-Layer Interface. */
+
+/* Register: AMLI_RAMPRI_CPU0 */
+/* Description: Configurable priority configuration register for CPU0. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_CPU0_RAM7_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_CPU0_RAM6_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_CPU0_RAM5_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_CPU0_RAM4_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_CPU0_RAM3_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_CPU0_RAM2_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_CPU0_RAM1_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_CPU0_RAM0_Msk (0xFUL << AMLI_RAMPRI_CPU0_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CPU0_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Register: AMLI_RAMPRI_SPIS1 */
+/* Description: Configurable priority configuration register for SPIS1. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Msk (0xFUL << AMLI_RAMPRI_SPIS1_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_SPIS1_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Register: AMLI_RAMPRI_RADIO */
+/* Description: Configurable priority configuration register for RADIO. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_RADIO_RAM7_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_RADIO_RAM6_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_RADIO_RAM5_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_RADIO_RAM4_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_RADIO_RAM3_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_RADIO_RAM2_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_RADIO_RAM1_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_RADIO_RAM0_Msk (0xFUL << AMLI_RAMPRI_RADIO_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_RADIO_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Register: AMLI_RAMPRI_ECB */
+/* Description: Configurable priority configuration register for ECB. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_ECB_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_ECB_RAM7_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_ECB_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_ECB_RAM6_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_ECB_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_ECB_RAM5_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_ECB_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_ECB_RAM4_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_ECB_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_ECB_RAM3_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_ECB_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_ECB_RAM2_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_ECB_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_ECB_RAM1_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_ECB_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_ECB_RAM0_Msk (0xFUL << AMLI_RAMPRI_ECB_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_ECB_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Register: AMLI_RAMPRI_CCM */
+/* Description: Configurable priority configuration register for CCM. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_CCM_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_CCM_RAM7_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_CCM_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_CCM_RAM6_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_CCM_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_CCM_RAM5_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_CCM_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_CCM_RAM4_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_CCM_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_CCM_RAM3_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_CCM_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_CCM_RAM2_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_CCM_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_CCM_RAM1_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_CCM_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_CCM_RAM0_Msk (0xFUL << AMLI_RAMPRI_CCM_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_CCM_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Register: AMLI_RAMPRI_AAR */
+/* Description: Configurable priority configuration register for AAR. */
+
+/* Bits 31..28 : Configuration field for RAM block 7. */
+#define AMLI_RAMPRI_AAR_RAM7_Pos (28UL) /*!< Position of RAM7 field. */
+#define AMLI_RAMPRI_AAR_RAM7_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM7_Pos) /*!< Bit mask of RAM7 field. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM7_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 27..24 : Configuration field for RAM block 6. */
+#define AMLI_RAMPRI_AAR_RAM6_Pos (24UL) /*!< Position of RAM6 field. */
+#define AMLI_RAMPRI_AAR_RAM6_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM6_Pos) /*!< Bit mask of RAM6 field. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM6_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 23..20 : Configuration field for RAM block 5. */
+#define AMLI_RAMPRI_AAR_RAM5_Pos (20UL) /*!< Position of RAM5 field. */
+#define AMLI_RAMPRI_AAR_RAM5_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM5_Pos) /*!< Bit mask of RAM5 field. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM5_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 19..16 : Configuration field for RAM block 4. */
+#define AMLI_RAMPRI_AAR_RAM4_Pos (16UL) /*!< Position of RAM4 field. */
+#define AMLI_RAMPRI_AAR_RAM4_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM4_Pos) /*!< Bit mask of RAM4 field. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM4_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 15..12 : Configuration field for RAM block 3. */
+#define AMLI_RAMPRI_AAR_RAM3_Pos (12UL) /*!< Position of RAM3 field. */
+#define AMLI_RAMPRI_AAR_RAM3_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM3_Pos) /*!< Bit mask of RAM3 field. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM3_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 11..8 : Configuration field for RAM block 2. */
+#define AMLI_RAMPRI_AAR_RAM2_Pos (8UL) /*!< Position of RAM2 field. */
+#define AMLI_RAMPRI_AAR_RAM2_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM2_Pos) /*!< Bit mask of RAM2 field. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM2_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 7..4 : Configuration field for RAM block 1. */
+#define AMLI_RAMPRI_AAR_RAM1_Pos (4UL) /*!< Position of RAM1 field. */
+#define AMLI_RAMPRI_AAR_RAM1_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM1_Pos) /*!< Bit mask of RAM1 field. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM1_Pri14 (0xEUL) /*!< Priority 14. */
+
+/* Bits 3..0 : Configuration field for RAM block 0. */
+#define AMLI_RAMPRI_AAR_RAM0_Pos (0UL) /*!< Position of RAM0 field. */
+#define AMLI_RAMPRI_AAR_RAM0_Msk (0xFUL << AMLI_RAMPRI_AAR_RAM0_Pos) /*!< Bit mask of RAM0 field. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri0 (0x0UL) /*!< Priority 0. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri2 (0x2UL) /*!< Priority 2. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri4 (0x4UL) /*!< Priority 4. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri6 (0x6UL) /*!< Priority 6. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri8 (0x8UL) /*!< Priority 8. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri10 (0xAUL) /*!< Priority 10. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri12 (0xCUL) /*!< Priority 12. */
+#define AMLI_RAMPRI_AAR_RAM0_Pri14 (0xEUL) /*!< Priority 14. */
+
+
+/* Peripheral: CCM */
+/* Description: AES CCM Mode Encryption. */
+
+/* Register: CCM_SHORTS */
+/* Description: Shortcuts for the CCM. */
+
+/* Bit 0 : Shortcut between ENDKSGEN event and CRYPT task. */
+#define CCM_SHORTS_ENDKSGEN_CRYPT_Pos (0UL) /*!< Position of ENDKSGEN_CRYPT field. */
+#define CCM_SHORTS_ENDKSGEN_CRYPT_Msk (0x1UL << CCM_SHORTS_ENDKSGEN_CRYPT_Pos) /*!< Bit mask of ENDKSGEN_CRYPT field. */
+#define CCM_SHORTS_ENDKSGEN_CRYPT_Disabled (0UL) /*!< Shortcut disabled. */
+#define CCM_SHORTS_ENDKSGEN_CRYPT_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: CCM_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 2 : Enable interrupt on ERROR event. */
+#define CCM_INTENSET_ERROR_Pos (2UL) /*!< Position of ERROR field. */
+#define CCM_INTENSET_ERROR_Msk (0x1UL << CCM_INTENSET_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define CCM_INTENSET_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENSET_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENSET_ERROR_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on ENDCRYPT event. */
+#define CCM_INTENSET_ENDCRYPT_Pos (1UL) /*!< Position of ENDCRYPT field. */
+#define CCM_INTENSET_ENDCRYPT_Msk (0x1UL << CCM_INTENSET_ENDCRYPT_Pos) /*!< Bit mask of ENDCRYPT field. */
+#define CCM_INTENSET_ENDCRYPT_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENSET_ENDCRYPT_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENSET_ENDCRYPT_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on ENDKSGEN event. */
+#define CCM_INTENSET_ENDKSGEN_Pos (0UL) /*!< Position of ENDKSGEN field. */
+#define CCM_INTENSET_ENDKSGEN_Msk (0x1UL << CCM_INTENSET_ENDKSGEN_Pos) /*!< Bit mask of ENDKSGEN field. */
+#define CCM_INTENSET_ENDKSGEN_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENSET_ENDKSGEN_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENSET_ENDKSGEN_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: CCM_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 2 : Disable interrupt on ERROR event. */
+#define CCM_INTENCLR_ERROR_Pos (2UL) /*!< Position of ERROR field. */
+#define CCM_INTENCLR_ERROR_Msk (0x1UL << CCM_INTENCLR_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define CCM_INTENCLR_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENCLR_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENCLR_ERROR_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on ENDCRYPT event. */
+#define CCM_INTENCLR_ENDCRYPT_Pos (1UL) /*!< Position of ENDCRYPT field. */
+#define CCM_INTENCLR_ENDCRYPT_Msk (0x1UL << CCM_INTENCLR_ENDCRYPT_Pos) /*!< Bit mask of ENDCRYPT field. */
+#define CCM_INTENCLR_ENDCRYPT_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENCLR_ENDCRYPT_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENCLR_ENDCRYPT_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on ENDKSGEN event. */
+#define CCM_INTENCLR_ENDKSGEN_Pos (0UL) /*!< Position of ENDKSGEN field. */
+#define CCM_INTENCLR_ENDKSGEN_Msk (0x1UL << CCM_INTENCLR_ENDKSGEN_Pos) /*!< Bit mask of ENDKSGEN field. */
+#define CCM_INTENCLR_ENDKSGEN_Disabled (0UL) /*!< Interrupt disabled. */
+#define CCM_INTENCLR_ENDKSGEN_Enabled (1UL) /*!< Interrupt enabled. */
+#define CCM_INTENCLR_ENDKSGEN_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: CCM_MICSTATUS */
+/* Description: CCM RX MIC check result. */
+
+/* Bit 0 : Result of the MIC check performed during the previous CCM RX STARTCRYPT */
+#define CCM_MICSTATUS_MICSTATUS_Pos (0UL) /*!< Position of MICSTATUS field. */
+#define CCM_MICSTATUS_MICSTATUS_Msk (0x1UL << CCM_MICSTATUS_MICSTATUS_Pos) /*!< Bit mask of MICSTATUS field. */
+#define CCM_MICSTATUS_MICSTATUS_CheckFailed (0UL) /*!< MIC check failed. */
+#define CCM_MICSTATUS_MICSTATUS_CheckPassed (1UL) /*!< MIC check passed. */
+
+/* Register: CCM_ENABLE */
+/* Description: CCM enable. */
+
+/* Bits 1..0 : CCM enable. */
+#define CCM_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define CCM_ENABLE_ENABLE_Msk (0x3UL << CCM_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define CCM_ENABLE_ENABLE_Disabled (0x00UL) /*!< CCM is disabled. */
+#define CCM_ENABLE_ENABLE_Enabled (0x02UL) /*!< CCM is enabled. */
+
+/* Register: CCM_MODE */
+/* Description: Operation mode. */
+
+/* Bit 0 : CCM mode operation. */
+#define CCM_MODE_MODE_Pos (0UL) /*!< Position of MODE field. */
+#define CCM_MODE_MODE_Msk (0x1UL << CCM_MODE_MODE_Pos) /*!< Bit mask of MODE field. */
+#define CCM_MODE_MODE_Encryption (0UL) /*!< CCM mode TX */
+#define CCM_MODE_MODE_Decryption (1UL) /*!< CCM mode TX */
+
+/* Register: CCM_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define CCM_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define CCM_POWER_POWER_Msk (0x1UL << CCM_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define CCM_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define CCM_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: CLOCK */
+/* Description: Clock control. */
+
+/* Register: CLOCK_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 4 : Enable interrupt on CTTO event. */
+#define CLOCK_INTENSET_CTTO_Pos (4UL) /*!< Position of CTTO field. */
+#define CLOCK_INTENSET_CTTO_Msk (0x1UL << CLOCK_INTENSET_CTTO_Pos) /*!< Bit mask of CTTO field. */
+#define CLOCK_INTENSET_CTTO_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENSET_CTTO_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENSET_CTTO_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 3 : Enable interrupt on DONE event. */
+#define CLOCK_INTENSET_DONE_Pos (3UL) /*!< Position of DONE field. */
+#define CLOCK_INTENSET_DONE_Msk (0x1UL << CLOCK_INTENSET_DONE_Pos) /*!< Bit mask of DONE field. */
+#define CLOCK_INTENSET_DONE_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENSET_DONE_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENSET_DONE_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on LFCLKSTARTED event. */
+#define CLOCK_INTENSET_LFCLKSTARTED_Pos (1UL) /*!< Position of LFCLKSTARTED field. */
+#define CLOCK_INTENSET_LFCLKSTARTED_Msk (0x1UL << CLOCK_INTENSET_LFCLKSTARTED_Pos) /*!< Bit mask of LFCLKSTARTED field. */
+#define CLOCK_INTENSET_LFCLKSTARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENSET_LFCLKSTARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENSET_LFCLKSTARTED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on HFCLKSTARTED event. */
+#define CLOCK_INTENSET_HFCLKSTARTED_Pos (0UL) /*!< Position of HFCLKSTARTED field. */
+#define CLOCK_INTENSET_HFCLKSTARTED_Msk (0x1UL << CLOCK_INTENSET_HFCLKSTARTED_Pos) /*!< Bit mask of HFCLKSTARTED field. */
+#define CLOCK_INTENSET_HFCLKSTARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENSET_HFCLKSTARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENSET_HFCLKSTARTED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: CLOCK_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 4 : Disable interrupt on CTTO event. */
+#define CLOCK_INTENCLR_CTTO_Pos (4UL) /*!< Position of CTTO field. */
+#define CLOCK_INTENCLR_CTTO_Msk (0x1UL << CLOCK_INTENCLR_CTTO_Pos) /*!< Bit mask of CTTO field. */
+#define CLOCK_INTENCLR_CTTO_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENCLR_CTTO_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENCLR_CTTO_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 3 : Disable interrupt on DONE event. */
+#define CLOCK_INTENCLR_DONE_Pos (3UL) /*!< Position of DONE field. */
+#define CLOCK_INTENCLR_DONE_Msk (0x1UL << CLOCK_INTENCLR_DONE_Pos) /*!< Bit mask of DONE field. */
+#define CLOCK_INTENCLR_DONE_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENCLR_DONE_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENCLR_DONE_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on LFCLKSTARTED event. */
+#define CLOCK_INTENCLR_LFCLKSTARTED_Pos (1UL) /*!< Position of LFCLKSTARTED field. */
+#define CLOCK_INTENCLR_LFCLKSTARTED_Msk (0x1UL << CLOCK_INTENCLR_LFCLKSTARTED_Pos) /*!< Bit mask of LFCLKSTARTED field. */
+#define CLOCK_INTENCLR_LFCLKSTARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENCLR_LFCLKSTARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENCLR_LFCLKSTARTED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on HFCLKSTARTED event. */
+#define CLOCK_INTENCLR_HFCLKSTARTED_Pos (0UL) /*!< Position of HFCLKSTARTED field. */
+#define CLOCK_INTENCLR_HFCLKSTARTED_Msk (0x1UL << CLOCK_INTENCLR_HFCLKSTARTED_Pos) /*!< Bit mask of HFCLKSTARTED field. */
+#define CLOCK_INTENCLR_HFCLKSTARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define CLOCK_INTENCLR_HFCLKSTARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define CLOCK_INTENCLR_HFCLKSTARTED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: CLOCK_HFCLKRUN */
+/* Description: Task HFCLKSTART trigger status. */
+
+/* Bit 0 : Task HFCLKSTART trigger status. */
+#define CLOCK_HFCLKRUN_STATUS_Pos (0UL) /*!< Position of STATUS field. */
+#define CLOCK_HFCLKRUN_STATUS_Msk (0x1UL << CLOCK_HFCLKRUN_STATUS_Pos) /*!< Bit mask of STATUS field. */
+#define CLOCK_HFCLKRUN_STATUS_NotTriggered (0UL) /*!< Task HFCLKSTART has not been triggered. */
+#define CLOCK_HFCLKRUN_STATUS_Triggered (1UL) /*!< Task HFCLKSTART has been triggered. */
+
+/* Register: CLOCK_HFCLKSTAT */
+/* Description: High frequency clock status. */
+
+/* Bit 16 : State for the HFCLK. */
+#define CLOCK_HFCLKSTAT_STATE_Pos (16UL) /*!< Position of STATE field. */
+#define CLOCK_HFCLKSTAT_STATE_Msk (0x1UL << CLOCK_HFCLKSTAT_STATE_Pos) /*!< Bit mask of STATE field. */
+#define CLOCK_HFCLKSTAT_STATE_NotRunning (0UL) /*!< HFCLK clock not running. */
+#define CLOCK_HFCLKSTAT_STATE_Running (1UL) /*!< HFCLK clock running. */
+
+/* Bit 0 : Active clock source for the HF clock. */
+#define CLOCK_HFCLKSTAT_SRC_Pos (0UL) /*!< Position of SRC field. */
+#define CLOCK_HFCLKSTAT_SRC_Msk (0x1UL << CLOCK_HFCLKSTAT_SRC_Pos) /*!< Bit mask of SRC field. */
+#define CLOCK_HFCLKSTAT_SRC_RC (0UL) /*!< Internal 16MHz RC oscillator running and generating the HFCLK clock. */
+#define CLOCK_HFCLKSTAT_SRC_Xtal (1UL) /*!< External 16MHz/32MHz crystal oscillator running and generating the HFCLK clock. */
+
+/* Register: CLOCK_LFCLKRUN */
+/* Description: Task LFCLKSTART triggered status. */
+
+/* Bit 0 : Task LFCLKSTART triggered status. */
+#define CLOCK_LFCLKRUN_STATUS_Pos (0UL) /*!< Position of STATUS field. */
+#define CLOCK_LFCLKRUN_STATUS_Msk (0x1UL << CLOCK_LFCLKRUN_STATUS_Pos) /*!< Bit mask of STATUS field. */
+#define CLOCK_LFCLKRUN_STATUS_NotTriggered (0UL) /*!< Task LFCLKSTART has not been triggered. */
+#define CLOCK_LFCLKRUN_STATUS_Triggered (1UL) /*!< Task LFCLKSTART has been triggered. */
+
+/* Register: CLOCK_LFCLKSTAT */
+/* Description: Low frequency clock status. */
+
+/* Bit 16 : State for the LF clock. */
+#define CLOCK_LFCLKSTAT_STATE_Pos (16UL) /*!< Position of STATE field. */
+#define CLOCK_LFCLKSTAT_STATE_Msk (0x1UL << CLOCK_LFCLKSTAT_STATE_Pos) /*!< Bit mask of STATE field. */
+#define CLOCK_LFCLKSTAT_STATE_NotRunning (0UL) /*!< LFCLK clock not running. */
+#define CLOCK_LFCLKSTAT_STATE_Running (1UL) /*!< LFCLK clock running. */
+
+/* Bits 1..0 : Active clock source for the LF clock. */
+#define CLOCK_LFCLKSTAT_SRC_Pos (0UL) /*!< Position of SRC field. */
+#define CLOCK_LFCLKSTAT_SRC_Msk (0x3UL << CLOCK_LFCLKSTAT_SRC_Pos) /*!< Bit mask of SRC field. */
+#define CLOCK_LFCLKSTAT_SRC_RC (0UL) /*!< Internal 32KiHz RC oscillator running and generating the LFCLK clock. */
+#define CLOCK_LFCLKSTAT_SRC_Xtal (1UL) /*!< External 32KiHz crystal oscillator running and generating the LFCLK clock. */
+#define CLOCK_LFCLKSTAT_SRC_Synth (2UL) /*!< Internal 32KiHz synthesizer from the HFCLK running and generating the LFCLK clock. */
+
+/* Register: CLOCK_LFCLKSRCCOPY */
+/* Description: Clock source for the LFCLK clock, set when task LKCLKSTART is triggered. */
+
+/* Bits 1..0 : Clock source for the LFCLK clock, set when task LKCLKSTART is triggered. */
+#define CLOCK_LFCLKSRCCOPY_SRC_Pos (0UL) /*!< Position of SRC field. */
+#define CLOCK_LFCLKSRCCOPY_SRC_Msk (0x3UL << CLOCK_LFCLKSRCCOPY_SRC_Pos) /*!< Bit mask of SRC field. */
+#define CLOCK_LFCLKSRCCOPY_SRC_RC (0UL) /*!< Internal 32KiHz RC oscillator. */
+#define CLOCK_LFCLKSRCCOPY_SRC_Xtal (1UL) /*!< External 32KiHz crystal. */
+#define CLOCK_LFCLKSRCCOPY_SRC_Synth (2UL) /*!< Internal 32KiHz synthesizer from HFCLK system clock. */
+
+/* Register: CLOCK_LFCLKSRC */
+/* Description: Clock source for the LFCLK clock. */
+
+/* Bits 1..0 : Clock source. */
+#define CLOCK_LFCLKSRC_SRC_Pos (0UL) /*!< Position of SRC field. */
+#define CLOCK_LFCLKSRC_SRC_Msk (0x3UL << CLOCK_LFCLKSRC_SRC_Pos) /*!< Bit mask of SRC field. */
+#define CLOCK_LFCLKSRC_SRC_RC (0UL) /*!< Internal 32KiHz RC oscillator. */
+#define CLOCK_LFCLKSRC_SRC_Xtal (1UL) /*!< External 32KiHz crystal. */
+#define CLOCK_LFCLKSRC_SRC_Synth (2UL) /*!< Internal 32KiHz synthesizer from HFCLK system clock. */
+
+/* Register: CLOCK_CTIV */
+/* Description: Calibration timer interval. */
+
+/* Bits 6..0 : Calibration timer interval in 0.25s resolution. */
+#define CLOCK_CTIV_CTIV_Pos (0UL) /*!< Position of CTIV field. */
+#define CLOCK_CTIV_CTIV_Msk (0x7FUL << CLOCK_CTIV_CTIV_Pos) /*!< Bit mask of CTIV field. */
+
+/* Register: CLOCK_XTALFREQ */
+/* Description: Crystal frequency. */
+
+/* Bits 7..0 : External Xtal frequency selection. */
+#define CLOCK_XTALFREQ_XTALFREQ_Pos (0UL) /*!< Position of XTALFREQ field. */
+#define CLOCK_XTALFREQ_XTALFREQ_Msk (0xFFUL << CLOCK_XTALFREQ_XTALFREQ_Pos) /*!< Bit mask of XTALFREQ field. */
+#define CLOCK_XTALFREQ_XTALFREQ_32MHz (0x00UL) /*!< 32MHz xtal is used as source for the HFCLK oscillator. */
+#define CLOCK_XTALFREQ_XTALFREQ_16MHz (0xFFUL) /*!< 16MHz xtal is used as source for the HFCLK oscillator. */
+
+
+/* Peripheral: ECB */
+/* Description: AES ECB Mode Encryption. */
+
+/* Register: ECB_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 1 : Enable interrupt on ERRORECB event. */
+#define ECB_INTENSET_ERRORECB_Pos (1UL) /*!< Position of ERRORECB field. */
+#define ECB_INTENSET_ERRORECB_Msk (0x1UL << ECB_INTENSET_ERRORECB_Pos) /*!< Bit mask of ERRORECB field. */
+#define ECB_INTENSET_ERRORECB_Disabled (0UL) /*!< Interrupt disabled. */
+#define ECB_INTENSET_ERRORECB_Enabled (1UL) /*!< Interrupt enabled. */
+#define ECB_INTENSET_ERRORECB_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on ENDECB event. */
+#define ECB_INTENSET_ENDECB_Pos (0UL) /*!< Position of ENDECB field. */
+#define ECB_INTENSET_ENDECB_Msk (0x1UL << ECB_INTENSET_ENDECB_Pos) /*!< Bit mask of ENDECB field. */
+#define ECB_INTENSET_ENDECB_Disabled (0UL) /*!< Interrupt disabled. */
+#define ECB_INTENSET_ENDECB_Enabled (1UL) /*!< Interrupt enabled. */
+#define ECB_INTENSET_ENDECB_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: ECB_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 1 : Disable interrupt on ERRORECB event. */
+#define ECB_INTENCLR_ERRORECB_Pos (1UL) /*!< Position of ERRORECB field. */
+#define ECB_INTENCLR_ERRORECB_Msk (0x1UL << ECB_INTENCLR_ERRORECB_Pos) /*!< Bit mask of ERRORECB field. */
+#define ECB_INTENCLR_ERRORECB_Disabled (0UL) /*!< Interrupt disabled. */
+#define ECB_INTENCLR_ERRORECB_Enabled (1UL) /*!< Interrupt enabled. */
+#define ECB_INTENCLR_ERRORECB_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on ENDECB event. */
+#define ECB_INTENCLR_ENDECB_Pos (0UL) /*!< Position of ENDECB field. */
+#define ECB_INTENCLR_ENDECB_Msk (0x1UL << ECB_INTENCLR_ENDECB_Pos) /*!< Bit mask of ENDECB field. */
+#define ECB_INTENCLR_ENDECB_Disabled (0UL) /*!< Interrupt disabled. */
+#define ECB_INTENCLR_ENDECB_Enabled (1UL) /*!< Interrupt enabled. */
+#define ECB_INTENCLR_ENDECB_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: ECB_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define ECB_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define ECB_POWER_POWER_Msk (0x1UL << ECB_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define ECB_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define ECB_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: FICR */
+/* Description: Factory Information Configuration. */
+
+/* Register: FICR_PPFC */
+/* Description: Pre-programmed factory code present. */
+
+/* Bits 7..0 : Pre-programmed factory code present. */
+#define FICR_PPFC_PPFC_Pos (0UL) /*!< Position of PPFC field. */
+#define FICR_PPFC_PPFC_Msk (0xFFUL << FICR_PPFC_PPFC_Pos) /*!< Bit mask of PPFC field. */
+#define FICR_PPFC_PPFC_Present (0x00UL) /*!< Present. */
+#define FICR_PPFC_PPFC_NotPresent (0xFFUL) /*!< Not present. */
+
+/* Register: FICR_CONFIGID */
+/* Description: Configuration identifier. */
+
+/* Bits 31..16 : Firmware Identification Number pre-loaded into the flash. */
+#define FICR_CONFIGID_FWID_Pos (16UL) /*!< Position of FWID field. */
+#define FICR_CONFIGID_FWID_Msk (0xFFFFUL << FICR_CONFIGID_FWID_Pos) /*!< Bit mask of FWID field. */
+
+/* Bits 15..0 : Hardware Identification Number. */
+#define FICR_CONFIGID_HWID_Pos (0UL) /*!< Position of HWID field. */
+#define FICR_CONFIGID_HWID_Msk (0xFFFFUL << FICR_CONFIGID_HWID_Pos) /*!< Bit mask of HWID field. */
+
+/* Register: FICR_DEVICEADDRTYPE */
+/* Description: Device address type. */
+
+/* Bit 0 : Device address type. */
+#define FICR_DEVICEADDRTYPE_DEVICEADDRTYPE_Pos (0UL) /*!< Position of DEVICEADDRTYPE field. */
+#define FICR_DEVICEADDRTYPE_DEVICEADDRTYPE_Msk (0x1UL << FICR_DEVICEADDRTYPE_DEVICEADDRTYPE_Pos) /*!< Bit mask of DEVICEADDRTYPE field. */
+#define FICR_DEVICEADDRTYPE_DEVICEADDRTYPE_Public (0UL) /*!< Public address. */
+#define FICR_DEVICEADDRTYPE_DEVICEADDRTYPE_Random (1UL) /*!< Random address. */
+
+/* Register: FICR_OVERRIDEEN */
+/* Description: Radio calibration override enable. */
+
+/* Bit 3 : Override default values for BLE_1Mbit mode. */
+#define FICR_OVERRIDEEN_BLE_1MBIT_Pos (3UL) /*!< Position of BLE_1MBIT field. */
+#define FICR_OVERRIDEEN_BLE_1MBIT_Msk (0x1UL << FICR_OVERRIDEEN_BLE_1MBIT_Pos) /*!< Bit mask of BLE_1MBIT field. */
+#define FICR_OVERRIDEEN_BLE_1MBIT_Override (0UL) /*!< Override the default values for BLE_1Mbit mode. */
+#define FICR_OVERRIDEEN_BLE_1MBIT_NotOverride (1UL) /*!< Do not override the default values for BLE_1Mbit mode. */
+
+/* Bit 0 : Override default values for NRF_1Mbit mode. */
+#define FICR_OVERRIDEEN_NRF_1MBIT_Pos (0UL) /*!< Position of NRF_1MBIT field. */
+#define FICR_OVERRIDEEN_NRF_1MBIT_Msk (0x1UL << FICR_OVERRIDEEN_NRF_1MBIT_Pos) /*!< Bit mask of NRF_1MBIT field. */
+#define FICR_OVERRIDEEN_NRF_1MBIT_Override (0UL) /*!< Override the default values for NRF_1Mbit mode. */
+#define FICR_OVERRIDEEN_NRF_1MBIT_NotOverride (1UL) /*!< Do not override the default values for NRF_1Mbit mode. */
+
+
+/* Peripheral: GPIO */
+/* Description: General purpose input and output. */
+
+/* Register: GPIO_OUT */
+/* Description: Write GPIO port. */
+
+/* Bit 31 : Pin 31. */
+#define GPIO_OUT_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_OUT_PIN31_Msk (0x1UL << GPIO_OUT_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_OUT_PIN31_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN31_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 30 : Pin 30. */
+#define GPIO_OUT_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_OUT_PIN30_Msk (0x1UL << GPIO_OUT_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_OUT_PIN30_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN30_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 29 : Pin 29. */
+#define GPIO_OUT_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_OUT_PIN29_Msk (0x1UL << GPIO_OUT_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_OUT_PIN29_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN29_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 28 : Pin 28. */
+#define GPIO_OUT_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_OUT_PIN28_Msk (0x1UL << GPIO_OUT_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_OUT_PIN28_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN28_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 27 : Pin 27. */
+#define GPIO_OUT_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_OUT_PIN27_Msk (0x1UL << GPIO_OUT_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_OUT_PIN27_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN27_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 26 : Pin 26. */
+#define GPIO_OUT_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_OUT_PIN26_Msk (0x1UL << GPIO_OUT_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_OUT_PIN26_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN26_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 25 : Pin 25. */
+#define GPIO_OUT_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_OUT_PIN25_Msk (0x1UL << GPIO_OUT_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_OUT_PIN25_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN25_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 24 : Pin 24. */
+#define GPIO_OUT_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_OUT_PIN24_Msk (0x1UL << GPIO_OUT_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_OUT_PIN24_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN24_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 23 : Pin 23. */
+#define GPIO_OUT_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_OUT_PIN23_Msk (0x1UL << GPIO_OUT_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_OUT_PIN23_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN23_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 22 : Pin 22. */
+#define GPIO_OUT_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_OUT_PIN22_Msk (0x1UL << GPIO_OUT_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_OUT_PIN22_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN22_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 21 : Pin 21. */
+#define GPIO_OUT_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_OUT_PIN21_Msk (0x1UL << GPIO_OUT_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_OUT_PIN21_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN21_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 20 : Pin 20. */
+#define GPIO_OUT_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_OUT_PIN20_Msk (0x1UL << GPIO_OUT_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_OUT_PIN20_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN20_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 19 : Pin 19. */
+#define GPIO_OUT_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_OUT_PIN19_Msk (0x1UL << GPIO_OUT_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_OUT_PIN19_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN19_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 18 : Pin 18. */
+#define GPIO_OUT_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_OUT_PIN18_Msk (0x1UL << GPIO_OUT_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_OUT_PIN18_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN18_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 17 : Pin 17. */
+#define GPIO_OUT_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_OUT_PIN17_Msk (0x1UL << GPIO_OUT_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_OUT_PIN17_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN17_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 16 : Pin 16. */
+#define GPIO_OUT_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_OUT_PIN16_Msk (0x1UL << GPIO_OUT_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_OUT_PIN16_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN16_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 15 : Pin 15. */
+#define GPIO_OUT_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_OUT_PIN15_Msk (0x1UL << GPIO_OUT_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_OUT_PIN15_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN15_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 14 : Pin 14. */
+#define GPIO_OUT_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_OUT_PIN14_Msk (0x1UL << GPIO_OUT_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_OUT_PIN14_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN14_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 13 : Pin 13. */
+#define GPIO_OUT_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_OUT_PIN13_Msk (0x1UL << GPIO_OUT_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_OUT_PIN13_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN13_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 12 : Pin 12. */
+#define GPIO_OUT_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_OUT_PIN12_Msk (0x1UL << GPIO_OUT_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_OUT_PIN12_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN12_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 11 : Pin 11. */
+#define GPIO_OUT_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_OUT_PIN11_Msk (0x1UL << GPIO_OUT_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_OUT_PIN11_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN11_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 10 : Pin 10. */
+#define GPIO_OUT_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_OUT_PIN10_Msk (0x1UL << GPIO_OUT_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_OUT_PIN10_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN10_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 9 : Pin 9. */
+#define GPIO_OUT_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_OUT_PIN9_Msk (0x1UL << GPIO_OUT_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_OUT_PIN9_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN9_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 8 : Pin 8. */
+#define GPIO_OUT_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_OUT_PIN8_Msk (0x1UL << GPIO_OUT_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_OUT_PIN8_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN8_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 7 : Pin 7. */
+#define GPIO_OUT_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_OUT_PIN7_Msk (0x1UL << GPIO_OUT_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_OUT_PIN7_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN7_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 6 : Pin 6. */
+#define GPIO_OUT_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_OUT_PIN6_Msk (0x1UL << GPIO_OUT_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_OUT_PIN6_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN6_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 5 : Pin 5. */
+#define GPIO_OUT_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_OUT_PIN5_Msk (0x1UL << GPIO_OUT_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_OUT_PIN5_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN5_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 4 : Pin 4. */
+#define GPIO_OUT_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_OUT_PIN4_Msk (0x1UL << GPIO_OUT_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_OUT_PIN4_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN4_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 3 : Pin 3. */
+#define GPIO_OUT_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_OUT_PIN3_Msk (0x1UL << GPIO_OUT_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_OUT_PIN3_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN3_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 2 : Pin 2. */
+#define GPIO_OUT_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_OUT_PIN2_Msk (0x1UL << GPIO_OUT_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_OUT_PIN2_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN2_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 1 : Pin 1. */
+#define GPIO_OUT_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_OUT_PIN1_Msk (0x1UL << GPIO_OUT_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_OUT_PIN1_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN1_High (1UL) /*!< Pin driver is high. */
+
+/* Bit 0 : Pin 0. */
+#define GPIO_OUT_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_OUT_PIN0_Msk (0x1UL << GPIO_OUT_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_OUT_PIN0_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUT_PIN0_High (1UL) /*!< Pin driver is high. */
+
+/* Register: GPIO_OUTSET */
+/* Description: Set individual bits in GPIO port. */
+
+/* Bit 31 : Pin 31. */
+#define GPIO_OUTSET_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_OUTSET_PIN31_Msk (0x1UL << GPIO_OUTSET_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_OUTSET_PIN31_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN31_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN31_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 30 : Pin 30. */
+#define GPIO_OUTSET_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_OUTSET_PIN30_Msk (0x1UL << GPIO_OUTSET_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_OUTSET_PIN30_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN30_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN30_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 29 : Pin 29. */
+#define GPIO_OUTSET_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_OUTSET_PIN29_Msk (0x1UL << GPIO_OUTSET_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_OUTSET_PIN29_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN29_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN29_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 28 : Pin 28. */
+#define GPIO_OUTSET_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_OUTSET_PIN28_Msk (0x1UL << GPIO_OUTSET_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_OUTSET_PIN28_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN28_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN28_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 27 : Pin 27. */
+#define GPIO_OUTSET_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_OUTSET_PIN27_Msk (0x1UL << GPIO_OUTSET_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_OUTSET_PIN27_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN27_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN27_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 26 : Pin 26. */
+#define GPIO_OUTSET_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_OUTSET_PIN26_Msk (0x1UL << GPIO_OUTSET_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_OUTSET_PIN26_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN26_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN26_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 25 : Pin 25. */
+#define GPIO_OUTSET_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_OUTSET_PIN25_Msk (0x1UL << GPIO_OUTSET_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_OUTSET_PIN25_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN25_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN25_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 24 : Pin 24. */
+#define GPIO_OUTSET_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_OUTSET_PIN24_Msk (0x1UL << GPIO_OUTSET_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_OUTSET_PIN24_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN24_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN24_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 23 : Pin 23. */
+#define GPIO_OUTSET_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_OUTSET_PIN23_Msk (0x1UL << GPIO_OUTSET_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_OUTSET_PIN23_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN23_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN23_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 22 : Pin 22. */
+#define GPIO_OUTSET_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_OUTSET_PIN22_Msk (0x1UL << GPIO_OUTSET_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_OUTSET_PIN22_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN22_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN22_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 21 : Pin 21. */
+#define GPIO_OUTSET_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_OUTSET_PIN21_Msk (0x1UL << GPIO_OUTSET_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_OUTSET_PIN21_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN21_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN21_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 20 : Pin 20. */
+#define GPIO_OUTSET_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_OUTSET_PIN20_Msk (0x1UL << GPIO_OUTSET_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_OUTSET_PIN20_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN20_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN20_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 19 : Pin 19. */
+#define GPIO_OUTSET_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_OUTSET_PIN19_Msk (0x1UL << GPIO_OUTSET_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_OUTSET_PIN19_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN19_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN19_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 18 : Pin 18. */
+#define GPIO_OUTSET_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_OUTSET_PIN18_Msk (0x1UL << GPIO_OUTSET_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_OUTSET_PIN18_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN18_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN18_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 17 : Pin 17. */
+#define GPIO_OUTSET_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_OUTSET_PIN17_Msk (0x1UL << GPIO_OUTSET_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_OUTSET_PIN17_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN17_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN17_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 16 : Pin 16. */
+#define GPIO_OUTSET_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_OUTSET_PIN16_Msk (0x1UL << GPIO_OUTSET_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_OUTSET_PIN16_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN16_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN16_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 15 : Pin 15. */
+#define GPIO_OUTSET_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_OUTSET_PIN15_Msk (0x1UL << GPIO_OUTSET_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_OUTSET_PIN15_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN15_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN15_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 14 : Pin 14. */
+#define GPIO_OUTSET_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_OUTSET_PIN14_Msk (0x1UL << GPIO_OUTSET_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_OUTSET_PIN14_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN14_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN14_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 13 : Pin 13. */
+#define GPIO_OUTSET_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_OUTSET_PIN13_Msk (0x1UL << GPIO_OUTSET_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_OUTSET_PIN13_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN13_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN13_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 12 : Pin 12. */
+#define GPIO_OUTSET_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_OUTSET_PIN12_Msk (0x1UL << GPIO_OUTSET_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_OUTSET_PIN12_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN12_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN12_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 11 : Pin 11. */
+#define GPIO_OUTSET_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_OUTSET_PIN11_Msk (0x1UL << GPIO_OUTSET_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_OUTSET_PIN11_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN11_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN11_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 10 : Pin 10. */
+#define GPIO_OUTSET_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_OUTSET_PIN10_Msk (0x1UL << GPIO_OUTSET_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_OUTSET_PIN10_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN10_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN10_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 9 : Pin 9. */
+#define GPIO_OUTSET_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_OUTSET_PIN9_Msk (0x1UL << GPIO_OUTSET_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_OUTSET_PIN9_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN9_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN9_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 8 : Pin 8. */
+#define GPIO_OUTSET_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_OUTSET_PIN8_Msk (0x1UL << GPIO_OUTSET_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_OUTSET_PIN8_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN8_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN8_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 7 : Pin 7. */
+#define GPIO_OUTSET_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_OUTSET_PIN7_Msk (0x1UL << GPIO_OUTSET_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_OUTSET_PIN7_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN7_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN7_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 6 : Pin 6. */
+#define GPIO_OUTSET_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_OUTSET_PIN6_Msk (0x1UL << GPIO_OUTSET_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_OUTSET_PIN6_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN6_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN6_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 5 : Pin 5. */
+#define GPIO_OUTSET_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_OUTSET_PIN5_Msk (0x1UL << GPIO_OUTSET_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_OUTSET_PIN5_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN5_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN5_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 4 : Pin 4. */
+#define GPIO_OUTSET_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_OUTSET_PIN4_Msk (0x1UL << GPIO_OUTSET_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_OUTSET_PIN4_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN4_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN4_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 3 : Pin 3. */
+#define GPIO_OUTSET_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_OUTSET_PIN3_Msk (0x1UL << GPIO_OUTSET_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_OUTSET_PIN3_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN3_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN3_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 2 : Pin 2. */
+#define GPIO_OUTSET_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_OUTSET_PIN2_Msk (0x1UL << GPIO_OUTSET_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_OUTSET_PIN2_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN2_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN2_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 1 : Pin 1. */
+#define GPIO_OUTSET_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_OUTSET_PIN1_Msk (0x1UL << GPIO_OUTSET_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_OUTSET_PIN1_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN1_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN1_Set (1UL) /*!< Set pin driver high. */
+
+/* Bit 0 : Pin 0. */
+#define GPIO_OUTSET_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_OUTSET_PIN0_Msk (0x1UL << GPIO_OUTSET_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_OUTSET_PIN0_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTSET_PIN0_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTSET_PIN0_Set (1UL) /*!< Set pin driver high. */
+
+/* Register: GPIO_OUTCLR */
+/* Description: Clear individual bits in GPIO port. */
+
+/* Bit 31 : Pin 31. */
+#define GPIO_OUTCLR_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_OUTCLR_PIN31_Msk (0x1UL << GPIO_OUTCLR_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_OUTCLR_PIN31_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN31_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN31_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 30 : Pin 30. */
+#define GPIO_OUTCLR_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_OUTCLR_PIN30_Msk (0x1UL << GPIO_OUTCLR_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_OUTCLR_PIN30_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN30_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN30_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 29 : Pin 29. */
+#define GPIO_OUTCLR_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_OUTCLR_PIN29_Msk (0x1UL << GPIO_OUTCLR_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_OUTCLR_PIN29_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN29_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN29_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 28 : Pin 28. */
+#define GPIO_OUTCLR_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_OUTCLR_PIN28_Msk (0x1UL << GPIO_OUTCLR_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_OUTCLR_PIN28_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN28_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN28_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 27 : Pin 27. */
+#define GPIO_OUTCLR_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_OUTCLR_PIN27_Msk (0x1UL << GPIO_OUTCLR_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_OUTCLR_PIN27_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN27_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN27_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 26 : Pin 26. */
+#define GPIO_OUTCLR_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_OUTCLR_PIN26_Msk (0x1UL << GPIO_OUTCLR_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_OUTCLR_PIN26_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN26_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN26_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 25 : Pin 25. */
+#define GPIO_OUTCLR_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_OUTCLR_PIN25_Msk (0x1UL << GPIO_OUTCLR_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_OUTCLR_PIN25_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN25_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN25_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 24 : Pin 24. */
+#define GPIO_OUTCLR_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_OUTCLR_PIN24_Msk (0x1UL << GPIO_OUTCLR_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_OUTCLR_PIN24_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN24_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN24_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 23 : Pin 23. */
+#define GPIO_OUTCLR_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_OUTCLR_PIN23_Msk (0x1UL << GPIO_OUTCLR_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_OUTCLR_PIN23_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN23_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN23_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 22 : Pin 22. */
+#define GPIO_OUTCLR_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_OUTCLR_PIN22_Msk (0x1UL << GPIO_OUTCLR_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_OUTCLR_PIN22_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN22_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN22_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 21 : Pin 21. */
+#define GPIO_OUTCLR_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_OUTCLR_PIN21_Msk (0x1UL << GPIO_OUTCLR_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_OUTCLR_PIN21_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN21_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN21_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 20 : Pin 20. */
+#define GPIO_OUTCLR_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_OUTCLR_PIN20_Msk (0x1UL << GPIO_OUTCLR_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_OUTCLR_PIN20_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN20_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN20_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 19 : Pin 19. */
+#define GPIO_OUTCLR_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_OUTCLR_PIN19_Msk (0x1UL << GPIO_OUTCLR_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_OUTCLR_PIN19_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN19_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN19_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 18 : Pin 18. */
+#define GPIO_OUTCLR_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_OUTCLR_PIN18_Msk (0x1UL << GPIO_OUTCLR_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_OUTCLR_PIN18_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN18_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN18_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 17 : Pin 17. */
+#define GPIO_OUTCLR_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_OUTCLR_PIN17_Msk (0x1UL << GPIO_OUTCLR_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_OUTCLR_PIN17_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN17_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN17_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 16 : Pin 16. */
+#define GPIO_OUTCLR_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_OUTCLR_PIN16_Msk (0x1UL << GPIO_OUTCLR_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_OUTCLR_PIN16_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN16_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN16_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 15 : Pin 15. */
+#define GPIO_OUTCLR_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_OUTCLR_PIN15_Msk (0x1UL << GPIO_OUTCLR_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_OUTCLR_PIN15_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN15_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN15_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 14 : Pin 14. */
+#define GPIO_OUTCLR_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_OUTCLR_PIN14_Msk (0x1UL << GPIO_OUTCLR_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_OUTCLR_PIN14_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN14_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN14_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 13 : Pin 13. */
+#define GPIO_OUTCLR_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_OUTCLR_PIN13_Msk (0x1UL << GPIO_OUTCLR_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_OUTCLR_PIN13_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN13_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN13_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 12 : Pin 12. */
+#define GPIO_OUTCLR_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_OUTCLR_PIN12_Msk (0x1UL << GPIO_OUTCLR_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_OUTCLR_PIN12_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN12_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN12_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 11 : Pin 11. */
+#define GPIO_OUTCLR_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_OUTCLR_PIN11_Msk (0x1UL << GPIO_OUTCLR_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_OUTCLR_PIN11_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN11_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN11_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 10 : Pin 10. */
+#define GPIO_OUTCLR_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_OUTCLR_PIN10_Msk (0x1UL << GPIO_OUTCLR_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_OUTCLR_PIN10_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN10_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN10_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 9 : Pin 9. */
+#define GPIO_OUTCLR_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_OUTCLR_PIN9_Msk (0x1UL << GPIO_OUTCLR_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_OUTCLR_PIN9_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN9_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN9_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 8 : Pin 8. */
+#define GPIO_OUTCLR_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_OUTCLR_PIN8_Msk (0x1UL << GPIO_OUTCLR_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_OUTCLR_PIN8_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN8_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN8_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 7 : Pin 7. */
+#define GPIO_OUTCLR_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_OUTCLR_PIN7_Msk (0x1UL << GPIO_OUTCLR_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_OUTCLR_PIN7_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN7_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN7_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 6 : Pin 6. */
+#define GPIO_OUTCLR_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_OUTCLR_PIN6_Msk (0x1UL << GPIO_OUTCLR_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_OUTCLR_PIN6_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN6_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN6_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 5 : Pin 5. */
+#define GPIO_OUTCLR_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_OUTCLR_PIN5_Msk (0x1UL << GPIO_OUTCLR_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_OUTCLR_PIN5_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN5_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN5_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 4 : Pin 4. */
+#define GPIO_OUTCLR_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_OUTCLR_PIN4_Msk (0x1UL << GPIO_OUTCLR_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_OUTCLR_PIN4_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN4_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN4_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 3 : Pin 3. */
+#define GPIO_OUTCLR_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_OUTCLR_PIN3_Msk (0x1UL << GPIO_OUTCLR_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_OUTCLR_PIN3_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN3_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN3_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 2 : Pin 2. */
+#define GPIO_OUTCLR_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_OUTCLR_PIN2_Msk (0x1UL << GPIO_OUTCLR_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_OUTCLR_PIN2_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN2_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN2_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 1 : Pin 1. */
+#define GPIO_OUTCLR_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_OUTCLR_PIN1_Msk (0x1UL << GPIO_OUTCLR_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_OUTCLR_PIN1_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN1_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN1_Clear (1UL) /*!< Set pin driver low. */
+
+/* Bit 0 : Pin 0. */
+#define GPIO_OUTCLR_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_OUTCLR_PIN0_Msk (0x1UL << GPIO_OUTCLR_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_OUTCLR_PIN0_Low (0UL) /*!< Pin driver is low. */
+#define GPIO_OUTCLR_PIN0_High (1UL) /*!< Pin driver is high. */
+#define GPIO_OUTCLR_PIN0_Clear (1UL) /*!< Set pin driver low. */
+
+/* Register: GPIO_IN */
+/* Description: Read GPIO port. */
+
+/* Bit 31 : Pin 31. */
+#define GPIO_IN_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_IN_PIN31_Msk (0x1UL << GPIO_IN_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_IN_PIN31_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN31_High (1UL) /*!< Pin input is high. */
+
+/* Bit 30 : Pin 30. */
+#define GPIO_IN_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_IN_PIN30_Msk (0x1UL << GPIO_IN_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_IN_PIN30_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN30_High (1UL) /*!< Pin input is high. */
+
+/* Bit 29 : Pin 29. */
+#define GPIO_IN_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_IN_PIN29_Msk (0x1UL << GPIO_IN_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_IN_PIN29_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN29_High (1UL) /*!< Pin input is high. */
+
+/* Bit 28 : Pin 28. */
+#define GPIO_IN_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_IN_PIN28_Msk (0x1UL << GPIO_IN_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_IN_PIN28_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN28_High (1UL) /*!< Pin input is high. */
+
+/* Bit 27 : Pin 27. */
+#define GPIO_IN_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_IN_PIN27_Msk (0x1UL << GPIO_IN_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_IN_PIN27_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN27_High (1UL) /*!< Pin input is high. */
+
+/* Bit 26 : Pin 26. */
+#define GPIO_IN_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_IN_PIN26_Msk (0x1UL << GPIO_IN_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_IN_PIN26_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN26_High (1UL) /*!< Pin input is high. */
+
+/* Bit 25 : Pin 25. */
+#define GPIO_IN_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_IN_PIN25_Msk (0x1UL << GPIO_IN_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_IN_PIN25_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN25_High (1UL) /*!< Pin input is high. */
+
+/* Bit 24 : Pin 24. */
+#define GPIO_IN_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_IN_PIN24_Msk (0x1UL << GPIO_IN_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_IN_PIN24_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN24_High (1UL) /*!< Pin input is high. */
+
+/* Bit 23 : Pin 23. */
+#define GPIO_IN_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_IN_PIN23_Msk (0x1UL << GPIO_IN_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_IN_PIN23_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN23_High (1UL) /*!< Pin input is high. */
+
+/* Bit 22 : Pin 22. */
+#define GPIO_IN_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_IN_PIN22_Msk (0x1UL << GPIO_IN_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_IN_PIN22_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN22_High (1UL) /*!< Pin input is high. */
+
+/* Bit 21 : Pin 21. */
+#define GPIO_IN_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_IN_PIN21_Msk (0x1UL << GPIO_IN_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_IN_PIN21_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN21_High (1UL) /*!< Pin input is high. */
+
+/* Bit 20 : Pin 20. */
+#define GPIO_IN_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_IN_PIN20_Msk (0x1UL << GPIO_IN_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_IN_PIN20_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN20_High (1UL) /*!< Pin input is high. */
+
+/* Bit 19 : Pin 19. */
+#define GPIO_IN_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_IN_PIN19_Msk (0x1UL << GPIO_IN_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_IN_PIN19_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN19_High (1UL) /*!< Pin input is high. */
+
+/* Bit 18 : Pin 18. */
+#define GPIO_IN_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_IN_PIN18_Msk (0x1UL << GPIO_IN_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_IN_PIN18_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN18_High (1UL) /*!< Pin input is high. */
+
+/* Bit 17 : Pin 17. */
+#define GPIO_IN_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_IN_PIN17_Msk (0x1UL << GPIO_IN_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_IN_PIN17_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN17_High (1UL) /*!< Pin input is high. */
+
+/* Bit 16 : Pin 16. */
+#define GPIO_IN_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_IN_PIN16_Msk (0x1UL << GPIO_IN_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_IN_PIN16_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN16_High (1UL) /*!< Pin input is high. */
+
+/* Bit 15 : Pin 15. */
+#define GPIO_IN_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_IN_PIN15_Msk (0x1UL << GPIO_IN_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_IN_PIN15_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN15_High (1UL) /*!< Pin input is high. */
+
+/* Bit 14 : Pin 14. */
+#define GPIO_IN_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_IN_PIN14_Msk (0x1UL << GPIO_IN_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_IN_PIN14_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN14_High (1UL) /*!< Pin input is high. */
+
+/* Bit 13 : Pin 13. */
+#define GPIO_IN_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_IN_PIN13_Msk (0x1UL << GPIO_IN_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_IN_PIN13_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN13_High (1UL) /*!< Pin input is high. */
+
+/* Bit 12 : Pin 12. */
+#define GPIO_IN_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_IN_PIN12_Msk (0x1UL << GPIO_IN_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_IN_PIN12_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN12_High (1UL) /*!< Pin input is high. */
+
+/* Bit 11 : Pin 11. */
+#define GPIO_IN_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_IN_PIN11_Msk (0x1UL << GPIO_IN_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_IN_PIN11_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN11_High (1UL) /*!< Pin input is high. */
+
+/* Bit 10 : Pin 10. */
+#define GPIO_IN_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_IN_PIN10_Msk (0x1UL << GPIO_IN_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_IN_PIN10_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN10_High (1UL) /*!< Pin input is high. */
+
+/* Bit 9 : Pin 9. */
+#define GPIO_IN_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_IN_PIN9_Msk (0x1UL << GPIO_IN_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_IN_PIN9_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN9_High (1UL) /*!< Pin input is high. */
+
+/* Bit 8 : Pin 8. */
+#define GPIO_IN_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_IN_PIN8_Msk (0x1UL << GPIO_IN_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_IN_PIN8_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN8_High (1UL) /*!< Pin input is high. */
+
+/* Bit 7 : Pin 7. */
+#define GPIO_IN_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_IN_PIN7_Msk (0x1UL << GPIO_IN_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_IN_PIN7_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN7_High (1UL) /*!< Pin input is high. */
+
+/* Bit 6 : Pin 6. */
+#define GPIO_IN_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_IN_PIN6_Msk (0x1UL << GPIO_IN_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_IN_PIN6_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN6_High (1UL) /*!< Pin input is high. */
+
+/* Bit 5 : Pin 5. */
+#define GPIO_IN_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_IN_PIN5_Msk (0x1UL << GPIO_IN_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_IN_PIN5_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN5_High (1UL) /*!< Pin input is high. */
+
+/* Bit 4 : Pin 4. */
+#define GPIO_IN_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_IN_PIN4_Msk (0x1UL << GPIO_IN_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_IN_PIN4_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN4_High (1UL) /*!< Pin input is high. */
+
+/* Bit 3 : Pin 3. */
+#define GPIO_IN_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_IN_PIN3_Msk (0x1UL << GPIO_IN_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_IN_PIN3_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN3_High (1UL) /*!< Pin input is high. */
+
+/* Bit 2 : Pin 2. */
+#define GPIO_IN_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_IN_PIN2_Msk (0x1UL << GPIO_IN_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_IN_PIN2_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN2_High (1UL) /*!< Pin input is high. */
+
+/* Bit 1 : Pin 1. */
+#define GPIO_IN_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_IN_PIN1_Msk (0x1UL << GPIO_IN_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_IN_PIN1_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN1_High (1UL) /*!< Pin input is high. */
+
+/* Bit 0 : Pin 0. */
+#define GPIO_IN_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_IN_PIN0_Msk (0x1UL << GPIO_IN_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_IN_PIN0_Low (0UL) /*!< Pin input is low. */
+#define GPIO_IN_PIN0_High (1UL) /*!< Pin input is high. */
+
+/* Register: GPIO_DIR */
+/* Description: Direction of GPIO pins. */
+
+/* Bit 31 : Pin 31. */
+#define GPIO_DIR_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_DIR_PIN31_Msk (0x1UL << GPIO_DIR_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_DIR_PIN31_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN31_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 30 : Pin 30. */
+#define GPIO_DIR_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_DIR_PIN30_Msk (0x1UL << GPIO_DIR_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_DIR_PIN30_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN30_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 29 : Pin 29. */
+#define GPIO_DIR_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_DIR_PIN29_Msk (0x1UL << GPIO_DIR_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_DIR_PIN29_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN29_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 28 : Pin 28. */
+#define GPIO_DIR_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_DIR_PIN28_Msk (0x1UL << GPIO_DIR_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_DIR_PIN28_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN28_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 27 : Pin 27. */
+#define GPIO_DIR_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_DIR_PIN27_Msk (0x1UL << GPIO_DIR_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_DIR_PIN27_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN27_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 26 : Pin 26. */
+#define GPIO_DIR_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_DIR_PIN26_Msk (0x1UL << GPIO_DIR_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_DIR_PIN26_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN26_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 25 : Pin 25. */
+#define GPIO_DIR_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_DIR_PIN25_Msk (0x1UL << GPIO_DIR_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_DIR_PIN25_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN25_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 24 : Pin 24. */
+#define GPIO_DIR_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_DIR_PIN24_Msk (0x1UL << GPIO_DIR_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_DIR_PIN24_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN24_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 23 : Pin 23. */
+#define GPIO_DIR_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_DIR_PIN23_Msk (0x1UL << GPIO_DIR_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_DIR_PIN23_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN23_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 22 : Pin 22. */
+#define GPIO_DIR_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_DIR_PIN22_Msk (0x1UL << GPIO_DIR_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_DIR_PIN22_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN22_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 21 : Pin 21. */
+#define GPIO_DIR_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_DIR_PIN21_Msk (0x1UL << GPIO_DIR_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_DIR_PIN21_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN21_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 20 : Pin 20. */
+#define GPIO_DIR_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_DIR_PIN20_Msk (0x1UL << GPIO_DIR_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_DIR_PIN20_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN20_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 19 : Pin 19. */
+#define GPIO_DIR_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_DIR_PIN19_Msk (0x1UL << GPIO_DIR_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_DIR_PIN19_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN19_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 18 : Pin 18. */
+#define GPIO_DIR_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_DIR_PIN18_Msk (0x1UL << GPIO_DIR_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_DIR_PIN18_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN18_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 17 : Pin 17. */
+#define GPIO_DIR_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_DIR_PIN17_Msk (0x1UL << GPIO_DIR_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_DIR_PIN17_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN17_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 16 : Pin 16. */
+#define GPIO_DIR_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_DIR_PIN16_Msk (0x1UL << GPIO_DIR_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_DIR_PIN16_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN16_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 15 : Pin 15. */
+#define GPIO_DIR_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_DIR_PIN15_Msk (0x1UL << GPIO_DIR_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_DIR_PIN15_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN15_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 14 : Pin 14. */
+#define GPIO_DIR_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_DIR_PIN14_Msk (0x1UL << GPIO_DIR_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_DIR_PIN14_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN14_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 13 : Pin 13. */
+#define GPIO_DIR_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_DIR_PIN13_Msk (0x1UL << GPIO_DIR_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_DIR_PIN13_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN13_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 12 : Pin 12. */
+#define GPIO_DIR_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_DIR_PIN12_Msk (0x1UL << GPIO_DIR_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_DIR_PIN12_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN12_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 11 : Pin 11. */
+#define GPIO_DIR_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_DIR_PIN11_Msk (0x1UL << GPIO_DIR_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_DIR_PIN11_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN11_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 10 : Pin 10. */
+#define GPIO_DIR_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_DIR_PIN10_Msk (0x1UL << GPIO_DIR_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_DIR_PIN10_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN10_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 9 : Pin 9. */
+#define GPIO_DIR_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_DIR_PIN9_Msk (0x1UL << GPIO_DIR_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_DIR_PIN9_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN9_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 8 : Pin 8. */
+#define GPIO_DIR_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_DIR_PIN8_Msk (0x1UL << GPIO_DIR_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_DIR_PIN8_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN8_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 7 : Pin 7. */
+#define GPIO_DIR_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_DIR_PIN7_Msk (0x1UL << GPIO_DIR_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_DIR_PIN7_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN7_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 6 : Pin 6. */
+#define GPIO_DIR_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_DIR_PIN6_Msk (0x1UL << GPIO_DIR_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_DIR_PIN6_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN6_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 5 : Pin 5. */
+#define GPIO_DIR_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_DIR_PIN5_Msk (0x1UL << GPIO_DIR_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_DIR_PIN5_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN5_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 4 : Pin 4. */
+#define GPIO_DIR_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_DIR_PIN4_Msk (0x1UL << GPIO_DIR_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_DIR_PIN4_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN4_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 3 : Pin 3. */
+#define GPIO_DIR_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_DIR_PIN3_Msk (0x1UL << GPIO_DIR_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_DIR_PIN3_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN3_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 2 : Pin 2. */
+#define GPIO_DIR_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_DIR_PIN2_Msk (0x1UL << GPIO_DIR_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_DIR_PIN2_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN2_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 1 : Pin 1. */
+#define GPIO_DIR_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_DIR_PIN1_Msk (0x1UL << GPIO_DIR_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_DIR_PIN1_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN1_Output (1UL) /*!< Pin set as output. */
+
+/* Bit 0 : Pin 0. */
+#define GPIO_DIR_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_DIR_PIN0_Msk (0x1UL << GPIO_DIR_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_DIR_PIN0_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIR_PIN0_Output (1UL) /*!< Pin set as output. */
+
+/* Register: GPIO_DIRSET */
+/* Description: DIR set register. */
+
+/* Bit 31 : Set as output pin 31. */
+#define GPIO_DIRSET_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_DIRSET_PIN31_Msk (0x1UL << GPIO_DIRSET_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_DIRSET_PIN31_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN31_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN31_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 30 : Set as output pin 30. */
+#define GPIO_DIRSET_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_DIRSET_PIN30_Msk (0x1UL << GPIO_DIRSET_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_DIRSET_PIN30_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN30_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN30_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 29 : Set as output pin 29. */
+#define GPIO_DIRSET_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_DIRSET_PIN29_Msk (0x1UL << GPIO_DIRSET_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_DIRSET_PIN29_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN29_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN29_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 28 : Set as output pin 28. */
+#define GPIO_DIRSET_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_DIRSET_PIN28_Msk (0x1UL << GPIO_DIRSET_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_DIRSET_PIN28_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN28_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN28_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 27 : Set as output pin 27. */
+#define GPIO_DIRSET_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_DIRSET_PIN27_Msk (0x1UL << GPIO_DIRSET_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_DIRSET_PIN27_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN27_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN27_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 26 : Set as output pin 26. */
+#define GPIO_DIRSET_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_DIRSET_PIN26_Msk (0x1UL << GPIO_DIRSET_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_DIRSET_PIN26_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN26_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN26_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 25 : Set as output pin 25. */
+#define GPIO_DIRSET_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_DIRSET_PIN25_Msk (0x1UL << GPIO_DIRSET_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_DIRSET_PIN25_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN25_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN25_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 24 : Set as output pin 24. */
+#define GPIO_DIRSET_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_DIRSET_PIN24_Msk (0x1UL << GPIO_DIRSET_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_DIRSET_PIN24_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN24_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN24_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 23 : Set as output pin 23. */
+#define GPIO_DIRSET_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_DIRSET_PIN23_Msk (0x1UL << GPIO_DIRSET_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_DIRSET_PIN23_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN23_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN23_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 22 : Set as output pin 22. */
+#define GPIO_DIRSET_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_DIRSET_PIN22_Msk (0x1UL << GPIO_DIRSET_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_DIRSET_PIN22_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN22_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN22_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 21 : Set as output pin 21. */
+#define GPIO_DIRSET_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_DIRSET_PIN21_Msk (0x1UL << GPIO_DIRSET_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_DIRSET_PIN21_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN21_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN21_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 20 : Set as output pin 20. */
+#define GPIO_DIRSET_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_DIRSET_PIN20_Msk (0x1UL << GPIO_DIRSET_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_DIRSET_PIN20_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN20_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN20_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 19 : Set as output pin 19. */
+#define GPIO_DIRSET_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_DIRSET_PIN19_Msk (0x1UL << GPIO_DIRSET_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_DIRSET_PIN19_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN19_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN19_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 18 : Set as output pin 18. */
+#define GPIO_DIRSET_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_DIRSET_PIN18_Msk (0x1UL << GPIO_DIRSET_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_DIRSET_PIN18_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN18_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN18_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 17 : Set as output pin 17. */
+#define GPIO_DIRSET_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_DIRSET_PIN17_Msk (0x1UL << GPIO_DIRSET_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_DIRSET_PIN17_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN17_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN17_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 16 : Set as output pin 16. */
+#define GPIO_DIRSET_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_DIRSET_PIN16_Msk (0x1UL << GPIO_DIRSET_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_DIRSET_PIN16_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN16_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN16_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 15 : Set as output pin 15. */
+#define GPIO_DIRSET_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_DIRSET_PIN15_Msk (0x1UL << GPIO_DIRSET_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_DIRSET_PIN15_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN15_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN15_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 14 : Set as output pin 14. */
+#define GPIO_DIRSET_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_DIRSET_PIN14_Msk (0x1UL << GPIO_DIRSET_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_DIRSET_PIN14_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN14_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN14_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 13 : Set as output pin 13. */
+#define GPIO_DIRSET_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_DIRSET_PIN13_Msk (0x1UL << GPIO_DIRSET_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_DIRSET_PIN13_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN13_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN13_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 12 : Set as output pin 12. */
+#define GPIO_DIRSET_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_DIRSET_PIN12_Msk (0x1UL << GPIO_DIRSET_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_DIRSET_PIN12_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN12_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN12_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 11 : Set as output pin 11. */
+#define GPIO_DIRSET_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_DIRSET_PIN11_Msk (0x1UL << GPIO_DIRSET_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_DIRSET_PIN11_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN11_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN11_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 10 : Set as output pin 10. */
+#define GPIO_DIRSET_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_DIRSET_PIN10_Msk (0x1UL << GPIO_DIRSET_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_DIRSET_PIN10_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN10_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN10_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 9 : Set as output pin 9. */
+#define GPIO_DIRSET_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_DIRSET_PIN9_Msk (0x1UL << GPIO_DIRSET_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_DIRSET_PIN9_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN9_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN9_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 8 : Set as output pin 8. */
+#define GPIO_DIRSET_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_DIRSET_PIN8_Msk (0x1UL << GPIO_DIRSET_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_DIRSET_PIN8_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN8_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN8_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 7 : Set as output pin 7. */
+#define GPIO_DIRSET_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_DIRSET_PIN7_Msk (0x1UL << GPIO_DIRSET_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_DIRSET_PIN7_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN7_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN7_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 6 : Set as output pin 6. */
+#define GPIO_DIRSET_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_DIRSET_PIN6_Msk (0x1UL << GPIO_DIRSET_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_DIRSET_PIN6_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN6_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN6_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 5 : Set as output pin 5. */
+#define GPIO_DIRSET_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_DIRSET_PIN5_Msk (0x1UL << GPIO_DIRSET_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_DIRSET_PIN5_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN5_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN5_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 4 : Set as output pin 4. */
+#define GPIO_DIRSET_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_DIRSET_PIN4_Msk (0x1UL << GPIO_DIRSET_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_DIRSET_PIN4_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN4_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN4_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 3 : Set as output pin 3. */
+#define GPIO_DIRSET_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_DIRSET_PIN3_Msk (0x1UL << GPIO_DIRSET_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_DIRSET_PIN3_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN3_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN3_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 2 : Set as output pin 2. */
+#define GPIO_DIRSET_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_DIRSET_PIN2_Msk (0x1UL << GPIO_DIRSET_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_DIRSET_PIN2_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN2_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN2_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 1 : Set as output pin 1. */
+#define GPIO_DIRSET_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_DIRSET_PIN1_Msk (0x1UL << GPIO_DIRSET_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_DIRSET_PIN1_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN1_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN1_Set (1UL) /*!< Set pin as output. */
+
+/* Bit 0 : Set as output pin 0. */
+#define GPIO_DIRSET_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_DIRSET_PIN0_Msk (0x1UL << GPIO_DIRSET_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_DIRSET_PIN0_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRSET_PIN0_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRSET_PIN0_Set (1UL) /*!< Set pin as output. */
+
+/* Register: GPIO_DIRCLR */
+/* Description: DIR clear register. */
+
+/* Bit 31 : Set as input pin 31. */
+#define GPIO_DIRCLR_PIN31_Pos (31UL) /*!< Position of PIN31 field. */
+#define GPIO_DIRCLR_PIN31_Msk (0x1UL << GPIO_DIRCLR_PIN31_Pos) /*!< Bit mask of PIN31 field. */
+#define GPIO_DIRCLR_PIN31_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN31_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN31_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 30 : Set as input pin 30. */
+#define GPIO_DIRCLR_PIN30_Pos (30UL) /*!< Position of PIN30 field. */
+#define GPIO_DIRCLR_PIN30_Msk (0x1UL << GPIO_DIRCLR_PIN30_Pos) /*!< Bit mask of PIN30 field. */
+#define GPIO_DIRCLR_PIN30_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN30_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN30_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 29 : Set as input pin 29. */
+#define GPIO_DIRCLR_PIN29_Pos (29UL) /*!< Position of PIN29 field. */
+#define GPIO_DIRCLR_PIN29_Msk (0x1UL << GPIO_DIRCLR_PIN29_Pos) /*!< Bit mask of PIN29 field. */
+#define GPIO_DIRCLR_PIN29_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN29_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN29_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 28 : Set as input pin 28. */
+#define GPIO_DIRCLR_PIN28_Pos (28UL) /*!< Position of PIN28 field. */
+#define GPIO_DIRCLR_PIN28_Msk (0x1UL << GPIO_DIRCLR_PIN28_Pos) /*!< Bit mask of PIN28 field. */
+#define GPIO_DIRCLR_PIN28_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN28_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN28_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 27 : Set as input pin 27. */
+#define GPIO_DIRCLR_PIN27_Pos (27UL) /*!< Position of PIN27 field. */
+#define GPIO_DIRCLR_PIN27_Msk (0x1UL << GPIO_DIRCLR_PIN27_Pos) /*!< Bit mask of PIN27 field. */
+#define GPIO_DIRCLR_PIN27_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN27_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN27_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 26 : Set as input pin 26. */
+#define GPIO_DIRCLR_PIN26_Pos (26UL) /*!< Position of PIN26 field. */
+#define GPIO_DIRCLR_PIN26_Msk (0x1UL << GPIO_DIRCLR_PIN26_Pos) /*!< Bit mask of PIN26 field. */
+#define GPIO_DIRCLR_PIN26_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN26_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN26_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 25 : Set as input pin 25. */
+#define GPIO_DIRCLR_PIN25_Pos (25UL) /*!< Position of PIN25 field. */
+#define GPIO_DIRCLR_PIN25_Msk (0x1UL << GPIO_DIRCLR_PIN25_Pos) /*!< Bit mask of PIN25 field. */
+#define GPIO_DIRCLR_PIN25_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN25_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN25_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 24 : Set as input pin 24. */
+#define GPIO_DIRCLR_PIN24_Pos (24UL) /*!< Position of PIN24 field. */
+#define GPIO_DIRCLR_PIN24_Msk (0x1UL << GPIO_DIRCLR_PIN24_Pos) /*!< Bit mask of PIN24 field. */
+#define GPIO_DIRCLR_PIN24_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN24_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN24_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 23 : Set as input pin 23. */
+#define GPIO_DIRCLR_PIN23_Pos (23UL) /*!< Position of PIN23 field. */
+#define GPIO_DIRCLR_PIN23_Msk (0x1UL << GPIO_DIRCLR_PIN23_Pos) /*!< Bit mask of PIN23 field. */
+#define GPIO_DIRCLR_PIN23_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN23_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN23_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 22 : Set as input pin 22. */
+#define GPIO_DIRCLR_PIN22_Pos (22UL) /*!< Position of PIN22 field. */
+#define GPIO_DIRCLR_PIN22_Msk (0x1UL << GPIO_DIRCLR_PIN22_Pos) /*!< Bit mask of PIN22 field. */
+#define GPIO_DIRCLR_PIN22_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN22_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN22_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 21 : Set as input pin 21. */
+#define GPIO_DIRCLR_PIN21_Pos (21UL) /*!< Position of PIN21 field. */
+#define GPIO_DIRCLR_PIN21_Msk (0x1UL << GPIO_DIRCLR_PIN21_Pos) /*!< Bit mask of PIN21 field. */
+#define GPIO_DIRCLR_PIN21_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN21_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN21_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 20 : Set as input pin 20. */
+#define GPIO_DIRCLR_PIN20_Pos (20UL) /*!< Position of PIN20 field. */
+#define GPIO_DIRCLR_PIN20_Msk (0x1UL << GPIO_DIRCLR_PIN20_Pos) /*!< Bit mask of PIN20 field. */
+#define GPIO_DIRCLR_PIN20_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN20_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN20_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 19 : Set as input pin 19. */
+#define GPIO_DIRCLR_PIN19_Pos (19UL) /*!< Position of PIN19 field. */
+#define GPIO_DIRCLR_PIN19_Msk (0x1UL << GPIO_DIRCLR_PIN19_Pos) /*!< Bit mask of PIN19 field. */
+#define GPIO_DIRCLR_PIN19_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN19_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN19_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 18 : Set as input pin 18. */
+#define GPIO_DIRCLR_PIN18_Pos (18UL) /*!< Position of PIN18 field. */
+#define GPIO_DIRCLR_PIN18_Msk (0x1UL << GPIO_DIRCLR_PIN18_Pos) /*!< Bit mask of PIN18 field. */
+#define GPIO_DIRCLR_PIN18_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN18_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN18_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 17 : Set as input pin 17. */
+#define GPIO_DIRCLR_PIN17_Pos (17UL) /*!< Position of PIN17 field. */
+#define GPIO_DIRCLR_PIN17_Msk (0x1UL << GPIO_DIRCLR_PIN17_Pos) /*!< Bit mask of PIN17 field. */
+#define GPIO_DIRCLR_PIN17_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN17_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN17_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 16 : Set as input pin 16. */
+#define GPIO_DIRCLR_PIN16_Pos (16UL) /*!< Position of PIN16 field. */
+#define GPIO_DIRCLR_PIN16_Msk (0x1UL << GPIO_DIRCLR_PIN16_Pos) /*!< Bit mask of PIN16 field. */
+#define GPIO_DIRCLR_PIN16_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN16_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN16_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 15 : Set as input pin 15. */
+#define GPIO_DIRCLR_PIN15_Pos (15UL) /*!< Position of PIN15 field. */
+#define GPIO_DIRCLR_PIN15_Msk (0x1UL << GPIO_DIRCLR_PIN15_Pos) /*!< Bit mask of PIN15 field. */
+#define GPIO_DIRCLR_PIN15_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN15_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN15_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 14 : Set as input pin 14. */
+#define GPIO_DIRCLR_PIN14_Pos (14UL) /*!< Position of PIN14 field. */
+#define GPIO_DIRCLR_PIN14_Msk (0x1UL << GPIO_DIRCLR_PIN14_Pos) /*!< Bit mask of PIN14 field. */
+#define GPIO_DIRCLR_PIN14_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN14_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN14_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 13 : Set as input pin 13. */
+#define GPIO_DIRCLR_PIN13_Pos (13UL) /*!< Position of PIN13 field. */
+#define GPIO_DIRCLR_PIN13_Msk (0x1UL << GPIO_DIRCLR_PIN13_Pos) /*!< Bit mask of PIN13 field. */
+#define GPIO_DIRCLR_PIN13_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN13_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN13_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 12 : Set as input pin 12. */
+#define GPIO_DIRCLR_PIN12_Pos (12UL) /*!< Position of PIN12 field. */
+#define GPIO_DIRCLR_PIN12_Msk (0x1UL << GPIO_DIRCLR_PIN12_Pos) /*!< Bit mask of PIN12 field. */
+#define GPIO_DIRCLR_PIN12_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN12_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN12_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 11 : Set as input pin 11. */
+#define GPIO_DIRCLR_PIN11_Pos (11UL) /*!< Position of PIN11 field. */
+#define GPIO_DIRCLR_PIN11_Msk (0x1UL << GPIO_DIRCLR_PIN11_Pos) /*!< Bit mask of PIN11 field. */
+#define GPIO_DIRCLR_PIN11_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN11_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN11_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 10 : Set as input pin 10. */
+#define GPIO_DIRCLR_PIN10_Pos (10UL) /*!< Position of PIN10 field. */
+#define GPIO_DIRCLR_PIN10_Msk (0x1UL << GPIO_DIRCLR_PIN10_Pos) /*!< Bit mask of PIN10 field. */
+#define GPIO_DIRCLR_PIN10_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN10_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN10_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 9 : Set as input pin 9. */
+#define GPIO_DIRCLR_PIN9_Pos (9UL) /*!< Position of PIN9 field. */
+#define GPIO_DIRCLR_PIN9_Msk (0x1UL << GPIO_DIRCLR_PIN9_Pos) /*!< Bit mask of PIN9 field. */
+#define GPIO_DIRCLR_PIN9_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN9_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN9_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 8 : Set as input pin 8. */
+#define GPIO_DIRCLR_PIN8_Pos (8UL) /*!< Position of PIN8 field. */
+#define GPIO_DIRCLR_PIN8_Msk (0x1UL << GPIO_DIRCLR_PIN8_Pos) /*!< Bit mask of PIN8 field. */
+#define GPIO_DIRCLR_PIN8_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN8_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN8_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 7 : Set as input pin 7. */
+#define GPIO_DIRCLR_PIN7_Pos (7UL) /*!< Position of PIN7 field. */
+#define GPIO_DIRCLR_PIN7_Msk (0x1UL << GPIO_DIRCLR_PIN7_Pos) /*!< Bit mask of PIN7 field. */
+#define GPIO_DIRCLR_PIN7_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN7_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN7_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 6 : Set as input pin 6. */
+#define GPIO_DIRCLR_PIN6_Pos (6UL) /*!< Position of PIN6 field. */
+#define GPIO_DIRCLR_PIN6_Msk (0x1UL << GPIO_DIRCLR_PIN6_Pos) /*!< Bit mask of PIN6 field. */
+#define GPIO_DIRCLR_PIN6_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN6_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN6_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 5 : Set as input pin 5. */
+#define GPIO_DIRCLR_PIN5_Pos (5UL) /*!< Position of PIN5 field. */
+#define GPIO_DIRCLR_PIN5_Msk (0x1UL << GPIO_DIRCLR_PIN5_Pos) /*!< Bit mask of PIN5 field. */
+#define GPIO_DIRCLR_PIN5_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN5_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN5_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 4 : Set as input pin 4. */
+#define GPIO_DIRCLR_PIN4_Pos (4UL) /*!< Position of PIN4 field. */
+#define GPIO_DIRCLR_PIN4_Msk (0x1UL << GPIO_DIRCLR_PIN4_Pos) /*!< Bit mask of PIN4 field. */
+#define GPIO_DIRCLR_PIN4_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN4_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN4_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 3 : Set as input pin 3. */
+#define GPIO_DIRCLR_PIN3_Pos (3UL) /*!< Position of PIN3 field. */
+#define GPIO_DIRCLR_PIN3_Msk (0x1UL << GPIO_DIRCLR_PIN3_Pos) /*!< Bit mask of PIN3 field. */
+#define GPIO_DIRCLR_PIN3_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN3_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN3_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 2 : Set as input pin 2. */
+#define GPIO_DIRCLR_PIN2_Pos (2UL) /*!< Position of PIN2 field. */
+#define GPIO_DIRCLR_PIN2_Msk (0x1UL << GPIO_DIRCLR_PIN2_Pos) /*!< Bit mask of PIN2 field. */
+#define GPIO_DIRCLR_PIN2_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN2_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN2_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 1 : Set as input pin 1. */
+#define GPIO_DIRCLR_PIN1_Pos (1UL) /*!< Position of PIN1 field. */
+#define GPIO_DIRCLR_PIN1_Msk (0x1UL << GPIO_DIRCLR_PIN1_Pos) /*!< Bit mask of PIN1 field. */
+#define GPIO_DIRCLR_PIN1_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN1_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN1_Clear (1UL) /*!< Set pin as input. */
+
+/* Bit 0 : Set as input pin 0. */
+#define GPIO_DIRCLR_PIN0_Pos (0UL) /*!< Position of PIN0 field. */
+#define GPIO_DIRCLR_PIN0_Msk (0x1UL << GPIO_DIRCLR_PIN0_Pos) /*!< Bit mask of PIN0 field. */
+#define GPIO_DIRCLR_PIN0_Input (0UL) /*!< Pin set as input. */
+#define GPIO_DIRCLR_PIN0_Output (1UL) /*!< Pin set as output. */
+#define GPIO_DIRCLR_PIN0_Clear (1UL) /*!< Set pin as input. */
+
+/* Register: GPIO_PIN_CNF */
+/* Description: Configuration of GPIO pins. */
+
+/* Bits 17..16 : Pin sensing mechanism. */
+#define GPIO_PIN_CNF_SENSE_Pos (16UL) /*!< Position of SENSE field. */
+#define GPIO_PIN_CNF_SENSE_Msk (0x3UL << GPIO_PIN_CNF_SENSE_Pos) /*!< Bit mask of SENSE field. */
+#define GPIO_PIN_CNF_SENSE_Disabled (0x00UL) /*!< Disabled. */
+#define GPIO_PIN_CNF_SENSE_High (0x02UL) /*!< Wakeup on high level. */
+#define GPIO_PIN_CNF_SENSE_Low (0x03UL) /*!< Wakeup on low level. */
+
+/* Bits 10..8 : Drive configuration. */
+#define GPIO_PIN_CNF_DRIVE_Pos (8UL) /*!< Position of DRIVE field. */
+#define GPIO_PIN_CNF_DRIVE_Msk (0x7UL << GPIO_PIN_CNF_DRIVE_Pos) /*!< Bit mask of DRIVE field. */
+#define GPIO_PIN_CNF_DRIVE_S0S1 (0x00UL) /*!< Standard '0', Standard '1'. */
+#define GPIO_PIN_CNF_DRIVE_H0S1 (0x01UL) /*!< High '0', Standard '1'. */
+#define GPIO_PIN_CNF_DRIVE_S0H1 (0x02UL) /*!< Standard '0', High '1'. */
+#define GPIO_PIN_CNF_DRIVE_H0H1 (0x03UL) /*!< High '0', High '1'. */
+#define GPIO_PIN_CNF_DRIVE_D0S1 (0x04UL) /*!< Disconnected '0', Standard '1'. */
+#define GPIO_PIN_CNF_DRIVE_D0H1 (0x05UL) /*!< Disconnected '0', High '1'. */
+#define GPIO_PIN_CNF_DRIVE_S0D1 (0x06UL) /*!< Standard '0', Disconnected '1'. */
+#define GPIO_PIN_CNF_DRIVE_H0D1 (0x07UL) /*!< High '0', Disconnected '1'. */
+
+/* Bits 3..2 : Pull-up or -down configuration. */
+#define GPIO_PIN_CNF_PULL_Pos (2UL) /*!< Position of PULL field. */
+#define GPIO_PIN_CNF_PULL_Msk (0x3UL << GPIO_PIN_CNF_PULL_Pos) /*!< Bit mask of PULL field. */
+#define GPIO_PIN_CNF_PULL_Disabled (0x00UL) /*!< No pull. */
+#define GPIO_PIN_CNF_PULL_Pulldown (0x01UL) /*!< Pulldown on pin. */
+#define GPIO_PIN_CNF_PULL_Pullup (0x03UL) /*!< Pullup on pin. */
+
+/* Bit 1 : Connect or disconnect input path. */
+#define GPIO_PIN_CNF_INPUT_Pos (1UL) /*!< Position of INPUT field. */
+#define GPIO_PIN_CNF_INPUT_Msk (0x1UL << GPIO_PIN_CNF_INPUT_Pos) /*!< Bit mask of INPUT field. */
+#define GPIO_PIN_CNF_INPUT_Connect (0UL) /*!< Connect input pin. */
+#define GPIO_PIN_CNF_INPUT_Disconnect (1UL) /*!< Disconnect input pin. */
+
+/* Bit 0 : Pin direction. */
+#define GPIO_PIN_CNF_DIR_Pos (0UL) /*!< Position of DIR field. */
+#define GPIO_PIN_CNF_DIR_Msk (0x1UL << GPIO_PIN_CNF_DIR_Pos) /*!< Bit mask of DIR field. */
+#define GPIO_PIN_CNF_DIR_Input (0UL) /*!< Configure pin as an input pin. */
+#define GPIO_PIN_CNF_DIR_Output (1UL) /*!< Configure pin as an output pin. */
+
+
+/* Peripheral: GPIOTE */
+/* Description: GPIO tasks and events. */
+
+/* Register: GPIOTE_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 31 : Enable interrupt on PORT event. */
+#define GPIOTE_INTENSET_PORT_Pos (31UL) /*!< Position of PORT field. */
+#define GPIOTE_INTENSET_PORT_Msk (0x1UL << GPIOTE_INTENSET_PORT_Pos) /*!< Bit mask of PORT field. */
+#define GPIOTE_INTENSET_PORT_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENSET_PORT_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENSET_PORT_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 3 : Enable interrupt on IN[3] event. */
+#define GPIOTE_INTENSET_IN3_Pos (3UL) /*!< Position of IN3 field. */
+#define GPIOTE_INTENSET_IN3_Msk (0x1UL << GPIOTE_INTENSET_IN3_Pos) /*!< Bit mask of IN3 field. */
+#define GPIOTE_INTENSET_IN3_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENSET_IN3_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENSET_IN3_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 2 : Enable interrupt on IN[2] event. */
+#define GPIOTE_INTENSET_IN2_Pos (2UL) /*!< Position of IN2 field. */
+#define GPIOTE_INTENSET_IN2_Msk (0x1UL << GPIOTE_INTENSET_IN2_Pos) /*!< Bit mask of IN2 field. */
+#define GPIOTE_INTENSET_IN2_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENSET_IN2_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENSET_IN2_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on IN[1] event. */
+#define GPIOTE_INTENSET_IN1_Pos (1UL) /*!< Position of IN1 field. */
+#define GPIOTE_INTENSET_IN1_Msk (0x1UL << GPIOTE_INTENSET_IN1_Pos) /*!< Bit mask of IN1 field. */
+#define GPIOTE_INTENSET_IN1_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENSET_IN1_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENSET_IN1_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on IN[0] event. */
+#define GPIOTE_INTENSET_IN0_Pos (0UL) /*!< Position of IN0 field. */
+#define GPIOTE_INTENSET_IN0_Msk (0x1UL << GPIOTE_INTENSET_IN0_Pos) /*!< Bit mask of IN0 field. */
+#define GPIOTE_INTENSET_IN0_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENSET_IN0_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENSET_IN0_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: GPIOTE_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 31 : Disable interrupt on PORT event. */
+#define GPIOTE_INTENCLR_PORT_Pos (31UL) /*!< Position of PORT field. */
+#define GPIOTE_INTENCLR_PORT_Msk (0x1UL << GPIOTE_INTENCLR_PORT_Pos) /*!< Bit mask of PORT field. */
+#define GPIOTE_INTENCLR_PORT_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENCLR_PORT_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENCLR_PORT_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 3 : Disable interrupt on IN[3] event. */
+#define GPIOTE_INTENCLR_IN3_Pos (3UL) /*!< Position of IN3 field. */
+#define GPIOTE_INTENCLR_IN3_Msk (0x1UL << GPIOTE_INTENCLR_IN3_Pos) /*!< Bit mask of IN3 field. */
+#define GPIOTE_INTENCLR_IN3_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENCLR_IN3_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENCLR_IN3_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 2 : Disable interrupt on IN[2] event. */
+#define GPIOTE_INTENCLR_IN2_Pos (2UL) /*!< Position of IN2 field. */
+#define GPIOTE_INTENCLR_IN2_Msk (0x1UL << GPIOTE_INTENCLR_IN2_Pos) /*!< Bit mask of IN2 field. */
+#define GPIOTE_INTENCLR_IN2_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENCLR_IN2_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENCLR_IN2_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on IN[1] event. */
+#define GPIOTE_INTENCLR_IN1_Pos (1UL) /*!< Position of IN1 field. */
+#define GPIOTE_INTENCLR_IN1_Msk (0x1UL << GPIOTE_INTENCLR_IN1_Pos) /*!< Bit mask of IN1 field. */
+#define GPIOTE_INTENCLR_IN1_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENCLR_IN1_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENCLR_IN1_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on IN[0] event. */
+#define GPIOTE_INTENCLR_IN0_Pos (0UL) /*!< Position of IN0 field. */
+#define GPIOTE_INTENCLR_IN0_Msk (0x1UL << GPIOTE_INTENCLR_IN0_Pos) /*!< Bit mask of IN0 field. */
+#define GPIOTE_INTENCLR_IN0_Disabled (0UL) /*!< Interrupt disabled. */
+#define GPIOTE_INTENCLR_IN0_Enabled (1UL) /*!< Interrupt enabled. */
+#define GPIOTE_INTENCLR_IN0_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: GPIOTE_CONFIG */
+/* Description: Channel configuration registers. */
+
+/* Bit 20 : Initial value of the output when the GPIOTE channel is configured as a Task. */
+#define GPIOTE_CONFIG_OUTINIT_Pos (20UL) /*!< Position of OUTINIT field. */
+#define GPIOTE_CONFIG_OUTINIT_Msk (0x1UL << GPIOTE_CONFIG_OUTINIT_Pos) /*!< Bit mask of OUTINIT field. */
+#define GPIOTE_CONFIG_OUTINIT_Low (0UL) /*!< Initial low output when in task mode. */
+#define GPIOTE_CONFIG_OUTINIT_High (1UL) /*!< Initial high output when in task mode. */
+
+/* Bits 17..16 : Effects on output when in Task mode, or events on input that generates an event. */
+#define GPIOTE_CONFIG_POLARITY_Pos (16UL) /*!< Position of POLARITY field. */
+#define GPIOTE_CONFIG_POLARITY_Msk (0x3UL << GPIOTE_CONFIG_POLARITY_Pos) /*!< Bit mask of POLARITY field. */
+#define GPIOTE_CONFIG_POLARITY_None (0x00UL) /*!< No task or event. */
+#define GPIOTE_CONFIG_POLARITY_LoToHi (0x01UL) /*!< Low to high. */
+#define GPIOTE_CONFIG_POLARITY_HiToLo (0x02UL) /*!< High to low. */
+#define GPIOTE_CONFIG_POLARITY_Toggle (0x03UL) /*!< Toggle. */
+
+/* Bits 12..8 : Pin select. */
+#define GPIOTE_CONFIG_PSEL_Pos (8UL) /*!< Position of PSEL field. */
+#define GPIOTE_CONFIG_PSEL_Msk (0x1FUL << GPIOTE_CONFIG_PSEL_Pos) /*!< Bit mask of PSEL field. */
+
+/* Bits 1..0 : Mode */
+#define GPIOTE_CONFIG_MODE_Pos (0UL) /*!< Position of MODE field. */
+#define GPIOTE_CONFIG_MODE_Msk (0x3UL << GPIOTE_CONFIG_MODE_Pos) /*!< Bit mask of MODE field. */
+#define GPIOTE_CONFIG_MODE_Disabled (0x00UL) /*!< Disabled. */
+#define GPIOTE_CONFIG_MODE_Event (0x01UL) /*!< Channel configure in event mode. */
+#define GPIOTE_CONFIG_MODE_Task (0x03UL) /*!< Channel configure in task mode. */
+
+/* Register: GPIOTE_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define GPIOTE_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define GPIOTE_POWER_POWER_Msk (0x1UL << GPIOTE_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define GPIOTE_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define GPIOTE_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: LPCOMP */
+/* Description: Low power comparator. */
+
+/* Register: LPCOMP_SHORTS */
+/* Description: Shortcuts for the LPCOMP. */
+
+/* Bit 4 : Shortcut between CROSS event and STOP task. */
+#define LPCOMP_SHORTS_CROSS_STOP_Pos (4UL) /*!< Position of CROSS_STOP field. */
+#define LPCOMP_SHORTS_CROSS_STOP_Msk (0x1UL << LPCOMP_SHORTS_CROSS_STOP_Pos) /*!< Bit mask of CROSS_STOP field. */
+#define LPCOMP_SHORTS_CROSS_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define LPCOMP_SHORTS_CROSS_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 3 : Shortcut between UP event and STOP task. */
+#define LPCOMP_SHORTS_UP_STOP_Pos (3UL) /*!< Position of UP_STOP field. */
+#define LPCOMP_SHORTS_UP_STOP_Msk (0x1UL << LPCOMP_SHORTS_UP_STOP_Pos) /*!< Bit mask of UP_STOP field. */
+#define LPCOMP_SHORTS_UP_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define LPCOMP_SHORTS_UP_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 2 : Shortcut between DOWN event and STOP task. */
+#define LPCOMP_SHORTS_DOWN_STOP_Pos (2UL) /*!< Position of DOWN_STOP field. */
+#define LPCOMP_SHORTS_DOWN_STOP_Msk (0x1UL << LPCOMP_SHORTS_DOWN_STOP_Pos) /*!< Bit mask of DOWN_STOP field. */
+#define LPCOMP_SHORTS_DOWN_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define LPCOMP_SHORTS_DOWN_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 1 : Shortcut between RADY event and STOP task. */
+#define LPCOMP_SHORTS_READY_STOP_Pos (1UL) /*!< Position of READY_STOP field. */
+#define LPCOMP_SHORTS_READY_STOP_Msk (0x1UL << LPCOMP_SHORTS_READY_STOP_Pos) /*!< Bit mask of READY_STOP field. */
+#define LPCOMP_SHORTS_READY_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define LPCOMP_SHORTS_READY_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 0 : Shortcut between READY event and SAMPLE task. */
+#define LPCOMP_SHORTS_READY_SAMPLE_Pos (0UL) /*!< Position of READY_SAMPLE field. */
+#define LPCOMP_SHORTS_READY_SAMPLE_Msk (0x1UL << LPCOMP_SHORTS_READY_SAMPLE_Pos) /*!< Bit mask of READY_SAMPLE field. */
+#define LPCOMP_SHORTS_READY_SAMPLE_Disabled (0UL) /*!< Shortcut disabled. */
+#define LPCOMP_SHORTS_READY_SAMPLE_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: LPCOMP_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 3 : Enable interrupt on CROSS event. */
+#define LPCOMP_INTENSET_CROSS_Pos (3UL) /*!< Position of CROSS field. */
+#define LPCOMP_INTENSET_CROSS_Msk (0x1UL << LPCOMP_INTENSET_CROSS_Pos) /*!< Bit mask of CROSS field. */
+#define LPCOMP_INTENSET_CROSS_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENSET_CROSS_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENSET_CROSS_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 2 : Enable interrupt on UP event. */
+#define LPCOMP_INTENSET_UP_Pos (2UL) /*!< Position of UP field. */
+#define LPCOMP_INTENSET_UP_Msk (0x1UL << LPCOMP_INTENSET_UP_Pos) /*!< Bit mask of UP field. */
+#define LPCOMP_INTENSET_UP_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENSET_UP_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENSET_UP_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on DOWN event. */
+#define LPCOMP_INTENSET_DOWN_Pos (1UL) /*!< Position of DOWN field. */
+#define LPCOMP_INTENSET_DOWN_Msk (0x1UL << LPCOMP_INTENSET_DOWN_Pos) /*!< Bit mask of DOWN field. */
+#define LPCOMP_INTENSET_DOWN_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENSET_DOWN_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENSET_DOWN_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on READY event. */
+#define LPCOMP_INTENSET_READY_Pos (0UL) /*!< Position of READY field. */
+#define LPCOMP_INTENSET_READY_Msk (0x1UL << LPCOMP_INTENSET_READY_Pos) /*!< Bit mask of READY field. */
+#define LPCOMP_INTENSET_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENSET_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENSET_READY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: LPCOMP_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 3 : Disable interrupt on CROSS event. */
+#define LPCOMP_INTENCLR_CROSS_Pos (3UL) /*!< Position of CROSS field. */
+#define LPCOMP_INTENCLR_CROSS_Msk (0x1UL << LPCOMP_INTENCLR_CROSS_Pos) /*!< Bit mask of CROSS field. */
+#define LPCOMP_INTENCLR_CROSS_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENCLR_CROSS_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENCLR_CROSS_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 2 : Disable interrupt on UP event. */
+#define LPCOMP_INTENCLR_UP_Pos (2UL) /*!< Position of UP field. */
+#define LPCOMP_INTENCLR_UP_Msk (0x1UL << LPCOMP_INTENCLR_UP_Pos) /*!< Bit mask of UP field. */
+#define LPCOMP_INTENCLR_UP_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENCLR_UP_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENCLR_UP_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on DOWN event. */
+#define LPCOMP_INTENCLR_DOWN_Pos (1UL) /*!< Position of DOWN field. */
+#define LPCOMP_INTENCLR_DOWN_Msk (0x1UL << LPCOMP_INTENCLR_DOWN_Pos) /*!< Bit mask of DOWN field. */
+#define LPCOMP_INTENCLR_DOWN_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENCLR_DOWN_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENCLR_DOWN_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on READY event. */
+#define LPCOMP_INTENCLR_READY_Pos (0UL) /*!< Position of READY field. */
+#define LPCOMP_INTENCLR_READY_Msk (0x1UL << LPCOMP_INTENCLR_READY_Pos) /*!< Bit mask of READY field. */
+#define LPCOMP_INTENCLR_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define LPCOMP_INTENCLR_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define LPCOMP_INTENCLR_READY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: LPCOMP_RESULT */
+/* Description: Result of last compare. */
+
+/* Bit 0 : Result of last compare. Decision point SAMPLE task. */
+#define LPCOMP_RESULT_RESULT_Pos (0UL) /*!< Position of RESULT field. */
+#define LPCOMP_RESULT_RESULT_Msk (0x1UL << LPCOMP_RESULT_RESULT_Pos) /*!< Bit mask of RESULT field. */
+#define LPCOMP_RESULT_RESULT_Bellow (0UL) /*!< Input voltage is bellow the reference threshold. */
+#define LPCOMP_RESULT_RESULT_Above (1UL) /*!< Input voltage is above the reference threshold. */
+
+/* Register: LPCOMP_ENABLE */
+/* Description: Enable the LPCOMP. */
+
+/* Bits 1..0 : Enable or disable LPCOMP. */
+#define LPCOMP_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define LPCOMP_ENABLE_ENABLE_Msk (0x3UL << LPCOMP_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define LPCOMP_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled LPCOMP. */
+#define LPCOMP_ENABLE_ENABLE_Enabled (0x01UL) /*!< Enable LPCOMP. */
+
+/* Register: LPCOMP_PSEL */
+/* Description: Input pin select. */
+
+/* Bits 2..0 : Analog input pin select. */
+#define LPCOMP_PSEL_PSEL_Pos (0UL) /*!< Position of PSEL field. */
+#define LPCOMP_PSEL_PSEL_Msk (0x7UL << LPCOMP_PSEL_PSEL_Pos) /*!< Bit mask of PSEL field. */
+#define LPCOMP_PSEL_PSEL_AnalogInput0 (0UL) /*!< Use analog input 0 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput1 (1UL) /*!< Use analog input 1 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput2 (2UL) /*!< Use analog input 2 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput3 (3UL) /*!< Use analog input 3 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput4 (4UL) /*!< Use analog input 4 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput5 (5UL) /*!< Use analog input 5 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput6 (6UL) /*!< Use analog input 6 as analog input. */
+#define LPCOMP_PSEL_PSEL_AnalogInput7 (7UL) /*!< Use analog input 7 as analog input. */
+
+/* Register: LPCOMP_REFSEL */
+/* Description: Reference select. */
+
+/* Bits 2..0 : Reference select. */
+#define LPCOMP_REFSEL_REFSEL_Pos (0UL) /*!< Position of REFSEL field. */
+#define LPCOMP_REFSEL_REFSEL_Msk (0x7UL << LPCOMP_REFSEL_REFSEL_Pos) /*!< Bit mask of REFSEL field. */
+#define LPCOMP_REFSEL_REFSEL_SupplyOneEighthPrescaling (0UL) /*!< Use supply with a 1/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplyTwoEighthsPrescaling (1UL) /*!< Use supply with a 2/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplyThreeEighthsPrescaling (2UL) /*!< Use supply with a 3/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplyFourEighthsPrescaling (3UL) /*!< Use supply with a 4/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplyFiveEighthsPrescaling (4UL) /*!< Use supply with a 5/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplySixEighthsPrescaling (5UL) /*!< Use supply with a 6/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_SupplySevenEighthsPrescaling (6UL) /*!< Use supply with a 7/8 prescaler as reference. */
+#define LPCOMP_REFSEL_REFSEL_ARef (7UL) /*!< Use external analog reference as reference. */
+
+/* Register: LPCOMP_EXTREFSEL */
+/* Description: External reference select. */
+
+/* Bit 0 : External analog reference pin selection. */
+#define LPCOMP_EXTREFSEL_EXTREFSEL_Pos (0UL) /*!< Position of EXTREFSEL field. */
+#define LPCOMP_EXTREFSEL_EXTREFSEL_Msk (0x1UL << LPCOMP_EXTREFSEL_EXTREFSEL_Pos) /*!< Bit mask of EXTREFSEL field. */
+#define LPCOMP_EXTREFSEL_EXTREFSEL_AnalogReference0 (0UL) /*!< Use analog reference 0 as reference. */
+#define LPCOMP_EXTREFSEL_EXTREFSEL_AnalogReference1 (1UL) /*!< Use analog reference 1 as reference. */
+
+/* Register: LPCOMP_ANADETECT */
+/* Description: Analog detect configuration. */
+
+/* Bits 1..0 : Analog detect configuration. */
+#define LPCOMP_ANADETECT_ANADETECT_Pos (0UL) /*!< Position of ANADETECT field. */
+#define LPCOMP_ANADETECT_ANADETECT_Msk (0x3UL << LPCOMP_ANADETECT_ANADETECT_Pos) /*!< Bit mask of ANADETECT field. */
+#define LPCOMP_ANADETECT_ANADETECT_Cross (0UL) /*!< Generate ANADETEC on crossing, both upwards and downwards crossing. */
+#define LPCOMP_ANADETECT_ANADETECT_Up (1UL) /*!< Generate ANADETEC on upwards crossing only. */
+#define LPCOMP_ANADETECT_ANADETECT_Down (2UL) /*!< Generate ANADETEC on downwards crossing only. */
+
+/* Register: LPCOMP_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define LPCOMP_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define LPCOMP_POWER_POWER_Msk (0x1UL << LPCOMP_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define LPCOMP_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define LPCOMP_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: MPU */
+/* Description: Memory Protection Unit. */
+
+/* Register: MPU_PERR0 */
+/* Description: Configuration of peripherals in mpu regions. */
+
+/* Bit 31 : PPI region configuration. */
+#define MPU_PERR0_PPI_Pos (31UL) /*!< Position of PPI field. */
+#define MPU_PERR0_PPI_Msk (0x1UL << MPU_PERR0_PPI_Pos) /*!< Bit mask of PPI field. */
+#define MPU_PERR0_PPI_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_PPI_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 30 : NVMC region configuration. */
+#define MPU_PERR0_NVMC_Pos (30UL) /*!< Position of NVMC field. */
+#define MPU_PERR0_NVMC_Msk (0x1UL << MPU_PERR0_NVMC_Pos) /*!< Bit mask of NVMC field. */
+#define MPU_PERR0_NVMC_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_NVMC_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 19 : LPCOMP region configuration. */
+#define MPU_PERR0_LPCOMP_Pos (19UL) /*!< Position of LPCOMP field. */
+#define MPU_PERR0_LPCOMP_Msk (0x1UL << MPU_PERR0_LPCOMP_Pos) /*!< Bit mask of LPCOMP field. */
+#define MPU_PERR0_LPCOMP_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_LPCOMP_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 18 : QDEC region configuration. */
+#define MPU_PERR0_QDEC_Pos (18UL) /*!< Position of QDEC field. */
+#define MPU_PERR0_QDEC_Msk (0x1UL << MPU_PERR0_QDEC_Pos) /*!< Bit mask of QDEC field. */
+#define MPU_PERR0_QDEC_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_QDEC_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 17 : RTC1 region configuration. */
+#define MPU_PERR0_RTC1_Pos (17UL) /*!< Position of RTC1 field. */
+#define MPU_PERR0_RTC1_Msk (0x1UL << MPU_PERR0_RTC1_Pos) /*!< Bit mask of RTC1 field. */
+#define MPU_PERR0_RTC1_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_RTC1_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 16 : WDT region configuration. */
+#define MPU_PERR0_WDT_Pos (16UL) /*!< Position of WDT field. */
+#define MPU_PERR0_WDT_Msk (0x1UL << MPU_PERR0_WDT_Pos) /*!< Bit mask of WDT field. */
+#define MPU_PERR0_WDT_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_WDT_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 15 : CCM and AAR region configuration. */
+#define MPU_PERR0_CCM_AAR_Pos (15UL) /*!< Position of CCM_AAR field. */
+#define MPU_PERR0_CCM_AAR_Msk (0x1UL << MPU_PERR0_CCM_AAR_Pos) /*!< Bit mask of CCM_AAR field. */
+#define MPU_PERR0_CCM_AAR_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_CCM_AAR_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 14 : ECB region configuration. */
+#define MPU_PERR0_ECB_Pos (14UL) /*!< Position of ECB field. */
+#define MPU_PERR0_ECB_Msk (0x1UL << MPU_PERR0_ECB_Pos) /*!< Bit mask of ECB field. */
+#define MPU_PERR0_ECB_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_ECB_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 13 : RNG region configuration. */
+#define MPU_PERR0_RNG_Pos (13UL) /*!< Position of RNG field. */
+#define MPU_PERR0_RNG_Msk (0x1UL << MPU_PERR0_RNG_Pos) /*!< Bit mask of RNG field. */
+#define MPU_PERR0_RNG_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_RNG_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 12 : TEMP region configuration. */
+#define MPU_PERR0_TEMP_Pos (12UL) /*!< Position of TEMP field. */
+#define MPU_PERR0_TEMP_Msk (0x1UL << MPU_PERR0_TEMP_Pos) /*!< Bit mask of TEMP field. */
+#define MPU_PERR0_TEMP_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_TEMP_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 11 : RTC0 region configuration. */
+#define MPU_PERR0_RTC0_Pos (11UL) /*!< Position of RTC0 field. */
+#define MPU_PERR0_RTC0_Msk (0x1UL << MPU_PERR0_RTC0_Pos) /*!< Bit mask of RTC0 field. */
+#define MPU_PERR0_RTC0_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_RTC0_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 10 : TIMER2 region configuration. */
+#define MPU_PERR0_TIMER2_Pos (10UL) /*!< Position of TIMER2 field. */
+#define MPU_PERR0_TIMER2_Msk (0x1UL << MPU_PERR0_TIMER2_Pos) /*!< Bit mask of TIMER2 field. */
+#define MPU_PERR0_TIMER2_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_TIMER2_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 9 : TIMER1 region configuration. */
+#define MPU_PERR0_TIMER1_Pos (9UL) /*!< Position of TIMER1 field. */
+#define MPU_PERR0_TIMER1_Msk (0x1UL << MPU_PERR0_TIMER1_Pos) /*!< Bit mask of TIMER1 field. */
+#define MPU_PERR0_TIMER1_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_TIMER1_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 8 : TIMER0 region configuration. */
+#define MPU_PERR0_TIMER0_Pos (8UL) /*!< Position of TIMER0 field. */
+#define MPU_PERR0_TIMER0_Msk (0x1UL << MPU_PERR0_TIMER0_Pos) /*!< Bit mask of TIMER0 field. */
+#define MPU_PERR0_TIMER0_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_TIMER0_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 7 : ADC region configuration. */
+#define MPU_PERR0_ADC_Pos (7UL) /*!< Position of ADC field. */
+#define MPU_PERR0_ADC_Msk (0x1UL << MPU_PERR0_ADC_Pos) /*!< Bit mask of ADC field. */
+#define MPU_PERR0_ADC_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_ADC_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 6 : GPIOTE region configuration. */
+#define MPU_PERR0_GPIOTE_Pos (6UL) /*!< Position of GPIOTE field. */
+#define MPU_PERR0_GPIOTE_Msk (0x1UL << MPU_PERR0_GPIOTE_Pos) /*!< Bit mask of GPIOTE field. */
+#define MPU_PERR0_GPIOTE_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_GPIOTE_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 4 : SPI1 and TWI1 region configuration. */
+#define MPU_PERR0_SPI1_TWI1_Pos (4UL) /*!< Position of SPI1_TWI1 field. */
+#define MPU_PERR0_SPI1_TWI1_Msk (0x1UL << MPU_PERR0_SPI1_TWI1_Pos) /*!< Bit mask of SPI1_TWI1 field. */
+#define MPU_PERR0_SPI1_TWI1_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_SPI1_TWI1_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 3 : SPI0 and TWI0 region configuration. */
+#define MPU_PERR0_SPI0_TWI0_Pos (3UL) /*!< Position of SPI0_TWI0 field. */
+#define MPU_PERR0_SPI0_TWI0_Msk (0x1UL << MPU_PERR0_SPI0_TWI0_Pos) /*!< Bit mask of SPI0_TWI0 field. */
+#define MPU_PERR0_SPI0_TWI0_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_SPI0_TWI0_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 2 : UART0 region configuration. */
+#define MPU_PERR0_UART0_Pos (2UL) /*!< Position of UART0 field. */
+#define MPU_PERR0_UART0_Msk (0x1UL << MPU_PERR0_UART0_Pos) /*!< Bit mask of UART0 field. */
+#define MPU_PERR0_UART0_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_UART0_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 1 : RADIO region configuration. */
+#define MPU_PERR0_RADIO_Pos (1UL) /*!< Position of RADIO field. */
+#define MPU_PERR0_RADIO_Msk (0x1UL << MPU_PERR0_RADIO_Pos) /*!< Bit mask of RADIO field. */
+#define MPU_PERR0_RADIO_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_RADIO_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Bit 0 : POWER_CLOCK region configuration. */
+#define MPU_PERR0_POWER_CLOCK_Pos (0UL) /*!< Position of POWER_CLOCK field. */
+#define MPU_PERR0_POWER_CLOCK_Msk (0x1UL << MPU_PERR0_POWER_CLOCK_Pos) /*!< Bit mask of POWER_CLOCK field. */
+#define MPU_PERR0_POWER_CLOCK_InRegion1 (0UL) /*!< Peripheral configured in region 1. */
+#define MPU_PERR0_POWER_CLOCK_InRegion0 (1UL) /*!< Peripheral configured in region 0. */
+
+/* Register: MPU_PROTENSET0 */
+/* Description: Erase and write protection bit enable set register. */
+
+/* Bit 31 : Protection enable for region 31. */
+#define MPU_PROTENSET0_PROTREG31_Pos (31UL) /*!< Position of PROTREG31 field. */
+#define MPU_PROTENSET0_PROTREG31_Msk (0x1UL << MPU_PROTENSET0_PROTREG31_Pos) /*!< Bit mask of PROTREG31 field. */
+#define MPU_PROTENSET0_PROTREG31_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG31_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG31_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 30 : Protection enable for region 30. */
+#define MPU_PROTENSET0_PROTREG30_Pos (30UL) /*!< Position of PROTREG30 field. */
+#define MPU_PROTENSET0_PROTREG30_Msk (0x1UL << MPU_PROTENSET0_PROTREG30_Pos) /*!< Bit mask of PROTREG30 field. */
+#define MPU_PROTENSET0_PROTREG30_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG30_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG30_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 29 : Protection enable for region 29. */
+#define MPU_PROTENSET0_PROTREG29_Pos (29UL) /*!< Position of PROTREG29 field. */
+#define MPU_PROTENSET0_PROTREG29_Msk (0x1UL << MPU_PROTENSET0_PROTREG29_Pos) /*!< Bit mask of PROTREG29 field. */
+#define MPU_PROTENSET0_PROTREG29_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG29_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG29_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 28 : Protection enable for region 28. */
+#define MPU_PROTENSET0_PROTREG28_Pos (28UL) /*!< Position of PROTREG28 field. */
+#define MPU_PROTENSET0_PROTREG28_Msk (0x1UL << MPU_PROTENSET0_PROTREG28_Pos) /*!< Bit mask of PROTREG28 field. */
+#define MPU_PROTENSET0_PROTREG28_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG28_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG28_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 27 : Protection enable for region 27. */
+#define MPU_PROTENSET0_PROTREG27_Pos (27UL) /*!< Position of PROTREG27 field. */
+#define MPU_PROTENSET0_PROTREG27_Msk (0x1UL << MPU_PROTENSET0_PROTREG27_Pos) /*!< Bit mask of PROTREG27 field. */
+#define MPU_PROTENSET0_PROTREG27_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG27_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG27_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 26 : Protection enable for region 26. */
+#define MPU_PROTENSET0_PROTREG26_Pos (26UL) /*!< Position of PROTREG26 field. */
+#define MPU_PROTENSET0_PROTREG26_Msk (0x1UL << MPU_PROTENSET0_PROTREG26_Pos) /*!< Bit mask of PROTREG26 field. */
+#define MPU_PROTENSET0_PROTREG26_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG26_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG26_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 25 : Protection enable for region 25. */
+#define MPU_PROTENSET0_PROTREG25_Pos (25UL) /*!< Position of PROTREG25 field. */
+#define MPU_PROTENSET0_PROTREG25_Msk (0x1UL << MPU_PROTENSET0_PROTREG25_Pos) /*!< Bit mask of PROTREG25 field. */
+#define MPU_PROTENSET0_PROTREG25_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG25_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG25_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 24 : Protection enable for region 24. */
+#define MPU_PROTENSET0_PROTREG24_Pos (24UL) /*!< Position of PROTREG24 field. */
+#define MPU_PROTENSET0_PROTREG24_Msk (0x1UL << MPU_PROTENSET0_PROTREG24_Pos) /*!< Bit mask of PROTREG24 field. */
+#define MPU_PROTENSET0_PROTREG24_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG24_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG24_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 23 : Protection enable for region 23. */
+#define MPU_PROTENSET0_PROTREG23_Pos (23UL) /*!< Position of PROTREG23 field. */
+#define MPU_PROTENSET0_PROTREG23_Msk (0x1UL << MPU_PROTENSET0_PROTREG23_Pos) /*!< Bit mask of PROTREG23 field. */
+#define MPU_PROTENSET0_PROTREG23_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG23_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG23_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 22 : Protection enable for region 22. */
+#define MPU_PROTENSET0_PROTREG22_Pos (22UL) /*!< Position of PROTREG22 field. */
+#define MPU_PROTENSET0_PROTREG22_Msk (0x1UL << MPU_PROTENSET0_PROTREG22_Pos) /*!< Bit mask of PROTREG22 field. */
+#define MPU_PROTENSET0_PROTREG22_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG22_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG22_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 21 : Protection enable for region 21. */
+#define MPU_PROTENSET0_PROTREG21_Pos (21UL) /*!< Position of PROTREG21 field. */
+#define MPU_PROTENSET0_PROTREG21_Msk (0x1UL << MPU_PROTENSET0_PROTREG21_Pos) /*!< Bit mask of PROTREG21 field. */
+#define MPU_PROTENSET0_PROTREG21_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG21_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG21_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 20 : Protection enable for region 20. */
+#define MPU_PROTENSET0_PROTREG20_Pos (20UL) /*!< Position of PROTREG20 field. */
+#define MPU_PROTENSET0_PROTREG20_Msk (0x1UL << MPU_PROTENSET0_PROTREG20_Pos) /*!< Bit mask of PROTREG20 field. */
+#define MPU_PROTENSET0_PROTREG20_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG20_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG20_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 19 : Protection enable for region 19. */
+#define MPU_PROTENSET0_PROTREG19_Pos (19UL) /*!< Position of PROTREG19 field. */
+#define MPU_PROTENSET0_PROTREG19_Msk (0x1UL << MPU_PROTENSET0_PROTREG19_Pos) /*!< Bit mask of PROTREG19 field. */
+#define MPU_PROTENSET0_PROTREG19_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG19_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG19_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 18 : Protection enable for region 18. */
+#define MPU_PROTENSET0_PROTREG18_Pos (18UL) /*!< Position of PROTREG18 field. */
+#define MPU_PROTENSET0_PROTREG18_Msk (0x1UL << MPU_PROTENSET0_PROTREG18_Pos) /*!< Bit mask of PROTREG18 field. */
+#define MPU_PROTENSET0_PROTREG18_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG18_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG18_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 17 : Protection enable for region 17. */
+#define MPU_PROTENSET0_PROTREG17_Pos (17UL) /*!< Position of PROTREG17 field. */
+#define MPU_PROTENSET0_PROTREG17_Msk (0x1UL << MPU_PROTENSET0_PROTREG17_Pos) /*!< Bit mask of PROTREG17 field. */
+#define MPU_PROTENSET0_PROTREG17_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG17_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG17_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 16 : Protection enable for region 16. */
+#define MPU_PROTENSET0_PROTREG16_Pos (16UL) /*!< Position of PROTREG16 field. */
+#define MPU_PROTENSET0_PROTREG16_Msk (0x1UL << MPU_PROTENSET0_PROTREG16_Pos) /*!< Bit mask of PROTREG16 field. */
+#define MPU_PROTENSET0_PROTREG16_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG16_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG16_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 15 : Protection enable for region 15. */
+#define MPU_PROTENSET0_PROTREG15_Pos (15UL) /*!< Position of PROTREG15 field. */
+#define MPU_PROTENSET0_PROTREG15_Msk (0x1UL << MPU_PROTENSET0_PROTREG15_Pos) /*!< Bit mask of PROTREG15 field. */
+#define MPU_PROTENSET0_PROTREG15_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG15_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG15_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 14 : Protection enable for region 14. */
+#define MPU_PROTENSET0_PROTREG14_Pos (14UL) /*!< Position of PROTREG14 field. */
+#define MPU_PROTENSET0_PROTREG14_Msk (0x1UL << MPU_PROTENSET0_PROTREG14_Pos) /*!< Bit mask of PROTREG14 field. */
+#define MPU_PROTENSET0_PROTREG14_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG14_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG14_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 13 : Protection enable for region 13. */
+#define MPU_PROTENSET0_PROTREG13_Pos (13UL) /*!< Position of PROTREG13 field. */
+#define MPU_PROTENSET0_PROTREG13_Msk (0x1UL << MPU_PROTENSET0_PROTREG13_Pos) /*!< Bit mask of PROTREG13 field. */
+#define MPU_PROTENSET0_PROTREG13_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG13_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG13_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 12 : Protection enable for region 12. */
+#define MPU_PROTENSET0_PROTREG12_Pos (12UL) /*!< Position of PROTREG12 field. */
+#define MPU_PROTENSET0_PROTREG12_Msk (0x1UL << MPU_PROTENSET0_PROTREG12_Pos) /*!< Bit mask of PROTREG12 field. */
+#define MPU_PROTENSET0_PROTREG12_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG12_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG12_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 11 : Protection enable for region 11. */
+#define MPU_PROTENSET0_PROTREG11_Pos (11UL) /*!< Position of PROTREG11 field. */
+#define MPU_PROTENSET0_PROTREG11_Msk (0x1UL << MPU_PROTENSET0_PROTREG11_Pos) /*!< Bit mask of PROTREG11 field. */
+#define MPU_PROTENSET0_PROTREG11_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG11_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG11_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 10 : Protection enable for region 10. */
+#define MPU_PROTENSET0_PROTREG10_Pos (10UL) /*!< Position of PROTREG10 field. */
+#define MPU_PROTENSET0_PROTREG10_Msk (0x1UL << MPU_PROTENSET0_PROTREG10_Pos) /*!< Bit mask of PROTREG10 field. */
+#define MPU_PROTENSET0_PROTREG10_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG10_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG10_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 9 : Protection enable for region 9. */
+#define MPU_PROTENSET0_PROTREG9_Pos (9UL) /*!< Position of PROTREG9 field. */
+#define MPU_PROTENSET0_PROTREG9_Msk (0x1UL << MPU_PROTENSET0_PROTREG9_Pos) /*!< Bit mask of PROTREG9 field. */
+#define MPU_PROTENSET0_PROTREG9_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG9_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG9_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 8 : Protection enable for region 8. */
+#define MPU_PROTENSET0_PROTREG8_Pos (8UL) /*!< Position of PROTREG8 field. */
+#define MPU_PROTENSET0_PROTREG8_Msk (0x1UL << MPU_PROTENSET0_PROTREG8_Pos) /*!< Bit mask of PROTREG8 field. */
+#define MPU_PROTENSET0_PROTREG8_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG8_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG8_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 7 : Protection enable for region 7. */
+#define MPU_PROTENSET0_PROTREG7_Pos (7UL) /*!< Position of PROTREG7 field. */
+#define MPU_PROTENSET0_PROTREG7_Msk (0x1UL << MPU_PROTENSET0_PROTREG7_Pos) /*!< Bit mask of PROTREG7 field. */
+#define MPU_PROTENSET0_PROTREG7_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG7_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG7_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 6 : Protection enable for region 6. */
+#define MPU_PROTENSET0_PROTREG6_Pos (6UL) /*!< Position of PROTREG6 field. */
+#define MPU_PROTENSET0_PROTREG6_Msk (0x1UL << MPU_PROTENSET0_PROTREG6_Pos) /*!< Bit mask of PROTREG6 field. */
+#define MPU_PROTENSET0_PROTREG6_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG6_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG6_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 5 : Protection enable for region 5. */
+#define MPU_PROTENSET0_PROTREG5_Pos (5UL) /*!< Position of PROTREG5 field. */
+#define MPU_PROTENSET0_PROTREG5_Msk (0x1UL << MPU_PROTENSET0_PROTREG5_Pos) /*!< Bit mask of PROTREG5 field. */
+#define MPU_PROTENSET0_PROTREG5_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG5_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG5_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 4 : Protection enable for region 4. */
+#define MPU_PROTENSET0_PROTREG4_Pos (4UL) /*!< Position of PROTREG4 field. */
+#define MPU_PROTENSET0_PROTREG4_Msk (0x1UL << MPU_PROTENSET0_PROTREG4_Pos) /*!< Bit mask of PROTREG4 field. */
+#define MPU_PROTENSET0_PROTREG4_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG4_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG4_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 3 : Protection enable for region 3. */
+#define MPU_PROTENSET0_PROTREG3_Pos (3UL) /*!< Position of PROTREG3 field. */
+#define MPU_PROTENSET0_PROTREG3_Msk (0x1UL << MPU_PROTENSET0_PROTREG3_Pos) /*!< Bit mask of PROTREG3 field. */
+#define MPU_PROTENSET0_PROTREG3_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG3_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG3_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 2 : Protection enable for region 2. */
+#define MPU_PROTENSET0_PROTREG2_Pos (2UL) /*!< Position of PROTREG2 field. */
+#define MPU_PROTENSET0_PROTREG2_Msk (0x1UL << MPU_PROTENSET0_PROTREG2_Pos) /*!< Bit mask of PROTREG2 field. */
+#define MPU_PROTENSET0_PROTREG2_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG2_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG2_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 1 : Protection enable for region 1. */
+#define MPU_PROTENSET0_PROTREG1_Pos (1UL) /*!< Position of PROTREG1 field. */
+#define MPU_PROTENSET0_PROTREG1_Msk (0x1UL << MPU_PROTENSET0_PROTREG1_Pos) /*!< Bit mask of PROTREG1 field. */
+#define MPU_PROTENSET0_PROTREG1_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG1_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG1_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 0 : Protection enable for region 0. */
+#define MPU_PROTENSET0_PROTREG0_Pos (0UL) /*!< Position of PROTREG0 field. */
+#define MPU_PROTENSET0_PROTREG0_Msk (0x1UL << MPU_PROTENSET0_PROTREG0_Pos) /*!< Bit mask of PROTREG0 field. */
+#define MPU_PROTENSET0_PROTREG0_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET0_PROTREG0_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET0_PROTREG0_Set (1UL) /*!< Enable protection on write. */
+
+/* Register: MPU_PROTENSET1 */
+/* Description: Erase and write protection bit enable set register. */
+
+/* Bit 31 : Protection enable for region 63. */
+#define MPU_PROTENSET1_PROTREG63_Pos (31UL) /*!< Position of PROTREG63 field. */
+#define MPU_PROTENSET1_PROTREG63_Msk (0x1UL << MPU_PROTENSET1_PROTREG63_Pos) /*!< Bit mask of PROTREG63 field. */
+#define MPU_PROTENSET1_PROTREG63_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG63_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG63_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 30 : Protection enable for region 62. */
+#define MPU_PROTENSET1_PROTREG62_Pos (30UL) /*!< Position of PROTREG62 field. */
+#define MPU_PROTENSET1_PROTREG62_Msk (0x1UL << MPU_PROTENSET1_PROTREG62_Pos) /*!< Bit mask of PROTREG62 field. */
+#define MPU_PROTENSET1_PROTREG62_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG62_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG62_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 29 : Protection enable for region 61. */
+#define MPU_PROTENSET1_PROTREG61_Pos (29UL) /*!< Position of PROTREG61 field. */
+#define MPU_PROTENSET1_PROTREG61_Msk (0x1UL << MPU_PROTENSET1_PROTREG61_Pos) /*!< Bit mask of PROTREG61 field. */
+#define MPU_PROTENSET1_PROTREG61_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG61_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG61_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 28 : Protection enable for region 60. */
+#define MPU_PROTENSET1_PROTREG60_Pos (28UL) /*!< Position of PROTREG60 field. */
+#define MPU_PROTENSET1_PROTREG60_Msk (0x1UL << MPU_PROTENSET1_PROTREG60_Pos) /*!< Bit mask of PROTREG60 field. */
+#define MPU_PROTENSET1_PROTREG60_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG60_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG60_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 27 : Protection enable for region 59. */
+#define MPU_PROTENSET1_PROTREG59_Pos (27UL) /*!< Position of PROTREG59 field. */
+#define MPU_PROTENSET1_PROTREG59_Msk (0x1UL << MPU_PROTENSET1_PROTREG59_Pos) /*!< Bit mask of PROTREG59 field. */
+#define MPU_PROTENSET1_PROTREG59_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG59_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG59_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 26 : Protection enable for region 58. */
+#define MPU_PROTENSET1_PROTREG58_Pos (26UL) /*!< Position of PROTREG58 field. */
+#define MPU_PROTENSET1_PROTREG58_Msk (0x1UL << MPU_PROTENSET1_PROTREG58_Pos) /*!< Bit mask of PROTREG58 field. */
+#define MPU_PROTENSET1_PROTREG58_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG58_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG58_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 25 : Protection enable for region 57. */
+#define MPU_PROTENSET1_PROTREG57_Pos (25UL) /*!< Position of PROTREG57 field. */
+#define MPU_PROTENSET1_PROTREG57_Msk (0x1UL << MPU_PROTENSET1_PROTREG57_Pos) /*!< Bit mask of PROTREG57 field. */
+#define MPU_PROTENSET1_PROTREG57_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG57_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG57_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 24 : Protection enable for region 56. */
+#define MPU_PROTENSET1_PROTREG56_Pos (24UL) /*!< Position of PROTREG56 field. */
+#define MPU_PROTENSET1_PROTREG56_Msk (0x1UL << MPU_PROTENSET1_PROTREG56_Pos) /*!< Bit mask of PROTREG56 field. */
+#define MPU_PROTENSET1_PROTREG56_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG56_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG56_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 23 : Protection enable for region 55. */
+#define MPU_PROTENSET1_PROTREG55_Pos (23UL) /*!< Position of PROTREG55 field. */
+#define MPU_PROTENSET1_PROTREG55_Msk (0x1UL << MPU_PROTENSET1_PROTREG55_Pos) /*!< Bit mask of PROTREG55 field. */
+#define MPU_PROTENSET1_PROTREG55_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG55_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG55_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 22 : Protection enable for region 54. */
+#define MPU_PROTENSET1_PROTREG54_Pos (22UL) /*!< Position of PROTREG54 field. */
+#define MPU_PROTENSET1_PROTREG54_Msk (0x1UL << MPU_PROTENSET1_PROTREG54_Pos) /*!< Bit mask of PROTREG54 field. */
+#define MPU_PROTENSET1_PROTREG54_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG54_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG54_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 21 : Protection enable for region 53. */
+#define MPU_PROTENSET1_PROTREG53_Pos (21UL) /*!< Position of PROTREG53 field. */
+#define MPU_PROTENSET1_PROTREG53_Msk (0x1UL << MPU_PROTENSET1_PROTREG53_Pos) /*!< Bit mask of PROTREG53 field. */
+#define MPU_PROTENSET1_PROTREG53_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG53_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG53_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 20 : Protection enable for region 52. */
+#define MPU_PROTENSET1_PROTREG52_Pos (20UL) /*!< Position of PROTREG52 field. */
+#define MPU_PROTENSET1_PROTREG52_Msk (0x1UL << MPU_PROTENSET1_PROTREG52_Pos) /*!< Bit mask of PROTREG52 field. */
+#define MPU_PROTENSET1_PROTREG52_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG52_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG52_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 19 : Protection enable for region 51. */
+#define MPU_PROTENSET1_PROTREG51_Pos (19UL) /*!< Position of PROTREG51 field. */
+#define MPU_PROTENSET1_PROTREG51_Msk (0x1UL << MPU_PROTENSET1_PROTREG51_Pos) /*!< Bit mask of PROTREG51 field. */
+#define MPU_PROTENSET1_PROTREG51_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG51_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG51_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 18 : Protection enable for region 50. */
+#define MPU_PROTENSET1_PROTREG50_Pos (18UL) /*!< Position of PROTREG50 field. */
+#define MPU_PROTENSET1_PROTREG50_Msk (0x1UL << MPU_PROTENSET1_PROTREG50_Pos) /*!< Bit mask of PROTREG50 field. */
+#define MPU_PROTENSET1_PROTREG50_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG50_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG50_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 17 : Protection enable for region 49. */
+#define MPU_PROTENSET1_PROTREG49_Pos (17UL) /*!< Position of PROTREG49 field. */
+#define MPU_PROTENSET1_PROTREG49_Msk (0x1UL << MPU_PROTENSET1_PROTREG49_Pos) /*!< Bit mask of PROTREG49 field. */
+#define MPU_PROTENSET1_PROTREG49_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG49_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG49_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 16 : Protection enable for region 48. */
+#define MPU_PROTENSET1_PROTREG48_Pos (16UL) /*!< Position of PROTREG48 field. */
+#define MPU_PROTENSET1_PROTREG48_Msk (0x1UL << MPU_PROTENSET1_PROTREG48_Pos) /*!< Bit mask of PROTREG48 field. */
+#define MPU_PROTENSET1_PROTREG48_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG48_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG48_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 15 : Protection enable for region 47. */
+#define MPU_PROTENSET1_PROTREG47_Pos (15UL) /*!< Position of PROTREG47 field. */
+#define MPU_PROTENSET1_PROTREG47_Msk (0x1UL << MPU_PROTENSET1_PROTREG47_Pos) /*!< Bit mask of PROTREG47 field. */
+#define MPU_PROTENSET1_PROTREG47_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG47_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG47_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 14 : Protection enable for region 46. */
+#define MPU_PROTENSET1_PROTREG46_Pos (14UL) /*!< Position of PROTREG46 field. */
+#define MPU_PROTENSET1_PROTREG46_Msk (0x1UL << MPU_PROTENSET1_PROTREG46_Pos) /*!< Bit mask of PROTREG46 field. */
+#define MPU_PROTENSET1_PROTREG46_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG46_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG46_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 13 : Protection enable for region 45. */
+#define MPU_PROTENSET1_PROTREG45_Pos (13UL) /*!< Position of PROTREG45 field. */
+#define MPU_PROTENSET1_PROTREG45_Msk (0x1UL << MPU_PROTENSET1_PROTREG45_Pos) /*!< Bit mask of PROTREG45 field. */
+#define MPU_PROTENSET1_PROTREG45_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG45_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG45_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 12 : Protection enable for region 44. */
+#define MPU_PROTENSET1_PROTREG44_Pos (12UL) /*!< Position of PROTREG44 field. */
+#define MPU_PROTENSET1_PROTREG44_Msk (0x1UL << MPU_PROTENSET1_PROTREG44_Pos) /*!< Bit mask of PROTREG44 field. */
+#define MPU_PROTENSET1_PROTREG44_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG44_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG44_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 11 : Protection enable for region 43. */
+#define MPU_PROTENSET1_PROTREG43_Pos (11UL) /*!< Position of PROTREG43 field. */
+#define MPU_PROTENSET1_PROTREG43_Msk (0x1UL << MPU_PROTENSET1_PROTREG43_Pos) /*!< Bit mask of PROTREG43 field. */
+#define MPU_PROTENSET1_PROTREG43_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG43_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG43_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 10 : Protection enable for region 42. */
+#define MPU_PROTENSET1_PROTREG42_Pos (10UL) /*!< Position of PROTREG42 field. */
+#define MPU_PROTENSET1_PROTREG42_Msk (0x1UL << MPU_PROTENSET1_PROTREG42_Pos) /*!< Bit mask of PROTREG42 field. */
+#define MPU_PROTENSET1_PROTREG42_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG42_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG42_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 9 : Protection enable for region 41. */
+#define MPU_PROTENSET1_PROTREG41_Pos (9UL) /*!< Position of PROTREG41 field. */
+#define MPU_PROTENSET1_PROTREG41_Msk (0x1UL << MPU_PROTENSET1_PROTREG41_Pos) /*!< Bit mask of PROTREG41 field. */
+#define MPU_PROTENSET1_PROTREG41_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG41_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG41_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 8 : Protection enable for region 40. */
+#define MPU_PROTENSET1_PROTREG40_Pos (8UL) /*!< Position of PROTREG40 field. */
+#define MPU_PROTENSET1_PROTREG40_Msk (0x1UL << MPU_PROTENSET1_PROTREG40_Pos) /*!< Bit mask of PROTREG40 field. */
+#define MPU_PROTENSET1_PROTREG40_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG40_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG40_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 7 : Protection enable for region 39. */
+#define MPU_PROTENSET1_PROTREG39_Pos (7UL) /*!< Position of PROTREG39 field. */
+#define MPU_PROTENSET1_PROTREG39_Msk (0x1UL << MPU_PROTENSET1_PROTREG39_Pos) /*!< Bit mask of PROTREG39 field. */
+#define MPU_PROTENSET1_PROTREG39_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG39_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG39_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 6 : Protection enable for region 38. */
+#define MPU_PROTENSET1_PROTREG38_Pos (6UL) /*!< Position of PROTREG38 field. */
+#define MPU_PROTENSET1_PROTREG38_Msk (0x1UL << MPU_PROTENSET1_PROTREG38_Pos) /*!< Bit mask of PROTREG38 field. */
+#define MPU_PROTENSET1_PROTREG38_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG38_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG38_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 5 : Protection enable for region 37. */
+#define MPU_PROTENSET1_PROTREG37_Pos (5UL) /*!< Position of PROTREG37 field. */
+#define MPU_PROTENSET1_PROTREG37_Msk (0x1UL << MPU_PROTENSET1_PROTREG37_Pos) /*!< Bit mask of PROTREG37 field. */
+#define MPU_PROTENSET1_PROTREG37_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG37_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG37_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 4 : Protection enable for region 36. */
+#define MPU_PROTENSET1_PROTREG36_Pos (4UL) /*!< Position of PROTREG36 field. */
+#define MPU_PROTENSET1_PROTREG36_Msk (0x1UL << MPU_PROTENSET1_PROTREG36_Pos) /*!< Bit mask of PROTREG36 field. */
+#define MPU_PROTENSET1_PROTREG36_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG36_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG36_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 3 : Protection enable for region 35. */
+#define MPU_PROTENSET1_PROTREG35_Pos (3UL) /*!< Position of PROTREG35 field. */
+#define MPU_PROTENSET1_PROTREG35_Msk (0x1UL << MPU_PROTENSET1_PROTREG35_Pos) /*!< Bit mask of PROTREG35 field. */
+#define MPU_PROTENSET1_PROTREG35_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG35_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG35_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 2 : Protection enable for region 34. */
+#define MPU_PROTENSET1_PROTREG34_Pos (2UL) /*!< Position of PROTREG34 field. */
+#define MPU_PROTENSET1_PROTREG34_Msk (0x1UL << MPU_PROTENSET1_PROTREG34_Pos) /*!< Bit mask of PROTREG34 field. */
+#define MPU_PROTENSET1_PROTREG34_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG34_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG34_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 1 : Protection enable for region 33. */
+#define MPU_PROTENSET1_PROTREG33_Pos (1UL) /*!< Position of PROTREG33 field. */
+#define MPU_PROTENSET1_PROTREG33_Msk (0x1UL << MPU_PROTENSET1_PROTREG33_Pos) /*!< Bit mask of PROTREG33 field. */
+#define MPU_PROTENSET1_PROTREG33_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG33_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG33_Set (1UL) /*!< Enable protection on write. */
+
+/* Bit 0 : Protection enable for region 32. */
+#define MPU_PROTENSET1_PROTREG32_Pos (0UL) /*!< Position of PROTREG32 field. */
+#define MPU_PROTENSET1_PROTREG32_Msk (0x1UL << MPU_PROTENSET1_PROTREG32_Pos) /*!< Bit mask of PROTREG32 field. */
+#define MPU_PROTENSET1_PROTREG32_Disabled (0UL) /*!< Protection disabled. */
+#define MPU_PROTENSET1_PROTREG32_Enabled (1UL) /*!< Protection enabled. */
+#define MPU_PROTENSET1_PROTREG32_Set (1UL) /*!< Enable protection on write. */
+
+/* Register: MPU_DISABLEINDEBUG */
+/* Description: Disable erase and write protection mechanism in debug mode. */
+
+/* Bit 0 : Disable protection mechanism in debug mode. */
+#define MPU_DISABLEINDEBUG_DISABLEINDEBUG_Pos (0UL) /*!< Position of DISABLEINDEBUG field. */
+#define MPU_DISABLEINDEBUG_DISABLEINDEBUG_Msk (0x1UL << MPU_DISABLEINDEBUG_DISABLEINDEBUG_Pos) /*!< Bit mask of DISABLEINDEBUG field. */
+#define MPU_DISABLEINDEBUG_DISABLEINDEBUG_Enabled (0UL) /*!< Protection enabled. */
+#define MPU_DISABLEINDEBUG_DISABLEINDEBUG_Disabled (1UL) /*!< Protection disabled. */
+
+/* Register: MPU_PROTBLOCKSIZE */
+/* Description: Erase and write protection block size. */
+
+/* Bits 1..0 : Erase and write protection block size. */
+#define MPU_PROTBLOCKSIZE_PROTBLOCKSIZE_Pos (0UL) /*!< Position of PROTBLOCKSIZE field. */
+#define MPU_PROTBLOCKSIZE_PROTBLOCKSIZE_Msk (0x3UL << MPU_PROTBLOCKSIZE_PROTBLOCKSIZE_Pos) /*!< Bit mask of PROTBLOCKSIZE field. */
+#define MPU_PROTBLOCKSIZE_PROTBLOCKSIZE_4k (0UL) /*!< Erase and write protection block size is 4k. */
+
+
+/* Peripheral: NVMC */
+/* Description: Non Volatile Memory Controller. */
+
+/* Register: NVMC_READY */
+/* Description: Ready flag. */
+
+/* Bit 0 : NVMC ready. */
+#define NVMC_READY_READY_Pos (0UL) /*!< Position of READY field. */
+#define NVMC_READY_READY_Msk (0x1UL << NVMC_READY_READY_Pos) /*!< Bit mask of READY field. */
+#define NVMC_READY_READY_Busy (0UL) /*!< NVMC is busy (on-going write or erase operation). */
+#define NVMC_READY_READY_Ready (1UL) /*!< NVMC is ready. */
+
+/* Register: NVMC_CONFIG */
+/* Description: Configuration register. */
+
+/* Bits 1..0 : Program write enable. */
+#define NVMC_CONFIG_WEN_Pos (0UL) /*!< Position of WEN field. */
+#define NVMC_CONFIG_WEN_Msk (0x3UL << NVMC_CONFIG_WEN_Pos) /*!< Bit mask of WEN field. */
+#define NVMC_CONFIG_WEN_Ren (0x00UL) /*!< Read only access. */
+#define NVMC_CONFIG_WEN_Wen (0x01UL) /*!< Write enabled. */
+#define NVMC_CONFIG_WEN_Een (0x02UL) /*!< Erase enabled. */
+
+/* Register: NVMC_ERASEALL */
+/* Description: Register for erasing all non-volatile user memory. */
+
+/* Bit 0 : Starts the erasing of all user NVM (code region 0/1 and UICR registers). */
+#define NVMC_ERASEALL_ERASEALL_Pos (0UL) /*!< Position of ERASEALL field. */
+#define NVMC_ERASEALL_ERASEALL_Msk (0x1UL << NVMC_ERASEALL_ERASEALL_Pos) /*!< Bit mask of ERASEALL field. */
+#define NVMC_ERASEALL_ERASEALL_NoOperation (0UL) /*!< No operation. */
+#define NVMC_ERASEALL_ERASEALL_Erase (1UL) /*!< Start chip erase. */
+
+/* Register: NVMC_ERASEUICR */
+/* Description: Register for start erasing User Information Congfiguration Registers. */
+
+/* Bit 0 : It can only be used when all contents of code region 1 are erased. */
+#define NVMC_ERASEUICR_ERASEUICR_Pos (0UL) /*!< Position of ERASEUICR field. */
+#define NVMC_ERASEUICR_ERASEUICR_Msk (0x1UL << NVMC_ERASEUICR_ERASEUICR_Pos) /*!< Bit mask of ERASEUICR field. */
+#define NVMC_ERASEUICR_ERASEUICR_NoOperation (0UL) /*!< No operation. */
+#define NVMC_ERASEUICR_ERASEUICR_Erase (1UL) /*!< Start UICR erase. */
+
+
+/* Peripheral: POWER */
+/* Description: Power Control. */
+
+/* Register: POWER_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 2 : Enable interrupt on POFWARN event. */
+#define POWER_INTENSET_POFWARN_Pos (2UL) /*!< Position of POFWARN field. */
+#define POWER_INTENSET_POFWARN_Msk (0x1UL << POWER_INTENSET_POFWARN_Pos) /*!< Bit mask of POFWARN field. */
+#define POWER_INTENSET_POFWARN_Disabled (0UL) /*!< Interrupt disabled. */
+#define POWER_INTENSET_POFWARN_Enabled (1UL) /*!< Interrupt enabled. */
+#define POWER_INTENSET_POFWARN_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: POWER_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 2 : Disable interrupt on POFWARN event. */
+#define POWER_INTENCLR_POFWARN_Pos (2UL) /*!< Position of POFWARN field. */
+#define POWER_INTENCLR_POFWARN_Msk (0x1UL << POWER_INTENCLR_POFWARN_Pos) /*!< Bit mask of POFWARN field. */
+#define POWER_INTENCLR_POFWARN_Disabled (0UL) /*!< Interrupt disabled. */
+#define POWER_INTENCLR_POFWARN_Enabled (1UL) /*!< Interrupt enabled. */
+#define POWER_INTENCLR_POFWARN_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: POWER_RESETREAS */
+/* Description: Reset reason. */
+
+/* Bit 18 : Reset from wake-up from OFF mode detected by entering into debug interface mode. */
+#define POWER_RESETREAS_DIF_Pos (18UL) /*!< Position of DIF field. */
+#define POWER_RESETREAS_DIF_Msk (0x1UL << POWER_RESETREAS_DIF_Pos) /*!< Bit mask of DIF field. */
+#define POWER_RESETREAS_DIF_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_DIF_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 17 : Reset from wake-up from OFF mode detected by the use of ANADETECT signal from LPCOMP. */
+#define POWER_RESETREAS_LPCOMP_Pos (17UL) /*!< Position of LPCOMP field. */
+#define POWER_RESETREAS_LPCOMP_Msk (0x1UL << POWER_RESETREAS_LPCOMP_Pos) /*!< Bit mask of LPCOMP field. */
+#define POWER_RESETREAS_LPCOMP_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_LPCOMP_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 16 : Reset from wake-up from OFF mode detected by the use of DETECT signal from GPIO. */
+#define POWER_RESETREAS_OFF_Pos (16UL) /*!< Position of OFF field. */
+#define POWER_RESETREAS_OFF_Msk (0x1UL << POWER_RESETREAS_OFF_Pos) /*!< Bit mask of OFF field. */
+#define POWER_RESETREAS_OFF_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_OFF_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 3 : Reset from CPU lock-up detected. */
+#define POWER_RESETREAS_LOCKUP_Pos (3UL) /*!< Position of LOCKUP field. */
+#define POWER_RESETREAS_LOCKUP_Msk (0x1UL << POWER_RESETREAS_LOCKUP_Pos) /*!< Bit mask of LOCKUP field. */
+#define POWER_RESETREAS_LOCKUP_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_LOCKUP_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 2 : Reset from AIRCR.SYSRESETREQ detected. */
+#define POWER_RESETREAS_SREQ_Pos (2UL) /*!< Position of SREQ field. */
+#define POWER_RESETREAS_SREQ_Msk (0x1UL << POWER_RESETREAS_SREQ_Pos) /*!< Bit mask of SREQ field. */
+#define POWER_RESETREAS_SREQ_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_SREQ_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 1 : Reset from watchdog detected. */
+#define POWER_RESETREAS_DOG_Pos (1UL) /*!< Position of DOG field. */
+#define POWER_RESETREAS_DOG_Msk (0x1UL << POWER_RESETREAS_DOG_Pos) /*!< Bit mask of DOG field. */
+#define POWER_RESETREAS_DOG_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_DOG_Detected (1UL) /*!< Reset detected. */
+
+/* Bit 0 : Reset from pin-reset detected. */
+#define POWER_RESETREAS_RESETPIN_Pos (0UL) /*!< Position of RESETPIN field. */
+#define POWER_RESETREAS_RESETPIN_Msk (0x1UL << POWER_RESETREAS_RESETPIN_Pos) /*!< Bit mask of RESETPIN field. */
+#define POWER_RESETREAS_RESETPIN_NotDetected (0UL) /*!< Reset not detected. */
+#define POWER_RESETREAS_RESETPIN_Detected (1UL) /*!< Reset detected. */
+
+/* Register: POWER_RAMSTATUS */
+/* Description: Ram status register. */
+
+/* Bit 3 : RAM block 3 status. */
+#define POWER_RAMSTATUS_RAMBLOCK3_Pos (3UL) /*!< Position of RAMBLOCK3 field. */
+#define POWER_RAMSTATUS_RAMBLOCK3_Msk (0x1UL << POWER_RAMSTATUS_RAMBLOCK3_Pos) /*!< Bit mask of RAMBLOCK3 field. */
+#define POWER_RAMSTATUS_RAMBLOCK3_Off (0UL) /*!< RAM block 3 is off or powering up. */
+#define POWER_RAMSTATUS_RAMBLOCK3_On (1UL) /*!< RAM block 3 is on. */
+
+/* Bit 2 : RAM block 2 status. */
+#define POWER_RAMSTATUS_RAMBLOCK2_Pos (2UL) /*!< Position of RAMBLOCK2 field. */
+#define POWER_RAMSTATUS_RAMBLOCK2_Msk (0x1UL << POWER_RAMSTATUS_RAMBLOCK2_Pos) /*!< Bit mask of RAMBLOCK2 field. */
+#define POWER_RAMSTATUS_RAMBLOCK2_Off (0UL) /*!< RAM block 2 is off or powering up. */
+#define POWER_RAMSTATUS_RAMBLOCK2_On (1UL) /*!< RAM block 2 is on. */
+
+/* Bit 1 : RAM block 1 status. */
+#define POWER_RAMSTATUS_RAMBLOCK1_Pos (1UL) /*!< Position of RAMBLOCK1 field. */
+#define POWER_RAMSTATUS_RAMBLOCK1_Msk (0x1UL << POWER_RAMSTATUS_RAMBLOCK1_Pos) /*!< Bit mask of RAMBLOCK1 field. */
+#define POWER_RAMSTATUS_RAMBLOCK1_Off (0UL) /*!< RAM block 1 is off or powering up. */
+#define POWER_RAMSTATUS_RAMBLOCK1_On (1UL) /*!< RAM block 1 is on. */
+
+/* Bit 0 : RAM block 0 status. */
+#define POWER_RAMSTATUS_RAMBLOCK0_Pos (0UL) /*!< Position of RAMBLOCK0 field. */
+#define POWER_RAMSTATUS_RAMBLOCK0_Msk (0x1UL << POWER_RAMSTATUS_RAMBLOCK0_Pos) /*!< Bit mask of RAMBLOCK0 field. */
+#define POWER_RAMSTATUS_RAMBLOCK0_Off (0UL) /*!< RAM block 0 is off or powering up. */
+#define POWER_RAMSTATUS_RAMBLOCK0_On (1UL) /*!< RAM block 0 is on. */
+
+/* Register: POWER_SYSTEMOFF */
+/* Description: System off register. */
+
+/* Bit 0 : Enter system off mode. */
+#define POWER_SYSTEMOFF_SYSTEMOFF_Pos (0UL) /*!< Position of SYSTEMOFF field. */
+#define POWER_SYSTEMOFF_SYSTEMOFF_Msk (0x1UL << POWER_SYSTEMOFF_SYSTEMOFF_Pos) /*!< Bit mask of SYSTEMOFF field. */
+#define POWER_SYSTEMOFF_SYSTEMOFF_Enter (1UL) /*!< Enter system off mode. */
+
+/* Register: POWER_POFCON */
+/* Description: Power failure configuration. */
+
+/* Bits 2..1 : Set threshold level. */
+#define POWER_POFCON_THRESHOLD_Pos (1UL) /*!< Position of THRESHOLD field. */
+#define POWER_POFCON_THRESHOLD_Msk (0x3UL << POWER_POFCON_THRESHOLD_Pos) /*!< Bit mask of THRESHOLD field. */
+#define POWER_POFCON_THRESHOLD_V21 (0x00UL) /*!< Set threshold to 2.1Volts. */
+#define POWER_POFCON_THRESHOLD_V23 (0x01UL) /*!< Set threshold to 2.3Volts. */
+#define POWER_POFCON_THRESHOLD_V25 (0x02UL) /*!< Set threshold to 2.5Volts. */
+#define POWER_POFCON_THRESHOLD_V27 (0x03UL) /*!< Set threshold to 2.7Volts. */
+
+/* Bit 0 : Power failure comparator enable. */
+#define POWER_POFCON_POF_Pos (0UL) /*!< Position of POF field. */
+#define POWER_POFCON_POF_Msk (0x1UL << POWER_POFCON_POF_Pos) /*!< Bit mask of POF field. */
+#define POWER_POFCON_POF_Disabled (0UL) /*!< Disabled. */
+#define POWER_POFCON_POF_Enabled (1UL) /*!< Enabled. */
+
+/* Register: POWER_GPREGRET */
+/* Description: General purpose retention register. This register is a retained register. */
+
+/* Bits 7..0 : General purpose retention register. */
+#define POWER_GPREGRET_GPREGRET_Pos (0UL) /*!< Position of GPREGRET field. */
+#define POWER_GPREGRET_GPREGRET_Msk (0xFFUL << POWER_GPREGRET_GPREGRET_Pos) /*!< Bit mask of GPREGRET field. */
+
+/* Register: POWER_RAMON */
+/* Description: Ram on/off. */
+
+/* Bit 17 : RAM block 1 behaviour in OFF mode. */
+#define POWER_RAMON_OFFRAM1_Pos (17UL) /*!< Position of OFFRAM1 field. */
+#define POWER_RAMON_OFFRAM1_Msk (0x1UL << POWER_RAMON_OFFRAM1_Pos) /*!< Bit mask of OFFRAM1 field. */
+#define POWER_RAMON_OFFRAM1_RAM1Off (0UL) /*!< RAM block 1 OFF in OFF mode. */
+#define POWER_RAMON_OFFRAM1_RAM1On (1UL) /*!< RAM block 1 ON in OFF mode. */
+
+/* Bit 16 : RAM block 0 behaviour in OFF mode. */
+#define POWER_RAMON_OFFRAM0_Pos (16UL) /*!< Position of OFFRAM0 field. */
+#define POWER_RAMON_OFFRAM0_Msk (0x1UL << POWER_RAMON_OFFRAM0_Pos) /*!< Bit mask of OFFRAM0 field. */
+#define POWER_RAMON_OFFRAM0_RAM0Off (0UL) /*!< RAM block 0 OFF in OFF mode. */
+#define POWER_RAMON_OFFRAM0_RAM0On (1UL) /*!< RAM block 0 ON in OFF mode. */
+
+/* Bit 1 : RAM block 1 behaviour in ON mode. */
+#define POWER_RAMON_ONRAM1_Pos (1UL) /*!< Position of ONRAM1 field. */
+#define POWER_RAMON_ONRAM1_Msk (0x1UL << POWER_RAMON_ONRAM1_Pos) /*!< Bit mask of ONRAM1 field. */
+#define POWER_RAMON_ONRAM1_RAM1Off (0UL) /*!< RAM block 1 OFF in ON mode. */
+#define POWER_RAMON_ONRAM1_RAM1On (1UL) /*!< RAM block 1 ON in ON mode. */
+
+/* Bit 0 : RAM block 0 behaviour in ON mode. */
+#define POWER_RAMON_ONRAM0_Pos (0UL) /*!< Position of ONRAM0 field. */
+#define POWER_RAMON_ONRAM0_Msk (0x1UL << POWER_RAMON_ONRAM0_Pos) /*!< Bit mask of ONRAM0 field. */
+#define POWER_RAMON_ONRAM0_RAM0Off (0UL) /*!< RAM block 0 OFF in ON mode. */
+#define POWER_RAMON_ONRAM0_RAM0On (1UL) /*!< RAM block 0 ON in ON mode. */
+
+/* Register: POWER_RESET */
+/* Description: Pin reset functionality configuration register. This register is a retained register. */
+
+/* Bit 0 : Enable or disable pin reset in debug interface mode. */
+#define POWER_RESET_RESET_Pos (0UL) /*!< Position of RESET field. */
+#define POWER_RESET_RESET_Msk (0x1UL << POWER_RESET_RESET_Pos) /*!< Bit mask of RESET field. */
+#define POWER_RESET_RESET_Disabled (0UL) /*!< Pin reset in debug interface mode disabled. */
+#define POWER_RESET_RESET_Enabled (1UL) /*!< Pin reset in debug interface mode enabled. */
+
+/* Register: POWER_RAMONB */
+/* Description: Ram on/off. */
+
+/* Bit 17 : RAM block 3 behaviour in OFF mode. */
+#define POWER_RAMONB_OFFRAM3_Pos (17UL) /*!< Position of OFFRAM3 field. */
+#define POWER_RAMONB_OFFRAM3_Msk (0x1UL << POWER_RAMONB_OFFRAM3_Pos) /*!< Bit mask of OFFRAM3 field. */
+#define POWER_RAMONB_OFFRAM3_RAM3Off (0UL) /*!< RAM block 3 OFF in OFF mode. */
+#define POWER_RAMONB_OFFRAM3_RAM3On (1UL) /*!< RAM block 3 ON in OFF mode. */
+
+/* Bit 16 : RAM block 2 behaviour in OFF mode. */
+#define POWER_RAMONB_OFFRAM2_Pos (16UL) /*!< Position of OFFRAM2 field. */
+#define POWER_RAMONB_OFFRAM2_Msk (0x1UL << POWER_RAMONB_OFFRAM2_Pos) /*!< Bit mask of OFFRAM2 field. */
+#define POWER_RAMONB_OFFRAM2_RAM2Off (0UL) /*!< RAM block 2 OFF in OFF mode. */
+#define POWER_RAMONB_OFFRAM2_RAM2On (1UL) /*!< RAM block 2 ON in OFF mode. */
+
+/* Bit 1 : RAM block 3 behaviour in ON mode. */
+#define POWER_RAMONB_ONRAM3_Pos (1UL) /*!< Position of ONRAM3 field. */
+#define POWER_RAMONB_ONRAM3_Msk (0x1UL << POWER_RAMONB_ONRAM3_Pos) /*!< Bit mask of ONRAM3 field. */
+#define POWER_RAMONB_ONRAM3_RAM3Off (0UL) /*!< RAM block 33 OFF in ON mode. */
+#define POWER_RAMONB_ONRAM3_RAM3On (1UL) /*!< RAM block 3 ON in ON mode. */
+
+/* Bit 0 : RAM block 2 behaviour in ON mode. */
+#define POWER_RAMONB_ONRAM2_Pos (0UL) /*!< Position of ONRAM2 field. */
+#define POWER_RAMONB_ONRAM2_Msk (0x1UL << POWER_RAMONB_ONRAM2_Pos) /*!< Bit mask of ONRAM2 field. */
+#define POWER_RAMONB_ONRAM2_RAM2Off (0UL) /*!< RAM block 2 OFF in ON mode. */
+#define POWER_RAMONB_ONRAM2_RAM2On (1UL) /*!< RAM block 2 ON in ON mode. */
+
+/* Register: POWER_DCDCEN */
+/* Description: DCDC converter enable configuration register. */
+
+/* Bit 0 : Enable DCDC converter. */
+#define POWER_DCDCEN_DCDCEN_Pos (0UL) /*!< Position of DCDCEN field. */
+#define POWER_DCDCEN_DCDCEN_Msk (0x1UL << POWER_DCDCEN_DCDCEN_Pos) /*!< Bit mask of DCDCEN field. */
+#define POWER_DCDCEN_DCDCEN_Disabled (0UL) /*!< DCDC converter disabled. */
+#define POWER_DCDCEN_DCDCEN_Enabled (1UL) /*!< DCDC converter enabled. */
+
+/* Register: POWER_DCDCFORCE */
+/* Description: DCDC power-up force register. */
+
+/* Bit 1 : DCDC power-up force on. */
+#define POWER_DCDCFORCE_FORCEON_Pos (1UL) /*!< Position of FORCEON field. */
+#define POWER_DCDCFORCE_FORCEON_Msk (0x1UL << POWER_DCDCFORCE_FORCEON_Pos) /*!< Bit mask of FORCEON field. */
+#define POWER_DCDCFORCE_FORCEON_NoForce (0UL) /*!< No force. */
+#define POWER_DCDCFORCE_FORCEON_Force (1UL) /*!< Force. */
+
+/* Bit 0 : DCDC power-up force off. */
+#define POWER_DCDCFORCE_FORCEOFF_Pos (0UL) /*!< Position of FORCEOFF field. */
+#define POWER_DCDCFORCE_FORCEOFF_Msk (0x1UL << POWER_DCDCFORCE_FORCEOFF_Pos) /*!< Bit mask of FORCEOFF field. */
+#define POWER_DCDCFORCE_FORCEOFF_NoForce (0UL) /*!< No force. */
+#define POWER_DCDCFORCE_FORCEOFF_Force (1UL) /*!< Force. */
+
+
+/* Peripheral: PPI */
+/* Description: PPI controller. */
+
+/* Register: PPI_CHEN */
+/* Description: Channel enable. */
+
+/* Bit 31 : Enable PPI channel 31. */
+#define PPI_CHEN_CH31_Pos (31UL) /*!< Position of CH31 field. */
+#define PPI_CHEN_CH31_Msk (0x1UL << PPI_CHEN_CH31_Pos) /*!< Bit mask of CH31 field. */
+#define PPI_CHEN_CH31_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH31_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 30 : Enable PPI channel 30. */
+#define PPI_CHEN_CH30_Pos (30UL) /*!< Position of CH30 field. */
+#define PPI_CHEN_CH30_Msk (0x1UL << PPI_CHEN_CH30_Pos) /*!< Bit mask of CH30 field. */
+#define PPI_CHEN_CH30_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH30_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 29 : Enable PPI channel 29. */
+#define PPI_CHEN_CH29_Pos (29UL) /*!< Position of CH29 field. */
+#define PPI_CHEN_CH29_Msk (0x1UL << PPI_CHEN_CH29_Pos) /*!< Bit mask of CH29 field. */
+#define PPI_CHEN_CH29_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH29_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 28 : Enable PPI channel 28. */
+#define PPI_CHEN_CH28_Pos (28UL) /*!< Position of CH28 field. */
+#define PPI_CHEN_CH28_Msk (0x1UL << PPI_CHEN_CH28_Pos) /*!< Bit mask of CH28 field. */
+#define PPI_CHEN_CH28_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH28_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 27 : Enable PPI channel 27. */
+#define PPI_CHEN_CH27_Pos (27UL) /*!< Position of CH27 field. */
+#define PPI_CHEN_CH27_Msk (0x1UL << PPI_CHEN_CH27_Pos) /*!< Bit mask of CH27 field. */
+#define PPI_CHEN_CH27_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH27_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 26 : Enable PPI channel 26. */
+#define PPI_CHEN_CH26_Pos (26UL) /*!< Position of CH26 field. */
+#define PPI_CHEN_CH26_Msk (0x1UL << PPI_CHEN_CH26_Pos) /*!< Bit mask of CH26 field. */
+#define PPI_CHEN_CH26_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH26_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 25 : Enable PPI channel 25. */
+#define PPI_CHEN_CH25_Pos (25UL) /*!< Position of CH25 field. */
+#define PPI_CHEN_CH25_Msk (0x1UL << PPI_CHEN_CH25_Pos) /*!< Bit mask of CH25 field. */
+#define PPI_CHEN_CH25_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH25_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 24 : Enable PPI channel 24. */
+#define PPI_CHEN_CH24_Pos (24UL) /*!< Position of CH24 field. */
+#define PPI_CHEN_CH24_Msk (0x1UL << PPI_CHEN_CH24_Pos) /*!< Bit mask of CH24 field. */
+#define PPI_CHEN_CH24_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH24_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 23 : Enable PPI channel 23. */
+#define PPI_CHEN_CH23_Pos (23UL) /*!< Position of CH23 field. */
+#define PPI_CHEN_CH23_Msk (0x1UL << PPI_CHEN_CH23_Pos) /*!< Bit mask of CH23 field. */
+#define PPI_CHEN_CH23_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH23_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 22 : Enable PPI channel 22. */
+#define PPI_CHEN_CH22_Pos (22UL) /*!< Position of CH22 field. */
+#define PPI_CHEN_CH22_Msk (0x1UL << PPI_CHEN_CH22_Pos) /*!< Bit mask of CH22 field. */
+#define PPI_CHEN_CH22_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH22_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 21 : Enable PPI channel 21. */
+#define PPI_CHEN_CH21_Pos (21UL) /*!< Position of CH21 field. */
+#define PPI_CHEN_CH21_Msk (0x1UL << PPI_CHEN_CH21_Pos) /*!< Bit mask of CH21 field. */
+#define PPI_CHEN_CH21_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH21_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 20 : Enable PPI channel 20. */
+#define PPI_CHEN_CH20_Pos (20UL) /*!< Position of CH20 field. */
+#define PPI_CHEN_CH20_Msk (0x1UL << PPI_CHEN_CH20_Pos) /*!< Bit mask of CH20 field. */
+#define PPI_CHEN_CH20_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH20_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 15 : Enable PPI channel 15. */
+#define PPI_CHEN_CH15_Pos (15UL) /*!< Position of CH15 field. */
+#define PPI_CHEN_CH15_Msk (0x1UL << PPI_CHEN_CH15_Pos) /*!< Bit mask of CH15 field. */
+#define PPI_CHEN_CH15_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH15_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 14 : Enable PPI channel 14. */
+#define PPI_CHEN_CH14_Pos (14UL) /*!< Position of CH14 field. */
+#define PPI_CHEN_CH14_Msk (0x1UL << PPI_CHEN_CH14_Pos) /*!< Bit mask of CH14 field. */
+#define PPI_CHEN_CH14_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH14_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 13 : Enable PPI channel 13. */
+#define PPI_CHEN_CH13_Pos (13UL) /*!< Position of CH13 field. */
+#define PPI_CHEN_CH13_Msk (0x1UL << PPI_CHEN_CH13_Pos) /*!< Bit mask of CH13 field. */
+#define PPI_CHEN_CH13_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH13_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 12 : Enable PPI channel 12. */
+#define PPI_CHEN_CH12_Pos (12UL) /*!< Position of CH12 field. */
+#define PPI_CHEN_CH12_Msk (0x1UL << PPI_CHEN_CH12_Pos) /*!< Bit mask of CH12 field. */
+#define PPI_CHEN_CH12_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH12_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 11 : Enable PPI channel 11. */
+#define PPI_CHEN_CH11_Pos (11UL) /*!< Position of CH11 field. */
+#define PPI_CHEN_CH11_Msk (0x1UL << PPI_CHEN_CH11_Pos) /*!< Bit mask of CH11 field. */
+#define PPI_CHEN_CH11_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH11_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 10 : Enable PPI channel 10. */
+#define PPI_CHEN_CH10_Pos (10UL) /*!< Position of CH10 field. */
+#define PPI_CHEN_CH10_Msk (0x1UL << PPI_CHEN_CH10_Pos) /*!< Bit mask of CH10 field. */
+#define PPI_CHEN_CH10_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH10_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 9 : Enable PPI channel 9. */
+#define PPI_CHEN_CH9_Pos (9UL) /*!< Position of CH9 field. */
+#define PPI_CHEN_CH9_Msk (0x1UL << PPI_CHEN_CH9_Pos) /*!< Bit mask of CH9 field. */
+#define PPI_CHEN_CH9_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH9_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 8 : Enable PPI channel 8. */
+#define PPI_CHEN_CH8_Pos (8UL) /*!< Position of CH8 field. */
+#define PPI_CHEN_CH8_Msk (0x1UL << PPI_CHEN_CH8_Pos) /*!< Bit mask of CH8 field. */
+#define PPI_CHEN_CH8_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH8_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 7 : Enable PPI channel 7. */
+#define PPI_CHEN_CH7_Pos (7UL) /*!< Position of CH7 field. */
+#define PPI_CHEN_CH7_Msk (0x1UL << PPI_CHEN_CH7_Pos) /*!< Bit mask of CH7 field. */
+#define PPI_CHEN_CH7_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH7_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 6 : Enable PPI channel 6. */
+#define PPI_CHEN_CH6_Pos (6UL) /*!< Position of CH6 field. */
+#define PPI_CHEN_CH6_Msk (0x1UL << PPI_CHEN_CH6_Pos) /*!< Bit mask of CH6 field. */
+#define PPI_CHEN_CH6_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH6_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 5 : Enable PPI channel 5. */
+#define PPI_CHEN_CH5_Pos (5UL) /*!< Position of CH5 field. */
+#define PPI_CHEN_CH5_Msk (0x1UL << PPI_CHEN_CH5_Pos) /*!< Bit mask of CH5 field. */
+#define PPI_CHEN_CH5_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH5_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 4 : Enable PPI channel 4. */
+#define PPI_CHEN_CH4_Pos (4UL) /*!< Position of CH4 field. */
+#define PPI_CHEN_CH4_Msk (0x1UL << PPI_CHEN_CH4_Pos) /*!< Bit mask of CH4 field. */
+#define PPI_CHEN_CH4_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH4_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 3 : Enable PPI channel 3. */
+#define PPI_CHEN_CH3_Pos (3UL) /*!< Position of CH3 field. */
+#define PPI_CHEN_CH3_Msk (0x1UL << PPI_CHEN_CH3_Pos) /*!< Bit mask of CH3 field. */
+#define PPI_CHEN_CH3_Disabled (0UL) /*!< Channel disabled */
+#define PPI_CHEN_CH3_Enabled (1UL) /*!< Channel enabled */
+
+/* Bit 2 : Enable PPI channel 2. */
+#define PPI_CHEN_CH2_Pos (2UL) /*!< Position of CH2 field. */
+#define PPI_CHEN_CH2_Msk (0x1UL << PPI_CHEN_CH2_Pos) /*!< Bit mask of CH2 field. */
+#define PPI_CHEN_CH2_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH2_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 1 : Enable PPI channel 1. */
+#define PPI_CHEN_CH1_Pos (1UL) /*!< Position of CH1 field. */
+#define PPI_CHEN_CH1_Msk (0x1UL << PPI_CHEN_CH1_Pos) /*!< Bit mask of CH1 field. */
+#define PPI_CHEN_CH1_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH1_Enabled (1UL) /*!< Channel enabled. */
+
+/* Bit 0 : Enable PPI channel 0. */
+#define PPI_CHEN_CH0_Pos (0UL) /*!< Position of CH0 field. */
+#define PPI_CHEN_CH0_Msk (0x1UL << PPI_CHEN_CH0_Pos) /*!< Bit mask of CH0 field. */
+#define PPI_CHEN_CH0_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHEN_CH0_Enabled (1UL) /*!< Channel enabled. */
+
+/* Register: PPI_CHENSET */
+/* Description: Channel enable set. */
+
+/* Bit 31 : Enable PPI channel 31. */
+#define PPI_CHENSET_CH31_Pos (31UL) /*!< Position of CH31 field. */
+#define PPI_CHENSET_CH31_Msk (0x1UL << PPI_CHENSET_CH31_Pos) /*!< Bit mask of CH31 field. */
+#define PPI_CHENSET_CH31_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH31_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH31_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 30 : Enable PPI channel 30. */
+#define PPI_CHENSET_CH30_Pos (30UL) /*!< Position of CH30 field. */
+#define PPI_CHENSET_CH30_Msk (0x1UL << PPI_CHENSET_CH30_Pos) /*!< Bit mask of CH30 field. */
+#define PPI_CHENSET_CH30_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH30_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH30_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 29 : Enable PPI channel 29. */
+#define PPI_CHENSET_CH29_Pos (29UL) /*!< Position of CH29 field. */
+#define PPI_CHENSET_CH29_Msk (0x1UL << PPI_CHENSET_CH29_Pos) /*!< Bit mask of CH29 field. */
+#define PPI_CHENSET_CH29_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH29_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH29_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 28 : Enable PPI channel 28. */
+#define PPI_CHENSET_CH28_Pos (28UL) /*!< Position of CH28 field. */
+#define PPI_CHENSET_CH28_Msk (0x1UL << PPI_CHENSET_CH28_Pos) /*!< Bit mask of CH28 field. */
+#define PPI_CHENSET_CH28_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH28_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH28_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 27 : Enable PPI channel 27. */
+#define PPI_CHENSET_CH27_Pos (27UL) /*!< Position of CH27 field. */
+#define PPI_CHENSET_CH27_Msk (0x1UL << PPI_CHENSET_CH27_Pos) /*!< Bit mask of CH27 field. */
+#define PPI_CHENSET_CH27_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH27_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH27_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 26 : Enable PPI channel 26. */
+#define PPI_CHENSET_CH26_Pos (26UL) /*!< Position of CH26 field. */
+#define PPI_CHENSET_CH26_Msk (0x1UL << PPI_CHENSET_CH26_Pos) /*!< Bit mask of CH26 field. */
+#define PPI_CHENSET_CH26_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH26_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH26_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 25 : Enable PPI channel 25. */
+#define PPI_CHENSET_CH25_Pos (25UL) /*!< Position of CH25 field. */
+#define PPI_CHENSET_CH25_Msk (0x1UL << PPI_CHENSET_CH25_Pos) /*!< Bit mask of CH25 field. */
+#define PPI_CHENSET_CH25_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH25_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH25_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 24 : Enable PPI channel 24. */
+#define PPI_CHENSET_CH24_Pos (24UL) /*!< Position of CH24 field. */
+#define PPI_CHENSET_CH24_Msk (0x1UL << PPI_CHENSET_CH24_Pos) /*!< Bit mask of CH24 field. */
+#define PPI_CHENSET_CH24_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH24_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH24_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 23 : Enable PPI channel 23. */
+#define PPI_CHENSET_CH23_Pos (23UL) /*!< Position of CH23 field. */
+#define PPI_CHENSET_CH23_Msk (0x1UL << PPI_CHENSET_CH23_Pos) /*!< Bit mask of CH23 field. */
+#define PPI_CHENSET_CH23_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH23_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH23_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 22 : Enable PPI channel 22. */
+#define PPI_CHENSET_CH22_Pos (22UL) /*!< Position of CH22 field. */
+#define PPI_CHENSET_CH22_Msk (0x1UL << PPI_CHENSET_CH22_Pos) /*!< Bit mask of CH22 field. */
+#define PPI_CHENSET_CH22_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH22_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH22_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 21 : Enable PPI channel 21. */
+#define PPI_CHENSET_CH21_Pos (21UL) /*!< Position of CH21 field. */
+#define PPI_CHENSET_CH21_Msk (0x1UL << PPI_CHENSET_CH21_Pos) /*!< Bit mask of CH21 field. */
+#define PPI_CHENSET_CH21_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH21_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH21_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 20 : Enable PPI channel 20. */
+#define PPI_CHENSET_CH20_Pos (20UL) /*!< Position of CH20 field. */
+#define PPI_CHENSET_CH20_Msk (0x1UL << PPI_CHENSET_CH20_Pos) /*!< Bit mask of CH20 field. */
+#define PPI_CHENSET_CH20_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH20_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH20_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 15 : Enable PPI channel 15. */
+#define PPI_CHENSET_CH15_Pos (15UL) /*!< Position of CH15 field. */
+#define PPI_CHENSET_CH15_Msk (0x1UL << PPI_CHENSET_CH15_Pos) /*!< Bit mask of CH15 field. */
+#define PPI_CHENSET_CH15_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH15_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH15_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 14 : Enable PPI channel 14. */
+#define PPI_CHENSET_CH14_Pos (14UL) /*!< Position of CH14 field. */
+#define PPI_CHENSET_CH14_Msk (0x1UL << PPI_CHENSET_CH14_Pos) /*!< Bit mask of CH14 field. */
+#define PPI_CHENSET_CH14_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH14_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH14_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 13 : Enable PPI channel 13. */
+#define PPI_CHENSET_CH13_Pos (13UL) /*!< Position of CH13 field. */
+#define PPI_CHENSET_CH13_Msk (0x1UL << PPI_CHENSET_CH13_Pos) /*!< Bit mask of CH13 field. */
+#define PPI_CHENSET_CH13_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH13_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH13_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 12 : Enable PPI channel 12. */
+#define PPI_CHENSET_CH12_Pos (12UL) /*!< Position of CH12 field. */
+#define PPI_CHENSET_CH12_Msk (0x1UL << PPI_CHENSET_CH12_Pos) /*!< Bit mask of CH12 field. */
+#define PPI_CHENSET_CH12_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH12_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH12_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 11 : Enable PPI channel 11. */
+#define PPI_CHENSET_CH11_Pos (11UL) /*!< Position of CH11 field. */
+#define PPI_CHENSET_CH11_Msk (0x1UL << PPI_CHENSET_CH11_Pos) /*!< Bit mask of CH11 field. */
+#define PPI_CHENSET_CH11_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH11_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH11_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 10 : Enable PPI channel 10. */
+#define PPI_CHENSET_CH10_Pos (10UL) /*!< Position of CH10 field. */
+#define PPI_CHENSET_CH10_Msk (0x1UL << PPI_CHENSET_CH10_Pos) /*!< Bit mask of CH10 field. */
+#define PPI_CHENSET_CH10_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH10_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH10_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 9 : Enable PPI channel 9. */
+#define PPI_CHENSET_CH9_Pos (9UL) /*!< Position of CH9 field. */
+#define PPI_CHENSET_CH9_Msk (0x1UL << PPI_CHENSET_CH9_Pos) /*!< Bit mask of CH9 field. */
+#define PPI_CHENSET_CH9_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH9_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH9_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 8 : Enable PPI channel 8. */
+#define PPI_CHENSET_CH8_Pos (8UL) /*!< Position of CH8 field. */
+#define PPI_CHENSET_CH8_Msk (0x1UL << PPI_CHENSET_CH8_Pos) /*!< Bit mask of CH8 field. */
+#define PPI_CHENSET_CH8_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH8_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH8_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 7 : Enable PPI channel 7. */
+#define PPI_CHENSET_CH7_Pos (7UL) /*!< Position of CH7 field. */
+#define PPI_CHENSET_CH7_Msk (0x1UL << PPI_CHENSET_CH7_Pos) /*!< Bit mask of CH7 field. */
+#define PPI_CHENSET_CH7_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH7_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH7_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 6 : Enable PPI channel 6. */
+#define PPI_CHENSET_CH6_Pos (6UL) /*!< Position of CH6 field. */
+#define PPI_CHENSET_CH6_Msk (0x1UL << PPI_CHENSET_CH6_Pos) /*!< Bit mask of CH6 field. */
+#define PPI_CHENSET_CH6_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH6_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH6_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 5 : Enable PPI channel 5. */
+#define PPI_CHENSET_CH5_Pos (5UL) /*!< Position of CH5 field. */
+#define PPI_CHENSET_CH5_Msk (0x1UL << PPI_CHENSET_CH5_Pos) /*!< Bit mask of CH5 field. */
+#define PPI_CHENSET_CH5_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH5_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH5_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 4 : Enable PPI channel 4. */
+#define PPI_CHENSET_CH4_Pos (4UL) /*!< Position of CH4 field. */
+#define PPI_CHENSET_CH4_Msk (0x1UL << PPI_CHENSET_CH4_Pos) /*!< Bit mask of CH4 field. */
+#define PPI_CHENSET_CH4_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH4_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH4_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 3 : Enable PPI channel 3. */
+#define PPI_CHENSET_CH3_Pos (3UL) /*!< Position of CH3 field. */
+#define PPI_CHENSET_CH3_Msk (0x1UL << PPI_CHENSET_CH3_Pos) /*!< Bit mask of CH3 field. */
+#define PPI_CHENSET_CH3_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH3_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH3_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 2 : Enable PPI channel 2. */
+#define PPI_CHENSET_CH2_Pos (2UL) /*!< Position of CH2 field. */
+#define PPI_CHENSET_CH2_Msk (0x1UL << PPI_CHENSET_CH2_Pos) /*!< Bit mask of CH2 field. */
+#define PPI_CHENSET_CH2_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH2_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH2_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 1 : Enable PPI channel 1. */
+#define PPI_CHENSET_CH1_Pos (1UL) /*!< Position of CH1 field. */
+#define PPI_CHENSET_CH1_Msk (0x1UL << PPI_CHENSET_CH1_Pos) /*!< Bit mask of CH1 field. */
+#define PPI_CHENSET_CH1_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH1_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH1_Set (1UL) /*!< Enable channel on write. */
+
+/* Bit 0 : Enable PPI channel 0. */
+#define PPI_CHENSET_CH0_Pos (0UL) /*!< Position of CH0 field. */
+#define PPI_CHENSET_CH0_Msk (0x1UL << PPI_CHENSET_CH0_Pos) /*!< Bit mask of CH0 field. */
+#define PPI_CHENSET_CH0_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENSET_CH0_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENSET_CH0_Set (1UL) /*!< Enable channel on write. */
+
+/* Register: PPI_CHENCLR */
+/* Description: Channel enable clear. */
+
+/* Bit 31 : Disable PPI channel 31. */
+#define PPI_CHENCLR_CH31_Pos (31UL) /*!< Position of CH31 field. */
+#define PPI_CHENCLR_CH31_Msk (0x1UL << PPI_CHENCLR_CH31_Pos) /*!< Bit mask of CH31 field. */
+#define PPI_CHENCLR_CH31_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH31_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH31_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 30 : Disable PPI channel 30. */
+#define PPI_CHENCLR_CH30_Pos (30UL) /*!< Position of CH30 field. */
+#define PPI_CHENCLR_CH30_Msk (0x1UL << PPI_CHENCLR_CH30_Pos) /*!< Bit mask of CH30 field. */
+#define PPI_CHENCLR_CH30_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH30_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH30_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 29 : Disable PPI channel 29. */
+#define PPI_CHENCLR_CH29_Pos (29UL) /*!< Position of CH29 field. */
+#define PPI_CHENCLR_CH29_Msk (0x1UL << PPI_CHENCLR_CH29_Pos) /*!< Bit mask of CH29 field. */
+#define PPI_CHENCLR_CH29_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH29_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH29_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 28 : Disable PPI channel 28. */
+#define PPI_CHENCLR_CH28_Pos (28UL) /*!< Position of CH28 field. */
+#define PPI_CHENCLR_CH28_Msk (0x1UL << PPI_CHENCLR_CH28_Pos) /*!< Bit mask of CH28 field. */
+#define PPI_CHENCLR_CH28_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH28_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH28_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 27 : Disable PPI channel 27. */
+#define PPI_CHENCLR_CH27_Pos (27UL) /*!< Position of CH27 field. */
+#define PPI_CHENCLR_CH27_Msk (0x1UL << PPI_CHENCLR_CH27_Pos) /*!< Bit mask of CH27 field. */
+#define PPI_CHENCLR_CH27_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH27_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH27_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 26 : Disable PPI channel 26. */
+#define PPI_CHENCLR_CH26_Pos (26UL) /*!< Position of CH26 field. */
+#define PPI_CHENCLR_CH26_Msk (0x1UL << PPI_CHENCLR_CH26_Pos) /*!< Bit mask of CH26 field. */
+#define PPI_CHENCLR_CH26_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH26_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH26_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 25 : Disable PPI channel 25. */
+#define PPI_CHENCLR_CH25_Pos (25UL) /*!< Position of CH25 field. */
+#define PPI_CHENCLR_CH25_Msk (0x1UL << PPI_CHENCLR_CH25_Pos) /*!< Bit mask of CH25 field. */
+#define PPI_CHENCLR_CH25_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH25_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH25_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 24 : Disable PPI channel 24. */
+#define PPI_CHENCLR_CH24_Pos (24UL) /*!< Position of CH24 field. */
+#define PPI_CHENCLR_CH24_Msk (0x1UL << PPI_CHENCLR_CH24_Pos) /*!< Bit mask of CH24 field. */
+#define PPI_CHENCLR_CH24_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH24_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH24_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 23 : Disable PPI channel 23. */
+#define PPI_CHENCLR_CH23_Pos (23UL) /*!< Position of CH23 field. */
+#define PPI_CHENCLR_CH23_Msk (0x1UL << PPI_CHENCLR_CH23_Pos) /*!< Bit mask of CH23 field. */
+#define PPI_CHENCLR_CH23_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH23_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH23_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 22 : Disable PPI channel 22. */
+#define PPI_CHENCLR_CH22_Pos (22UL) /*!< Position of CH22 field. */
+#define PPI_CHENCLR_CH22_Msk (0x1UL << PPI_CHENCLR_CH22_Pos) /*!< Bit mask of CH22 field. */
+#define PPI_CHENCLR_CH22_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH22_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH22_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 21 : Disable PPI channel 21. */
+#define PPI_CHENCLR_CH21_Pos (21UL) /*!< Position of CH21 field. */
+#define PPI_CHENCLR_CH21_Msk (0x1UL << PPI_CHENCLR_CH21_Pos) /*!< Bit mask of CH21 field. */
+#define PPI_CHENCLR_CH21_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH21_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH21_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 20 : Disable PPI channel 20. */
+#define PPI_CHENCLR_CH20_Pos (20UL) /*!< Position of CH20 field. */
+#define PPI_CHENCLR_CH20_Msk (0x1UL << PPI_CHENCLR_CH20_Pos) /*!< Bit mask of CH20 field. */
+#define PPI_CHENCLR_CH20_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH20_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH20_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 15 : Disable PPI channel 15. */
+#define PPI_CHENCLR_CH15_Pos (15UL) /*!< Position of CH15 field. */
+#define PPI_CHENCLR_CH15_Msk (0x1UL << PPI_CHENCLR_CH15_Pos) /*!< Bit mask of CH15 field. */
+#define PPI_CHENCLR_CH15_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH15_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH15_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 14 : Disable PPI channel 14. */
+#define PPI_CHENCLR_CH14_Pos (14UL) /*!< Position of CH14 field. */
+#define PPI_CHENCLR_CH14_Msk (0x1UL << PPI_CHENCLR_CH14_Pos) /*!< Bit mask of CH14 field. */
+#define PPI_CHENCLR_CH14_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH14_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH14_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 13 : Disable PPI channel 13. */
+#define PPI_CHENCLR_CH13_Pos (13UL) /*!< Position of CH13 field. */
+#define PPI_CHENCLR_CH13_Msk (0x1UL << PPI_CHENCLR_CH13_Pos) /*!< Bit mask of CH13 field. */
+#define PPI_CHENCLR_CH13_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH13_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH13_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 12 : Disable PPI channel 12. */
+#define PPI_CHENCLR_CH12_Pos (12UL) /*!< Position of CH12 field. */
+#define PPI_CHENCLR_CH12_Msk (0x1UL << PPI_CHENCLR_CH12_Pos) /*!< Bit mask of CH12 field. */
+#define PPI_CHENCLR_CH12_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH12_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH12_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 11 : Disable PPI channel 11. */
+#define PPI_CHENCLR_CH11_Pos (11UL) /*!< Position of CH11 field. */
+#define PPI_CHENCLR_CH11_Msk (0x1UL << PPI_CHENCLR_CH11_Pos) /*!< Bit mask of CH11 field. */
+#define PPI_CHENCLR_CH11_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH11_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH11_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 10 : Disable PPI channel 10. */
+#define PPI_CHENCLR_CH10_Pos (10UL) /*!< Position of CH10 field. */
+#define PPI_CHENCLR_CH10_Msk (0x1UL << PPI_CHENCLR_CH10_Pos) /*!< Bit mask of CH10 field. */
+#define PPI_CHENCLR_CH10_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH10_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH10_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 9 : Disable PPI channel 9. */
+#define PPI_CHENCLR_CH9_Pos (9UL) /*!< Position of CH9 field. */
+#define PPI_CHENCLR_CH9_Msk (0x1UL << PPI_CHENCLR_CH9_Pos) /*!< Bit mask of CH9 field. */
+#define PPI_CHENCLR_CH9_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH9_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH9_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 8 : Disable PPI channel 8. */
+#define PPI_CHENCLR_CH8_Pos (8UL) /*!< Position of CH8 field. */
+#define PPI_CHENCLR_CH8_Msk (0x1UL << PPI_CHENCLR_CH8_Pos) /*!< Bit mask of CH8 field. */
+#define PPI_CHENCLR_CH8_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH8_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH8_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 7 : Disable PPI channel 7. */
+#define PPI_CHENCLR_CH7_Pos (7UL) /*!< Position of CH7 field. */
+#define PPI_CHENCLR_CH7_Msk (0x1UL << PPI_CHENCLR_CH7_Pos) /*!< Bit mask of CH7 field. */
+#define PPI_CHENCLR_CH7_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH7_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH7_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 6 : Disable PPI channel 6. */
+#define PPI_CHENCLR_CH6_Pos (6UL) /*!< Position of CH6 field. */
+#define PPI_CHENCLR_CH6_Msk (0x1UL << PPI_CHENCLR_CH6_Pos) /*!< Bit mask of CH6 field. */
+#define PPI_CHENCLR_CH6_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH6_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH6_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 5 : Disable PPI channel 5. */
+#define PPI_CHENCLR_CH5_Pos (5UL) /*!< Position of CH5 field. */
+#define PPI_CHENCLR_CH5_Msk (0x1UL << PPI_CHENCLR_CH5_Pos) /*!< Bit mask of CH5 field. */
+#define PPI_CHENCLR_CH5_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH5_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH5_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 4 : Disable PPI channel 4. */
+#define PPI_CHENCLR_CH4_Pos (4UL) /*!< Position of CH4 field. */
+#define PPI_CHENCLR_CH4_Msk (0x1UL << PPI_CHENCLR_CH4_Pos) /*!< Bit mask of CH4 field. */
+#define PPI_CHENCLR_CH4_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH4_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH4_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 3 : Disable PPI channel 3. */
+#define PPI_CHENCLR_CH3_Pos (3UL) /*!< Position of CH3 field. */
+#define PPI_CHENCLR_CH3_Msk (0x1UL << PPI_CHENCLR_CH3_Pos) /*!< Bit mask of CH3 field. */
+#define PPI_CHENCLR_CH3_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH3_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH3_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 2 : Disable PPI channel 2. */
+#define PPI_CHENCLR_CH2_Pos (2UL) /*!< Position of CH2 field. */
+#define PPI_CHENCLR_CH2_Msk (0x1UL << PPI_CHENCLR_CH2_Pos) /*!< Bit mask of CH2 field. */
+#define PPI_CHENCLR_CH2_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH2_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH2_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 1 : Disable PPI channel 1. */
+#define PPI_CHENCLR_CH1_Pos (1UL) /*!< Position of CH1 field. */
+#define PPI_CHENCLR_CH1_Msk (0x1UL << PPI_CHENCLR_CH1_Pos) /*!< Bit mask of CH1 field. */
+#define PPI_CHENCLR_CH1_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH1_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH1_Clear (1UL) /*!< Disable channel on write. */
+
+/* Bit 0 : Disable PPI channel 0. */
+#define PPI_CHENCLR_CH0_Pos (0UL) /*!< Position of CH0 field. */
+#define PPI_CHENCLR_CH0_Msk (0x1UL << PPI_CHENCLR_CH0_Pos) /*!< Bit mask of CH0 field. */
+#define PPI_CHENCLR_CH0_Disabled (0UL) /*!< Channel disabled. */
+#define PPI_CHENCLR_CH0_Enabled (1UL) /*!< Channel enabled. */
+#define PPI_CHENCLR_CH0_Clear (1UL) /*!< Disable channel on write. */
+
+/* Register: PPI_CHG */
+/* Description: Channel group configuration. */
+
+/* Bit 31 : Include CH31 in channel group. */
+#define PPI_CHG_CH31_Pos (31UL) /*!< Position of CH31 field. */
+#define PPI_CHG_CH31_Msk (0x1UL << PPI_CHG_CH31_Pos) /*!< Bit mask of CH31 field. */
+#define PPI_CHG_CH31_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH31_Included (1UL) /*!< Channel included. */
+
+/* Bit 30 : Include CH30 in channel group. */
+#define PPI_CHG_CH30_Pos (30UL) /*!< Position of CH30 field. */
+#define PPI_CHG_CH30_Msk (0x1UL << PPI_CHG_CH30_Pos) /*!< Bit mask of CH30 field. */
+#define PPI_CHG_CH30_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH30_Included (1UL) /*!< Channel included. */
+
+/* Bit 29 : Include CH29 in channel group. */
+#define PPI_CHG_CH29_Pos (29UL) /*!< Position of CH29 field. */
+#define PPI_CHG_CH29_Msk (0x1UL << PPI_CHG_CH29_Pos) /*!< Bit mask of CH29 field. */
+#define PPI_CHG_CH29_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH29_Included (1UL) /*!< Channel included. */
+
+/* Bit 28 : Include CH28 in channel group. */
+#define PPI_CHG_CH28_Pos (28UL) /*!< Position of CH28 field. */
+#define PPI_CHG_CH28_Msk (0x1UL << PPI_CHG_CH28_Pos) /*!< Bit mask of CH28 field. */
+#define PPI_CHG_CH28_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH28_Included (1UL) /*!< Channel included. */
+
+/* Bit 27 : Include CH27 in channel group. */
+#define PPI_CHG_CH27_Pos (27UL) /*!< Position of CH27 field. */
+#define PPI_CHG_CH27_Msk (0x1UL << PPI_CHG_CH27_Pos) /*!< Bit mask of CH27 field. */
+#define PPI_CHG_CH27_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH27_Included (1UL) /*!< Channel included. */
+
+/* Bit 26 : Include CH26 in channel group. */
+#define PPI_CHG_CH26_Pos (26UL) /*!< Position of CH26 field. */
+#define PPI_CHG_CH26_Msk (0x1UL << PPI_CHG_CH26_Pos) /*!< Bit mask of CH26 field. */
+#define PPI_CHG_CH26_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH26_Included (1UL) /*!< Channel included. */
+
+/* Bit 25 : Include CH25 in channel group. */
+#define PPI_CHG_CH25_Pos (25UL) /*!< Position of CH25 field. */
+#define PPI_CHG_CH25_Msk (0x1UL << PPI_CHG_CH25_Pos) /*!< Bit mask of CH25 field. */
+#define PPI_CHG_CH25_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH25_Included (1UL) /*!< Channel included. */
+
+/* Bit 24 : Include CH24 in channel group. */
+#define PPI_CHG_CH24_Pos (24UL) /*!< Position of CH24 field. */
+#define PPI_CHG_CH24_Msk (0x1UL << PPI_CHG_CH24_Pos) /*!< Bit mask of CH24 field. */
+#define PPI_CHG_CH24_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH24_Included (1UL) /*!< Channel included. */
+
+/* Bit 23 : Include CH23 in channel group. */
+#define PPI_CHG_CH23_Pos (23UL) /*!< Position of CH23 field. */
+#define PPI_CHG_CH23_Msk (0x1UL << PPI_CHG_CH23_Pos) /*!< Bit mask of CH23 field. */
+#define PPI_CHG_CH23_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH23_Included (1UL) /*!< Channel included. */
+
+/* Bit 22 : Include CH22 in channel group. */
+#define PPI_CHG_CH22_Pos (22UL) /*!< Position of CH22 field. */
+#define PPI_CHG_CH22_Msk (0x1UL << PPI_CHG_CH22_Pos) /*!< Bit mask of CH22 field. */
+#define PPI_CHG_CH22_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH22_Included (1UL) /*!< Channel included. */
+
+/* Bit 21 : Include CH21 in channel group. */
+#define PPI_CHG_CH21_Pos (21UL) /*!< Position of CH21 field. */
+#define PPI_CHG_CH21_Msk (0x1UL << PPI_CHG_CH21_Pos) /*!< Bit mask of CH21 field. */
+#define PPI_CHG_CH21_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH21_Included (1UL) /*!< Channel included. */
+
+/* Bit 20 : Include CH20 in channel group. */
+#define PPI_CHG_CH20_Pos (20UL) /*!< Position of CH20 field. */
+#define PPI_CHG_CH20_Msk (0x1UL << PPI_CHG_CH20_Pos) /*!< Bit mask of CH20 field. */
+#define PPI_CHG_CH20_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH20_Included (1UL) /*!< Channel included. */
+
+/* Bit 15 : Include CH15 in channel group. */
+#define PPI_CHG_CH15_Pos (15UL) /*!< Position of CH15 field. */
+#define PPI_CHG_CH15_Msk (0x1UL << PPI_CHG_CH15_Pos) /*!< Bit mask of CH15 field. */
+#define PPI_CHG_CH15_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH15_Included (1UL) /*!< Channel included. */
+
+/* Bit 14 : Include CH14 in channel group. */
+#define PPI_CHG_CH14_Pos (14UL) /*!< Position of CH14 field. */
+#define PPI_CHG_CH14_Msk (0x1UL << PPI_CHG_CH14_Pos) /*!< Bit mask of CH14 field. */
+#define PPI_CHG_CH14_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH14_Included (1UL) /*!< Channel included. */
+
+/* Bit 13 : Include CH13 in channel group. */
+#define PPI_CHG_CH13_Pos (13UL) /*!< Position of CH13 field. */
+#define PPI_CHG_CH13_Msk (0x1UL << PPI_CHG_CH13_Pos) /*!< Bit mask of CH13 field. */
+#define PPI_CHG_CH13_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH13_Included (1UL) /*!< Channel included. */
+
+/* Bit 12 : Include CH12 in channel group. */
+#define PPI_CHG_CH12_Pos (12UL) /*!< Position of CH12 field. */
+#define PPI_CHG_CH12_Msk (0x1UL << PPI_CHG_CH12_Pos) /*!< Bit mask of CH12 field. */
+#define PPI_CHG_CH12_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH12_Included (1UL) /*!< Channel included. */
+
+/* Bit 11 : Include CH11 in channel group. */
+#define PPI_CHG_CH11_Pos (11UL) /*!< Position of CH11 field. */
+#define PPI_CHG_CH11_Msk (0x1UL << PPI_CHG_CH11_Pos) /*!< Bit mask of CH11 field. */
+#define PPI_CHG_CH11_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH11_Included (1UL) /*!< Channel included. */
+
+/* Bit 10 : Include CH10 in channel group. */
+#define PPI_CHG_CH10_Pos (10UL) /*!< Position of CH10 field. */
+#define PPI_CHG_CH10_Msk (0x1UL << PPI_CHG_CH10_Pos) /*!< Bit mask of CH10 field. */
+#define PPI_CHG_CH10_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH10_Included (1UL) /*!< Channel included. */
+
+/* Bit 9 : Include CH9 in channel group. */
+#define PPI_CHG_CH9_Pos (9UL) /*!< Position of CH9 field. */
+#define PPI_CHG_CH9_Msk (0x1UL << PPI_CHG_CH9_Pos) /*!< Bit mask of CH9 field. */
+#define PPI_CHG_CH9_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH9_Included (1UL) /*!< Channel included. */
+
+/* Bit 8 : Include CH8 in channel group. */
+#define PPI_CHG_CH8_Pos (8UL) /*!< Position of CH8 field. */
+#define PPI_CHG_CH8_Msk (0x1UL << PPI_CHG_CH8_Pos) /*!< Bit mask of CH8 field. */
+#define PPI_CHG_CH8_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH8_Included (1UL) /*!< Channel included. */
+
+/* Bit 7 : Include CH7 in channel group. */
+#define PPI_CHG_CH7_Pos (7UL) /*!< Position of CH7 field. */
+#define PPI_CHG_CH7_Msk (0x1UL << PPI_CHG_CH7_Pos) /*!< Bit mask of CH7 field. */
+#define PPI_CHG_CH7_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH7_Included (1UL) /*!< Channel included. */
+
+/* Bit 6 : Include CH6 in channel group. */
+#define PPI_CHG_CH6_Pos (6UL) /*!< Position of CH6 field. */
+#define PPI_CHG_CH6_Msk (0x1UL << PPI_CHG_CH6_Pos) /*!< Bit mask of CH6 field. */
+#define PPI_CHG_CH6_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH6_Included (1UL) /*!< Channel included. */
+
+/* Bit 5 : Include CH5 in channel group. */
+#define PPI_CHG_CH5_Pos (5UL) /*!< Position of CH5 field. */
+#define PPI_CHG_CH5_Msk (0x1UL << PPI_CHG_CH5_Pos) /*!< Bit mask of CH5 field. */
+#define PPI_CHG_CH5_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH5_Included (1UL) /*!< Channel included. */
+
+/* Bit 4 : Include CH4 in channel group. */
+#define PPI_CHG_CH4_Pos (4UL) /*!< Position of CH4 field. */
+#define PPI_CHG_CH4_Msk (0x1UL << PPI_CHG_CH4_Pos) /*!< Bit mask of CH4 field. */
+#define PPI_CHG_CH4_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH4_Included (1UL) /*!< Channel included. */
+
+/* Bit 3 : Include CH3 in channel group. */
+#define PPI_CHG_CH3_Pos (3UL) /*!< Position of CH3 field. */
+#define PPI_CHG_CH3_Msk (0x1UL << PPI_CHG_CH3_Pos) /*!< Bit mask of CH3 field. */
+#define PPI_CHG_CH3_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH3_Included (1UL) /*!< Channel included. */
+
+/* Bit 2 : Include CH2 in channel group. */
+#define PPI_CHG_CH2_Pos (2UL) /*!< Position of CH2 field. */
+#define PPI_CHG_CH2_Msk (0x1UL << PPI_CHG_CH2_Pos) /*!< Bit mask of CH2 field. */
+#define PPI_CHG_CH2_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH2_Included (1UL) /*!< Channel included. */
+
+/* Bit 1 : Include CH1 in channel group. */
+#define PPI_CHG_CH1_Pos (1UL) /*!< Position of CH1 field. */
+#define PPI_CHG_CH1_Msk (0x1UL << PPI_CHG_CH1_Pos) /*!< Bit mask of CH1 field. */
+#define PPI_CHG_CH1_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH1_Included (1UL) /*!< Channel included. */
+
+/* Bit 0 : Include CH0 in channel group. */
+#define PPI_CHG_CH0_Pos (0UL) /*!< Position of CH0 field. */
+#define PPI_CHG_CH0_Msk (0x1UL << PPI_CHG_CH0_Pos) /*!< Bit mask of CH0 field. */
+#define PPI_CHG_CH0_Excluded (0UL) /*!< Channel excluded. */
+#define PPI_CHG_CH0_Included (1UL) /*!< Channel included. */
+
+
+/* Peripheral: QDEC */
+/* Description: Rotary decoder. */
+
+/* Register: QDEC_SHORTS */
+/* Description: Shortcuts for the QDEC. */
+
+/* Bit 1 : Shortcut between SAMPLERDY event and STOP task. */
+#define QDEC_SHORTS_SAMPLERDY_STOP_Pos (1UL) /*!< Position of SAMPLERDY_STOP field. */
+#define QDEC_SHORTS_SAMPLERDY_STOP_Msk (0x1UL << QDEC_SHORTS_SAMPLERDY_STOP_Pos) /*!< Bit mask of SAMPLERDY_STOP field. */
+#define QDEC_SHORTS_SAMPLERDY_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define QDEC_SHORTS_SAMPLERDY_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 0 : Shortcut between REPORTRDY event and READCLRACC task. */
+#define QDEC_SHORTS_REPORTRDY_READCLRACC_Pos (0UL) /*!< Position of REPORTRDY_READCLRACC field. */
+#define QDEC_SHORTS_REPORTRDY_READCLRACC_Msk (0x1UL << QDEC_SHORTS_REPORTRDY_READCLRACC_Pos) /*!< Bit mask of REPORTRDY_READCLRACC field. */
+#define QDEC_SHORTS_REPORTRDY_READCLRACC_Disabled (0UL) /*!< Shortcut disabled. */
+#define QDEC_SHORTS_REPORTRDY_READCLRACC_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: QDEC_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 2 : Enable interrupt on ACCOF event. */
+#define QDEC_INTENSET_ACCOF_Pos (2UL) /*!< Position of ACCOF field. */
+#define QDEC_INTENSET_ACCOF_Msk (0x1UL << QDEC_INTENSET_ACCOF_Pos) /*!< Bit mask of ACCOF field. */
+#define QDEC_INTENSET_ACCOF_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENSET_ACCOF_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENSET_ACCOF_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on REPORTRDY event. */
+#define QDEC_INTENSET_REPORTRDY_Pos (1UL) /*!< Position of REPORTRDY field. */
+#define QDEC_INTENSET_REPORTRDY_Msk (0x1UL << QDEC_INTENSET_REPORTRDY_Pos) /*!< Bit mask of REPORTRDY field. */
+#define QDEC_INTENSET_REPORTRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENSET_REPORTRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENSET_REPORTRDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on SAMPLERDY event. */
+#define QDEC_INTENSET_SAMPLERDY_Pos (0UL) /*!< Position of SAMPLERDY field. */
+#define QDEC_INTENSET_SAMPLERDY_Msk (0x1UL << QDEC_INTENSET_SAMPLERDY_Pos) /*!< Bit mask of SAMPLERDY field. */
+#define QDEC_INTENSET_SAMPLERDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENSET_SAMPLERDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENSET_SAMPLERDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: QDEC_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 2 : Disable interrupt on ACCOF event. */
+#define QDEC_INTENCLR_ACCOF_Pos (2UL) /*!< Position of ACCOF field. */
+#define QDEC_INTENCLR_ACCOF_Msk (0x1UL << QDEC_INTENCLR_ACCOF_Pos) /*!< Bit mask of ACCOF field. */
+#define QDEC_INTENCLR_ACCOF_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENCLR_ACCOF_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENCLR_ACCOF_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on REPORTRDY event. */
+#define QDEC_INTENCLR_REPORTRDY_Pos (1UL) /*!< Position of REPORTRDY field. */
+#define QDEC_INTENCLR_REPORTRDY_Msk (0x1UL << QDEC_INTENCLR_REPORTRDY_Pos) /*!< Bit mask of REPORTRDY field. */
+#define QDEC_INTENCLR_REPORTRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENCLR_REPORTRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENCLR_REPORTRDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on SAMPLERDY event. */
+#define QDEC_INTENCLR_SAMPLERDY_Pos (0UL) /*!< Position of SAMPLERDY field. */
+#define QDEC_INTENCLR_SAMPLERDY_Msk (0x1UL << QDEC_INTENCLR_SAMPLERDY_Pos) /*!< Bit mask of SAMPLERDY field. */
+#define QDEC_INTENCLR_SAMPLERDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define QDEC_INTENCLR_SAMPLERDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define QDEC_INTENCLR_SAMPLERDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: QDEC_ENABLE */
+/* Description: Enable the QDEC. */
+
+/* Bit 0 : Enable or disable QDEC. */
+#define QDEC_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define QDEC_ENABLE_ENABLE_Msk (0x1UL << QDEC_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define QDEC_ENABLE_ENABLE_Disabled (0UL) /*!< Disabled QDEC. */
+#define QDEC_ENABLE_ENABLE_Enabled (1UL) /*!< Enable QDEC. */
+
+/* Register: QDEC_LEDPOL */
+/* Description: LED output pin polarity. */
+
+/* Bit 0 : LED output pin polarity. */
+#define QDEC_LEDPOL_LEDPOL_Pos (0UL) /*!< Position of LEDPOL field. */
+#define QDEC_LEDPOL_LEDPOL_Msk (0x1UL << QDEC_LEDPOL_LEDPOL_Pos) /*!< Bit mask of LEDPOL field. */
+#define QDEC_LEDPOL_LEDPOL_ActiveLow (0UL) /*!< LED output is active low. */
+#define QDEC_LEDPOL_LEDPOL_ActiveHigh (1UL) /*!< LED output is active high. */
+
+/* Register: QDEC_SAMPLEPER */
+/* Description: Sample period. */
+
+/* Bits 2..0 : Sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_Pos (0UL) /*!< Position of SAMPLEPER field. */
+#define QDEC_SAMPLEPER_SAMPLEPER_Msk (0x7UL << QDEC_SAMPLEPER_SAMPLEPER_Pos) /*!< Bit mask of SAMPLEPER field. */
+#define QDEC_SAMPLEPER_SAMPLEPER_128us (0x00UL) /*!< 128us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_256us (0x01UL) /*!< 256us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_512us (0x02UL) /*!< 512us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_1024us (0x03UL) /*!< 1024us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_2048us (0x04UL) /*!< 2048us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_4096us (0x05UL) /*!< 4096us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_8192us (0x06UL) /*!< 8192us sample period. */
+#define QDEC_SAMPLEPER_SAMPLEPER_16384us (0x07UL) /*!< 16384us sample period. */
+
+/* Register: QDEC_SAMPLE */
+/* Description: Motion sample value. */
+
+/* Bits 31..0 : Last sample taken in compliment to 2. */
+#define QDEC_SAMPLE_SAMPLE_Pos (0UL) /*!< Position of SAMPLE field. */
+#define QDEC_SAMPLE_SAMPLE_Msk (0xFFFFFFFFUL << QDEC_SAMPLE_SAMPLE_Pos) /*!< Bit mask of SAMPLE field. */
+
+/* Register: QDEC_REPORTPER */
+/* Description: Number of samples to generate an EVENT_REPORTRDY. */
+
+/* Bits 2..0 : Number of samples to generate an EVENT_REPORTRDY. */
+#define QDEC_REPORTPER_REPORTPER_Pos (0UL) /*!< Position of REPORTPER field. */
+#define QDEC_REPORTPER_REPORTPER_Msk (0x7UL << QDEC_REPORTPER_REPORTPER_Pos) /*!< Bit mask of REPORTPER field. */
+#define QDEC_REPORTPER_REPORTPER_10Smpl (0x00UL) /*!< 10 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_40Smpl (0x01UL) /*!< 40 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_80Smpl (0x02UL) /*!< 80 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_120Smpl (0x03UL) /*!< 120 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_160Smpl (0x04UL) /*!< 160 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_200Smpl (0x05UL) /*!< 200 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_240Smpl (0x06UL) /*!< 240 samples per report. */
+#define QDEC_REPORTPER_REPORTPER_280Smpl (0x07UL) /*!< 280 samples per report. */
+
+/* Register: QDEC_DBFEN */
+/* Description: Enable debouncer input filters. */
+
+/* Bit 0 : Enable debounce input filters. */
+#define QDEC_DBFEN_DBFEN_Pos (0UL) /*!< Position of DBFEN field. */
+#define QDEC_DBFEN_DBFEN_Msk (0x1UL << QDEC_DBFEN_DBFEN_Pos) /*!< Bit mask of DBFEN field. */
+#define QDEC_DBFEN_DBFEN_Disabled (0UL) /*!< Debounce input filters disabled. */
+#define QDEC_DBFEN_DBFEN_Enabled (1UL) /*!< Debounce input filters enabled. */
+
+/* Register: QDEC_LEDPRE */
+/* Description: Time LED is switched ON before the sample. */
+
+/* Bits 8..0 : Period in us the LED in switched on prior to sampling. */
+#define QDEC_LEDPRE_LEDPRE_Pos (0UL) /*!< Position of LEDPRE field. */
+#define QDEC_LEDPRE_LEDPRE_Msk (0x1FFUL << QDEC_LEDPRE_LEDPRE_Pos) /*!< Bit mask of LEDPRE field. */
+
+/* Register: QDEC_ACCDBL */
+/* Description: Accumulated double (error) transitions register. */
+
+/* Bits 3..0 : Accumulated double (error) transitions. */
+#define QDEC_ACCDBL_ACCDBL_Pos (0UL) /*!< Position of ACCDBL field. */
+#define QDEC_ACCDBL_ACCDBL_Msk (0xFUL << QDEC_ACCDBL_ACCDBL_Pos) /*!< Bit mask of ACCDBL field. */
+
+/* Register: QDEC_ACCDBLREAD */
+/* Description: Snapshot of ACCDBL register. Value generated by the TASKS_READCLEACC task. */
+
+/* Bits 3..0 : Snapshot of accumulated double (error) transitions. */
+#define QDEC_ACCDBLREAD_ACCDBLREAD_Pos (0UL) /*!< Position of ACCDBLREAD field. */
+#define QDEC_ACCDBLREAD_ACCDBLREAD_Msk (0xFUL << QDEC_ACCDBLREAD_ACCDBLREAD_Pos) /*!< Bit mask of ACCDBLREAD field. */
+
+/* Register: QDEC_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define QDEC_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define QDEC_POWER_POWER_Msk (0x1UL << QDEC_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define QDEC_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define QDEC_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: RADIO */
+/* Description: The radio. */
+
+/* Register: RADIO_SHORTS */
+/* Description: Shortcuts for the radio. */
+
+/* Bit 8 : Shortcut between DISABLED event and RSSISTOP task. */
+#define RADIO_SHORTS_DISABLED_RSSISTOP_Pos (8UL) /*!< Position of DISABLED_RSSISTOP field. */
+#define RADIO_SHORTS_DISABLED_RSSISTOP_Msk (0x1UL << RADIO_SHORTS_DISABLED_RSSISTOP_Pos) /*!< Bit mask of DISABLED_RSSISTOP field. */
+#define RADIO_SHORTS_DISABLED_RSSISTOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_DISABLED_RSSISTOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 6 : Shortcut between ADDRESS event and BCSTART task. */
+#define RADIO_SHORTS_ADDRESS_BCSTART_Pos (6UL) /*!< Position of ADDRESS_BCSTART field. */
+#define RADIO_SHORTS_ADDRESS_BCSTART_Msk (0x1UL << RADIO_SHORTS_ADDRESS_BCSTART_Pos) /*!< Bit mask of ADDRESS_BCSTART field. */
+#define RADIO_SHORTS_ADDRESS_BCSTART_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_ADDRESS_BCSTART_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 5 : Shortcut between END event and START task. */
+#define RADIO_SHORTS_END_START_Pos (5UL) /*!< Position of END_START field. */
+#define RADIO_SHORTS_END_START_Msk (0x1UL << RADIO_SHORTS_END_START_Pos) /*!< Bit mask of END_START field. */
+#define RADIO_SHORTS_END_START_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_END_START_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 4 : Shortcut between ADDRESS event and RSSISTART task. */
+#define RADIO_SHORTS_ADDRESS_RSSISTART_Pos (4UL) /*!< Position of ADDRESS_RSSISTART field. */
+#define RADIO_SHORTS_ADDRESS_RSSISTART_Msk (0x1UL << RADIO_SHORTS_ADDRESS_RSSISTART_Pos) /*!< Bit mask of ADDRESS_RSSISTART field. */
+#define RADIO_SHORTS_ADDRESS_RSSISTART_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_ADDRESS_RSSISTART_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 3 : Shortcut between DISABLED event and RXEN task. */
+#define RADIO_SHORTS_DISABLED_RXEN_Pos (3UL) /*!< Position of DISABLED_RXEN field. */
+#define RADIO_SHORTS_DISABLED_RXEN_Msk (0x1UL << RADIO_SHORTS_DISABLED_RXEN_Pos) /*!< Bit mask of DISABLED_RXEN field. */
+#define RADIO_SHORTS_DISABLED_RXEN_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_DISABLED_RXEN_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 2 : Shortcut between DISABLED event and TXEN task.  */
+#define RADIO_SHORTS_DISABLED_TXEN_Pos (2UL) /*!< Position of DISABLED_TXEN field. */
+#define RADIO_SHORTS_DISABLED_TXEN_Msk (0x1UL << RADIO_SHORTS_DISABLED_TXEN_Pos) /*!< Bit mask of DISABLED_TXEN field. */
+#define RADIO_SHORTS_DISABLED_TXEN_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_DISABLED_TXEN_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 1 : Shortcut between END event and DISABLE task. */
+#define RADIO_SHORTS_END_DISABLE_Pos (1UL) /*!< Position of END_DISABLE field. */
+#define RADIO_SHORTS_END_DISABLE_Msk (0x1UL << RADIO_SHORTS_END_DISABLE_Pos) /*!< Bit mask of END_DISABLE field. */
+#define RADIO_SHORTS_END_DISABLE_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_END_DISABLE_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 0 : Shortcut between READY event and START task. */
+#define RADIO_SHORTS_READY_START_Pos (0UL) /*!< Position of READY_START field. */
+#define RADIO_SHORTS_READY_START_Msk (0x1UL << RADIO_SHORTS_READY_START_Pos) /*!< Bit mask of READY_START field. */
+#define RADIO_SHORTS_READY_START_Disabled (0UL) /*!< Shortcut disabled. */
+#define RADIO_SHORTS_READY_START_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: RADIO_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 10 : Enable interrupt on BCMATCH event. */
+#define RADIO_INTENSET_BCMATCH_Pos (10UL) /*!< Position of BCMATCH field. */
+#define RADIO_INTENSET_BCMATCH_Msk (0x1UL << RADIO_INTENSET_BCMATCH_Pos) /*!< Bit mask of BCMATCH field. */
+#define RADIO_INTENSET_BCMATCH_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_BCMATCH_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_BCMATCH_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 7 : Enable interrupt on RSSIEND event. */
+#define RADIO_INTENSET_RSSIEND_Pos (7UL) /*!< Position of RSSIEND field. */
+#define RADIO_INTENSET_RSSIEND_Msk (0x1UL << RADIO_INTENSET_RSSIEND_Pos) /*!< Bit mask of RSSIEND field. */
+#define RADIO_INTENSET_RSSIEND_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_RSSIEND_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_RSSIEND_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 6 : Enable interrupt on DEVMISS event. */
+#define RADIO_INTENSET_DEVMISS_Pos (6UL) /*!< Position of DEVMISS field. */
+#define RADIO_INTENSET_DEVMISS_Msk (0x1UL << RADIO_INTENSET_DEVMISS_Pos) /*!< Bit mask of DEVMISS field. */
+#define RADIO_INTENSET_DEVMISS_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_DEVMISS_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_DEVMISS_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 5 : Enable interrupt on DEVMATCH event. */
+#define RADIO_INTENSET_DEVMATCH_Pos (5UL) /*!< Position of DEVMATCH field. */
+#define RADIO_INTENSET_DEVMATCH_Msk (0x1UL << RADIO_INTENSET_DEVMATCH_Pos) /*!< Bit mask of DEVMATCH field. */
+#define RADIO_INTENSET_DEVMATCH_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_DEVMATCH_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_DEVMATCH_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 4 : Enable interrupt on DISABLED event. */
+#define RADIO_INTENSET_DISABLED_Pos (4UL) /*!< Position of DISABLED field. */
+#define RADIO_INTENSET_DISABLED_Msk (0x1UL << RADIO_INTENSET_DISABLED_Pos) /*!< Bit mask of DISABLED field. */
+#define RADIO_INTENSET_DISABLED_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_DISABLED_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_DISABLED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 3 : Enable interrupt on END event. */
+#define RADIO_INTENSET_END_Pos (3UL) /*!< Position of END field. */
+#define RADIO_INTENSET_END_Msk (0x1UL << RADIO_INTENSET_END_Pos) /*!< Bit mask of END field. */
+#define RADIO_INTENSET_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_END_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 2 : Enable interrupt on PAYLOAD event. */
+#define RADIO_INTENSET_PAYLOAD_Pos (2UL) /*!< Position of PAYLOAD field. */
+#define RADIO_INTENSET_PAYLOAD_Msk (0x1UL << RADIO_INTENSET_PAYLOAD_Pos) /*!< Bit mask of PAYLOAD field. */
+#define RADIO_INTENSET_PAYLOAD_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_PAYLOAD_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_PAYLOAD_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on ADDRESS event. */
+#define RADIO_INTENSET_ADDRESS_Pos (1UL) /*!< Position of ADDRESS field. */
+#define RADIO_INTENSET_ADDRESS_Msk (0x1UL << RADIO_INTENSET_ADDRESS_Pos) /*!< Bit mask of ADDRESS field. */
+#define RADIO_INTENSET_ADDRESS_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_ADDRESS_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_ADDRESS_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on READY event. */
+#define RADIO_INTENSET_READY_Pos (0UL) /*!< Position of READY field. */
+#define RADIO_INTENSET_READY_Msk (0x1UL << RADIO_INTENSET_READY_Pos) /*!< Bit mask of READY field. */
+#define RADIO_INTENSET_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENSET_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENSET_READY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: RADIO_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 10 : Disable interrupt on BCMATCH event. */
+#define RADIO_INTENCLR_BCMATCH_Pos (10UL) /*!< Position of BCMATCH field. */
+#define RADIO_INTENCLR_BCMATCH_Msk (0x1UL << RADIO_INTENCLR_BCMATCH_Pos) /*!< Bit mask of BCMATCH field. */
+#define RADIO_INTENCLR_BCMATCH_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_BCMATCH_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_BCMATCH_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 7 : Disable interrupt on RSSIEND event. */
+#define RADIO_INTENCLR_RSSIEND_Pos (7UL) /*!< Position of RSSIEND field. */
+#define RADIO_INTENCLR_RSSIEND_Msk (0x1UL << RADIO_INTENCLR_RSSIEND_Pos) /*!< Bit mask of RSSIEND field. */
+#define RADIO_INTENCLR_RSSIEND_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_RSSIEND_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_RSSIEND_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 6 : Disable interrupt on DEVMISS event. */
+#define RADIO_INTENCLR_DEVMISS_Pos (6UL) /*!< Position of DEVMISS field. */
+#define RADIO_INTENCLR_DEVMISS_Msk (0x1UL << RADIO_INTENCLR_DEVMISS_Pos) /*!< Bit mask of DEVMISS field. */
+#define RADIO_INTENCLR_DEVMISS_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_DEVMISS_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_DEVMISS_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 5 : Disable interrupt on DEVMATCH event. */
+#define RADIO_INTENCLR_DEVMATCH_Pos (5UL) /*!< Position of DEVMATCH field. */
+#define RADIO_INTENCLR_DEVMATCH_Msk (0x1UL << RADIO_INTENCLR_DEVMATCH_Pos) /*!< Bit mask of DEVMATCH field. */
+#define RADIO_INTENCLR_DEVMATCH_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_DEVMATCH_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_DEVMATCH_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 4 : Disable interrupt on DISABLED event. */
+#define RADIO_INTENCLR_DISABLED_Pos (4UL) /*!< Position of DISABLED field. */
+#define RADIO_INTENCLR_DISABLED_Msk (0x1UL << RADIO_INTENCLR_DISABLED_Pos) /*!< Bit mask of DISABLED field. */
+#define RADIO_INTENCLR_DISABLED_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_DISABLED_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_DISABLED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 3 : Disable interrupt on END event. */
+#define RADIO_INTENCLR_END_Pos (3UL) /*!< Position of END field. */
+#define RADIO_INTENCLR_END_Msk (0x1UL << RADIO_INTENCLR_END_Pos) /*!< Bit mask of END field. */
+#define RADIO_INTENCLR_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_END_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 2 : Disable interrupt on PAYLOAD event. */
+#define RADIO_INTENCLR_PAYLOAD_Pos (2UL) /*!< Position of PAYLOAD field. */
+#define RADIO_INTENCLR_PAYLOAD_Msk (0x1UL << RADIO_INTENCLR_PAYLOAD_Pos) /*!< Bit mask of PAYLOAD field. */
+#define RADIO_INTENCLR_PAYLOAD_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_PAYLOAD_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_PAYLOAD_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on ADDRESS event. */
+#define RADIO_INTENCLR_ADDRESS_Pos (1UL) /*!< Position of ADDRESS field. */
+#define RADIO_INTENCLR_ADDRESS_Msk (0x1UL << RADIO_INTENCLR_ADDRESS_Pos) /*!< Bit mask of ADDRESS field. */
+#define RADIO_INTENCLR_ADDRESS_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_ADDRESS_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_ADDRESS_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on READY event. */
+#define RADIO_INTENCLR_READY_Pos (0UL) /*!< Position of READY field. */
+#define RADIO_INTENCLR_READY_Msk (0x1UL << RADIO_INTENCLR_READY_Pos) /*!< Bit mask of READY field. */
+#define RADIO_INTENCLR_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define RADIO_INTENCLR_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define RADIO_INTENCLR_READY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: RADIO_CRCSTATUS */
+/* Description: CRC status of received packet. */
+
+/* Bit 0 : CRC status of received packet. */
+#define RADIO_CRCSTATUS_CRCSTATUS_Pos (0UL) /*!< Position of CRCSTATUS field. */
+#define RADIO_CRCSTATUS_CRCSTATUS_Msk (0x1UL << RADIO_CRCSTATUS_CRCSTATUS_Pos) /*!< Bit mask of CRCSTATUS field. */
+#define RADIO_CRCSTATUS_CRCSTATUS_CRCError (0UL) /*!< Packet received with CRC error. */
+#define RADIO_CRCSTATUS_CRCSTATUS_CRCOk (1UL) /*!< Packet received with CRC ok. */
+
+/* Register: RADIO_RXMATCH */
+/* Description: Received address. */
+
+/* Bits 2..0 : Logical address in which previous packet was received. */
+#define RADIO_RXMATCH_RXMATCH_Pos (0UL) /*!< Position of RXMATCH field. */
+#define RADIO_RXMATCH_RXMATCH_Msk (0x7UL << RADIO_RXMATCH_RXMATCH_Pos) /*!< Bit mask of RXMATCH field. */
+
+/* Register: RADIO_RXCRC */
+/* Description: Received CRC. */
+
+/* Bits 23..0 : CRC field of previously received packet. */
+#define RADIO_RXCRC_RXCRC_Pos (0UL) /*!< Position of RXCRC field. */
+#define RADIO_RXCRC_RXCRC_Msk (0xFFFFFFUL << RADIO_RXCRC_RXCRC_Pos) /*!< Bit mask of RXCRC field. */
+
+/* Register: RADIO_DAI */
+/* Description: Device address match index. */
+
+/* Bits 2..0 : Index (n) of device address (see DAB[n] and DAP[n]) that obtained an address match. */
+#define RADIO_DAI_DAI_Pos (0UL) /*!< Position of DAI field. */
+#define RADIO_DAI_DAI_Msk (0x7UL << RADIO_DAI_DAI_Pos) /*!< Bit mask of DAI field. */
+
+/* Register: RADIO_FREQUENCY */
+/* Description: Frequency. */
+
+/* Bits 6..0 : Radio channel frequency offset in MHz: RF Frequency = 2400 + FREQUENCY (MHz). Decision point: TXEN or RXEN task.  */
+#define RADIO_FREQUENCY_FREQUENCY_Pos (0UL) /*!< Position of FREQUENCY field. */
+#define RADIO_FREQUENCY_FREQUENCY_Msk (0x7FUL << RADIO_FREQUENCY_FREQUENCY_Pos) /*!< Bit mask of FREQUENCY field. */
+
+/* Register: RADIO_TXPOWER */
+/* Description: Output power. */
+
+/* Bits 7..0 : Radio output power. Decision point: TXEN task. */
+#define RADIO_TXPOWER_TXPOWER_Pos (0UL) /*!< Position of TXPOWER field. */
+#define RADIO_TXPOWER_TXPOWER_Msk (0xFFUL << RADIO_TXPOWER_TXPOWER_Pos) /*!< Bit mask of TXPOWER field. */
+#define RADIO_TXPOWER_TXPOWER_0dBm (0x00UL) /*!< 0dBm. */
+#define RADIO_TXPOWER_TXPOWER_Pos4dBm (0x04UL) /*!< +4dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg30dBm (0xD8UL) /*!< -30dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg20dBm (0xECUL) /*!< -20dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg16dBm (0xF0UL) /*!< -16dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg12dBm (0xF4UL) /*!< -12dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg8dBm (0xF8UL) /*!< -8dBm. */
+#define RADIO_TXPOWER_TXPOWER_Neg4dBm (0xFCUL) /*!< -4dBm. */
+
+/* Register: RADIO_MODE */
+/* Description: Data rate and modulation. */
+
+/* Bits 1..0 : Radio data rate and modulation setting. Decision point: TXEN or RXEN task. */
+#define RADIO_MODE_MODE_Pos (0UL) /*!< Position of MODE field. */
+#define RADIO_MODE_MODE_Msk (0x3UL << RADIO_MODE_MODE_Pos) /*!< Bit mask of MODE field. */
+#define RADIO_MODE_MODE_Nrf_1Mbit (0x00UL) /*!< 1Mbit/s Nordic propietary radio mode. */
+#define RADIO_MODE_MODE_Nrf_2Mbit (0x01UL) /*!< 2Mbit/s Nordic propietary radio mode. */
+#define RADIO_MODE_MODE_Nrf_250Kbit (0x02UL) /*!< 250kbit/s Nordic propietary radio mode. */
+#define RADIO_MODE_MODE_Ble_1Mbit (0x03UL) /*!< 1Mbit/s Bluetooth Low Energy */
+
+/* Register: RADIO_PCNF0 */
+/* Description: Packet configuration 0. */
+
+/* Bits 19..16 : Length of S1 field in number of bits. Decision point: START task. */
+#define RADIO_PCNF0_S1LEN_Pos (16UL) /*!< Position of S1LEN field. */
+#define RADIO_PCNF0_S1LEN_Msk (0xFUL << RADIO_PCNF0_S1LEN_Pos) /*!< Bit mask of S1LEN field. */
+
+/* Bit 8 : Length of S0 field in number of bytes. Decision point: START task. */
+#define RADIO_PCNF0_S0LEN_Pos (8UL) /*!< Position of S0LEN field. */
+#define RADIO_PCNF0_S0LEN_Msk (0x1UL << RADIO_PCNF0_S0LEN_Pos) /*!< Bit mask of S0LEN field. */
+
+/* Bits 3..0 : Length of length field in number of bits. Decision point: START task. */
+#define RADIO_PCNF0_LFLEN_Pos (0UL) /*!< Position of LFLEN field. */
+#define RADIO_PCNF0_LFLEN_Msk (0xFUL << RADIO_PCNF0_LFLEN_Pos) /*!< Bit mask of LFLEN field. */
+
+/* Register: RADIO_PCNF1 */
+/* Description: Packet configuration 1. */
+
+/* Bit 25 : Packet whitening enable. */
+#define RADIO_PCNF1_WHITEEN_Pos (25UL) /*!< Position of WHITEEN field. */
+#define RADIO_PCNF1_WHITEEN_Msk (0x1UL << RADIO_PCNF1_WHITEEN_Pos) /*!< Bit mask of WHITEEN field. */
+#define RADIO_PCNF1_WHITEEN_Disabled (0UL) /*!< Whitening disabled. */
+#define RADIO_PCNF1_WHITEEN_Enabled (1UL) /*!< Whitening enabled. */
+
+/* Bit 24 : On air endianness of packet length field. Decision point: START task. */
+#define RADIO_PCNF1_ENDIAN_Pos (24UL) /*!< Position of ENDIAN field. */
+#define RADIO_PCNF1_ENDIAN_Msk (0x1UL << RADIO_PCNF1_ENDIAN_Pos) /*!< Bit mask of ENDIAN field. */
+#define RADIO_PCNF1_ENDIAN_Little (0UL) /*!< Least significant bit on air first */
+#define RADIO_PCNF1_ENDIAN_Big (1UL) /*!< Most significant bit on air first */
+
+/* Bits 18..16 : Base address length in number of bytes. Decision point: START task. */
+#define RADIO_PCNF1_BALEN_Pos (16UL) /*!< Position of BALEN field. */
+#define RADIO_PCNF1_BALEN_Msk (0x7UL << RADIO_PCNF1_BALEN_Pos) /*!< Bit mask of BALEN field. */
+
+/* Bits 15..8 : Static length in number of bytes. Decision point: START task. */
+#define RADIO_PCNF1_STATLEN_Pos (8UL) /*!< Position of STATLEN field. */
+#define RADIO_PCNF1_STATLEN_Msk (0xFFUL << RADIO_PCNF1_STATLEN_Pos) /*!< Bit mask of STATLEN field. */
+
+/* Bits 7..0 : Maximum length of packet payload in number of bytes. */
+#define RADIO_PCNF1_MAXLEN_Pos (0UL) /*!< Position of MAXLEN field. */
+#define RADIO_PCNF1_MAXLEN_Msk (0xFFUL << RADIO_PCNF1_MAXLEN_Pos) /*!< Bit mask of MAXLEN field. */
+
+/* Register: RADIO_PREFIX0 */
+/* Description: Prefixes bytes for logical addresses 0 to 3. */
+
+/* Bits 31..24 : Address prefix 3. Decision point: START task. */
+#define RADIO_PREFIX0_AP3_Pos (24UL) /*!< Position of AP3 field. */
+#define RADIO_PREFIX0_AP3_Msk (0xFFUL << RADIO_PREFIX0_AP3_Pos) /*!< Bit mask of AP3 field. */
+
+/* Bits 23..16 : Address prefix 2. Decision point: START task. */
+#define RADIO_PREFIX0_AP2_Pos (16UL) /*!< Position of AP2 field. */
+#define RADIO_PREFIX0_AP2_Msk (0xFFUL << RADIO_PREFIX0_AP2_Pos) /*!< Bit mask of AP2 field. */
+
+/* Bits 15..8 : Address prefix 1. Decision point: START task. */
+#define RADIO_PREFIX0_AP1_Pos (8UL) /*!< Position of AP1 field. */
+#define RADIO_PREFIX0_AP1_Msk (0xFFUL << RADIO_PREFIX0_AP1_Pos) /*!< Bit mask of AP1 field. */
+
+/* Bits 7..0 : Address prefix 0. Decision point: START task. */
+#define RADIO_PREFIX0_AP0_Pos (0UL) /*!< Position of AP0 field. */
+#define RADIO_PREFIX0_AP0_Msk (0xFFUL << RADIO_PREFIX0_AP0_Pos) /*!< Bit mask of AP0 field. */
+
+/* Register: RADIO_PREFIX1 */
+/* Description: Prefixes bytes for logical addresses 4 to 7. */
+
+/* Bits 31..24 : Address prefix 7. Decision point: START task. */
+#define RADIO_PREFIX1_AP7_Pos (24UL) /*!< Position of AP7 field. */
+#define RADIO_PREFIX1_AP7_Msk (0xFFUL << RADIO_PREFIX1_AP7_Pos) /*!< Bit mask of AP7 field. */
+
+/* Bits 23..16 : Address prefix 6. Decision point: START task. */
+#define RADIO_PREFIX1_AP6_Pos (16UL) /*!< Position of AP6 field. */
+#define RADIO_PREFIX1_AP6_Msk (0xFFUL << RADIO_PREFIX1_AP6_Pos) /*!< Bit mask of AP6 field. */
+
+/* Bits 15..8 : Address prefix 5. Decision point: START task. */
+#define RADIO_PREFIX1_AP5_Pos (8UL) /*!< Position of AP5 field. */
+#define RADIO_PREFIX1_AP5_Msk (0xFFUL << RADIO_PREFIX1_AP5_Pos) /*!< Bit mask of AP5 field. */
+
+/* Bits 7..0 : Address prefix 4. Decision point: START task. */
+#define RADIO_PREFIX1_AP4_Pos (0UL) /*!< Position of AP4 field. */
+#define RADIO_PREFIX1_AP4_Msk (0xFFUL << RADIO_PREFIX1_AP4_Pos) /*!< Bit mask of AP4 field. */
+
+/* Register: RADIO_TXADDRESS */
+/* Description: Transmit address select. */
+
+/* Bits 2..0 : Logical address to be used when transmitting a packet. Decision point: START task. */
+#define RADIO_TXADDRESS_TXADDRESS_Pos (0UL) /*!< Position of TXADDRESS field. */
+#define RADIO_TXADDRESS_TXADDRESS_Msk (0x7UL << RADIO_TXADDRESS_TXADDRESS_Pos) /*!< Bit mask of TXADDRESS field. */
+
+/* Register: RADIO_RXADDRESSES */
+/* Description: Receive address select. */
+
+/* Bit 7 : Enable reception on logical address 7. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR7_Pos (7UL) /*!< Position of ADDR7 field. */
+#define RADIO_RXADDRESSES_ADDR7_Msk (0x1UL << RADIO_RXADDRESSES_ADDR7_Pos) /*!< Bit mask of ADDR7 field. */
+#define RADIO_RXADDRESSES_ADDR7_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR7_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 6 : Enable reception on logical address 6. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR6_Pos (6UL) /*!< Position of ADDR6 field. */
+#define RADIO_RXADDRESSES_ADDR6_Msk (0x1UL << RADIO_RXADDRESSES_ADDR6_Pos) /*!< Bit mask of ADDR6 field. */
+#define RADIO_RXADDRESSES_ADDR6_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR6_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 5 : Enable reception on logical address 5. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR5_Pos (5UL) /*!< Position of ADDR5 field. */
+#define RADIO_RXADDRESSES_ADDR5_Msk (0x1UL << RADIO_RXADDRESSES_ADDR5_Pos) /*!< Bit mask of ADDR5 field. */
+#define RADIO_RXADDRESSES_ADDR5_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR5_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 4 : Enable reception on logical address 4. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR4_Pos (4UL) /*!< Position of ADDR4 field. */
+#define RADIO_RXADDRESSES_ADDR4_Msk (0x1UL << RADIO_RXADDRESSES_ADDR4_Pos) /*!< Bit mask of ADDR4 field. */
+#define RADIO_RXADDRESSES_ADDR4_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR4_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 3 : Enable reception on logical address 3. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR3_Pos (3UL) /*!< Position of ADDR3 field. */
+#define RADIO_RXADDRESSES_ADDR3_Msk (0x1UL << RADIO_RXADDRESSES_ADDR3_Pos) /*!< Bit mask of ADDR3 field. */
+#define RADIO_RXADDRESSES_ADDR3_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR3_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 2 : Enable reception on logical address 2. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR2_Pos (2UL) /*!< Position of ADDR2 field. */
+#define RADIO_RXADDRESSES_ADDR2_Msk (0x1UL << RADIO_RXADDRESSES_ADDR2_Pos) /*!< Bit mask of ADDR2 field. */
+#define RADIO_RXADDRESSES_ADDR2_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR2_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 1 : Enable reception on logical address 1. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR1_Pos (1UL) /*!< Position of ADDR1 field. */
+#define RADIO_RXADDRESSES_ADDR1_Msk (0x1UL << RADIO_RXADDRESSES_ADDR1_Pos) /*!< Bit mask of ADDR1 field. */
+#define RADIO_RXADDRESSES_ADDR1_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR1_Enabled (1UL) /*!< Reception enabled. */
+
+/* Bit 0 : Enable reception on logical address 0. Decision point: START task. */
+#define RADIO_RXADDRESSES_ADDR0_Pos (0UL) /*!< Position of ADDR0 field. */
+#define RADIO_RXADDRESSES_ADDR0_Msk (0x1UL << RADIO_RXADDRESSES_ADDR0_Pos) /*!< Bit mask of ADDR0 field. */
+#define RADIO_RXADDRESSES_ADDR0_Disabled (0UL) /*!< Reception disabled. */
+#define RADIO_RXADDRESSES_ADDR0_Enabled (1UL) /*!< Reception enabled. */
+
+/* Register: RADIO_CRCCNF */
+/* Description: CRC configuration. */
+
+/* Bit 8 : Leave packet address field out of the CRC calculation. Decision point: START task. */
+#define RADIO_CRCCNF_SKIPADDR_Pos (8UL) /*!< Position of SKIPADDR field. */
+#define RADIO_CRCCNF_SKIPADDR_Msk (0x1UL << RADIO_CRCCNF_SKIPADDR_Pos) /*!< Bit mask of SKIPADDR field. */
+#define RADIO_CRCCNF_SKIPADDR_Include (0UL) /*!< Include packet address in CRC calculation. */
+#define RADIO_CRCCNF_SKIPADDR_Skip (1UL) /*!< Packet address is skipped in CRC calculation. The CRC calculation will start at the first byte after the address. */
+
+/* Bits 1..0 : CRC length. Decision point: START task. */
+#define RADIO_CRCCNF_LEN_Pos (0UL) /*!< Position of LEN field. */
+#define RADIO_CRCCNF_LEN_Msk (0x3UL << RADIO_CRCCNF_LEN_Pos) /*!< Bit mask of LEN field. */
+#define RADIO_CRCCNF_LEN_Disabled (0UL) /*!< CRC calculation disabled. */
+#define RADIO_CRCCNF_LEN_One (1UL) /*!< One byte long CRC. */
+#define RADIO_CRCCNF_LEN_Two (2UL) /*!< Two bytes long CRC. */
+#define RADIO_CRCCNF_LEN_Three (3UL) /*!< Three bytes long CRC. */
+
+/* Register: RADIO_CRCPOLY */
+/* Description: CRC polynomial. */
+
+/* Bits 23..0 : CRC polynomial. Decision point: START task. */
+#define RADIO_CRCPOLY_CRCPOLY_Pos (0UL) /*!< Position of CRCPOLY field. */
+#define RADIO_CRCPOLY_CRCPOLY_Msk (0xFFFFFFUL << RADIO_CRCPOLY_CRCPOLY_Pos) /*!< Bit mask of CRCPOLY field. */
+
+/* Register: RADIO_CRCINIT */
+/* Description: CRC initial value. */
+
+/* Bits 23..0 : Initial value for CRC calculation. Decision point: START task. */
+#define RADIO_CRCINIT_CRCINIT_Pos (0UL) /*!< Position of CRCINIT field. */
+#define RADIO_CRCINIT_CRCINIT_Msk (0xFFFFFFUL << RADIO_CRCINIT_CRCINIT_Pos) /*!< Bit mask of CRCINIT field. */
+
+/* Register: RADIO_TEST */
+/* Description: Test features enable register. */
+
+/* Bit 1 : PLL lock. Decision point: TXEN or RXEN task. */
+#define RADIO_TEST_PLLLOCK_Pos (1UL) /*!< Position of PLLLOCK field. */
+#define RADIO_TEST_PLLLOCK_Msk (0x1UL << RADIO_TEST_PLLLOCK_Pos) /*!< Bit mask of PLLLOCK field. */
+#define RADIO_TEST_PLLLOCK_Disabled (0UL) /*!< PLL lock disabled. */
+#define RADIO_TEST_PLLLOCK_Enabled (1UL) /*!< PLL lock enabled. */
+
+/* Bit 0 : Constant carrier. Decision point: TXEN task. */
+#define RADIO_TEST_CONSTCARRIER_Pos (0UL) /*!< Position of CONSTCARRIER field. */
+#define RADIO_TEST_CONSTCARRIER_Msk (0x1UL << RADIO_TEST_CONSTCARRIER_Pos) /*!< Bit mask of CONSTCARRIER field. */
+#define RADIO_TEST_CONSTCARRIER_Disabled (0UL) /*!< Constant carrier disabled. */
+#define RADIO_TEST_CONSTCARRIER_Enabled (1UL) /*!< Constant carrier enabled. */
+
+/* Register: RADIO_TIFS */
+/* Description: Inter Frame Spacing in microseconds. */
+
+/* Bits 7..0 : Inter frame spacing in microseconds. Decision point: START rask */
+#define RADIO_TIFS_TIFS_Pos (0UL) /*!< Position of TIFS field. */
+#define RADIO_TIFS_TIFS_Msk (0xFFUL << RADIO_TIFS_TIFS_Pos) /*!< Bit mask of TIFS field. */
+
+/* Register: RADIO_RSSISAMPLE */
+/* Description: RSSI sample. */
+
+/* Bits 6..0 : RSSI sample result. The result is read as a positive value so that ReceivedSignalStrength = -RSSISAMPLE dBm */
+#define RADIO_RSSISAMPLE_RSSISAMPLE_Pos (0UL) /*!< Position of RSSISAMPLE field. */
+#define RADIO_RSSISAMPLE_RSSISAMPLE_Msk (0x7FUL << RADIO_RSSISAMPLE_RSSISAMPLE_Pos) /*!< Bit mask of RSSISAMPLE field. */
+
+/* Register: RADIO_STATE */
+/* Description: Current radio state. */
+
+/* Bits 3..0 : Current radio state. */
+#define RADIO_STATE_STATE_Pos (0UL) /*!< Position of STATE field. */
+#define RADIO_STATE_STATE_Msk (0xFUL << RADIO_STATE_STATE_Pos) /*!< Bit mask of STATE field. */
+#define RADIO_STATE_STATE_Disabled (0x00UL) /*!< Radio is in the Disabled state. */
+#define RADIO_STATE_STATE_RxRu (0x01UL) /*!< Radio is in the Rx Ramp Up state. */
+#define RADIO_STATE_STATE_RxIdle (0x02UL) /*!< Radio is in the Rx Idle state. */
+#define RADIO_STATE_STATE_Rx (0x03UL) /*!< Radio is in the Rx state. */
+#define RADIO_STATE_STATE_RxDisable (0x04UL) /*!< Radio is in the Rx Disable state. */
+#define RADIO_STATE_STATE_TxRu (0x09UL) /*!< Radio is in the Tx Ramp Up state. */
+#define RADIO_STATE_STATE_TxIdle (0x0AUL) /*!< Radio is in the Tx Idle state. */
+#define RADIO_STATE_STATE_Tx (0x0BUL) /*!< Radio is in the Tx state. */
+#define RADIO_STATE_STATE_TxDisable (0x0CUL) /*!< Radio is in the Tx Disable state. */
+
+/* Register: RADIO_DATAWHITEIV */
+/* Description: Data whitening initial value. */
+
+/* Bits 6..0 : Data whitening initial value. Bit 0 corresponds to Position 0 of the LSFR, Bit 1 to position 5... Decision point: TXEN or RXEN task. */
+#define RADIO_DATAWHITEIV_DATAWHITEIV_Pos (0UL) /*!< Position of DATAWHITEIV field. */
+#define RADIO_DATAWHITEIV_DATAWHITEIV_Msk (0x7FUL << RADIO_DATAWHITEIV_DATAWHITEIV_Pos) /*!< Bit mask of DATAWHITEIV field. */
+
+/* Register: RADIO_DAP */
+/* Description: Device address prefix. */
+
+/* Bits 15..0 : Device address prefix. */
+#define RADIO_DAP_DAP_Pos (0UL) /*!< Position of DAP field. */
+#define RADIO_DAP_DAP_Msk (0xFFFFUL << RADIO_DAP_DAP_Pos) /*!< Bit mask of DAP field. */
+
+/* Register: RADIO_DACNF */
+/* Description: Device address match configuration. */
+
+/* Bit 15 : TxAdd for device address 7. */
+#define RADIO_DACNF_TXADD7_Pos (15UL) /*!< Position of TXADD7 field. */
+#define RADIO_DACNF_TXADD7_Msk (0x1UL << RADIO_DACNF_TXADD7_Pos) /*!< Bit mask of TXADD7 field. */
+
+/* Bit 14 : TxAdd for device address 6. */
+#define RADIO_DACNF_TXADD6_Pos (14UL) /*!< Position of TXADD6 field. */
+#define RADIO_DACNF_TXADD6_Msk (0x1UL << RADIO_DACNF_TXADD6_Pos) /*!< Bit mask of TXADD6 field. */
+
+/* Bit 13 : TxAdd for device address 5. */
+#define RADIO_DACNF_TXADD5_Pos (13UL) /*!< Position of TXADD5 field. */
+#define RADIO_DACNF_TXADD5_Msk (0x1UL << RADIO_DACNF_TXADD5_Pos) /*!< Bit mask of TXADD5 field. */
+
+/* Bit 12 : TxAdd for device address 4. */
+#define RADIO_DACNF_TXADD4_Pos (12UL) /*!< Position of TXADD4 field. */
+#define RADIO_DACNF_TXADD4_Msk (0x1UL << RADIO_DACNF_TXADD4_Pos) /*!< Bit mask of TXADD4 field. */
+
+/* Bit 11 : TxAdd for device address 3. */
+#define RADIO_DACNF_TXADD3_Pos (11UL) /*!< Position of TXADD3 field. */
+#define RADIO_DACNF_TXADD3_Msk (0x1UL << RADIO_DACNF_TXADD3_Pos) /*!< Bit mask of TXADD3 field. */
+
+/* Bit 10 : TxAdd for device address 2. */
+#define RADIO_DACNF_TXADD2_Pos (10UL) /*!< Position of TXADD2 field. */
+#define RADIO_DACNF_TXADD2_Msk (0x1UL << RADIO_DACNF_TXADD2_Pos) /*!< Bit mask of TXADD2 field. */
+
+/* Bit 9 : TxAdd for device address 1. */
+#define RADIO_DACNF_TXADD1_Pos (9UL) /*!< Position of TXADD1 field. */
+#define RADIO_DACNF_TXADD1_Msk (0x1UL << RADIO_DACNF_TXADD1_Pos) /*!< Bit mask of TXADD1 field. */
+
+/* Bit 8 : TxAdd for device address 0. */
+#define RADIO_DACNF_TXADD0_Pos (8UL) /*!< Position of TXADD0 field. */
+#define RADIO_DACNF_TXADD0_Msk (0x1UL << RADIO_DACNF_TXADD0_Pos) /*!< Bit mask of TXADD0 field. */
+
+/* Bit 7 : Enable or disable device address matching using device address 7. */
+#define RADIO_DACNF_ENA7_Pos (7UL) /*!< Position of ENA7 field. */
+#define RADIO_DACNF_ENA7_Msk (0x1UL << RADIO_DACNF_ENA7_Pos) /*!< Bit mask of ENA7 field. */
+#define RADIO_DACNF_ENA7_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA7_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 6 : Enable or disable device address matching using device address 6. */
+#define RADIO_DACNF_ENA6_Pos (6UL) /*!< Position of ENA6 field. */
+#define RADIO_DACNF_ENA6_Msk (0x1UL << RADIO_DACNF_ENA6_Pos) /*!< Bit mask of ENA6 field. */
+#define RADIO_DACNF_ENA6_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA6_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 5 : Enable or disable device address matching using device address 5. */
+#define RADIO_DACNF_ENA5_Pos (5UL) /*!< Position of ENA5 field. */
+#define RADIO_DACNF_ENA5_Msk (0x1UL << RADIO_DACNF_ENA5_Pos) /*!< Bit mask of ENA5 field. */
+#define RADIO_DACNF_ENA5_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA5_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 4 : Enable or disable device address matching using device address 4. */
+#define RADIO_DACNF_ENA4_Pos (4UL) /*!< Position of ENA4 field. */
+#define RADIO_DACNF_ENA4_Msk (0x1UL << RADIO_DACNF_ENA4_Pos) /*!< Bit mask of ENA4 field. */
+#define RADIO_DACNF_ENA4_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA4_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 3 : Enable or disable device address matching using device address 3. */
+#define RADIO_DACNF_ENA3_Pos (3UL) /*!< Position of ENA3 field. */
+#define RADIO_DACNF_ENA3_Msk (0x1UL << RADIO_DACNF_ENA3_Pos) /*!< Bit mask of ENA3 field. */
+#define RADIO_DACNF_ENA3_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA3_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 2 : Enable or disable device address matching using device address 2. */
+#define RADIO_DACNF_ENA2_Pos (2UL) /*!< Position of ENA2 field. */
+#define RADIO_DACNF_ENA2_Msk (0x1UL << RADIO_DACNF_ENA2_Pos) /*!< Bit mask of ENA2 field. */
+#define RADIO_DACNF_ENA2_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA2_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 1 : Enable or disable device address matching using device address 1. */
+#define RADIO_DACNF_ENA1_Pos (1UL) /*!< Position of ENA1 field. */
+#define RADIO_DACNF_ENA1_Msk (0x1UL << RADIO_DACNF_ENA1_Pos) /*!< Bit mask of ENA1 field. */
+#define RADIO_DACNF_ENA1_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA1_Enabled (1UL) /*!< Enabled. */
+
+/* Bit 0 : Enable or disable device address matching using device address 0. */
+#define RADIO_DACNF_ENA0_Pos (0UL) /*!< Position of ENA0 field. */
+#define RADIO_DACNF_ENA0_Msk (0x1UL << RADIO_DACNF_ENA0_Pos) /*!< Bit mask of ENA0 field. */
+#define RADIO_DACNF_ENA0_Disabled (0UL) /*!< Disabled. */
+#define RADIO_DACNF_ENA0_Enabled (1UL) /*!< Enabled. */
+
+/* Register: RADIO_OVERRIDE0 */
+/* Description: Trim value override register 0. */
+
+/* Bits 31..0 : Trim value override 0. */
+#define RADIO_OVERRIDE0_OVERRIDE0_Pos (0UL) /*!< Position of OVERRIDE0 field. */
+#define RADIO_OVERRIDE0_OVERRIDE0_Msk (0xFFFFFFFFUL << RADIO_OVERRIDE0_OVERRIDE0_Pos) /*!< Bit mask of OVERRIDE0 field. */
+
+/* Register: RADIO_OVERRIDE1 */
+/* Description: Trim value override register 1. */
+
+/* Bits 31..0 : Trim value override 1. */
+#define RADIO_OVERRIDE1_OVERRIDE1_Pos (0UL) /*!< Position of OVERRIDE1 field. */
+#define RADIO_OVERRIDE1_OVERRIDE1_Msk (0xFFFFFFFFUL << RADIO_OVERRIDE1_OVERRIDE1_Pos) /*!< Bit mask of OVERRIDE1 field. */
+
+/* Register: RADIO_OVERRIDE2 */
+/* Description: Trim value override register 2. */
+
+/* Bits 31..0 : Trim value override 2. */
+#define RADIO_OVERRIDE2_OVERRIDE2_Pos (0UL) /*!< Position of OVERRIDE2 field. */
+#define RADIO_OVERRIDE2_OVERRIDE2_Msk (0xFFFFFFFFUL << RADIO_OVERRIDE2_OVERRIDE2_Pos) /*!< Bit mask of OVERRIDE2 field. */
+
+/* Register: RADIO_OVERRIDE3 */
+/* Description: Trim value override register 3. */
+
+/* Bits 31..0 : Trim value override 3. */
+#define RADIO_OVERRIDE3_OVERRIDE3_Pos (0UL) /*!< Position of OVERRIDE3 field. */
+#define RADIO_OVERRIDE3_OVERRIDE3_Msk (0xFFFFFFFFUL << RADIO_OVERRIDE3_OVERRIDE3_Pos) /*!< Bit mask of OVERRIDE3 field. */
+
+/* Register: RADIO_OVERRIDE4 */
+/* Description: Trim value override register 4. */
+
+/* Bit 31 : Enable or disable override of default trim values. */
+#define RADIO_OVERRIDE4_ENABLE_Pos (31UL) /*!< Position of ENABLE field. */
+#define RADIO_OVERRIDE4_ENABLE_Msk (0x1UL << RADIO_OVERRIDE4_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define RADIO_OVERRIDE4_ENABLE_Disabled (0UL) /*!< Override trim values disabled. */
+#define RADIO_OVERRIDE4_ENABLE_Enabled (1UL) /*!< Override trim values enabled. */
+
+/* Bits 27..0 : Trim value override 4. */
+#define RADIO_OVERRIDE4_OVERRIDE4_Pos (0UL) /*!< Position of OVERRIDE4 field. */
+#define RADIO_OVERRIDE4_OVERRIDE4_Msk (0xFFFFFFFUL << RADIO_OVERRIDE4_OVERRIDE4_Pos) /*!< Bit mask of OVERRIDE4 field. */
+
+/* Register: RADIO_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define RADIO_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define RADIO_POWER_POWER_Msk (0x1UL << RADIO_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define RADIO_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define RADIO_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: RNG */
+/* Description: Random Number Generator. */
+
+/* Register: RNG_SHORTS */
+/* Description: Shortcuts for the RNG. */
+
+/* Bit 0 : Shortcut between VALRDY event and STOP task. */
+#define RNG_SHORTS_VALRDY_STOP_Pos (0UL) /*!< Position of VALRDY_STOP field. */
+#define RNG_SHORTS_VALRDY_STOP_Msk (0x1UL << RNG_SHORTS_VALRDY_STOP_Pos) /*!< Bit mask of VALRDY_STOP field. */
+#define RNG_SHORTS_VALRDY_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define RNG_SHORTS_VALRDY_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: RNG_INTENSET */
+/* Description: Interrupt enable set register */
+
+/* Bit 0 : Enable interrupt on VALRDY event. */
+#define RNG_INTENSET_VALRDY_Pos (0UL) /*!< Position of VALRDY field. */
+#define RNG_INTENSET_VALRDY_Msk (0x1UL << RNG_INTENSET_VALRDY_Pos) /*!< Bit mask of VALRDY field. */
+#define RNG_INTENSET_VALRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define RNG_INTENSET_VALRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define RNG_INTENSET_VALRDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: RNG_INTENCLR */
+/* Description: Interrupt enable clear register */
+
+/* Bit 0 : Disable interrupt on VALRDY event. */
+#define RNG_INTENCLR_VALRDY_Pos (0UL) /*!< Position of VALRDY field. */
+#define RNG_INTENCLR_VALRDY_Msk (0x1UL << RNG_INTENCLR_VALRDY_Pos) /*!< Bit mask of VALRDY field. */
+#define RNG_INTENCLR_VALRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define RNG_INTENCLR_VALRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define RNG_INTENCLR_VALRDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: RNG_CONFIG */
+/* Description: Configuration register. */
+
+/* Bit 0 : Digital error correction enable. */
+#define RNG_CONFIG_DERCEN_Pos (0UL) /*!< Position of DERCEN field. */
+#define RNG_CONFIG_DERCEN_Msk (0x1UL << RNG_CONFIG_DERCEN_Pos) /*!< Bit mask of DERCEN field. */
+#define RNG_CONFIG_DERCEN_Disabled (0UL) /*!< Digital error correction disabled. */
+#define RNG_CONFIG_DERCEN_Enabled (1UL) /*!< Digital error correction enabled. */
+
+/* Register: RNG_VALUE */
+/* Description: RNG random number. */
+
+/* Bits 7..0 : Generated random number. */
+#define RNG_VALUE_VALUE_Pos (0UL) /*!< Position of VALUE field. */
+#define RNG_VALUE_VALUE_Msk (0xFFUL << RNG_VALUE_VALUE_Pos) /*!< Bit mask of VALUE field. */
+
+/* Register: RNG_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define RNG_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define RNG_POWER_POWER_Msk (0x1UL << RNG_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define RNG_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define RNG_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: RTC */
+/* Description: Real time counter 0. */
+
+/* Register: RTC_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 19 : Enable interrupt on COMPARE[3] event. */
+#define RTC_INTENSET_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define RTC_INTENSET_COMPARE3_Msk (0x1UL << RTC_INTENSET_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define RTC_INTENSET_COMPARE3_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_COMPARE3_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_COMPARE3_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 18 : Enable interrupt on COMPARE[2] event. */
+#define RTC_INTENSET_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define RTC_INTENSET_COMPARE2_Msk (0x1UL << RTC_INTENSET_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define RTC_INTENSET_COMPARE2_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_COMPARE2_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_COMPARE2_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 17 : Enable interrupt on COMPARE[1] event. */
+#define RTC_INTENSET_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define RTC_INTENSET_COMPARE1_Msk (0x1UL << RTC_INTENSET_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define RTC_INTENSET_COMPARE1_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_COMPARE1_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_COMPARE1_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 16 : Enable interrupt on COMPARE[0] event. */
+#define RTC_INTENSET_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define RTC_INTENSET_COMPARE0_Msk (0x1UL << RTC_INTENSET_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define RTC_INTENSET_COMPARE0_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_COMPARE0_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_COMPARE0_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on OVRFLW event. */
+#define RTC_INTENSET_OVRFLW_Pos (1UL) /*!< Position of OVRFLW field. */
+#define RTC_INTENSET_OVRFLW_Msk (0x1UL << RTC_INTENSET_OVRFLW_Pos) /*!< Bit mask of OVRFLW field. */
+#define RTC_INTENSET_OVRFLW_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_OVRFLW_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_OVRFLW_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on TICK event. */
+#define RTC_INTENSET_TICK_Pos (0UL) /*!< Position of TICK field. */
+#define RTC_INTENSET_TICK_Msk (0x1UL << RTC_INTENSET_TICK_Pos) /*!< Bit mask of TICK field. */
+#define RTC_INTENSET_TICK_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENSET_TICK_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENSET_TICK_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: RTC_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 19 : Disable interrupt on COMPARE[3] event. */
+#define RTC_INTENCLR_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define RTC_INTENCLR_COMPARE3_Msk (0x1UL << RTC_INTENCLR_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define RTC_INTENCLR_COMPARE3_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_COMPARE3_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_COMPARE3_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 18 : Disable interrupt on COMPARE[2] event. */
+#define RTC_INTENCLR_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define RTC_INTENCLR_COMPARE2_Msk (0x1UL << RTC_INTENCLR_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define RTC_INTENCLR_COMPARE2_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_COMPARE2_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_COMPARE2_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 17 : Disable interrupt on COMPARE[1] event. */
+#define RTC_INTENCLR_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define RTC_INTENCLR_COMPARE1_Msk (0x1UL << RTC_INTENCLR_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define RTC_INTENCLR_COMPARE1_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_COMPARE1_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_COMPARE1_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 16 : Disable interrupt on COMPARE[0] event. */
+#define RTC_INTENCLR_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define RTC_INTENCLR_COMPARE0_Msk (0x1UL << RTC_INTENCLR_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define RTC_INTENCLR_COMPARE0_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_COMPARE0_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_COMPARE0_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on OVRFLW event. */
+#define RTC_INTENCLR_OVRFLW_Pos (1UL) /*!< Position of OVRFLW field. */
+#define RTC_INTENCLR_OVRFLW_Msk (0x1UL << RTC_INTENCLR_OVRFLW_Pos) /*!< Bit mask of OVRFLW field. */
+#define RTC_INTENCLR_OVRFLW_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_OVRFLW_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_OVRFLW_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on TICK event. */
+#define RTC_INTENCLR_TICK_Pos (0UL) /*!< Position of TICK field. */
+#define RTC_INTENCLR_TICK_Msk (0x1UL << RTC_INTENCLR_TICK_Pos) /*!< Bit mask of TICK field. */
+#define RTC_INTENCLR_TICK_Disabled (0UL) /*!< Interrupt disabled. */
+#define RTC_INTENCLR_TICK_Enabled (1UL) /*!< Interrupt enabled. */
+#define RTC_INTENCLR_TICK_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: RTC_EVTEN */
+/* Description: Configures event enable routing to PPI for each RTC event. */
+
+/* Bit 19 : COMPARE[3] event enable. */
+#define RTC_EVTEN_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define RTC_EVTEN_COMPARE3_Msk (0x1UL << RTC_EVTEN_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define RTC_EVTEN_COMPARE3_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_COMPARE3_Enabled (1UL) /*!< Event enabled. */
+
+/* Bit 18 : COMPARE[2] event enable. */
+#define RTC_EVTEN_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define RTC_EVTEN_COMPARE2_Msk (0x1UL << RTC_EVTEN_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define RTC_EVTEN_COMPARE2_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_COMPARE2_Enabled (1UL) /*!< Event enabled. */
+
+/* Bit 17 : COMPARE[1] event enable. */
+#define RTC_EVTEN_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define RTC_EVTEN_COMPARE1_Msk (0x1UL << RTC_EVTEN_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define RTC_EVTEN_COMPARE1_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_COMPARE1_Enabled (1UL) /*!< Event enabled. */
+
+/* Bit 16 : COMPARE[0] event enable. */
+#define RTC_EVTEN_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define RTC_EVTEN_COMPARE0_Msk (0x1UL << RTC_EVTEN_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define RTC_EVTEN_COMPARE0_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_COMPARE0_Enabled (1UL) /*!< Event enabled. */
+
+/* Bit 1 : OVRFLW event enable. */
+#define RTC_EVTEN_OVRFLW_Pos (1UL) /*!< Position of OVRFLW field. */
+#define RTC_EVTEN_OVRFLW_Msk (0x1UL << RTC_EVTEN_OVRFLW_Pos) /*!< Bit mask of OVRFLW field. */
+#define RTC_EVTEN_OVRFLW_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_OVRFLW_Enabled (1UL) /*!< Event enabled. */
+
+/* Bit 0 : TICK event enable. */
+#define RTC_EVTEN_TICK_Pos (0UL) /*!< Position of TICK field. */
+#define RTC_EVTEN_TICK_Msk (0x1UL << RTC_EVTEN_TICK_Pos) /*!< Bit mask of TICK field. */
+#define RTC_EVTEN_TICK_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTEN_TICK_Enabled (1UL) /*!< Event enabled. */
+
+/* Register: RTC_EVTENSET */
+/* Description: Enable events routing to PPI. The reading of this register gives the value of EVTEN. */
+
+/* Bit 19 : Enable routing to PPI of COMPARE[3] event. */
+#define RTC_EVTENSET_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define RTC_EVTENSET_COMPARE3_Msk (0x1UL << RTC_EVTENSET_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define RTC_EVTENSET_COMPARE3_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_COMPARE3_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_COMPARE3_Set (1UL) /*!< Enable event on write. */
+
+/* Bit 18 : Enable routing to PPI of COMPARE[2] event. */
+#define RTC_EVTENSET_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define RTC_EVTENSET_COMPARE2_Msk (0x1UL << RTC_EVTENSET_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define RTC_EVTENSET_COMPARE2_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_COMPARE2_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_COMPARE2_Set (1UL) /*!< Enable event on write. */
+
+/* Bit 17 : Enable routing to PPI of COMPARE[1] event. */
+#define RTC_EVTENSET_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define RTC_EVTENSET_COMPARE1_Msk (0x1UL << RTC_EVTENSET_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define RTC_EVTENSET_COMPARE1_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_COMPARE1_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_COMPARE1_Set (1UL) /*!< Enable event on write. */
+
+/* Bit 16 : Enable routing to PPI of COMPARE[0] event. */
+#define RTC_EVTENSET_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define RTC_EVTENSET_COMPARE0_Msk (0x1UL << RTC_EVTENSET_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define RTC_EVTENSET_COMPARE0_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_COMPARE0_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_COMPARE0_Set (1UL) /*!< Enable event on write. */
+
+/* Bit 1 : Enable routing to PPI of OVRFLW event. */
+#define RTC_EVTENSET_OVRFLW_Pos (1UL) /*!< Position of OVRFLW field. */
+#define RTC_EVTENSET_OVRFLW_Msk (0x1UL << RTC_EVTENSET_OVRFLW_Pos) /*!< Bit mask of OVRFLW field. */
+#define RTC_EVTENSET_OVRFLW_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_OVRFLW_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_OVRFLW_Set (1UL) /*!< Enable event on write. */
+
+/* Bit 0 : Enable routing to PPI of TICK event. */
+#define RTC_EVTENSET_TICK_Pos (0UL) /*!< Position of TICK field. */
+#define RTC_EVTENSET_TICK_Msk (0x1UL << RTC_EVTENSET_TICK_Pos) /*!< Bit mask of TICK field. */
+#define RTC_EVTENSET_TICK_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENSET_TICK_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENSET_TICK_Set (1UL) /*!< Enable event on write. */
+
+/* Register: RTC_EVTENCLR */
+/* Description: Disable events routing to PPI. The reading of this register gives the value of EVTEN. */
+
+/* Bit 19 : Disable routing to PPI of COMPARE[3] event. */
+#define RTC_EVTENCLR_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define RTC_EVTENCLR_COMPARE3_Msk (0x1UL << RTC_EVTENCLR_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define RTC_EVTENCLR_COMPARE3_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_COMPARE3_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_COMPARE3_Clear (1UL) /*!< Disable event on write. */
+
+/* Bit 18 : Disable routing to PPI of COMPARE[2] event. */
+#define RTC_EVTENCLR_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define RTC_EVTENCLR_COMPARE2_Msk (0x1UL << RTC_EVTENCLR_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define RTC_EVTENCLR_COMPARE2_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_COMPARE2_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_COMPARE2_Clear (1UL) /*!< Disable event on write. */
+
+/* Bit 17 : Disable routing to PPI of COMPARE[1] event. */
+#define RTC_EVTENCLR_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define RTC_EVTENCLR_COMPARE1_Msk (0x1UL << RTC_EVTENCLR_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define RTC_EVTENCLR_COMPARE1_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_COMPARE1_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_COMPARE1_Clear (1UL) /*!< Disable event on write. */
+
+/* Bit 16 : Disable routing to PPI of COMPARE[0] event. */
+#define RTC_EVTENCLR_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define RTC_EVTENCLR_COMPARE0_Msk (0x1UL << RTC_EVTENCLR_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define RTC_EVTENCLR_COMPARE0_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_COMPARE0_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_COMPARE0_Clear (1UL) /*!< Disable event on write. */
+
+/* Bit 1 : Disable routing to PPI of OVRFLW event. */
+#define RTC_EVTENCLR_OVRFLW_Pos (1UL) /*!< Position of OVRFLW field. */
+#define RTC_EVTENCLR_OVRFLW_Msk (0x1UL << RTC_EVTENCLR_OVRFLW_Pos) /*!< Bit mask of OVRFLW field. */
+#define RTC_EVTENCLR_OVRFLW_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_OVRFLW_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_OVRFLW_Clear (1UL) /*!< Disable event on write. */
+
+/* Bit 0 : Disable routing to PPI of TICK event. */
+#define RTC_EVTENCLR_TICK_Pos (0UL) /*!< Position of TICK field. */
+#define RTC_EVTENCLR_TICK_Msk (0x1UL << RTC_EVTENCLR_TICK_Pos) /*!< Bit mask of TICK field. */
+#define RTC_EVTENCLR_TICK_Disabled (0UL) /*!< Event disabled. */
+#define RTC_EVTENCLR_TICK_Enabled (1UL) /*!< Event enabled. */
+#define RTC_EVTENCLR_TICK_Clear (1UL) /*!< Disable event on write. */
+
+/* Register: RTC_COUNTER */
+/* Description: Current COUNTER value. */
+
+/* Bits 23..0 : Counter value. */
+#define RTC_COUNTER_COUNTER_Pos (0UL) /*!< Position of COUNTER field. */
+#define RTC_COUNTER_COUNTER_Msk (0xFFFFFFUL << RTC_COUNTER_COUNTER_Pos) /*!< Bit mask of COUNTER field. */
+
+/* Register: RTC_PRESCALER */
+/* Description: 12-bit prescaler for COUNTER frequency (32768/(PRESCALER+1)). Must be written when RTC is STOPed. */
+
+/* Bits 11..0 : RTC PRESCALER value. */
+#define RTC_PRESCALER_PRESCALER_Pos (0UL) /*!< Position of PRESCALER field. */
+#define RTC_PRESCALER_PRESCALER_Msk (0xFFFUL << RTC_PRESCALER_PRESCALER_Pos) /*!< Bit mask of PRESCALER field. */
+
+/* Register: RTC_CC */
+/* Description: Capture/compare registers. */
+
+/* Bits 23..0 : Compare value. */
+#define RTC_CC_COMPARE_Pos (0UL) /*!< Position of COMPARE field. */
+#define RTC_CC_COMPARE_Msk (0xFFFFFFUL << RTC_CC_COMPARE_Pos) /*!< Bit mask of COMPARE field. */
+
+/* Register: RTC_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define RTC_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define RTC_POWER_POWER_Msk (0x1UL << RTC_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define RTC_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define RTC_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: SPI */
+/* Description: SPI master 0. */
+
+/* Register: SPI_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 2 : Enable interrupt on READY event. */
+#define SPI_INTENSET_READY_Pos (2UL) /*!< Position of READY field. */
+#define SPI_INTENSET_READY_Msk (0x1UL << SPI_INTENSET_READY_Pos) /*!< Bit mask of READY field. */
+#define SPI_INTENSET_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPI_INTENSET_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPI_INTENSET_READY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: SPI_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 2 : Disable interrupt on READY event. */
+#define SPI_INTENCLR_READY_Pos (2UL) /*!< Position of READY field. */
+#define SPI_INTENCLR_READY_Msk (0x1UL << SPI_INTENCLR_READY_Pos) /*!< Bit mask of READY field. */
+#define SPI_INTENCLR_READY_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPI_INTENCLR_READY_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPI_INTENCLR_READY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: SPI_ENABLE */
+/* Description: Enable SPI. */
+
+/* Bits 2..0 : Enable or disable SPI. */
+#define SPI_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define SPI_ENABLE_ENABLE_Msk (0x7UL << SPI_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define SPI_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled SPI. */
+#define SPI_ENABLE_ENABLE_Enabled (0x01UL) /*!< Enable SPI. */
+
+/* Register: SPI_RXD */
+/* Description: RX data. */
+
+/* Bits 7..0 : RX data from last transfer. */
+#define SPI_RXD_RXD_Pos (0UL) /*!< Position of RXD field. */
+#define SPI_RXD_RXD_Msk (0xFFUL << SPI_RXD_RXD_Pos) /*!< Bit mask of RXD field. */
+
+/* Register: SPI_TXD */
+/* Description: TX data. */
+
+/* Bits 7..0 : TX data for next transfer. */
+#define SPI_TXD_TXD_Pos (0UL) /*!< Position of TXD field. */
+#define SPI_TXD_TXD_Msk (0xFFUL << SPI_TXD_TXD_Pos) /*!< Bit mask of TXD field. */
+
+/* Register: SPI_FREQUENCY */
+/* Description: SPI frequency */
+
+/* Bits 31..0 : SPI data rate. */
+#define SPI_FREQUENCY_FREQUENCY_Pos (0UL) /*!< Position of FREQUENCY field. */
+#define SPI_FREQUENCY_FREQUENCY_Msk (0xFFFFFFFFUL << SPI_FREQUENCY_FREQUENCY_Pos) /*!< Bit mask of FREQUENCY field. */
+#define SPI_FREQUENCY_FREQUENCY_K125 (0x02000000UL) /*!< 125kbps. */
+#define SPI_FREQUENCY_FREQUENCY_K250 (0x04000000UL) /*!< 250kbps. */
+#define SPI_FREQUENCY_FREQUENCY_K500 (0x08000000UL) /*!< 500kbps. */
+#define SPI_FREQUENCY_FREQUENCY_M1 (0x10000000UL) /*!< 1Mbps. */
+#define SPI_FREQUENCY_FREQUENCY_M2 (0x20000000UL) /*!< 2Mbps. */
+#define SPI_FREQUENCY_FREQUENCY_M4 (0x40000000UL) /*!< 4Mbps. */
+#define SPI_FREQUENCY_FREQUENCY_M8 (0x80000000UL) /*!< 8Mbps. */
+
+/* Register: SPI_CONFIG */
+/* Description: Configuration register. */
+
+/* Bit 2 : Serial clock (SCK) polarity. */
+#define SPI_CONFIG_CPOL_Pos (2UL) /*!< Position of CPOL field. */
+#define SPI_CONFIG_CPOL_Msk (0x1UL << SPI_CONFIG_CPOL_Pos) /*!< Bit mask of CPOL field. */
+#define SPI_CONFIG_CPOL_ActiveHigh (0UL) /*!< Active high. */
+#define SPI_CONFIG_CPOL_ActiveLow (1UL) /*!< Active low. */
+
+/* Bit 1 : Serial clock (SCK) phase. */
+#define SPI_CONFIG_CPHA_Pos (1UL) /*!< Position of CPHA field. */
+#define SPI_CONFIG_CPHA_Msk (0x1UL << SPI_CONFIG_CPHA_Pos) /*!< Bit mask of CPHA field. */
+#define SPI_CONFIG_CPHA_Leading (0UL) /*!< Sample on leading edge of the clock. Shift serial data on trailing edge. */
+#define SPI_CONFIG_CPHA_Trailing (1UL) /*!< Sample on trailing edge of the clock. Shift serial data on leading edge. */
+
+/* Bit 0 : Bit order. */
+#define SPI_CONFIG_ORDER_Pos (0UL) /*!< Position of ORDER field. */
+#define SPI_CONFIG_ORDER_Msk (0x1UL << SPI_CONFIG_ORDER_Pos) /*!< Bit mask of ORDER field. */
+#define SPI_CONFIG_ORDER_MsbFirst (0UL) /*!< Most significant bit transmitted out first. */
+#define SPI_CONFIG_ORDER_LsbFirst (1UL) /*!< Least significant bit transmitted out first. */
+
+/* Register: SPI_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define SPI_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define SPI_POWER_POWER_Msk (0x1UL << SPI_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define SPI_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define SPI_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: SPIM */
+/* Description: SPI master with easyDMA 1. */
+
+/* Register: SPIM_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 19 : Enable interrupt on STARTED event. */
+#define SPIM_INTENSET_STARTED_Pos (19UL) /*!< Position of STARTED field. */
+#define SPIM_INTENSET_STARTED_Msk (0x1UL << SPIM_INTENSET_STARTED_Pos) /*!< Bit mask of STARTED field. */
+#define SPIM_INTENSET_STARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENSET_STARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENSET_STARTED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 8 : Enable interrupt on ENDTX event. */
+#define SPIM_INTENSET_ENDTX_Pos (8UL) /*!< Position of ENDTX field. */
+#define SPIM_INTENSET_ENDTX_Msk (0x1UL << SPIM_INTENSET_ENDTX_Pos) /*!< Bit mask of ENDTX field. */
+#define SPIM_INTENSET_ENDTX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENSET_ENDTX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENSET_ENDTX_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 4 : Enable interrupt on ENDRX event. */
+#define SPIM_INTENSET_ENDRX_Pos (4UL) /*!< Position of ENDRX field. */
+#define SPIM_INTENSET_ENDRX_Msk (0x1UL << SPIM_INTENSET_ENDRX_Pos) /*!< Bit mask of ENDRX field. */
+#define SPIM_INTENSET_ENDRX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENSET_ENDRX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENSET_ENDRX_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on STOPPED event. */
+#define SPIM_INTENSET_STOPPED_Pos (1UL) /*!< Position of STOPPED field. */
+#define SPIM_INTENSET_STOPPED_Msk (0x1UL << SPIM_INTENSET_STOPPED_Pos) /*!< Bit mask of STOPPED field. */
+#define SPIM_INTENSET_STOPPED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENSET_STOPPED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENSET_STOPPED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: SPIM_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 19 : Disable interrupt on STARTED event. */
+#define SPIM_INTENCLR_STARTED_Pos (19UL) /*!< Position of STARTED field. */
+#define SPIM_INTENCLR_STARTED_Msk (0x1UL << SPIM_INTENCLR_STARTED_Pos) /*!< Bit mask of STARTED field. */
+#define SPIM_INTENCLR_STARTED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENCLR_STARTED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENCLR_STARTED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 8 : Disable interrupt on ENDTX event. */
+#define SPIM_INTENCLR_ENDTX_Pos (8UL) /*!< Position of ENDTX field. */
+#define SPIM_INTENCLR_ENDTX_Msk (0x1UL << SPIM_INTENCLR_ENDTX_Pos) /*!< Bit mask of ENDTX field. */
+#define SPIM_INTENCLR_ENDTX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENCLR_ENDTX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENCLR_ENDTX_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 4 : Disable interrupt on ENDRX event. */
+#define SPIM_INTENCLR_ENDRX_Pos (4UL) /*!< Position of ENDRX field. */
+#define SPIM_INTENCLR_ENDRX_Msk (0x1UL << SPIM_INTENCLR_ENDRX_Pos) /*!< Bit mask of ENDRX field. */
+#define SPIM_INTENCLR_ENDRX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENCLR_ENDRX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENCLR_ENDRX_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on STOPPED event. */
+#define SPIM_INTENCLR_STOPPED_Pos (1UL) /*!< Position of STOPPED field. */
+#define SPIM_INTENCLR_STOPPED_Msk (0x1UL << SPIM_INTENCLR_STOPPED_Pos) /*!< Bit mask of STOPPED field. */
+#define SPIM_INTENCLR_STOPPED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIM_INTENCLR_STOPPED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIM_INTENCLR_STOPPED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: SPIM_ENABLE */
+/* Description: Enable SPIM. */
+
+/* Bits 3..0 : Enable or disable SPIM. */
+#define SPIM_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define SPIM_ENABLE_ENABLE_Msk (0xFUL << SPIM_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define SPIM_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled SPIM. */
+#define SPIM_ENABLE_ENABLE_Enabled (0x07UL) /*!< Enable SPIM. */
+
+/* Register: SPIM_FREQUENCY */
+/* Description: SPI frequency. */
+
+/* Bits 31..0 : SPI master data rate. */
+#define SPIM_FREQUENCY_FREQUENCY_Pos (0UL) /*!< Position of FREQUENCY field. */
+#define SPIM_FREQUENCY_FREQUENCY_Msk (0xFFFFFFFFUL << SPIM_FREQUENCY_FREQUENCY_Pos) /*!< Bit mask of FREQUENCY field. */
+#define SPIM_FREQUENCY_FREQUENCY_K125 (0x02000000UL) /*!< 125 kbps. */
+#define SPIM_FREQUENCY_FREQUENCY_K250 (0x04000000UL) /*!< 250 kbps. */
+#define SPIM_FREQUENCY_FREQUENCY_K500 (0x08000000UL) /*!< 500 kbps. */
+#define SPIM_FREQUENCY_FREQUENCY_M1 (0x10000000UL) /*!< 1 Mbps. */
+#define SPIM_FREQUENCY_FREQUENCY_M2 (0x20000000UL) /*!< 2 Mbps. */
+#define SPIM_FREQUENCY_FREQUENCY_M4 (0x40000000UL) /*!< 4 Mbps. */
+#define SPIM_FREQUENCY_FREQUENCY_M8 (0x80000000UL) /*!< 8 Mbps. */
+
+/* Register: SPIM_RXD_PTR */
+/* Description: Data pointer. */
+
+/* Bits 31..0 : Data pointer. */
+#define SPIM_RXD_PTR_PTR_Pos (0UL) /*!< Position of PTR field. */
+#define SPIM_RXD_PTR_PTR_Msk (0xFFFFFFFFUL << SPIM_RXD_PTR_PTR_Pos) /*!< Bit mask of PTR field. */
+
+/* Register: SPIM_RXD_MAXCNT */
+/* Description: Maximum number of buffer bytes to receive. */
+
+/* Bits 7..0 : Maximum number of buffer bytes to receive. */
+#define SPIM_RXD_MAXCNT_MAXCNT_Pos (0UL) /*!< Position of MAXCNT field. */
+#define SPIM_RXD_MAXCNT_MAXCNT_Msk (0xFFUL << SPIM_RXD_MAXCNT_MAXCNT_Pos) /*!< Bit mask of MAXCNT field. */
+
+/* Register: SPIM_RXD_AMOUNT */
+/* Description: Number of bytes received in the last transaction. */
+
+/* Bits 7..0 : Number of bytes received in the last transaction. */
+#define SPIM_RXD_AMOUNT_AMOUNT_Pos (0UL) /*!< Position of AMOUNT field. */
+#define SPIM_RXD_AMOUNT_AMOUNT_Msk (0xFFUL << SPIM_RXD_AMOUNT_AMOUNT_Pos) /*!< Bit mask of AMOUNT field. */
+
+/* Register: SPIM_TXD_PTR */
+/* Description: Data pointer. */
+
+/* Bits 31..0 : Data pointer. */
+#define SPIM_TXD_PTR_PTR_Pos (0UL) /*!< Position of PTR field. */
+#define SPIM_TXD_PTR_PTR_Msk (0xFFFFFFFFUL << SPIM_TXD_PTR_PTR_Pos) /*!< Bit mask of PTR field. */
+
+/* Register: SPIM_TXD_MAXCNT */
+/* Description: Maximum number of buffer bytes to send. */
+
+/* Bits 7..0 : Maximum number of buffer bytes to send. */
+#define SPIM_TXD_MAXCNT_MAXCNT_Pos (0UL) /*!< Position of MAXCNT field. */
+#define SPIM_TXD_MAXCNT_MAXCNT_Msk (0xFFUL << SPIM_TXD_MAXCNT_MAXCNT_Pos) /*!< Bit mask of MAXCNT field. */
+
+/* Register: SPIM_TXD_AMOUNT */
+/* Description: Number of bytes sent in the last transaction. */
+
+/* Bits 7..0 : Number of bytes sent in the last transaction. */
+#define SPIM_TXD_AMOUNT_AMOUNT_Pos (0UL) /*!< Position of AMOUNT field. */
+#define SPIM_TXD_AMOUNT_AMOUNT_Msk (0xFFUL << SPIM_TXD_AMOUNT_AMOUNT_Pos) /*!< Bit mask of AMOUNT field. */
+
+/* Register: SPIM_CONFIG */
+/* Description: Configuration register. */
+
+/* Bit 2 : Serial clock (SCK) polarity. */
+#define SPIM_CONFIG_CPOL_Pos (2UL) /*!< Position of CPOL field. */
+#define SPIM_CONFIG_CPOL_Msk (0x1UL << SPIM_CONFIG_CPOL_Pos) /*!< Bit mask of CPOL field. */
+#define SPIM_CONFIG_CPOL_ActiveHigh (0UL) /*!< Active high. */
+#define SPIM_CONFIG_CPOL_ActiveLow (1UL) /*!< Active low. */
+
+/* Bit 1 : Serial clock (SCK) phase. */
+#define SPIM_CONFIG_CPHA_Pos (1UL) /*!< Position of CPHA field. */
+#define SPIM_CONFIG_CPHA_Msk (0x1UL << SPIM_CONFIG_CPHA_Pos) /*!< Bit mask of CPHA field. */
+#define SPIM_CONFIG_CPHA_Leading (0UL) /*!< Sample on leading edge of the clock. Shift serial data on trailing edge. */
+#define SPIM_CONFIG_CPHA_Trailing (1UL) /*!< Sample on trailing edge of the clock. Shift serial data on leading edge. */
+
+/* Bit 0 : Bit order. */
+#define SPIM_CONFIG_ORDER_Pos (0UL) /*!< Position of ORDER field. */
+#define SPIM_CONFIG_ORDER_Msk (0x1UL << SPIM_CONFIG_ORDER_Pos) /*!< Bit mask of ORDER field. */
+#define SPIM_CONFIG_ORDER_MsbFirst (0UL) /*!< Most significant bit transmitted out first. */
+#define SPIM_CONFIG_ORDER_LsbFirst (1UL) /*!< Least significant bit transmitted out first. */
+
+/* Register: SPIM_ORC */
+/* Description: Over-read character. */
+
+/* Bits 7..0 : Over-read character. */
+#define SPIM_ORC_ORC_Pos (0UL) /*!< Position of ORC field. */
+#define SPIM_ORC_ORC_Msk (0xFFUL << SPIM_ORC_ORC_Pos) /*!< Bit mask of ORC field. */
+
+/* Register: SPIM_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define SPIM_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define SPIM_POWER_POWER_Msk (0x1UL << SPIM_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define SPIM_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define SPIM_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: SPIS */
+/* Description: SPI slave 1. */
+
+/* Register: SPIS_SHORTS */
+/* Description: Shortcuts for SPIS. */
+
+/* Bit 2 : Shortcut between END event and the ACQUIRE task. */
+#define SPIS_SHORTS_END_ACQUIRE_Pos (2UL) /*!< Position of END_ACQUIRE field. */
+#define SPIS_SHORTS_END_ACQUIRE_Msk (0x1UL << SPIS_SHORTS_END_ACQUIRE_Pos) /*!< Bit mask of END_ACQUIRE field. */
+#define SPIS_SHORTS_END_ACQUIRE_Disabled (0UL) /*!< Shortcut disabled. */
+#define SPIS_SHORTS_END_ACQUIRE_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: SPIS_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 10 : Enable interrupt on ACQUIRED event. */
+#define SPIS_INTENSET_ACQUIRED_Pos (10UL) /*!< Position of ACQUIRED field. */
+#define SPIS_INTENSET_ACQUIRED_Msk (0x1UL << SPIS_INTENSET_ACQUIRED_Pos) /*!< Bit mask of ACQUIRED field. */
+#define SPIS_INTENSET_ACQUIRED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENSET_ACQUIRED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENSET_ACQUIRED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 4 : enable interrupt on ENDRX event. */
+#define SPIS_INTENSET_ENDRX_Pos (4UL) /*!< Position of ENDRX field. */
+#define SPIS_INTENSET_ENDRX_Msk (0x1UL << SPIS_INTENSET_ENDRX_Pos) /*!< Bit mask of ENDRX field. */
+#define SPIS_INTENSET_ENDRX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENSET_ENDRX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENSET_ENDRX_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on END event. */
+#define SPIS_INTENSET_END_Pos (1UL) /*!< Position of END field. */
+#define SPIS_INTENSET_END_Msk (0x1UL << SPIS_INTENSET_END_Pos) /*!< Bit mask of END field. */
+#define SPIS_INTENSET_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENSET_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENSET_END_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: SPIS_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 10 : Disable interrupt on ACQUIRED event. */
+#define SPIS_INTENCLR_ACQUIRED_Pos (10UL) /*!< Position of ACQUIRED field. */
+#define SPIS_INTENCLR_ACQUIRED_Msk (0x1UL << SPIS_INTENCLR_ACQUIRED_Pos) /*!< Bit mask of ACQUIRED field. */
+#define SPIS_INTENCLR_ACQUIRED_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENCLR_ACQUIRED_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENCLR_ACQUIRED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 4 : Disable interrupt on ENDRX event. */
+#define SPIS_INTENCLR_ENDRX_Pos (4UL) /*!< Position of ENDRX field. */
+#define SPIS_INTENCLR_ENDRX_Msk (0x1UL << SPIS_INTENCLR_ENDRX_Pos) /*!< Bit mask of ENDRX field. */
+#define SPIS_INTENCLR_ENDRX_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENCLR_ENDRX_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENCLR_ENDRX_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on END event. */
+#define SPIS_INTENCLR_END_Pos (1UL) /*!< Position of END field. */
+#define SPIS_INTENCLR_END_Msk (0x1UL << SPIS_INTENCLR_END_Pos) /*!< Bit mask of END field. */
+#define SPIS_INTENCLR_END_Disabled (0UL) /*!< Interrupt disabled. */
+#define SPIS_INTENCLR_END_Enabled (1UL) /*!< Interrupt enabled. */
+#define SPIS_INTENCLR_END_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: SPIS_SEMSTAT */
+/* Description: Semaphore status. */
+
+/* Bits 1..0 : Semaphore status. */
+#define SPIS_SEMSTAT_SEMSTAT_Pos (0UL) /*!< Position of SEMSTAT field. */
+#define SPIS_SEMSTAT_SEMSTAT_Msk (0x3UL << SPIS_SEMSTAT_SEMSTAT_Pos) /*!< Bit mask of SEMSTAT field. */
+#define SPIS_SEMSTAT_SEMSTAT_Free (0x00UL) /*!< Semaphore is free. */
+#define SPIS_SEMSTAT_SEMSTAT_CPU (0x01UL) /*!< Semaphore is assigned to the CPU. */
+#define SPIS_SEMSTAT_SEMSTAT_SPIS (0x02UL) /*!< Semaphore is assigned to the SPIS. */
+#define SPIS_SEMSTAT_SEMSTAT_CPUPending (0x03UL) /*!< Semaphore is assigned to the SPIS, but a handover to the CPU is pending. */
+
+/* Register: SPIS_STATUS */
+/* Description: Status from last transaction. */
+
+/* Bit 1 : RX buffer overflow detected, and prevented. */
+#define SPIS_STATUS_OVERFLOW_Pos (1UL) /*!< Position of OVERFLOW field. */
+#define SPIS_STATUS_OVERFLOW_Msk (0x1UL << SPIS_STATUS_OVERFLOW_Pos) /*!< Bit mask of OVERFLOW field. */
+#define SPIS_STATUS_OVERFLOW_NotPresent (0UL) /*!< Error not present. */
+#define SPIS_STATUS_OVERFLOW_Present (1UL) /*!< Error present. */
+#define SPIS_STATUS_OVERFLOW_Clear (1UL) /*!< Clear on write. */
+
+/* Bit 0 : TX buffer overread detected, and prevented. */
+#define SPIS_STATUS_OVERREAD_Pos (0UL) /*!< Position of OVERREAD field. */
+#define SPIS_STATUS_OVERREAD_Msk (0x1UL << SPIS_STATUS_OVERREAD_Pos) /*!< Bit mask of OVERREAD field. */
+#define SPIS_STATUS_OVERREAD_NotPresent (0UL) /*!< Error not present. */
+#define SPIS_STATUS_OVERREAD_Present (1UL) /*!< Error present. */
+#define SPIS_STATUS_OVERREAD_Clear (1UL) /*!< Clear on write. */
+
+/* Register: SPIS_ENABLE */
+/* Description: Enable SPIS. */
+
+/* Bits 2..0 : Enable or disable SPIS. */
+#define SPIS_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define SPIS_ENABLE_ENABLE_Msk (0x7UL << SPIS_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define SPIS_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled SPIS. */
+#define SPIS_ENABLE_ENABLE_Enabled (0x02UL) /*!< Enable SPIS. */
+
+/* Register: SPIS_MAXRX */
+/* Description: Maximum number of bytes in the receive buffer. */
+
+/* Bits 7..0 : Maximum number of bytes in the receive buffer. */
+#define SPIS_MAXRX_MAXRX_Pos (0UL) /*!< Position of MAXRX field. */
+#define SPIS_MAXRX_MAXRX_Msk (0xFFUL << SPIS_MAXRX_MAXRX_Pos) /*!< Bit mask of MAXRX field. */
+
+/* Register: SPIS_AMOUNTRX */
+/* Description: Number of bytes received in last granted transaction. */
+
+/* Bits 7..0 : Number of bytes received in last granted transaction. */
+#define SPIS_AMOUNTRX_AMOUNTRX_Pos (0UL) /*!< Position of AMOUNTRX field. */
+#define SPIS_AMOUNTRX_AMOUNTRX_Msk (0xFFUL << SPIS_AMOUNTRX_AMOUNTRX_Pos) /*!< Bit mask of AMOUNTRX field. */
+
+/* Register: SPIS_MAXTX */
+/* Description: Maximum number of bytes in the transmit buffer. */
+
+/* Bits 7..0 : Maximum number of bytes in the transmit buffer. */
+#define SPIS_MAXTX_MAXTX_Pos (0UL) /*!< Position of MAXTX field. */
+#define SPIS_MAXTX_MAXTX_Msk (0xFFUL << SPIS_MAXTX_MAXTX_Pos) /*!< Bit mask of MAXTX field. */
+
+/* Register: SPIS_AMOUNTTX */
+/* Description: Number of bytes transmitted in last granted transaction. */
+
+/* Bits 7..0 : Number of bytes transmitted in last granted transaction. */
+#define SPIS_AMOUNTTX_AMOUNTTX_Pos (0UL) /*!< Position of AMOUNTTX field. */
+#define SPIS_AMOUNTTX_AMOUNTTX_Msk (0xFFUL << SPIS_AMOUNTTX_AMOUNTTX_Pos) /*!< Bit mask of AMOUNTTX field. */
+
+/* Register: SPIS_CONFIG */
+/* Description: Configuration register. */
+
+/* Bit 2 : Serial clock (SCK) polarity. */
+#define SPIS_CONFIG_CPOL_Pos (2UL) /*!< Position of CPOL field. */
+#define SPIS_CONFIG_CPOL_Msk (0x1UL << SPIS_CONFIG_CPOL_Pos) /*!< Bit mask of CPOL field. */
+#define SPIS_CONFIG_CPOL_ActiveHigh (0UL) /*!< Active high. */
+#define SPIS_CONFIG_CPOL_ActiveLow (1UL) /*!< Active low. */
+
+/* Bit 1 : Serial clock (SCK) phase. */
+#define SPIS_CONFIG_CPHA_Pos (1UL) /*!< Position of CPHA field. */
+#define SPIS_CONFIG_CPHA_Msk (0x1UL << SPIS_CONFIG_CPHA_Pos) /*!< Bit mask of CPHA field. */
+#define SPIS_CONFIG_CPHA_Leading (0UL) /*!< Sample on leading edge of the clock. Shift serial data on trailing edge. */
+#define SPIS_CONFIG_CPHA_Trailing (1UL) /*!< Sample on trailing edge of the clock. Shift serial data on leading edge. */
+
+/* Bit 0 : Bit order. */
+#define SPIS_CONFIG_ORDER_Pos (0UL) /*!< Position of ORDER field. */
+#define SPIS_CONFIG_ORDER_Msk (0x1UL << SPIS_CONFIG_ORDER_Pos) /*!< Bit mask of ORDER field. */
+#define SPIS_CONFIG_ORDER_MsbFirst (0UL) /*!< Most significant bit transmitted out first. */
+#define SPIS_CONFIG_ORDER_LsbFirst (1UL) /*!< Least significant bit transmitted out first. */
+
+/* Register: SPIS_DEF */
+/* Description: Default character. */
+
+/* Bits 7..0 : Default character. */
+#define SPIS_DEF_DEF_Pos (0UL) /*!< Position of DEF field. */
+#define SPIS_DEF_DEF_Msk (0xFFUL << SPIS_DEF_DEF_Pos) /*!< Bit mask of DEF field. */
+
+/* Register: SPIS_ORC */
+/* Description: Over-read character. */
+
+/* Bits 7..0 : Over-read character. */
+#define SPIS_ORC_ORC_Pos (0UL) /*!< Position of ORC field. */
+#define SPIS_ORC_ORC_Msk (0xFFUL << SPIS_ORC_ORC_Pos) /*!< Bit mask of ORC field. */
+
+/* Register: SPIS_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define SPIS_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define SPIS_POWER_POWER_Msk (0x1UL << SPIS_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define SPIS_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define SPIS_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: TEMP */
+/* Description: Temperature Sensor. */
+
+/* Register: TEMP_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 0 : Enable interrupt on DATARDY event. */
+#define TEMP_INTENSET_DATARDY_Pos (0UL) /*!< Position of DATARDY field. */
+#define TEMP_INTENSET_DATARDY_Msk (0x1UL << TEMP_INTENSET_DATARDY_Pos) /*!< Bit mask of DATARDY field. */
+#define TEMP_INTENSET_DATARDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define TEMP_INTENSET_DATARDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define TEMP_INTENSET_DATARDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: TEMP_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 0 : Disable interrupt on DATARDY event. */
+#define TEMP_INTENCLR_DATARDY_Pos (0UL) /*!< Position of DATARDY field. */
+#define TEMP_INTENCLR_DATARDY_Msk (0x1UL << TEMP_INTENCLR_DATARDY_Pos) /*!< Bit mask of DATARDY field. */
+#define TEMP_INTENCLR_DATARDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define TEMP_INTENCLR_DATARDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define TEMP_INTENCLR_DATARDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: TEMP_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define TEMP_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define TEMP_POWER_POWER_Msk (0x1UL << TEMP_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define TEMP_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define TEMP_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: TIMER */
+/* Description: Timer 0. */
+
+/* Register: TIMER_SHORTS */
+/* Description: Shortcuts for Timer. */
+
+/* Bit 11 : Shortcut between CC[3] event and the STOP task. */
+#define TIMER_SHORTS_COMPARE3_STOP_Pos (11UL) /*!< Position of COMPARE3_STOP field. */
+#define TIMER_SHORTS_COMPARE3_STOP_Msk (0x1UL << TIMER_SHORTS_COMPARE3_STOP_Pos) /*!< Bit mask of COMPARE3_STOP field. */
+#define TIMER_SHORTS_COMPARE3_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE3_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 10 : Shortcut between CC[2] event and the STOP task. */
+#define TIMER_SHORTS_COMPARE2_STOP_Pos (10UL) /*!< Position of COMPARE2_STOP field. */
+#define TIMER_SHORTS_COMPARE2_STOP_Msk (0x1UL << TIMER_SHORTS_COMPARE2_STOP_Pos) /*!< Bit mask of COMPARE2_STOP field. */
+#define TIMER_SHORTS_COMPARE2_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE2_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 9 : Shortcut between CC[1] event and the STOP task. */
+#define TIMER_SHORTS_COMPARE1_STOP_Pos (9UL) /*!< Position of COMPARE1_STOP field. */
+#define TIMER_SHORTS_COMPARE1_STOP_Msk (0x1UL << TIMER_SHORTS_COMPARE1_STOP_Pos) /*!< Bit mask of COMPARE1_STOP field. */
+#define TIMER_SHORTS_COMPARE1_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE1_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 8 : Shortcut between CC[0] event and the STOP task. */
+#define TIMER_SHORTS_COMPARE0_STOP_Pos (8UL) /*!< Position of COMPARE0_STOP field. */
+#define TIMER_SHORTS_COMPARE0_STOP_Msk (0x1UL << TIMER_SHORTS_COMPARE0_STOP_Pos) /*!< Bit mask of COMPARE0_STOP field. */
+#define TIMER_SHORTS_COMPARE0_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE0_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 3 : Shortcut between CC[3] event and the CLEAR task. */
+#define TIMER_SHORTS_COMPARE3_CLEAR_Pos (3UL) /*!< Position of COMPARE3_CLEAR field. */
+#define TIMER_SHORTS_COMPARE3_CLEAR_Msk (0x1UL << TIMER_SHORTS_COMPARE3_CLEAR_Pos) /*!< Bit mask of COMPARE3_CLEAR field. */
+#define TIMER_SHORTS_COMPARE3_CLEAR_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE3_CLEAR_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 2 : Shortcut between CC[2] event and the CLEAR task. */
+#define TIMER_SHORTS_COMPARE2_CLEAR_Pos (2UL) /*!< Position of COMPARE2_CLEAR field. */
+#define TIMER_SHORTS_COMPARE2_CLEAR_Msk (0x1UL << TIMER_SHORTS_COMPARE2_CLEAR_Pos) /*!< Bit mask of COMPARE2_CLEAR field. */
+#define TIMER_SHORTS_COMPARE2_CLEAR_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE2_CLEAR_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 1 : Shortcut between CC[1] event and the CLEAR task. */
+#define TIMER_SHORTS_COMPARE1_CLEAR_Pos (1UL) /*!< Position of COMPARE1_CLEAR field. */
+#define TIMER_SHORTS_COMPARE1_CLEAR_Msk (0x1UL << TIMER_SHORTS_COMPARE1_CLEAR_Pos) /*!< Bit mask of COMPARE1_CLEAR field. */
+#define TIMER_SHORTS_COMPARE1_CLEAR_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE1_CLEAR_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 0 : Shortcut between CC[0] event and the CLEAR task. */
+#define TIMER_SHORTS_COMPARE0_CLEAR_Pos (0UL) /*!< Position of COMPARE0_CLEAR field. */
+#define TIMER_SHORTS_COMPARE0_CLEAR_Msk (0x1UL << TIMER_SHORTS_COMPARE0_CLEAR_Pos) /*!< Bit mask of COMPARE0_CLEAR field. */
+#define TIMER_SHORTS_COMPARE0_CLEAR_Disabled (0UL) /*!< Shortcut disabled. */
+#define TIMER_SHORTS_COMPARE0_CLEAR_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: TIMER_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 19 : Enable interrupt on COMPARE[3] */
+#define TIMER_INTENSET_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define TIMER_INTENSET_COMPARE3_Msk (0x1UL << TIMER_INTENSET_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define TIMER_INTENSET_COMPARE3_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENSET_COMPARE3_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENSET_COMPARE3_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 18 : Enable interrupt on COMPARE[2] */
+#define TIMER_INTENSET_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define TIMER_INTENSET_COMPARE2_Msk (0x1UL << TIMER_INTENSET_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define TIMER_INTENSET_COMPARE2_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENSET_COMPARE2_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENSET_COMPARE2_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 17 : Enable interrupt on COMPARE[1] */
+#define TIMER_INTENSET_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define TIMER_INTENSET_COMPARE1_Msk (0x1UL << TIMER_INTENSET_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define TIMER_INTENSET_COMPARE1_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENSET_COMPARE1_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENSET_COMPARE1_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 16 : Enable interrupt on COMPARE[0] */
+#define TIMER_INTENSET_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define TIMER_INTENSET_COMPARE0_Msk (0x1UL << TIMER_INTENSET_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define TIMER_INTENSET_COMPARE0_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENSET_COMPARE0_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENSET_COMPARE0_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: TIMER_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 19 : Disable interrupt on COMPARE[3] */
+#define TIMER_INTENCLR_COMPARE3_Pos (19UL) /*!< Position of COMPARE3 field. */
+#define TIMER_INTENCLR_COMPARE3_Msk (0x1UL << TIMER_INTENCLR_COMPARE3_Pos) /*!< Bit mask of COMPARE3 field. */
+#define TIMER_INTENCLR_COMPARE3_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENCLR_COMPARE3_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENCLR_COMPARE3_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 18 : Disable interrupt on COMPARE[2] */
+#define TIMER_INTENCLR_COMPARE2_Pos (18UL) /*!< Position of COMPARE2 field. */
+#define TIMER_INTENCLR_COMPARE2_Msk (0x1UL << TIMER_INTENCLR_COMPARE2_Pos) /*!< Bit mask of COMPARE2 field. */
+#define TIMER_INTENCLR_COMPARE2_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENCLR_COMPARE2_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENCLR_COMPARE2_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 17 : Disable interrupt on COMPARE[1] */
+#define TIMER_INTENCLR_COMPARE1_Pos (17UL) /*!< Position of COMPARE1 field. */
+#define TIMER_INTENCLR_COMPARE1_Msk (0x1UL << TIMER_INTENCLR_COMPARE1_Pos) /*!< Bit mask of COMPARE1 field. */
+#define TIMER_INTENCLR_COMPARE1_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENCLR_COMPARE1_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENCLR_COMPARE1_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 16 : Disable interrupt on COMPARE[0] */
+#define TIMER_INTENCLR_COMPARE0_Pos (16UL) /*!< Position of COMPARE0 field. */
+#define TIMER_INTENCLR_COMPARE0_Msk (0x1UL << TIMER_INTENCLR_COMPARE0_Pos) /*!< Bit mask of COMPARE0 field. */
+#define TIMER_INTENCLR_COMPARE0_Disabled (0UL) /*!< Interrupt disabled. */
+#define TIMER_INTENCLR_COMPARE0_Enabled (1UL) /*!< Interrupt enabled. */
+#define TIMER_INTENCLR_COMPARE0_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: TIMER_MODE */
+/* Description: Timer Mode selection. */
+
+/* Bit 0 : Select Normal or Counter mode. */
+#define TIMER_MODE_MODE_Pos (0UL) /*!< Position of MODE field. */
+#define TIMER_MODE_MODE_Msk (0x1UL << TIMER_MODE_MODE_Pos) /*!< Bit mask of MODE field. */
+#define TIMER_MODE_MODE_Timer (0UL) /*!< Timer in Normal mode. */
+#define TIMER_MODE_MODE_Counter (1UL) /*!< Timer in Counter mode. */
+
+/* Register: TIMER_BITMODE */
+/* Description: Sets timer behaviour. */
+
+/* Bits 1..0 : Sets timer behaviour ro be like the implementation of a timer with width as indicated. */
+#define TIMER_BITMODE_BITMODE_Pos (0UL) /*!< Position of BITMODE field. */
+#define TIMER_BITMODE_BITMODE_Msk (0x3UL << TIMER_BITMODE_BITMODE_Pos) /*!< Bit mask of BITMODE field. */
+#define TIMER_BITMODE_BITMODE_16Bit (0x00UL) /*!< 16-bit timer behaviour. */
+#define TIMER_BITMODE_BITMODE_08Bit (0x01UL) /*!< 8-bit timer behaviour. */
+#define TIMER_BITMODE_BITMODE_24Bit (0x02UL) /*!< 24-bit timer behaviour. */
+#define TIMER_BITMODE_BITMODE_32Bit (0x03UL) /*!< 32-bit timer behaviour. */
+
+/* Register: TIMER_PRESCALER */
+/* Description: 4-bit prescaler to source clock frequency (max value 9). Source clock frequency is divided by 2^SCALE. */
+
+/* Bits 3..0 : Timer PRESCALER value. Max value is 9. */
+#define TIMER_PRESCALER_PRESCALER_Pos (0UL) /*!< Position of PRESCALER field. */
+#define TIMER_PRESCALER_PRESCALER_Msk (0xFUL << TIMER_PRESCALER_PRESCALER_Pos) /*!< Bit mask of PRESCALER field. */
+
+/* Register: TIMER_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define TIMER_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define TIMER_POWER_POWER_Msk (0x1UL << TIMER_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define TIMER_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define TIMER_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: TWI */
+/* Description: Two-wire interface master 0. */
+
+/* Register: TWI_SHORTS */
+/* Description: Shortcuts for TWI. */
+
+/* Bit 1 : Shortcut between BB event and the STOP task. */
+#define TWI_SHORTS_BB_STOP_Pos (1UL) /*!< Position of BB_STOP field. */
+#define TWI_SHORTS_BB_STOP_Msk (0x1UL << TWI_SHORTS_BB_STOP_Pos) /*!< Bit mask of BB_STOP field. */
+#define TWI_SHORTS_BB_STOP_Disabled (0UL) /*!< Shortcut disabled. */
+#define TWI_SHORTS_BB_STOP_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 0 : Shortcut between BB event and the SUSPEND task. */
+#define TWI_SHORTS_BB_SUSPEND_Pos (0UL) /*!< Position of BB_SUSPEND field. */
+#define TWI_SHORTS_BB_SUSPEND_Msk (0x1UL << TWI_SHORTS_BB_SUSPEND_Pos) /*!< Bit mask of BB_SUSPEND field. */
+#define TWI_SHORTS_BB_SUSPEND_Disabled (0UL) /*!< Shortcut disabled. */
+#define TWI_SHORTS_BB_SUSPEND_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: TWI_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 18 : Enable interrupt on SUSPENDED event. */
+#define TWI_INTENSET_SUSPENDED_Pos (18UL) /*!< Position of SUSPENDED field. */
+#define TWI_INTENSET_SUSPENDED_Msk (0x1UL << TWI_INTENSET_SUSPENDED_Pos) /*!< Bit mask of SUSPENDED field. */
+#define TWI_INTENSET_SUSPENDED_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_SUSPENDED_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_SUSPENDED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 14 : Enable interrupt on BB event. */
+#define TWI_INTENSET_BB_Pos (14UL) /*!< Position of BB field. */
+#define TWI_INTENSET_BB_Msk (0x1UL << TWI_INTENSET_BB_Pos) /*!< Bit mask of BB field. */
+#define TWI_INTENSET_BB_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_BB_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_BB_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 9 : Enable interrupt on ERROR event. */
+#define TWI_INTENSET_ERROR_Pos (9UL) /*!< Position of ERROR field. */
+#define TWI_INTENSET_ERROR_Msk (0x1UL << TWI_INTENSET_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define TWI_INTENSET_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_ERROR_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 7 : Enable interrupt on TXDSENT event. */
+#define TWI_INTENSET_TXDSENT_Pos (7UL) /*!< Position of TXDSENT field. */
+#define TWI_INTENSET_TXDSENT_Msk (0x1UL << TWI_INTENSET_TXDSENT_Pos) /*!< Bit mask of TXDSENT field. */
+#define TWI_INTENSET_TXDSENT_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_TXDSENT_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_TXDSENT_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 2 : Enable interrupt on READY event. */
+#define TWI_INTENSET_RXDREADY_Pos (2UL) /*!< Position of RXDREADY field. */
+#define TWI_INTENSET_RXDREADY_Msk (0x1UL << TWI_INTENSET_RXDREADY_Pos) /*!< Bit mask of RXDREADY field. */
+#define TWI_INTENSET_RXDREADY_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_RXDREADY_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_RXDREADY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on STOPPED event. */
+#define TWI_INTENSET_STOPPED_Pos (1UL) /*!< Position of STOPPED field. */
+#define TWI_INTENSET_STOPPED_Msk (0x1UL << TWI_INTENSET_STOPPED_Pos) /*!< Bit mask of STOPPED field. */
+#define TWI_INTENSET_STOPPED_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENSET_STOPPED_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENSET_STOPPED_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: TWI_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 18 : Disable interrupt on SUSPENDED event. */
+#define TWI_INTENCLR_SUSPENDED_Pos (18UL) /*!< Position of SUSPENDED field. */
+#define TWI_INTENCLR_SUSPENDED_Msk (0x1UL << TWI_INTENCLR_SUSPENDED_Pos) /*!< Bit mask of SUSPENDED field. */
+#define TWI_INTENCLR_SUSPENDED_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_SUSPENDED_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_SUSPENDED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 14 : Disable interrupt on BB event. */
+#define TWI_INTENCLR_BB_Pos (14UL) /*!< Position of BB field. */
+#define TWI_INTENCLR_BB_Msk (0x1UL << TWI_INTENCLR_BB_Pos) /*!< Bit mask of BB field. */
+#define TWI_INTENCLR_BB_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_BB_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_BB_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 9 : Disable interrupt on ERROR event. */
+#define TWI_INTENCLR_ERROR_Pos (9UL) /*!< Position of ERROR field. */
+#define TWI_INTENCLR_ERROR_Msk (0x1UL << TWI_INTENCLR_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define TWI_INTENCLR_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_ERROR_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 7 : Disable interrupt on TXDSENT event. */
+#define TWI_INTENCLR_TXDSENT_Pos (7UL) /*!< Position of TXDSENT field. */
+#define TWI_INTENCLR_TXDSENT_Msk (0x1UL << TWI_INTENCLR_TXDSENT_Pos) /*!< Bit mask of TXDSENT field. */
+#define TWI_INTENCLR_TXDSENT_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_TXDSENT_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_TXDSENT_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 2 : Disable interrupt on RXDREADY event. */
+#define TWI_INTENCLR_RXDREADY_Pos (2UL) /*!< Position of RXDREADY field. */
+#define TWI_INTENCLR_RXDREADY_Msk (0x1UL << TWI_INTENCLR_RXDREADY_Pos) /*!< Bit mask of RXDREADY field. */
+#define TWI_INTENCLR_RXDREADY_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_RXDREADY_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_RXDREADY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on STOPPED event. */
+#define TWI_INTENCLR_STOPPED_Pos (1UL) /*!< Position of STOPPED field. */
+#define TWI_INTENCLR_STOPPED_Msk (0x1UL << TWI_INTENCLR_STOPPED_Pos) /*!< Bit mask of STOPPED field. */
+#define TWI_INTENCLR_STOPPED_Disabled (0UL) /*!< Interrupt disabled. */
+#define TWI_INTENCLR_STOPPED_Enabled (1UL) /*!< Interrupt enabled. */
+#define TWI_INTENCLR_STOPPED_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: TWI_ERRORSRC */
+/* Description: Two-wire error source. Write error field to 1 to clear error. */
+
+/* Bit 2 : NACK received after sending a data byte. */
+#define TWI_ERRORSRC_DNACK_Pos (2UL) /*!< Position of DNACK field. */
+#define TWI_ERRORSRC_DNACK_Msk (0x1UL << TWI_ERRORSRC_DNACK_Pos) /*!< Bit mask of DNACK field. */
+#define TWI_ERRORSRC_DNACK_NotPresent (0UL) /*!< Error not present. */
+#define TWI_ERRORSRC_DNACK_Present (1UL) /*!< Error present. */
+#define TWI_ERRORSRC_DNACK_Clear (1UL) /*!< Clear error on write. */
+
+/* Bit 1 : NACK received after sending the address. */
+#define TWI_ERRORSRC_ANACK_Pos (1UL) /*!< Position of ANACK field. */
+#define TWI_ERRORSRC_ANACK_Msk (0x1UL << TWI_ERRORSRC_ANACK_Pos) /*!< Bit mask of ANACK field. */
+#define TWI_ERRORSRC_ANACK_NotPresent (0UL) /*!< Error not present. */
+#define TWI_ERRORSRC_ANACK_Present (1UL) /*!< Error present. */
+#define TWI_ERRORSRC_ANACK_Clear (1UL) /*!< Clear error on write. */
+
+/* Bit 0 : Byte received in RXD register before read of the last received byte (data loss). */
+#define TWI_ERRORSRC_OVERRUN_Pos (0UL) /*!< Position of OVERRUN field. */
+#define TWI_ERRORSRC_OVERRUN_Msk (0x1UL << TWI_ERRORSRC_OVERRUN_Pos) /*!< Bit mask of OVERRUN field. */
+#define TWI_ERRORSRC_OVERRUN_NotPresent (0UL) /*!< Error not present. */
+#define TWI_ERRORSRC_OVERRUN_Present (1UL) /*!< Error present. */
+#define TWI_ERRORSRC_OVERRUN_Clear (1UL) /*!< Clear error on write. */
+
+/* Register: TWI_ENABLE */
+/* Description: Enable two-wire master. */
+
+/* Bits 2..0 : Enable or disable W2M */
+#define TWI_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define TWI_ENABLE_ENABLE_Msk (0x7UL << TWI_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define TWI_ENABLE_ENABLE_Disabled (0x00UL) /*!< Disabled. */
+#define TWI_ENABLE_ENABLE_Enabled (0x05UL) /*!< Enabled. */
+
+/* Register: TWI_RXD */
+/* Description: RX data register. */
+
+/* Bits 7..0 : RX data from last transfer. */
+#define TWI_RXD_RXD_Pos (0UL) /*!< Position of RXD field. */
+#define TWI_RXD_RXD_Msk (0xFFUL << TWI_RXD_RXD_Pos) /*!< Bit mask of RXD field. */
+
+/* Register: TWI_TXD */
+/* Description: TX data register. */
+
+/* Bits 7..0 : TX data for next transfer. */
+#define TWI_TXD_TXD_Pos (0UL) /*!< Position of TXD field. */
+#define TWI_TXD_TXD_Msk (0xFFUL << TWI_TXD_TXD_Pos) /*!< Bit mask of TXD field. */
+
+/* Register: TWI_FREQUENCY */
+/* Description: Two-wire frequency. */
+
+/* Bits 31..0 : Two-wire master clock frequency. */
+#define TWI_FREQUENCY_FREQUENCY_Pos (0UL) /*!< Position of FREQUENCY field. */
+#define TWI_FREQUENCY_FREQUENCY_Msk (0xFFFFFFFFUL << TWI_FREQUENCY_FREQUENCY_Pos) /*!< Bit mask of FREQUENCY field. */
+#define TWI_FREQUENCY_FREQUENCY_K100 (0x01980000UL) /*!< 100 kbps. */
+#define TWI_FREQUENCY_FREQUENCY_K250 (0x04000000UL) /*!< 250 kbps. */
+#define TWI_FREQUENCY_FREQUENCY_K400 (0x06680000UL) /*!< 400 kbps. */
+
+/* Register: TWI_ADDRESS */
+/* Description: Address used in the two-wire transfer. */
+
+/* Bits 6..0 : Two-wire address. */
+#define TWI_ADDRESS_ADDRESS_Pos (0UL) /*!< Position of ADDRESS field. */
+#define TWI_ADDRESS_ADDRESS_Msk (0x7FUL << TWI_ADDRESS_ADDRESS_Pos) /*!< Bit mask of ADDRESS field. */
+
+/* Register: TWI_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define TWI_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define TWI_POWER_POWER_Msk (0x1UL << TWI_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define TWI_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define TWI_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: UART */
+/* Description: Universal Asynchronous Receiver/Transmitter. */
+
+/* Register: UART_SHORTS */
+/* Description: Shortcuts for UART. */
+
+/* Bit 4 : Shortcut between NCTS event and STOPRX task. */
+#define UART_SHORTS_NCTS_STOPRX_Pos (4UL) /*!< Position of NCTS_STOPRX field. */
+#define UART_SHORTS_NCTS_STOPRX_Msk (0x1UL << UART_SHORTS_NCTS_STOPRX_Pos) /*!< Bit mask of NCTS_STOPRX field. */
+#define UART_SHORTS_NCTS_STOPRX_Disabled (0UL) /*!< Shortcut disabled. */
+#define UART_SHORTS_NCTS_STOPRX_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Bit 3 : Shortcut between CTS event and STARTRX task. */
+#define UART_SHORTS_CTS_STARTRX_Pos (3UL) /*!< Position of CTS_STARTRX field. */
+#define UART_SHORTS_CTS_STARTRX_Msk (0x1UL << UART_SHORTS_CTS_STARTRX_Pos) /*!< Bit mask of CTS_STARTRX field. */
+#define UART_SHORTS_CTS_STARTRX_Disabled (0UL) /*!< Shortcut disabled. */
+#define UART_SHORTS_CTS_STARTRX_Enabled (1UL) /*!< Shortcut enabled. */
+
+/* Register: UART_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 17 : Enable interrupt on RXTO event. */
+#define UART_INTENSET_RXTO_Pos (17UL) /*!< Position of RXTO field. */
+#define UART_INTENSET_RXTO_Msk (0x1UL << UART_INTENSET_RXTO_Pos) /*!< Bit mask of RXTO field. */
+#define UART_INTENSET_RXTO_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_RXTO_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_RXTO_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 9 : Enable interrupt on ERROR event. */
+#define UART_INTENSET_ERROR_Pos (9UL) /*!< Position of ERROR field. */
+#define UART_INTENSET_ERROR_Msk (0x1UL << UART_INTENSET_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define UART_INTENSET_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_ERROR_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 7 : Enable interrupt on TXRDY event. */
+#define UART_INTENSET_TXDRDY_Pos (7UL) /*!< Position of TXDRDY field. */
+#define UART_INTENSET_TXDRDY_Msk (0x1UL << UART_INTENSET_TXDRDY_Pos) /*!< Bit mask of TXDRDY field. */
+#define UART_INTENSET_TXDRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_TXDRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_TXDRDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 2 : Enable interrupt on RXRDY event. */
+#define UART_INTENSET_RXDRDY_Pos (2UL) /*!< Position of RXDRDY field. */
+#define UART_INTENSET_RXDRDY_Msk (0x1UL << UART_INTENSET_RXDRDY_Pos) /*!< Bit mask of RXDRDY field. */
+#define UART_INTENSET_RXDRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_RXDRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_RXDRDY_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 1 : Enable interrupt on NCTS event. */
+#define UART_INTENSET_NCTS_Pos (1UL) /*!< Position of NCTS field. */
+#define UART_INTENSET_NCTS_Msk (0x1UL << UART_INTENSET_NCTS_Pos) /*!< Bit mask of NCTS field. */
+#define UART_INTENSET_NCTS_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_NCTS_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_NCTS_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Bit 0 : Enable interrupt on CTS event. */
+#define UART_INTENSET_CTS_Pos (0UL) /*!< Position of CTS field. */
+#define UART_INTENSET_CTS_Msk (0x1UL << UART_INTENSET_CTS_Pos) /*!< Bit mask of CTS field. */
+#define UART_INTENSET_CTS_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENSET_CTS_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENSET_CTS_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: UART_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 17 : Disable interrupt on RXTO event. */
+#define UART_INTENCLR_RXTO_Pos (17UL) /*!< Position of RXTO field. */
+#define UART_INTENCLR_RXTO_Msk (0x1UL << UART_INTENCLR_RXTO_Pos) /*!< Bit mask of RXTO field. */
+#define UART_INTENCLR_RXTO_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_RXTO_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_RXTO_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 9 : Disable interrupt on ERROR event. */
+#define UART_INTENCLR_ERROR_Pos (9UL) /*!< Position of ERROR field. */
+#define UART_INTENCLR_ERROR_Msk (0x1UL << UART_INTENCLR_ERROR_Pos) /*!< Bit mask of ERROR field. */
+#define UART_INTENCLR_ERROR_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_ERROR_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_ERROR_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 7 : Disable interrupt on TXRDY event. */
+#define UART_INTENCLR_TXDRDY_Pos (7UL) /*!< Position of TXDRDY field. */
+#define UART_INTENCLR_TXDRDY_Msk (0x1UL << UART_INTENCLR_TXDRDY_Pos) /*!< Bit mask of TXDRDY field. */
+#define UART_INTENCLR_TXDRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_TXDRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_TXDRDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 2 : Disable interrupt on RXRDY event. */
+#define UART_INTENCLR_RXDRDY_Pos (2UL) /*!< Position of RXDRDY field. */
+#define UART_INTENCLR_RXDRDY_Msk (0x1UL << UART_INTENCLR_RXDRDY_Pos) /*!< Bit mask of RXDRDY field. */
+#define UART_INTENCLR_RXDRDY_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_RXDRDY_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_RXDRDY_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 1 : Disable interrupt on NCTS event. */
+#define UART_INTENCLR_NCTS_Pos (1UL) /*!< Position of NCTS field. */
+#define UART_INTENCLR_NCTS_Msk (0x1UL << UART_INTENCLR_NCTS_Pos) /*!< Bit mask of NCTS field. */
+#define UART_INTENCLR_NCTS_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_NCTS_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_NCTS_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Bit 0 : Disable interrupt on CTS event. */
+#define UART_INTENCLR_CTS_Pos (0UL) /*!< Position of CTS field. */
+#define UART_INTENCLR_CTS_Msk (0x1UL << UART_INTENCLR_CTS_Pos) /*!< Bit mask of CTS field. */
+#define UART_INTENCLR_CTS_Disabled (0UL) /*!< Interrupt disabled. */
+#define UART_INTENCLR_CTS_Enabled (1UL) /*!< Interrupt enabled. */
+#define UART_INTENCLR_CTS_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: UART_ERRORSRC */
+/* Description: Error source. Write error field to 1 to clear error. */
+
+/* Bit 3 : The serial data input is '0' for longer than the length of a data frame. */
+#define UART_ERRORSRC_BREAK_Pos (3UL) /*!< Position of BREAK field. */
+#define UART_ERRORSRC_BREAK_Msk (0x1UL << UART_ERRORSRC_BREAK_Pos) /*!< Bit mask of BREAK field. */
+#define UART_ERRORSRC_BREAK_NotPresent (0UL) /*!< Error not present. */
+#define UART_ERRORSRC_BREAK_Present (1UL) /*!< Error present. */
+#define UART_ERRORSRC_BREAK_Clear (1UL) /*!< Clear error on write. */
+
+/* Bit 2 : A valid stop bit is not detected on the serial data input after all bits in a character have been received. */
+#define UART_ERRORSRC_FRAMING_Pos (2UL) /*!< Position of FRAMING field. */
+#define UART_ERRORSRC_FRAMING_Msk (0x1UL << UART_ERRORSRC_FRAMING_Pos) /*!< Bit mask of FRAMING field. */
+#define UART_ERRORSRC_FRAMING_NotPresent (0UL) /*!< Error not present. */
+#define UART_ERRORSRC_FRAMING_Present (1UL) /*!< Error present. */
+#define UART_ERRORSRC_FRAMING_Clear (1UL) /*!< Clear error on write. */
+
+/* Bit 1 : A character with bad parity is received. Only checked if HW parity control is enabled. */
+#define UART_ERRORSRC_PARITY_Pos (1UL) /*!< Position of PARITY field. */
+#define UART_ERRORSRC_PARITY_Msk (0x1UL << UART_ERRORSRC_PARITY_Pos) /*!< Bit mask of PARITY field. */
+#define UART_ERRORSRC_PARITY_NotPresent (0UL) /*!< Error not present. */
+#define UART_ERRORSRC_PARITY_Present (1UL) /*!< Error present. */
+#define UART_ERRORSRC_PARITY_Clear (1UL) /*!< Clear error on write. */
+
+/* Bit 0 : A start bit is received while the previous data still lies in RXD. (Data loss). */
+#define UART_ERRORSRC_OVERRUN_Pos (0UL) /*!< Position of OVERRUN field. */
+#define UART_ERRORSRC_OVERRUN_Msk (0x1UL << UART_ERRORSRC_OVERRUN_Pos) /*!< Bit mask of OVERRUN field. */
+#define UART_ERRORSRC_OVERRUN_NotPresent (0UL) /*!< Error not present. */
+#define UART_ERRORSRC_OVERRUN_Present (1UL) /*!< Error present. */
+#define UART_ERRORSRC_OVERRUN_Clear (1UL) /*!< Clear error on write. */
+
+/* Register: UART_ENABLE */
+/* Description: Enable UART and acquire IOs. */
+
+/* Bits 2..0 : Enable or disable UART and acquire IOs. */
+#define UART_ENABLE_ENABLE_Pos (0UL) /*!< Position of ENABLE field. */
+#define UART_ENABLE_ENABLE_Msk (0x7UL << UART_ENABLE_ENABLE_Pos) /*!< Bit mask of ENABLE field. */
+#define UART_ENABLE_ENABLE_Disabled (0x00UL) /*!< UART disabled. */
+#define UART_ENABLE_ENABLE_Enabled (0x04UL) /*!< UART enabled. */
+
+/* Register: UART_RXD */
+/* Description: RXD register. On read action the buffer pointer is displaced. Once read the character is consumed. If read when no character available, the UART will stop working. */
+
+/* Bits 7..0 : RX data from previous transfer. Double buffered. */
+#define UART_RXD_RXD_Pos (0UL) /*!< Position of RXD field. */
+#define UART_RXD_RXD_Msk (0xFFUL << UART_RXD_RXD_Pos) /*!< Bit mask of RXD field. */
+
+/* Register: UART_TXD */
+/* Description: TXD register. */
+
+/* Bits 7..0 : TX data for transfer. */
+#define UART_TXD_TXD_Pos (0UL) /*!< Position of TXD field. */
+#define UART_TXD_TXD_Msk (0xFFUL << UART_TXD_TXD_Pos) /*!< Bit mask of TXD field. */
+
+/* Register: UART_BAUDRATE */
+/* Description: UART Baudrate. */
+
+/* Bits 31..0 : UART baudrate. */
+#define UART_BAUDRATE_BAUDRATE_Pos (0UL) /*!< Position of BAUDRATE field. */
+#define UART_BAUDRATE_BAUDRATE_Msk (0xFFFFFFFFUL << UART_BAUDRATE_BAUDRATE_Pos) /*!< Bit mask of BAUDRATE field. */
+#define UART_BAUDRATE_BAUDRATE_Baud1200 (0x0004F000UL) /*!< 1200 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud2400 (0x0009D000UL) /*!< 2400 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud4800 (0x0013B000UL) /*!< 4800 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud9600 (0x00275000UL) /*!< 9600 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud14400 (0x003B0000UL) /*!< 14400 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud19200 (0x004EA000UL) /*!< 19200 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud28800 (0x0075F000UL) /*!< 28800 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud38400 (0x009D5000UL) /*!< 38400 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud57600 (0x00EBF000UL) /*!< 57600 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud76800 (0x013A9000UL) /*!< 76800 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud115200 (0x01D7E000UL) /*!< 115200 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud230400 (0x03AFB000UL) /*!< 230400 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud250000 (0x04000000UL) /*!< 250000 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud460800 (0x075F7000UL) /*!< 460800 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud921600 (0x0EBED000UL) /*!< 921600 baud. */
+#define UART_BAUDRATE_BAUDRATE_Baud1M (0x10000000UL) /*!< 1M baud. */
+
+/* Register: UART_CONFIG */
+/* Description: Configuration of parity and hardware flow control register. */
+
+/* Bits 3..1 : Include parity bit. */
+#define UART_CONFIG_PARITY_Pos (1UL) /*!< Position of PARITY field. */
+#define UART_CONFIG_PARITY_Msk (0x7UL << UART_CONFIG_PARITY_Pos) /*!< Bit mask of PARITY field. */
+#define UART_CONFIG_PARITY_Excluded (0UL) /*!< Parity bit excluded. */
+#define UART_CONFIG_PARITY_Included (7UL) /*!< Parity bit included. */
+
+/* Bit 0 : Hardware flow control. */
+#define UART_CONFIG_HWFC_Pos (0UL) /*!< Position of HWFC field. */
+#define UART_CONFIG_HWFC_Msk (0x1UL << UART_CONFIG_HWFC_Pos) /*!< Bit mask of HWFC field. */
+#define UART_CONFIG_HWFC_Disabled (0UL) /*!< Hardware flow control disabled. */
+#define UART_CONFIG_HWFC_Enabled (1UL) /*!< Hardware flow control enabled. */
+
+/* Register: UART_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define UART_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define UART_POWER_POWER_Msk (0x1UL << UART_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define UART_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define UART_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/* Peripheral: UICR */
+/* Description: User Information Configuration. */
+
+/* Register: UICR_RBPCONF */
+/* Description: Readback protection configuration. */
+
+/* Bits 15..8 : Readback protect all code in the device. */
+#define UICR_RBPCONF_PALL_Pos (8UL) /*!< Position of PALL field. */
+#define UICR_RBPCONF_PALL_Msk (0xFFUL << UICR_RBPCONF_PALL_Pos) /*!< Bit mask of PALL field. */
+#define UICR_RBPCONF_PALL_Enabled (0x00UL) /*!< Enabled. */
+#define UICR_RBPCONF_PALL_Disabled (0xFFUL) /*!< Disabled. */
+
+/* Bits 7..0 : Readback protect region 0. Will be ignored if pre-programmed factory code is present on the chip. */
+#define UICR_RBPCONF_PR0_Pos (0UL) /*!< Position of PR0 field. */
+#define UICR_RBPCONF_PR0_Msk (0xFFUL << UICR_RBPCONF_PR0_Pos) /*!< Bit mask of PR0 field. */
+#define UICR_RBPCONF_PR0_Enabled (0x00UL) /*!< Enabled. */
+#define UICR_RBPCONF_PR0_Disabled (0xFFUL) /*!< Disabled. */
+
+/* Register: UICR_XTALFREQ */
+/* Description: Reset value for CLOCK XTALFREQ register. */
+
+/* Bits 7..0 : Reset value for CLOCK XTALFREQ register. */
+#define UICR_XTALFREQ_XTALFREQ_Pos (0UL) /*!< Position of XTALFREQ field. */
+#define UICR_XTALFREQ_XTALFREQ_Msk (0xFFUL << UICR_XTALFREQ_XTALFREQ_Pos) /*!< Bit mask of XTALFREQ field. */
+#define UICR_XTALFREQ_XTALFREQ_32MHz (0x00UL) /*!< 32MHz Xtal is used. */
+#define UICR_XTALFREQ_XTALFREQ_16MHz (0xFFUL) /*!< 16MHz Xtal is used. */
+
+/* Register: UICR_FWID */
+/* Description: Firmware ID. */
+
+/* Bits 15..0 : Identification number for the firmware loaded into the chip. */
+#define UICR_FWID_FWID_Pos (0UL) /*!< Position of FWID field. */
+#define UICR_FWID_FWID_Msk (0xFFFFUL << UICR_FWID_FWID_Pos) /*!< Bit mask of FWID field. */
+
+
+/* Peripheral: WDT */
+/* Description: Watchdog Timer. */
+
+/* Register: WDT_INTENSET */
+/* Description: Interrupt enable set register. */
+
+/* Bit 0 : Enable interrupt on TIMEOUT event. */
+#define WDT_INTENSET_TIMEOUT_Pos (0UL) /*!< Position of TIMEOUT field. */
+#define WDT_INTENSET_TIMEOUT_Msk (0x1UL << WDT_INTENSET_TIMEOUT_Pos) /*!< Bit mask of TIMEOUT field. */
+#define WDT_INTENSET_TIMEOUT_Disabled (0UL) /*!< Interrupt disabled. */
+#define WDT_INTENSET_TIMEOUT_Enabled (1UL) /*!< Interrupt enabled. */
+#define WDT_INTENSET_TIMEOUT_Set (1UL) /*!< Enable interrupt on write. */
+
+/* Register: WDT_INTENCLR */
+/* Description: Interrupt enable clear register. */
+
+/* Bit 0 : Disable interrupt on TIMEOUT event. */
+#define WDT_INTENCLR_TIMEOUT_Pos (0UL) /*!< Position of TIMEOUT field. */
+#define WDT_INTENCLR_TIMEOUT_Msk (0x1UL << WDT_INTENCLR_TIMEOUT_Pos) /*!< Bit mask of TIMEOUT field. */
+#define WDT_INTENCLR_TIMEOUT_Disabled (0UL) /*!< Interrupt disabled. */
+#define WDT_INTENCLR_TIMEOUT_Enabled (1UL) /*!< Interrupt enabled. */
+#define WDT_INTENCLR_TIMEOUT_Clear (1UL) /*!< Disable interrupt on write. */
+
+/* Register: WDT_RUNSTATUS */
+/* Description: Watchdog running status. */
+
+/* Bit 0 : Watchdog running status. */
+#define WDT_RUNSTATUS_RUNSTATUS_Pos (0UL) /*!< Position of RUNSTATUS field. */
+#define WDT_RUNSTATUS_RUNSTATUS_Msk (0x1UL << WDT_RUNSTATUS_RUNSTATUS_Pos) /*!< Bit mask of RUNSTATUS field. */
+#define WDT_RUNSTATUS_RUNSTATUS_NotRunning (0UL) /*!< Watchdog timer is not running. */
+#define WDT_RUNSTATUS_RUNSTATUS_Running (1UL) /*!< Watchdog timer is running. */
+
+/* Register: WDT_REQSTATUS */
+/* Description: Request status. */
+
+/* Bit 7 : Request status for RR[7]. */
+#define WDT_REQSTATUS_RR7_Pos (7UL) /*!< Position of RR7 field. */
+#define WDT_REQSTATUS_RR7_Msk (0x1UL << WDT_REQSTATUS_RR7_Pos) /*!< Bit mask of RR7 field. */
+#define WDT_REQSTATUS_RR7_DisabledOrRequested (0UL) /*!< RR[7] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR7_EnabledAndUnrequested (1UL) /*!< RR[7] register is enabled and has not jet requested. */
+
+/* Bit 6 : Request status for RR[6]. */
+#define WDT_REQSTATUS_RR6_Pos (6UL) /*!< Position of RR6 field. */
+#define WDT_REQSTATUS_RR6_Msk (0x1UL << WDT_REQSTATUS_RR6_Pos) /*!< Bit mask of RR6 field. */
+#define WDT_REQSTATUS_RR6_DisabledOrRequested (0UL) /*!< RR[6] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR6_EnabledAndUnrequested (1UL) /*!< RR[6] register is enabled and has not jet requested. */
+
+/* Bit 5 : Request status for RR[5]. */
+#define WDT_REQSTATUS_RR5_Pos (5UL) /*!< Position of RR5 field. */
+#define WDT_REQSTATUS_RR5_Msk (0x1UL << WDT_REQSTATUS_RR5_Pos) /*!< Bit mask of RR5 field. */
+#define WDT_REQSTATUS_RR5_DisabledOrRequested (0UL) /*!< RR[5] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR5_EnabledAndUnrequested (1UL) /*!< RR[5] register is enabled and has not jet requested. */
+
+/* Bit 4 : Request status for RR[4]. */
+#define WDT_REQSTATUS_RR4_Pos (4UL) /*!< Position of RR4 field. */
+#define WDT_REQSTATUS_RR4_Msk (0x1UL << WDT_REQSTATUS_RR4_Pos) /*!< Bit mask of RR4 field. */
+#define WDT_REQSTATUS_RR4_DisabledOrRequested (0UL) /*!< RR[4] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR4_EnabledAndUnrequested (1UL) /*!< RR[4] register is enabled and has not jet requested. */
+
+/* Bit 3 : Request status for RR[3]. */
+#define WDT_REQSTATUS_RR3_Pos (3UL) /*!< Position of RR3 field. */
+#define WDT_REQSTATUS_RR3_Msk (0x1UL << WDT_REQSTATUS_RR3_Pos) /*!< Bit mask of RR3 field. */
+#define WDT_REQSTATUS_RR3_DisabledOrRequested (0UL) /*!< RR[3] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR3_EnabledAndUnrequested (1UL) /*!< RR[3] register is enabled and has not jet requested. */
+
+/* Bit 2 : Request status for RR[2]. */
+#define WDT_REQSTATUS_RR2_Pos (2UL) /*!< Position of RR2 field. */
+#define WDT_REQSTATUS_RR2_Msk (0x1UL << WDT_REQSTATUS_RR2_Pos) /*!< Bit mask of RR2 field. */
+#define WDT_REQSTATUS_RR2_DisabledOrRequested (0UL) /*!< RR[2] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR2_EnabledAndUnrequested (1UL) /*!< RR[2] register is enabled and has not jet requested. */
+
+/* Bit 1 : Request status for RR[1]. */
+#define WDT_REQSTATUS_RR1_Pos (1UL) /*!< Position of RR1 field. */
+#define WDT_REQSTATUS_RR1_Msk (0x1UL << WDT_REQSTATUS_RR1_Pos) /*!< Bit mask of RR1 field. */
+#define WDT_REQSTATUS_RR1_DisabledOrRequested (0UL) /*!< RR[1] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR1_EnabledAndUnrequested (1UL) /*!< RR[1] register is enabled and has not jet requested. */
+
+/* Bit 0 : Request status for RR[0]. */
+#define WDT_REQSTATUS_RR0_Pos (0UL) /*!< Position of RR0 field. */
+#define WDT_REQSTATUS_RR0_Msk (0x1UL << WDT_REQSTATUS_RR0_Pos) /*!< Bit mask of RR0 field. */
+#define WDT_REQSTATUS_RR0_DisabledOrRequested (0UL) /*!< RR[0] register is not enabled or has already requested reload. */
+#define WDT_REQSTATUS_RR0_EnabledAndUnrequested (1UL) /*!< RR[0] register is enabled and has not jet requested. */
+
+/* Register: WDT_RREN */
+/* Description: Reload request enable. */
+
+/* Bit 7 : Enable or disable RR[7] register. */
+#define WDT_RREN_RR7_Pos (7UL) /*!< Position of RR7 field. */
+#define WDT_RREN_RR7_Msk (0x1UL << WDT_RREN_RR7_Pos) /*!< Bit mask of RR7 field. */
+#define WDT_RREN_RR7_Disabled (0UL) /*!< RR[7] register is disabled. */
+#define WDT_RREN_RR7_Enabled (1UL) /*!< RR[7] register is enabled. */
+
+/* Bit 6 : Enable or disable RR[6] register. */
+#define WDT_RREN_RR6_Pos (6UL) /*!< Position of RR6 field. */
+#define WDT_RREN_RR6_Msk (0x1UL << WDT_RREN_RR6_Pos) /*!< Bit mask of RR6 field. */
+#define WDT_RREN_RR6_Disabled (0UL) /*!< RR[6] register is disabled. */
+#define WDT_RREN_RR6_Enabled (1UL) /*!< RR[6] register is enabled. */
+
+/* Bit 5 : Enable or disable RR[5] register. */
+#define WDT_RREN_RR5_Pos (5UL) /*!< Position of RR5 field. */
+#define WDT_RREN_RR5_Msk (0x1UL << WDT_RREN_RR5_Pos) /*!< Bit mask of RR5 field. */
+#define WDT_RREN_RR5_Disabled (0UL) /*!< RR[5] register is disabled. */
+#define WDT_RREN_RR5_Enabled (1UL) /*!< RR[5] register is enabled. */
+
+/* Bit 4 : Enable or disable RR[4] register. */
+#define WDT_RREN_RR4_Pos (4UL) /*!< Position of RR4 field. */
+#define WDT_RREN_RR4_Msk (0x1UL << WDT_RREN_RR4_Pos) /*!< Bit mask of RR4 field. */
+#define WDT_RREN_RR4_Disabled (0UL) /*!< RR[4] register is disabled. */
+#define WDT_RREN_RR4_Enabled (1UL) /*!< RR[4] register is enabled. */
+
+/* Bit 3 : Enable or disable RR[3] register. */
+#define WDT_RREN_RR3_Pos (3UL) /*!< Position of RR3 field. */
+#define WDT_RREN_RR3_Msk (0x1UL << WDT_RREN_RR3_Pos) /*!< Bit mask of RR3 field. */
+#define WDT_RREN_RR3_Disabled (0UL) /*!< RR[3] register is disabled. */
+#define WDT_RREN_RR3_Enabled (1UL) /*!< RR[3] register is enabled. */
+
+/* Bit 2 : Enable or disable RR[2] register. */
+#define WDT_RREN_RR2_Pos (2UL) /*!< Position of RR2 field. */
+#define WDT_RREN_RR2_Msk (0x1UL << WDT_RREN_RR2_Pos) /*!< Bit mask of RR2 field. */
+#define WDT_RREN_RR2_Disabled (0UL) /*!< RR[2] register is disabled. */
+#define WDT_RREN_RR2_Enabled (1UL) /*!< RR[2] register is enabled. */
+
+/* Bit 1 : Enable or disable RR[1] register. */
+#define WDT_RREN_RR1_Pos (1UL) /*!< Position of RR1 field. */
+#define WDT_RREN_RR1_Msk (0x1UL << WDT_RREN_RR1_Pos) /*!< Bit mask of RR1 field. */
+#define WDT_RREN_RR1_Disabled (0UL) /*!< RR[1] register is disabled. */
+#define WDT_RREN_RR1_Enabled (1UL) /*!< RR[1] register is enabled. */
+
+/* Bit 0 : Enable or disable RR[0] register. */
+#define WDT_RREN_RR0_Pos (0UL) /*!< Position of RR0 field. */
+#define WDT_RREN_RR0_Msk (0x1UL << WDT_RREN_RR0_Pos) /*!< Bit mask of RR0 field. */
+#define WDT_RREN_RR0_Disabled (0UL) /*!< RR[0] register is disabled. */
+#define WDT_RREN_RR0_Enabled (1UL) /*!< RR[0] register is enabled. */
+
+/* Register: WDT_CONFIG */
+/* Description: Configuration register. */
+
+/* Bit 3 : Configure the watchdog to pause or not while the CPU is halted by the debugger. */
+#define WDT_CONFIG_HALT_Pos (3UL) /*!< Position of HALT field. */
+#define WDT_CONFIG_HALT_Msk (0x1UL << WDT_CONFIG_HALT_Pos) /*!< Bit mask of HALT field. */
+#define WDT_CONFIG_HALT_Pause (0UL) /*!< Pause watchdog while the CPU is halted by the debugger. */
+#define WDT_CONFIG_HALT_Run (1UL) /*!< Do not pause watchdog while the CPU is halted by the debugger. */
+
+/* Bit 0 : Configure the watchdog to pause or not while the CPU is sleeping. */
+#define WDT_CONFIG_SLEEP_Pos (0UL) /*!< Position of SLEEP field. */
+#define WDT_CONFIG_SLEEP_Msk (0x1UL << WDT_CONFIG_SLEEP_Pos) /*!< Bit mask of SLEEP field. */
+#define WDT_CONFIG_SLEEP_Pause (0UL) /*!< Pause watchdog while the CPU is asleep. */
+#define WDT_CONFIG_SLEEP_Run (1UL) /*!< Do not pause watchdog while the CPU is asleep. */
+
+/* Register: WDT_RR */
+/* Description: Reload requests registers. */
+
+/* Bits 31..0 : Reload register. */
+#define WDT_RR_RR_Pos (0UL) /*!< Position of RR field. */
+#define WDT_RR_RR_Msk (0xFFFFFFFFUL << WDT_RR_RR_Pos) /*!< Bit mask of RR field. */
+#define WDT_RR_RR_Reload (0x6E524635UL) /*!< Value to request a reload of the watchdog timer. */
+
+/* Register: WDT_POWER */
+/* Description: Peripheral power control. */
+
+/* Bit 0 : Peripheral power control. */
+#define WDT_POWER_POWER_Pos (0UL) /*!< Position of POWER field. */
+#define WDT_POWER_POWER_Msk (0x1UL << WDT_POWER_POWER_Pos) /*!< Bit mask of POWER field. */
+#define WDT_POWER_POWER_Disabled (0UL) /*!< Module power disabled. */
+#define WDT_POWER_POWER_Enabled (1UL) /*!< Module power enabled. */
+
+
+/*lint --flb "Leave library region" */
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/device/nrf51_deprecated.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/device/nrf51_deprecated.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,440 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef NRF51_DEPRECATED_H
+#define NRF51_DEPRECATED_H
+
+/*lint ++flb "Enter library region */
+
+/* This file is given to prevent your SW from not compiling with the updates made to nrf51.h and 
+ * nrf51_bitfields.h. The macros defined in this file were available previously. Do not use these
+ * macros on purpose. Use the ones defined in nrf51.h and nrf51_bitfields.h instead.
+ */
+
+/* NVMC */
+/* The register ERASEPROTECTEDPAGE is called ERASEPCR0 in the documentation. */
+#define ERASEPROTECTEDPAGE   ERASEPCR0
+
+ 
+/* LPCOMP */
+/* The interrupt ISR was renamed. Adding old name to the macros. */
+#define LPCOMP_COMP_IRQHandler      LPCOMP_IRQHandler
+#define LPCOMP_COMP_IRQn            LPCOMP_IRQn
+ 
+ 
+/* MPU */
+/* The field MPU.PERR0.LPCOMP_COMP was renamed. Added into deprecated in case somebody was using the macros defined for it. */
+#define MPU_PERR0_LPCOMP_COMP_Pos           MPU_PERR0_LPCOMP_Pos
+#define MPU_PERR0_LPCOMP_COMP_Msk           MPU_PERR0_LPCOMP_Msk
+#define MPU_PERR0_LPCOMP_COMP_InRegion1     MPU_PERR0_LPCOMP_InRegion1
+#define MPU_PERR0_LPCOMP_COMP_InRegion0     MPU_PERR0_LPCOMP_InRegion0
+ 
+ 
+/* POWER */
+/* The field POWER.RAMON.OFFRAM3 was eliminated. Added into deprecated in case somebody was using the macros defined for it. */
+#define POWER_RAMON_OFFRAM3_Pos         (19UL)                                  
+#define POWER_RAMON_OFFRAM3_Msk         (0x1UL << POWER_RAMON_OFFRAM3_Pos)      
+#define POWER_RAMON_OFFRAM3_RAM3Off     (0UL)                                   
+#define POWER_RAMON_OFFRAM3_RAM3On      (1UL)                                   
+/* The field POWER.RAMON.OFFRAM2 was eliminated. Added into deprecated in case somebody was using the macros defined for it. */
+#define POWER_RAMON_OFFRAM2_Pos         (18UL)                                  
+#define POWER_RAMON_OFFRAM2_Msk         (0x1UL << POWER_RAMON_OFFRAM2_Pos)      
+#define POWER_RAMON_OFFRAM2_RAM2Off     (0UL)                                   
+#define POWER_RAMON_OFFRAM2_RAM2On      (1UL)                                  
+/* The field POWER.RAMON.ONRAM3 was eliminated. Added into deprecated in case somebody was using the macros defined for it. */
+#define POWER_RAMON_ONRAM3_Pos          (3UL)                                  
+#define POWER_RAMON_ONRAM3_Msk          (0x1UL << POWER_RAMON_ONRAM3_Pos)      
+#define POWER_RAMON_ONRAM3_RAM3Off      (0UL)                                  
+#define POWER_RAMON_ONRAM3_RAM3On       (1UL)                                  
+/* The field POWER.RAMON.ONRAM2 was eliminated. Added into deprecated in case somebody was using the macros defined for it. */
+#define POWER_RAMON_ONRAM2_Pos          (2UL)                                  
+#define POWER_RAMON_ONRAM2_Msk          (0x1UL << POWER_RAMON_ONRAM2_Pos)       
+#define POWER_RAMON_ONRAM2_RAM2Off      (0UL)                                  
+#define POWER_RAMON_ONRAM2_RAM2On       (1UL)                                 
+
+ 
+/* RADIO */
+/* The enumerated value RADIO.TXPOWER.TXPOWER.Neg40dBm was renamed. Added into deprecated with the new macro name. */
+#define RADIO_TXPOWER_TXPOWER_Neg40dBm  RADIO_TXPOWER_TXPOWER_Neg30dBm      
+/* The name of the field SKIPADDR was corrected. Old macros added for compatibility. */
+#define RADIO_CRCCNF_SKIP_ADDR_Pos      RADIO_CRCCNF_SKIPADDR_Pos 
+#define RADIO_CRCCNF_SKIP_ADDR_Msk      RADIO_CRCCNF_SKIPADDR_Msk 
+#define RADIO_CRCCNF_SKIP_ADDR_Include  RADIO_CRCCNF_SKIPADDR_Include 
+#define RADIO_CRCCNF_SKIP_ADDR_Skip     RADIO_CRCCNF_SKIPADDR_Skip 
+/* The name of the field PLLLOCK was corrected. Old macros added for compatibility. */
+#define RADIO_TEST_PLL_LOCK_Pos         RADIO_TEST_PLLLOCK_Pos 
+#define RADIO_TEST_PLL_LOCK_Msk         RADIO_TEST_PLLLOCK_Msk 
+#define RADIO_TEST_PLL_LOCK_Disabled    RADIO_TEST_PLLLOCK_Disabled 
+#define RADIO_TEST_PLL_LOCK_Enabled     RADIO_TEST_PLLLOCK_Enabled 
+/* The name of the field CONSTCARRIER was corrected. Old macros added for compatibility. */
+#define RADIO_TEST_CONST_CARRIER_Pos        RADIO_TEST_CONSTCARRIER_Pos 
+#define RADIO_TEST_CONST_CARRIER_Msk        RADIO_TEST_CONSTCARRIER_Msk 
+#define RADIO_TEST_CONST_CARRIER_Disabled   RADIO_TEST_CONSTCARRIER_Disabled 
+#define RADIO_TEST_CONST_CARRIER_Enabled    RADIO_TEST_CONSTCARRIER_Enabled 
+
+
+/* FICR */
+/* The registers FICR.SIZERAMBLOCK0, FICR.SIZERAMBLOCK1, FICR.SIZERAMBLOCK2 and FICR.SIZERAMBLOCK3 were renamed into an array. */
+#define SIZERAMBLOCK0   SIZERAMBLOCKS                   
+#define SIZERAMBLOCK1   SIZERAMBLOCKS                   
+#define SIZERAMBLOCK2   SIZERAMBLOCK[2]                 /*!< Note that this macro will disapear when SIZERAMBLOCK array is eliminated. SIZERAMBLOCK is a deprecated array. */
+#define SIZERAMBLOCK3   SIZERAMBLOCK[3]                 /*!< Note that this macro will disapear when SIZERAMBLOCK array is eliminated. SIZERAMBLOCK is a deprecated array. */
+/* The registers FICR.DEVICEID0 and FICR.DEVICEID1 were renamed into an array. */
+#define DEVICEID0       DEVICEID[0]                     
+#define DEVICEID1       DEVICEID[1]                     
+/* The registers FICR.ER0, FICR.ER1, FICR.ER2 and FICR.ER3 were renamed into an array. */
+#define ER0             ER[0]                           
+#define ER1             ER[1]                          
+#define ER2             ER[2]                       
+#define ER3             ER[3]                      
+/* The registers FICR.IR0, FICR.IR1, FICR.IR2 and FICR.IR3 were renamed into an array. */
+#define IR0             IR[0]                         
+#define IR1             IR[1]                         
+#define IR2             IR[2]                         
+#define IR3             IR[3]                          
+/* The registers FICR.DEVICEADDR0 and FICR.DEVICEADDR1 were renamed into an array. */
+#define DEVICEADDR0     DEVICEADDR[0]                  
+#define DEVICEADDR1     DEVICEADDR[1]                  
+
+
+/* PPI */
+/* The tasks PPI.TASKS_CHGxEN and PPI.TASKS_CHGxDIS were renamed into an array of structs. */
+#define TASKS_CHG0EN     TASKS_CHG[0].EN                    
+#define TASKS_CHG0DIS    TASKS_CHG[0].DIS                  
+#define TASKS_CHG1EN     TASKS_CHG[1].EN                    
+#define TASKS_CHG1DIS    TASKS_CHG[1].DIS                  
+#define TASKS_CHG2EN     TASKS_CHG[2].EN                   
+#define TASKS_CHG2DIS    TASKS_CHG[2].DIS                  
+#define TASKS_CHG3EN     TASKS_CHG[3].EN                    
+#define TASKS_CHG3DIS    TASKS_CHG[3].DIS                  
+/* The registers PPI.CHx_EEP and PPI.CHx_TEP were renamed into an array of structs. */
+#define CH0_EEP          CH[0].EEP                          
+#define CH0_TEP          CH[0].TEP                          
+#define CH1_EEP          CH[1].EEP                         
+#define CH1_TEP          CH[1].TEP                         
+#define CH2_EEP          CH[2].EEP                          
+#define CH2_TEP          CH[2].TEP                         
+#define CH3_EEP          CH[3].EEP                          
+#define CH3_TEP          CH[3].TEP                         
+#define CH4_EEP          CH[4].EEP                         
+#define CH4_TEP          CH[4].TEP                         
+#define CH5_EEP          CH[5].EEP                          
+#define CH5_TEP          CH[5].TEP                          
+#define CH6_EEP          CH[6].EEP                          
+#define CH6_TEP          CH[6].TEP                         
+#define CH7_EEP          CH[7].EEP                          
+#define CH7_TEP          CH[7].TEP                          
+#define CH8_EEP          CH[8].EEP                         
+#define CH8_TEP          CH[8].TEP                          
+#define CH9_EEP          CH[9].EEP                          
+#define CH9_TEP          CH[9].TEP                          
+#define CH10_EEP         CH[10].EEP                         
+#define CH10_TEP         CH[10].TEP                         
+#define CH11_EEP         CH[11].EEP                         
+#define CH11_TEP         CH[11].TEP                         
+#define CH12_EEP         CH[12].EEP                         
+#define CH12_TEP         CH[12].TEP                         
+#define CH13_EEP         CH[13].EEP                         
+#define CH13_TEP         CH[13].TEP                         
+#define CH14_EEP         CH[14].EEP                         
+#define CH14_TEP         CH[14].TEP                         
+#define CH15_EEP         CH[15].EEP                         
+#define CH15_TEP         CH[15].TEP                        
+/* The registers PPI.CHG0, PPI.CHG1, PPI.CHG2 and PPI.CHG3 were renamed into an array. */
+#define CHG0             CHG[0]                            
+#define CHG1             CHG[1]                            
+#define CHG2             CHG[2]                             
+#define CHG3             CHG[3]                           
+/* All bitfield macros for the CHGx registers therefore changed name. */
+#define PPI_CHG0_CH15_Pos       PPI_CHG_CH15_Pos            
+#define PPI_CHG0_CH15_Msk       PPI_CHG_CH15_Msk            
+#define PPI_CHG0_CH15_Excluded  PPI_CHG_CH15_Excluded       
+#define PPI_CHG0_CH15_Included  PPI_CHG_CH15_Included       
+#define PPI_CHG0_CH14_Pos       PPI_CHG_CH14_Pos            
+#define PPI_CHG0_CH14_Msk       PPI_CHG_CH14_Msk           
+#define PPI_CHG0_CH14_Excluded  PPI_CHG_CH14_Excluded       
+#define PPI_CHG0_CH14_Included  PPI_CHG_CH14_Included       
+#define PPI_CHG0_CH13_Pos       PPI_CHG_CH13_Pos            
+#define PPI_CHG0_CH13_Msk       PPI_CHG_CH13_Msk            
+#define PPI_CHG0_CH13_Excluded  PPI_CHG_CH13_Excluded      
+#define PPI_CHG0_CH13_Included  PPI_CHG_CH13_Included       
+#define PPI_CHG0_CH12_Pos       PPI_CHG_CH12_Pos            
+#define PPI_CHG0_CH12_Msk       PPI_CHG_CH12_Msk            
+#define PPI_CHG0_CH12_Excluded  PPI_CHG_CH12_Excluded       
+#define PPI_CHG0_CH12_Included  PPI_CHG_CH12_Included       
+#define PPI_CHG0_CH11_Pos       PPI_CHG_CH11_Pos            
+#define PPI_CHG0_CH11_Msk       PPI_CHG_CH11_Msk            
+#define PPI_CHG0_CH11_Excluded  PPI_CHG_CH11_Excluded       
+#define PPI_CHG0_CH11_Included  PPI_CHG_CH11_Included       
+#define PPI_CHG0_CH10_Pos       PPI_CHG_CH10_Pos            
+#define PPI_CHG0_CH10_Msk       PPI_CHG_CH10_Msk            
+#define PPI_CHG0_CH10_Excluded  PPI_CHG_CH10_Excluded       
+#define PPI_CHG0_CH10_Included  PPI_CHG_CH10_Included       
+#define PPI_CHG0_CH9_Pos        PPI_CHG_CH9_Pos             
+#define PPI_CHG0_CH9_Msk        PPI_CHG_CH9_Msk             
+#define PPI_CHG0_CH9_Excluded   PPI_CHG_CH9_Excluded        
+#define PPI_CHG0_CH9_Included   PPI_CHG_CH9_Included        
+#define PPI_CHG0_CH8_Pos        PPI_CHG_CH8_Pos             
+#define PPI_CHG0_CH8_Msk        PPI_CHG_CH8_Msk             
+#define PPI_CHG0_CH8_Excluded   PPI_CHG_CH8_Excluded        
+#define PPI_CHG0_CH8_Included   PPI_CHG_CH8_Included        
+#define PPI_CHG0_CH7_Pos        PPI_CHG_CH7_Pos             
+#define PPI_CHG0_CH7_Msk        PPI_CHG_CH7_Msk             
+#define PPI_CHG0_CH7_Excluded   PPI_CHG_CH7_Excluded        
+#define PPI_CHG0_CH7_Included   PPI_CHG_CH7_Included        
+#define PPI_CHG0_CH6_Pos        PPI_CHG_CH6_Pos             
+#define PPI_CHG0_CH6_Msk        PPI_CHG_CH6_Msk             
+#define PPI_CHG0_CH6_Excluded   PPI_CHG_CH6_Excluded        
+#define PPI_CHG0_CH6_Included   PPI_CHG_CH6_Included        
+#define PPI_CHG0_CH5_Pos        PPI_CHG_CH5_Pos             
+#define PPI_CHG0_CH5_Msk        PPI_CHG_CH5_Msk             
+#define PPI_CHG0_CH5_Excluded   PPI_CHG_CH5_Excluded       
+#define PPI_CHG0_CH5_Included   PPI_CHG_CH5_Included        
+#define PPI_CHG0_CH4_Pos        PPI_CHG_CH4_Pos             
+#define PPI_CHG0_CH4_Msk        PPI_CHG_CH4_Msk             
+#define PPI_CHG0_CH4_Excluded   PPI_CHG_CH4_Excluded       
+#define PPI_CHG0_CH4_Included   PPI_CHG_CH4_Included       
+#define PPI_CHG0_CH3_Pos        PPI_CHG_CH3_Pos             
+#define PPI_CHG0_CH3_Msk        PPI_CHG_CH3_Msk            
+#define PPI_CHG0_CH3_Excluded   PPI_CHG_CH3_Excluded        
+#define PPI_CHG0_CH3_Included   PPI_CHG_CH3_Included       
+#define PPI_CHG0_CH2_Pos        PPI_CHG_CH2_Pos            
+#define PPI_CHG0_CH2_Msk        PPI_CHG_CH2_Msk             
+#define PPI_CHG0_CH2_Excluded   PPI_CHG_CH2_Excluded       
+#define PPI_CHG0_CH2_Included   PPI_CHG_CH2_Included       
+#define PPI_CHG0_CH1_Pos        PPI_CHG_CH1_Pos            
+#define PPI_CHG0_CH1_Msk        PPI_CHG_CH1_Msk            
+#define PPI_CHG0_CH1_Excluded   PPI_CHG_CH1_Excluded        
+#define PPI_CHG0_CH1_Included   PPI_CHG_CH1_Included       
+#define PPI_CHG0_CH0_Pos        PPI_CHG_CH0_Pos            
+#define PPI_CHG0_CH0_Msk        PPI_CHG_CH0_Msk            
+#define PPI_CHG0_CH0_Excluded   PPI_CHG_CH0_Excluded        
+#define PPI_CHG0_CH0_Included   PPI_CHG_CH0_Included       
+#define PPI_CHG1_CH15_Pos       PPI_CHG_CH15_Pos           
+#define PPI_CHG1_CH15_Msk       PPI_CHG_CH15_Msk           
+#define PPI_CHG1_CH15_Excluded  PPI_CHG_CH15_Excluded       
+#define PPI_CHG1_CH15_Included  PPI_CHG_CH15_Included      
+#define PPI_CHG1_CH14_Pos       PPI_CHG_CH14_Pos           
+#define PPI_CHG1_CH14_Msk       PPI_CHG_CH14_Msk            
+#define PPI_CHG1_CH14_Excluded  PPI_CHG_CH14_Excluded      
+#define PPI_CHG1_CH14_Included  PPI_CHG_CH14_Included       
+#define PPI_CHG1_CH13_Pos       PPI_CHG_CH13_Pos           
+#define PPI_CHG1_CH13_Msk       PPI_CHG_CH13_Msk            
+#define PPI_CHG1_CH13_Excluded  PPI_CHG_CH13_Excluded      
+#define PPI_CHG1_CH13_Included  PPI_CHG_CH13_Included      
+#define PPI_CHG1_CH12_Pos       PPI_CHG_CH12_Pos            
+#define PPI_CHG1_CH12_Msk       PPI_CHG_CH12_Msk           
+#define PPI_CHG1_CH12_Excluded  PPI_CHG_CH12_Excluded      
+#define PPI_CHG1_CH12_Included  PPI_CHG_CH12_Included      
+#define PPI_CHG1_CH11_Pos       PPI_CHG_CH11_Pos            
+#define PPI_CHG1_CH11_Msk       PPI_CHG_CH11_Msk           
+#define PPI_CHG1_CH11_Excluded  PPI_CHG_CH11_Excluded      
+#define PPI_CHG1_CH11_Included  PPI_CHG_CH11_Included      
+#define PPI_CHG1_CH10_Pos       PPI_CHG_CH10_Pos           
+#define PPI_CHG1_CH10_Msk       PPI_CHG_CH10_Msk            
+#define PPI_CHG1_CH10_Excluded  PPI_CHG_CH10_Excluded      
+#define PPI_CHG1_CH10_Included  PPI_CHG_CH10_Included      
+#define PPI_CHG1_CH9_Pos        PPI_CHG_CH9_Pos            
+#define PPI_CHG1_CH9_Msk        PPI_CHG_CH9_Msk            
+#define PPI_CHG1_CH9_Excluded   PPI_CHG_CH9_Excluded       
+#define PPI_CHG1_CH9_Included   PPI_CHG_CH9_Included       
+#define PPI_CHG1_CH8_Pos        PPI_CHG_CH8_Pos            
+#define PPI_CHG1_CH8_Msk        PPI_CHG_CH8_Msk            
+#define PPI_CHG1_CH8_Excluded   PPI_CHG_CH8_Excluded       
+#define PPI_CHG1_CH8_Included   PPI_CHG_CH8_Included       
+#define PPI_CHG1_CH7_Pos        PPI_CHG_CH7_Pos             
+#define PPI_CHG1_CH7_Msk        PPI_CHG_CH7_Msk            
+#define PPI_CHG1_CH7_Excluded   PPI_CHG_CH7_Excluded        
+#define PPI_CHG1_CH7_Included   PPI_CHG_CH7_Included       
+#define PPI_CHG1_CH6_Pos        PPI_CHG_CH6_Pos             
+#define PPI_CHG1_CH6_Msk        PPI_CHG_CH6_Msk            
+#define PPI_CHG1_CH6_Excluded   PPI_CHG_CH6_Excluded       
+#define PPI_CHG1_CH6_Included   PPI_CHG_CH6_Included       
+#define PPI_CHG1_CH5_Pos        PPI_CHG_CH5_Pos             
+#define PPI_CHG1_CH5_Msk        PPI_CHG_CH5_Msk             
+#define PPI_CHG1_CH5_Excluded   PPI_CHG_CH5_Excluded       
+#define PPI_CHG1_CH5_Included   PPI_CHG_CH5_Included        
+#define PPI_CHG1_CH4_Pos        PPI_CHG_CH4_Pos             
+#define PPI_CHG1_CH4_Msk        PPI_CHG_CH4_Msk             
+#define PPI_CHG1_CH4_Excluded   PPI_CHG_CH4_Excluded        
+#define PPI_CHG1_CH4_Included   PPI_CHG_CH4_Included        
+#define PPI_CHG1_CH3_Pos        PPI_CHG_CH3_Pos            
+#define PPI_CHG1_CH3_Msk        PPI_CHG_CH3_Msk             
+#define PPI_CHG1_CH3_Excluded   PPI_CHG_CH3_Excluded        
+#define PPI_CHG1_CH3_Included   PPI_CHG_CH3_Included       
+#define PPI_CHG1_CH2_Pos        PPI_CHG_CH2_Pos            
+#define PPI_CHG1_CH2_Msk        PPI_CHG_CH2_Msk             
+#define PPI_CHG1_CH2_Excluded   PPI_CHG_CH2_Excluded        
+#define PPI_CHG1_CH2_Included   PPI_CHG_CH2_Included        
+#define PPI_CHG1_CH1_Pos        PPI_CHG_CH1_Pos             
+#define PPI_CHG1_CH1_Msk        PPI_CHG_CH1_Msk            
+#define PPI_CHG1_CH1_Excluded   PPI_CHG_CH1_Excluded        
+#define PPI_CHG1_CH1_Included   PPI_CHG_CH1_Included       
+#define PPI_CHG1_CH0_Pos        PPI_CHG_CH0_Pos             
+#define PPI_CHG1_CH0_Msk        PPI_CHG_CH0_Msk            
+#define PPI_CHG1_CH0_Excluded   PPI_CHG_CH0_Excluded       
+#define PPI_CHG1_CH0_Included   PPI_CHG_CH0_Included       
+#define PPI_CHG2_CH15_Pos       PPI_CHG_CH15_Pos           
+#define PPI_CHG2_CH15_Msk       PPI_CHG_CH15_Msk            
+#define PPI_CHG2_CH15_Excluded  PPI_CHG_CH15_Excluded      
+#define PPI_CHG2_CH15_Included  PPI_CHG_CH15_Included      
+#define PPI_CHG2_CH14_Pos       PPI_CHG_CH14_Pos           
+#define PPI_CHG2_CH14_Msk       PPI_CHG_CH14_Msk           
+#define PPI_CHG2_CH14_Excluded  PPI_CHG_CH14_Excluded       
+#define PPI_CHG2_CH14_Included  PPI_CHG_CH14_Included      
+#define PPI_CHG2_CH13_Pos       PPI_CHG_CH13_Pos           
+#define PPI_CHG2_CH13_Msk       PPI_CHG_CH13_Msk            
+#define PPI_CHG2_CH13_Excluded  PPI_CHG_CH13_Excluded       
+#define PPI_CHG2_CH13_Included  PPI_CHG_CH13_Included      
+#define PPI_CHG2_CH12_Pos       PPI_CHG_CH12_Pos            
+#define PPI_CHG2_CH12_Msk       PPI_CHG_CH12_Msk            
+#define PPI_CHG2_CH12_Excluded  PPI_CHG_CH12_Excluded      
+#define PPI_CHG2_CH12_Included  PPI_CHG_CH12_Included       
+#define PPI_CHG2_CH11_Pos       PPI_CHG_CH11_Pos           
+#define PPI_CHG2_CH11_Msk       PPI_CHG_CH11_Msk           
+#define PPI_CHG2_CH11_Excluded  PPI_CHG_CH11_Excluded       
+#define PPI_CHG2_CH11_Included  PPI_CHG_CH11_Included       
+#define PPI_CHG2_CH10_Pos       PPI_CHG_CH10_Pos            
+#define PPI_CHG2_CH10_Msk       PPI_CHG_CH10_Msk            
+#define PPI_CHG2_CH10_Excluded  PPI_CHG_CH10_Excluded      
+#define PPI_CHG2_CH10_Included  PPI_CHG_CH10_Included      
+#define PPI_CHG2_CH9_Pos        PPI_CHG_CH9_Pos            
+#define PPI_CHG2_CH9_Msk        PPI_CHG_CH9_Msk            
+#define PPI_CHG2_CH9_Excluded   PPI_CHG_CH9_Excluded        
+#define PPI_CHG2_CH9_Included   PPI_CHG_CH9_Included       
+#define PPI_CHG2_CH8_Pos        PPI_CHG_CH8_Pos            
+#define PPI_CHG2_CH8_Msk        PPI_CHG_CH8_Msk            
+#define PPI_CHG2_CH8_Excluded   PPI_CHG_CH8_Excluded       
+#define PPI_CHG2_CH8_Included   PPI_CHG_CH8_Included        
+#define PPI_CHG2_CH7_Pos        PPI_CHG_CH7_Pos            
+#define PPI_CHG2_CH7_Msk        PPI_CHG_CH7_Msk            
+#define PPI_CHG2_CH7_Excluded   PPI_CHG_CH7_Excluded       
+#define PPI_CHG2_CH7_Included   PPI_CHG_CH7_Included       
+#define PPI_CHG2_CH6_Pos        PPI_CHG_CH6_Pos            
+#define PPI_CHG2_CH6_Msk        PPI_CHG_CH6_Msk            
+#define PPI_CHG2_CH6_Excluded   PPI_CHG_CH6_Excluded       
+#define PPI_CHG2_CH6_Included   PPI_CHG_CH6_Included       
+#define PPI_CHG2_CH5_Pos        PPI_CHG_CH5_Pos            
+#define PPI_CHG2_CH5_Msk        PPI_CHG_CH5_Msk            
+#define PPI_CHG2_CH5_Excluded   PPI_CHG_CH5_Excluded       
+#define PPI_CHG2_CH5_Included   PPI_CHG_CH5_Included        
+#define PPI_CHG2_CH4_Pos        PPI_CHG_CH4_Pos             
+#define PPI_CHG2_CH4_Msk        PPI_CHG_CH4_Msk             
+#define PPI_CHG2_CH4_Excluded   PPI_CHG_CH4_Excluded        
+#define PPI_CHG2_CH4_Included   PPI_CHG_CH4_Included       
+#define PPI_CHG2_CH3_Pos        PPI_CHG_CH3_Pos            
+#define PPI_CHG2_CH3_Msk        PPI_CHG_CH3_Msk            
+#define PPI_CHG2_CH3_Excluded   PPI_CHG_CH3_Excluded       
+#define PPI_CHG2_CH3_Included   PPI_CHG_CH3_Included       
+#define PPI_CHG2_CH2_Pos        PPI_CHG_CH2_Pos            
+#define PPI_CHG2_CH2_Msk        PPI_CHG_CH2_Msk           
+#define PPI_CHG2_CH2_Excluded   PPI_CHG_CH2_Excluded       
+#define PPI_CHG2_CH2_Included   PPI_CHG_CH2_Included       
+#define PPI_CHG2_CH1_Pos        PPI_CHG_CH1_Pos             
+#define PPI_CHG2_CH1_Msk        PPI_CHG_CH1_Msk             
+#define PPI_CHG2_CH1_Excluded   PPI_CHG_CH1_Excluded       
+#define PPI_CHG2_CH1_Included   PPI_CHG_CH1_Included       
+#define PPI_CHG2_CH0_Pos        PPI_CHG_CH0_Pos            
+#define PPI_CHG2_CH0_Msk        PPI_CHG_CH0_Msk            
+#define PPI_CHG2_CH0_Excluded   PPI_CHG_CH0_Excluded       
+#define PPI_CHG2_CH0_Included   PPI_CHG_CH0_Included        
+#define PPI_CHG3_CH15_Pos       PPI_CHG_CH15_Pos           
+#define PPI_CHG3_CH15_Msk       PPI_CHG_CH15_Msk           
+#define PPI_CHG3_CH15_Excluded  PPI_CHG_CH15_Excluded     
+#define PPI_CHG3_CH15_Included  PPI_CHG_CH15_Included      
+#define PPI_CHG3_CH14_Pos       PPI_CHG_CH14_Pos          
+#define PPI_CHG3_CH14_Msk       PPI_CHG_CH14_Msk           
+#define PPI_CHG3_CH14_Excluded  PPI_CHG_CH14_Excluded      
+#define PPI_CHG3_CH14_Included  PPI_CHG_CH14_Included       
+#define PPI_CHG3_CH13_Pos       PPI_CHG_CH13_Pos           
+#define PPI_CHG3_CH13_Msk       PPI_CHG_CH13_Msk            
+#define PPI_CHG3_CH13_Excluded  PPI_CHG_CH13_Excluded      
+#define PPI_CHG3_CH13_Included  PPI_CHG_CH13_Included      
+#define PPI_CHG3_CH12_Pos       PPI_CHG_CH12_Pos            
+#define PPI_CHG3_CH12_Msk       PPI_CHG_CH12_Msk            
+#define PPI_CHG3_CH12_Excluded  PPI_CHG_CH12_Excluded       
+#define PPI_CHG3_CH12_Included  PPI_CHG_CH12_Included       
+#define PPI_CHG3_CH11_Pos       PPI_CHG_CH11_Pos            
+#define PPI_CHG3_CH11_Msk       PPI_CHG_CH11_Msk            
+#define PPI_CHG3_CH11_Excluded  PPI_CHG_CH11_Excluded      
+#define PPI_CHG3_CH11_Included  PPI_CHG_CH11_Included       
+#define PPI_CHG3_CH10_Pos       PPI_CHG_CH10_Pos            
+#define PPI_CHG3_CH10_Msk       PPI_CHG_CH10_Msk            
+#define PPI_CHG3_CH10_Excluded  PPI_CHG_CH10_Excluded      
+#define PPI_CHG3_CH10_Included  PPI_CHG_CH10_Included      
+#define PPI_CHG3_CH9_Pos        PPI_CHG_CH9_Pos            
+#define PPI_CHG3_CH9_Msk        PPI_CHG_CH9_Msk            
+#define PPI_CHG3_CH9_Excluded   PPI_CHG_CH9_Excluded       
+#define PPI_CHG3_CH9_Included   PPI_CHG_CH9_Included       
+#define PPI_CHG3_CH8_Pos        PPI_CHG_CH8_Pos            
+#define PPI_CHG3_CH8_Msk        PPI_CHG_CH8_Msk             
+#define PPI_CHG3_CH8_Excluded   PPI_CHG_CH8_Excluded       
+#define PPI_CHG3_CH8_Included   PPI_CHG_CH8_Included       
+#define PPI_CHG3_CH7_Pos        PPI_CHG_CH7_Pos             
+#define PPI_CHG3_CH7_Msk        PPI_CHG_CH7_Msk            
+#define PPI_CHG3_CH7_Excluded   PPI_CHG_CH7_Excluded        
+#define PPI_CHG3_CH7_Included   PPI_CHG_CH7_Included       
+#define PPI_CHG3_CH6_Pos        PPI_CHG_CH6_Pos             
+#define PPI_CHG3_CH6_Msk        PPI_CHG_CH6_Msk             
+#define PPI_CHG3_CH6_Excluded   PPI_CHG_CH6_Excluded       
+#define PPI_CHG3_CH6_Included   PPI_CHG_CH6_Included        
+#define PPI_CHG3_CH5_Pos        PPI_CHG_CH5_Pos             
+#define PPI_CHG3_CH5_Msk        PPI_CHG_CH5_Msk             
+#define PPI_CHG3_CH5_Excluded   PPI_CHG_CH5_Excluded        
+#define PPI_CHG3_CH5_Included   PPI_CHG_CH5_Included       
+#define PPI_CHG3_CH4_Pos        PPI_CHG_CH4_Pos             
+#define PPI_CHG3_CH4_Msk        PPI_CHG_CH4_Msk            
+#define PPI_CHG3_CH4_Excluded   PPI_CHG_CH4_Excluded        
+#define PPI_CHG3_CH4_Included   PPI_CHG_CH4_Included        
+#define PPI_CHG3_CH3_Pos        PPI_CHG_CH3_Pos             
+#define PPI_CHG3_CH3_Msk        PPI_CHG_CH3_Msk            
+#define PPI_CHG3_CH3_Excluded   PPI_CHG_CH3_Excluded        
+#define PPI_CHG3_CH3_Included   PPI_CHG_CH3_Included        
+#define PPI_CHG3_CH2_Pos        PPI_CHG_CH2_Pos             
+#define PPI_CHG3_CH2_Msk        PPI_CHG_CH2_Msk             
+#define PPI_CHG3_CH2_Excluded   PPI_CHG_CH2_Excluded        
+#define PPI_CHG3_CH2_Included   PPI_CHG_CH2_Included       
+#define PPI_CHG3_CH1_Pos        PPI_CHG_CH1_Pos             
+#define PPI_CHG3_CH1_Msk        PPI_CHG_CH1_Msk             
+#define PPI_CHG3_CH1_Excluded   PPI_CHG_CH1_Excluded        
+#define PPI_CHG3_CH1_Included   PPI_CHG_CH1_Included        
+#define PPI_CHG3_CH0_Pos        PPI_CHG_CH0_Pos             
+#define PPI_CHG3_CH0_Msk        PPI_CHG_CH0_Msk             
+#define PPI_CHG3_CH0_Excluded   PPI_CHG_CH0_Excluded        
+#define PPI_CHG3_CH0_Included   PPI_CHG_CH0_Included        
+
+
+
+/*lint --flb "Leave library region" */
+
+#endif /* NRF51_DEPRECATED_H */
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "ble_flash.h"
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include "nrf_soc.h"
+#include "nordic_common.h"
+#include "nrf_error.h"
+#include "nrf.h"
+#include "app_util.h"
+
+
+static volatile bool m_radio_active = false;  /**< TRUE if radio is active (or about to become active), FALSE otherwise. */
+
+
+uint16_t ble_flash_crc16_compute(uint8_t * p_data, uint16_t size, uint16_t * p_crc)
+{
+    uint16_t i;
+    uint16_t crc = (p_crc == NULL) ? 0xffff : *p_crc;
+
+    for (i = 0; i < size; i++)
+    {
+        crc  = (unsigned char)(crc >> 8) | (crc << 8);
+        crc ^= p_data[i];
+        crc ^= (unsigned char)(crc & 0xff) >> 4;
+        crc ^= (crc << 8) << 4;
+        crc ^= ((crc & 0xff) << 4) << 1;
+    }
+    return crc;
+}
+
+
+/**@brief Function for erasing a page in flash.
+ * 
+ * @param[in]  p_page  Pointer to first word in page to be erased.
+ */
+static void flash_page_erase(uint32_t * p_page)
+{
+    // Turn on flash erase enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+
+    // Erase page.
+    NRF_NVMC->ERASEPAGE = (uint32_t)p_page;
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+
+    // Turn off flash erase enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing
+    }
+}
+
+
+/**@brief Function for writing one word to flash. Unprotected write, which can interfere with radio communication.
+ *
+ * @details This function DOES NOT use the m_radio_active variable, but will force the write even
+ *          when the radio is active. To be used only from @ref ble_flash_page_write.
+ *
+ * @note Flash location to be written must have been erased previously.
+ *
+ * @param[in]  p_address   Pointer to flash location to be written.
+ * @param[in]  value       Value to write to flash.
+ */
+static void flash_word_unprotected_write(uint32_t * p_address, uint32_t value)
+{
+    // Turn on flash write enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+    *p_address = value;
+    
+    // Wait flash write to finish
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+
+    // Turn off flash write enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+}
+
+
+/**@brief Function for writing one word to flash.
+ *
+ * @note Flash location to be written must have been erased previously.
+ *
+ * @param[in]  p_address   Pointer to flash location to be written.
+ * @param[in]  value       Value to write to flash.
+ */
+static void flash_word_write(uint32_t * p_address, uint32_t value)
+{
+    // If radio is active, wait for it to become inactive.
+    while (m_radio_active)
+    {
+        // Do nothing (just wait for radio to become inactive).
+        (void) sd_app_evt_wait();
+    }
+
+    // Turn on flash write enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+
+    *p_address = value;
+    // Wait flash write to finish
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing.
+    }
+    // Turn off flash write enable and wait until the NVMC is ready.
+    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+        // Do nothing
+    }
+}
+
+
+uint32_t ble_flash_word_write(uint32_t * p_address, uint32_t value)
+{
+    flash_word_write(p_address, value);
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_flash_block_write(uint32_t * p_address, uint32_t * p_in_array, uint16_t word_count)
+{
+    uint16_t i;
+
+    for (i = 0; i < word_count; i++)
+    {
+        flash_word_write(p_address, p_in_array[i]);
+        p_address++;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_flash_page_erase(uint8_t page_num)
+{
+    uint32_t * p_page = (uint32_t *)(BLE_FLASH_PAGE_SIZE * page_num);
+    flash_page_erase(p_page);
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_flash_page_write(uint8_t page_num, uint32_t * p_in_array, uint8_t word_count)
+{
+    int        i;
+    uint32_t * p_page;
+    uint32_t * p_curr_addr;
+    uint16_t   in_data_crc;
+    uint16_t   flash_crc;
+    uint32_t   flash_header;
+
+    p_page      = (uint32_t *)(BLE_FLASH_PAGE_SIZE * page_num);
+    p_curr_addr = p_page;
+
+    // Calculate CRC of the data to write.
+    in_data_crc = ble_flash_crc16_compute((uint8_t *)p_in_array,
+                                          word_count * sizeof(uint32_t),
+                                          NULL);
+
+    // Compare the calculated to the one in flash.
+    flash_header = *p_curr_addr;
+    flash_crc    = (uint16_t)flash_header;
+
+    if (flash_crc == in_data_crc)
+    {
+        // Data is the same as the data already stored in flash, return without modifying flash.
+        return NRF_SUCCESS;
+    }
+
+    // Erase flash page
+    flash_page_erase(p_page);
+
+    // Reserve space for magic number (for detecting if flash content is valid).
+    p_curr_addr++;
+
+    // Reserve space for saving word_count.
+    p_curr_addr++;
+
+    // Write data
+    for (i = 0; i < word_count; i++)
+    {
+        flash_word_unprotected_write(p_curr_addr, p_in_array[i]);
+        p_curr_addr++;
+    }
+
+    // Write number of elements.
+    flash_word_write(p_page + 1, (uint32_t)(word_count));
+
+    // Write magic number and CRC to indicate that flash content is valid.
+    flash_header = BLE_FLASH_MAGIC_NUMBER | (uint32_t)in_data_crc;
+    flash_word_write(p_page, flash_header);
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_flash_page_read(uint8_t page_num, uint32_t * p_out_array, uint8_t * p_word_count)
+{
+    int        byte_count;
+    uint32_t * p_page;
+    uint32_t * p_curr_addr;
+    uint32_t   flash_header;
+    uint32_t   calc_header;
+    uint16_t   calc_crc;
+    uint32_t   tmp;
+
+    p_page      = (uint32_t *)(BLE_FLASH_PAGE_SIZE * page_num);    
+    p_curr_addr = p_page;
+
+    // Check if block is valid
+    flash_header = *p_curr_addr;
+    tmp = flash_header & 0xFFFF0000;
+    if (tmp != BLE_FLASH_MAGIC_NUMBER)
+    {
+        *p_word_count = 0;
+        return NRF_ERROR_NOT_FOUND;
+    }
+    p_curr_addr++;
+
+    // Read number of elements
+    *p_word_count = (uint8_t)(*(p_curr_addr));
+    p_curr_addr++;
+
+    // Read data
+    byte_count = (*p_word_count) * sizeof(uint32_t);
+    memcpy(p_out_array, p_curr_addr, byte_count);
+
+    // Check CRC
+    calc_crc = ble_flash_crc16_compute((uint8_t *)p_out_array,
+                                       (*p_word_count) * sizeof(uint32_t),
+                                       NULL);
+    calc_header = BLE_FLASH_MAGIC_NUMBER | (uint32_t)calc_crc;
+
+    if (calc_header != flash_header)
+    {
+        return NRF_ERROR_NOT_FOUND;
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t ble_flash_page_addr(uint8_t page_num, uint32_t ** pp_page_addr)
+{
+    *pp_page_addr = (uint32_t *)(BLE_FLASH_PAGE_SIZE * page_num);
+    return NRF_SUCCESS;
+}
+
+
+void ble_flash_on_radio_active_evt(bool radio_active)
+{
+    m_radio_active = radio_active;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/ble_flash/ble_flash.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup ble_flash_module Flash Manager
+ * @{
+ * @ingroup ble_sdk_lib
+ * @brief Module for accessing flash memory.
+ *
+ * @details It contains functions for reading, writing and erasing one page in flash.
+ *
+ *          The module uses the first 32 bits of the flash page to write a magic number in order to
+ *          determine if the page has been written or not.
+ *
+ * @note Be careful not to use a page number in the SoftDevice area (which currently occupies the
+ *       range 0 to 127), or in your application space! In both cases, this would end up
+ *       with a hard fault.
+ */
+
+#ifndef BLE_FLASH_H__
+#define BLE_FLASH_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "nrf.h"
+
+#define BLE_FLASH_PAGE_SIZE     ((uint16_t)NRF_FICR->CODEPAGESIZE)  /**< Size of one flash page. */
+#define BLE_FLASH_MAGIC_NUMBER  0x45DE0000                          /**< Magic value to identify if flash contains valid data. */
+#define BLE_FLASH_EMPTY_MASK    0xFFFFFFFF                          /**< Bit mask that defines an empty address in flash. */
+
+
+/**@brief Macro for getting the end of the flash available for application.
+ * 
+ * @details    The result flash page number indicates the end boundary of the flash available 
+ *             to the application. If a bootloader is used, the end will be the start of the 
+ *             bootloader region. Otherwise, the end will be the size of the flash. 
+ */
+#define BLE_FLASH_PAGE_END \
+    ((NRF_UICR->BOOTLOADERADDR != BLE_FLASH_EMPTY_MASK) \
+        ? (NRF_UICR->BOOTLOADERADDR / BLE_FLASH_PAGE_SIZE) \
+        : NRF_FICR->CODESIZE)
+
+/**@brief Function for erasing the specified flash page, and then writes the given data to this page.
+ *
+ * @warning This operation blocks the CPU. DO NOT use while in a connection!
+ *
+ * @param[in]  page_num     Page number to update.
+ * @param[in]  p_in_array   Pointer to a RAM area containing the elements to write in flash.
+ *                          This area has to be 32 bits aligned.
+ * @param[in]  word_count   Number of 32 bits words to write in flash.
+ *
+ * @return     NRF_SUCCESS on successful flash write, otherwise an error code.
+ */
+uint32_t ble_flash_page_write(uint8_t page_num, uint32_t * p_in_array, uint8_t word_count);
+
+/**@brief Function for reading data from flash to RAM.
+ *
+ * @param[in]  page_num       Page number to read.
+ * @param[out] p_out_array    Pointer to a RAM area where the found data will be written. 
+ *                            This area has to be 32 bits aligned.
+ * @param[out] p_word_count   Number of 32 bits words read.
+ *
+ * @return     NRF_SUCCESS on successful upload, NRF_ERROR_NOT_FOUND if no valid data has been found
+ *             in flash (first 32 bits not equal to the MAGIC_NUMBER+CRC).
+ */
+uint32_t ble_flash_page_read(uint8_t page_num, uint32_t * p_out_array, uint8_t * p_word_count);
+
+/**@brief Function for erasing a flash page.
+ *
+ * @note This operation blocks the CPU, so it should not be done while the radio is running!
+ *
+ * @param[in]  page_num   Page number to erase.
+ *
+ * @return     NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t ble_flash_page_erase(uint8_t page_num);
+
+/**@brief Function for writing one word to flash.
+ *
+ * @note Flash location to be written must have been erased previously.
+ *
+ * @param[in]  p_address   Pointer to flash location to be written.
+ * @param[in]  value       Value to write to flash.
+ *
+ * @return     NRF_SUCCESS.
+ */
+uint32_t ble_flash_word_write(uint32_t * p_address, uint32_t value);
+
+/**@brief Function for writing a data block to flash.
+ *
+ * @note Flash locations to be written must have been erased previously.
+ *
+ * @param[in]  p_address    Pointer to start of flash location to be written.
+ * @param[in]  p_in_array   Pointer to start of flash block to be written.
+ * @param[in]  word_count   Number of words to be written.
+ *
+ * @return     NRF_SUCCESS.
+ */
+uint32_t ble_flash_block_write(uint32_t * p_address, uint32_t * p_in_array, uint16_t word_count);
+
+/**@brief Function for computing pointer to start of specified flash page.
+ *
+ * @param[in]  page_num       Page number.
+ * @param[out] pp_page_addr   Pointer to start of flash page.
+ *
+ * @return     NRF_SUCCESS.
+ */
+uint32_t ble_flash_page_addr(uint8_t page_num, uint32_t ** pp_page_addr);
+
+/**@brief Function for calculating a 16 bit CRC using the CRC-16-CCITT scheme.
+ * 
+ * @param[in]  p_data   Pointer to data on which the CRC is to be calulated.
+ * @param[in]  size     Number of bytes on which the CRC is to be calulated.
+ * @param[in]  p_crc    Initial CRC value (if NULL, a preset value is used as the initial value).
+ *
+ * @return     Calculated CRC.
+ */
+uint16_t ble_flash_crc16_compute(uint8_t * p_data, uint16_t size, uint16_t * p_crc);
+
+/**@brief Function for handling flashing module Radio Notification event.
+ *
+ * @note For flash writing to work safely while in a connection or while advertising, this function
+ *       MUST be called from the Radio Notification module's event handler (see
+ *       @ref ble_radio_notification for details).
+ *
+ * @param[in]  radio_active   TRUE if radio is active (or about to become active), FALSE otherwise.
+ */
+void ble_flash_on_radio_active_evt(bool radio_active);
+
+#endif // BLE_FLASH_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+#include <stdio.h> 
+#include "compiler_abstraction.h"
+#include "nrf.h"
+#include "nrf_delay.h"
+
+/*lint --e{438} "Variable not used" */
+void nrf_delay_ms(uint32_t volatile number_of_ms)
+{
+    while(number_of_ms != 0)
+    {
+        number_of_ms--;
+        nrf_delay_us(999);
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/delay/nrf_delay.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef _NRF_DELAY_H
+#define _NRF_DELAY_H
+
+#include "nrf.h"
+
+/**
+ * @brief Function for delaying execution for number of microseconds.
+ *
+ * @note NRF52 has instruction cache and because of that delay is not precise.
+ *
+ * @param number_of_ms
+ */
+/*lint --e{438, 522} "Variable not used" "Function lacks side-effects" */
+#if defined ( __CC_ARM   )
+
+static __ASM void __INLINE nrf_delay_us(uint32_t volatile number_of_us)
+{
+loop
+        SUBS    R0, R0, #1
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+#ifdef NRF52
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+        NOP
+#endif
+        BNE    loop
+        BX     LR
+}
+
+#elif defined ( __ICCARM__ )
+
+static void __INLINE nrf_delay_us(uint32_t volatile number_of_us)
+{
+__ASM (
+"loop:\n\t"
+       " SUBS R0, R0, #1\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+       " NOP\n\t"
+#ifdef NRF52
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+        " NOP\n\t"
+#endif
+       " BNE.n loop\n\t");
+}
+
+#elif defined ( _WIN32 ) || defined ( __unix ) || defined( __APPLE__ )
+
+__STATIC_INLINE void nrf_delay_us(uint32_t volatile number_of_us);
+
+#ifndef CUSTOM_NRF_DELAY_US
+__STATIC_INLINE void nrf_delay_us(uint32_t volatile number_of_us)
+{}
+#endif
+
+#elif defined ( __GNUC__ )
+
+static void __INLINE nrf_delay_us(uint32_t volatile number_of_us) __attribute__((always_inline));
+static void __INLINE nrf_delay_us(uint32_t volatile number_of_us)
+{
+register uint32_t delay __ASM ("r0") = number_of_us;
+__ASM volatile (
+#ifdef NRF51
+        ".syntax unified\n"
+#endif
+    "1:\n"
+    " SUBS %0, %0, #1\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"   
+    " NOP\n"  
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+#ifdef NRF52
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+    " NOP\n"
+#endif
+    " BNE 1b\n"
+#ifdef NRF51
+    ".syntax divided\n"
+#endif
+    : "+r" (delay));
+}
+#endif
+
+void nrf_delay_ms(uint32_t volatile number_of_ms);
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */ 
+
+/** 
+ * @file
+ * @brief Implementation of AES ECB driver
+ */
+
+
+//lint -e438
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include "nrf.h" 
+#include "nrf_ecb.h"
+
+static uint8_t  ecb_data[48];   ///< ECB data structure for RNG peripheral to access.
+static uint8_t* ecb_key;        ///< Key:        Starts at ecb_data 
+static uint8_t* ecb_cleartext;  ///< Cleartext:  Starts at ecb_data + 16 bytes.
+static uint8_t* ecb_ciphertext; ///< Ciphertext: Starts at ecb_data + 32 bytes.
+
+bool nrf_ecb_init(void)
+{
+  ecb_key = ecb_data;
+  ecb_cleartext  = ecb_data + 16;
+  ecb_ciphertext = ecb_data + 32;
+
+  NRF_ECB->ECBDATAPTR = (uint32_t)ecb_data;
+  return true;
+}
+
+
+bool nrf_ecb_crypt(uint8_t * dest_buf, const uint8_t * src_buf)
+{
+   uint32_t counter = 0x1000000;
+   if(src_buf != ecb_cleartext)
+   {
+     memcpy(ecb_cleartext,src_buf,16);
+   }
+   NRF_ECB->EVENTS_ENDECB = 0;
+   NRF_ECB->TASKS_STARTECB = 1;
+   while(NRF_ECB->EVENTS_ENDECB == 0)
+   {
+    counter--;
+    if(counter == 0)
+    {
+      return false;
+    }
+   }
+   NRF_ECB->EVENTS_ENDECB = 0;
+   if(dest_buf != ecb_ciphertext)
+   {
+     memcpy(dest_buf,ecb_ciphertext,16);
+   }
+   return true;
+}
+
+void nrf_ecb_set_key(const uint8_t * key)
+{
+  memcpy(ecb_key,key,16);
+}
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_ecb.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * @file
+ * @brief ECB driver API.
+ */
+
+#ifndef NRF_ECB_H__
+#define NRF_ECB_H__
+
+/**
+ * @defgroup nrf_ecb AES ECB encryption
+ * @{
+ * @ingroup nrf_drivers
+ * @brief Driver for the AES Electronic Code Book (ECB) peripheral.
+ *
+ * To encrypt and decrypt data, the peripheral must first be powered on
+ * using @ref nrf_ecb_init. Next, the key must be set using @ref nrf_ecb_set_key.
+ */
+
+#include <stdint.h>
+
+/**
+ * @brief Function for initializing and powering on the ECB peripheral.
+ *
+ * This function allocates memory for the ECBDATAPTR.
+ * @retval true If initialization was successful.
+ * @retval false If powering on failed.
+ */
+bool nrf_ecb_init(void);
+
+/**
+ * @brief Function for encrypting and decrypting 16-byte data using current key.
+ *
+ * This function avoids unnecessary copying of data if the parameters point to the 
+ * correct locations in the ECB data structure.
+ *
+ * @param dst Result of encryption/decryption. 16 bytes will be written. 
+ * @param src Source with 16-byte data to be encrypted/decrypted.
+ *
+ * @retval true  If the encryption operation completed.
+ * @retval false If the encryption operation did not complete.
+ */
+bool nrf_ecb_crypt(uint8_t * dst, const uint8_t * src);
+
+/**
+ * @brief Function for setting the key to be used for encryption and decryption.
+ *
+ * @param key Pointer to the key. 16 bytes will be read.
+ */
+void nrf_ecb_set_key(const uint8_t * key);
+
+#endif  // NRF_ECB_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpio.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpio.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,667 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef NRF_GPIO_H__
+#define NRF_GPIO_H__
+
+#include "nrf.h"
+#include <stdbool.h>
+
+/**
+ * @defgroup nrf_gpio GPIO abstraction
+ * @{
+ * @ingroup nrf_drivers
+ * @brief GPIO pin abstraction and port abstraction for reading and writing byte-wise to GPIO ports.
+ *
+ * Here, the GPIO ports are defined as follows:
+ * - Port 0 -> pin 0-7
+ * - Port 1 -> pin 8-15
+ * - Port 2 -> pin 16-23
+ * - Port 3 -> pin 24-31
+ */
+
+#define NUMBER_OF_PINS 32
+
+/**
+ * @brief Enumerator used for selecting between port 0 - 3.
+ */
+typedef enum
+{
+    NRF_GPIO_PORT_SELECT_PORT0 = 0,           ///<  Port 0 (GPIO pin 0-7)
+    NRF_GPIO_PORT_SELECT_PORT1,               ///<  Port 1 (GPIO pin 8-15)
+    NRF_GPIO_PORT_SELECT_PORT2,               ///<  Port 2 (GPIO pin 16-23)
+    NRF_GPIO_PORT_SELECT_PORT3,               ///<  Port 3 (GPIO pin 24-31)
+} nrf_gpio_port_select_t;
+
+/**
+ * @brief Enumerator used for setting the direction of a GPIO port.
+ */
+typedef enum
+{
+    NRF_GPIO_PORT_DIR_OUTPUT,       ///<  Output
+    NRF_GPIO_PORT_DIR_INPUT         ///<  Input
+} nrf_gpio_port_dir_t;
+
+/**
+ * @brief Pin direction definitions.
+ */
+typedef enum
+{
+    NRF_GPIO_PIN_DIR_INPUT  = GPIO_PIN_CNF_DIR_Input,   ///< Input
+    NRF_GPIO_PIN_DIR_OUTPUT = GPIO_PIN_CNF_DIR_Output   ///< Output
+} nrf_gpio_pin_dir_t;
+
+/**
+ * @brief Connection of input buffer
+ */
+typedef enum
+{
+    NRF_GPIO_PIN_INPUT_CONNECT    = GPIO_PIN_CNF_INPUT_Connect,   ///< Connect input buffer
+    NRF_GPIO_PIN_INPUT_DISCONNECT = GPIO_PIN_CNF_INPUT_Disconnect ///< Disconnect input buffer
+} nrf_gpio_pin_input_t;
+
+/**
+ * @brief Enumerator used for selecting the pin to be pulled down or up at the time of pin configuration
+ */
+typedef enum
+{
+    NRF_GPIO_PIN_NOPULL   = GPIO_PIN_CNF_PULL_Disabled,                 ///<  Pin pullup resistor disabled
+    NRF_GPIO_PIN_PULLDOWN = GPIO_PIN_CNF_PULL_Pulldown,                 ///<  Pin pulldown resistor enabled
+    NRF_GPIO_PIN_PULLUP   = GPIO_PIN_CNF_PULL_Pullup,                   ///<  Pin pullup resistor enabled
+} nrf_gpio_pin_pull_t;
+
+/**
+ * @brief Enumerator used for selecting output drive mode
+ */
+typedef enum
+{
+    NRF_GPIO_PIN_S0S1 = GPIO_PIN_CNF_DRIVE_S0S1, ///< !< Standard '0', standard '1'
+    NRF_GPIO_PIN_H0S1 = GPIO_PIN_CNF_DRIVE_H0S1, ///< !< High drive '0', standard '1'
+    NRF_GPIO_PIN_S0H1 = GPIO_PIN_CNF_DRIVE_S0H1, ///< !< Standard '0', high drive '1'
+    NRF_GPIO_PIN_H0H1 = GPIO_PIN_CNF_DRIVE_H0H1, ///< !< High drive '0', high 'drive '1''
+    NRF_GPIO_PIN_D0S1 = GPIO_PIN_CNF_DRIVE_D0S1, ///< !< Disconnect '0' standard '1'
+    NRF_GPIO_PIN_D0H1 = GPIO_PIN_CNF_DRIVE_D0H1, ///< !< Disconnect '0', high drive '1'
+    NRF_GPIO_PIN_S0D1 = GPIO_PIN_CNF_DRIVE_S0D1, ///< !< Standard '0'. disconnect '1'
+    NRF_GPIO_PIN_H0D1 = GPIO_PIN_CNF_DRIVE_H0D1, ///< !< High drive '0', disconnect '1'
+} nrf_gpio_pin_drive_t;
+
+/**
+ * @brief Enumerator used for selecting the pin to sense high or low level on the pin input.
+ */
+typedef enum
+{
+    NRF_GPIO_PIN_NOSENSE    = GPIO_PIN_CNF_SENSE_Disabled,              ///<  Pin sense level disabled.
+    NRF_GPIO_PIN_SENSE_LOW  = GPIO_PIN_CNF_SENSE_Low,                   ///<  Pin sense low level.
+    NRF_GPIO_PIN_SENSE_HIGH = GPIO_PIN_CNF_SENSE_High,                  ///<  Pin sense high level.
+} nrf_gpio_pin_sense_t;
+
+
+/**
+ * @brief Function for configuring the GPIO pin range as outputs with normal drive strength.
+ *        This function can be used to configure pin range as simple output with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases).
+ *
+ * @param pin_range_start specifies the start number (inclusive) in the range of pin numbers to be configured (allowed values 0-30)
+ *
+ * @param pin_range_end specifies the end number (inclusive) in the range of pin numbers to be configured (allowed values 0-30)
+ *
+ * @note For configuring only one pin as output use @ref nrf_gpio_cfg_output
+ *       Sense capability on the pin is disabled, and input is disconnected from the buffer as the pins are configured as output.
+ */
+__STATIC_INLINE void nrf_gpio_range_cfg_output(uint32_t pin_range_start, uint32_t pin_range_end);
+
+/**
+ * @brief Function for configuring the GPIO pin range as inputs with given initial value set, hiding inner details.
+ *        This function can be used to configure pin range as simple input.
+ *
+ * @param pin_range_start specifies the start number (inclusive) in the range of pin numbers to be configured (allowed values 0-30)
+ *
+ * @param pin_range_end specifies the end number (inclusive) in the range of pin numbers to be configured (allowed values 0-30)
+ *
+ * @param pull_config State of the pin range pull resistor (no pull, pulled down or pulled high)
+ *
+ * @note  For configuring only one pin as input use @ref nrf_gpio_cfg_input
+ *        Sense capability on the pin is disabled, and input is connected to buffer so that the GPIO->IN register is readable
+ */
+__STATIC_INLINE void nrf_gpio_range_cfg_input(uint32_t pin_range_start, uint32_t pin_range_end, nrf_gpio_pin_pull_t pull_config);
+
+/**
+ * @brief Pin configuration function
+ *
+ * The main pin configuration function.
+ * This function allows to set any aspect in PIN_CNF register.
+ * @param pin_number Specifies the pin number (allowed values 0-31).
+ * @param dir   Pin direction
+ * @param input Connect or disconnect input buffer
+ * @param pull  Pull configuration
+ * @param drive Drive configuration
+ * @param sense Pin sensing mechanism
+ */
+__STATIC_INLINE void nrf_gpio_cfg(
+        uint32_t             pin_number,
+        nrf_gpio_pin_dir_t   dir,
+        nrf_gpio_pin_input_t input,
+        nrf_gpio_pin_pull_t  pull,
+        nrf_gpio_pin_drive_t drive,
+        nrf_gpio_pin_sense_t sense);
+
+/**
+ * @brief Function for configuring the given GPIO pin number as output with given initial value set, hiding inner details.
+ *        This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases).
+ *
+ * @param pin_number specifies the pin number (allowed values 0-31)
+ *
+ * @note  Sense capability on the pin is disabled, and input is disconnected from the buffer as the pins are configured as output.
+ */
+__STATIC_INLINE void nrf_gpio_cfg_output(uint32_t pin_number);
+
+/**
+ * @brief Function for configuring the given GPIO pin number as input with given initial value set, hiding inner details.
+ *        This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases).
+ *
+ * @param pin_number Specifies the pin number (allowed values 0-30).
+ * @param pull_config State of the pin range pull resistor (no pull, pulled down or pulled high).
+ *
+ * @note  Sense capability on the pin is disabled, and input is connected to buffer so that the GPIO->IN register is readable
+ */
+__STATIC_INLINE void nrf_gpio_cfg_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config);
+
+/**
+ * @brief Function for reseting pin configuration to its default state.
+ *
+ * @param pin_number Specifies the pin number (allowed values 0-31).
+ */
+__STATIC_INLINE void nrf_gpio_cfg_default(uint32_t pin_number);
+
+/**
+ * @brief Function for configuring the given GPIO pin number as a watcher. Only input is connected.
+ *
+ * @param pin_number Specifies the pin number (allowed values 0-31).
+ *
+ */
+__STATIC_INLINE void nrf_gpio_cfg_watcher(uint32_t pin_number);
+
+/**
+ * @brief Function for disconnecting input for the given GPIO.
+ *
+ * @param pin_number Specifies the pin number (allowed values 0-31).
+ *
+ */
+__STATIC_INLINE void nrf_gpio_input_disconnect(uint32_t pin_number);
+
+/**
+ * @brief Function for configuring the given GPIO pin number as input with given initial value set, hiding inner details.
+ *        This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases).
+ *        Sense capability on the pin is configurable, and input is connected to buffer so that the GPIO->IN register is readable.
+ *
+ * @param pin_number   Specifies the pin number (allowed values 0-30).
+ * @param pull_config  State of the pin pull resistor (no pull, pulled down or pulled high).
+ * @param sense_config Sense level of the pin (no sense, sense low or sense high).
+ */
+__STATIC_INLINE void nrf_gpio_cfg_sense_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config, nrf_gpio_pin_sense_t sense_config);
+
+/**
+ * @brief Function for configuring sense level for the given GPIO.
+ *
+ * @param pin_number   Specifies the pin number of gpio pin numbers to be configured (allowed values 0-30).
+ * @param sense_config Sense configuration.
+ *
+ */
+__STATIC_INLINE void nrf_gpio_cfg_sense_set(uint32_t pin_number, nrf_gpio_pin_sense_t sense_config);
+
+/**
+ * @brief Function for setting the direction for a GPIO pin.
+ *
+ * @param pin_number specifies the pin number [0:31] for which to
+ * set the direction.
+ *
+ * @param direction specifies the direction
+ */
+__STATIC_INLINE void nrf_gpio_pin_dir_set(uint32_t pin_number, nrf_gpio_pin_dir_t direction);
+
+/**
+ * @brief Function for setting a GPIO pin.
+ *
+ * Note that the pin must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * set.
+ */
+__STATIC_INLINE void nrf_gpio_pin_set(uint32_t pin_number);
+
+/**
+ * @brief Function for setting GPIO pins.
+ *
+ * Note that pins must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_mask Specifies the pins to set.
+ * set.
+ */
+__STATIC_INLINE void nrf_gpio_pins_set(uint32_t pin_mask);
+
+/**
+ * @brief Function for clearing a GPIO pin.
+ *
+ * Note that the pin must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * clear.
+ */
+__STATIC_INLINE void nrf_gpio_pin_clear(uint32_t pin_number);
+
+/**
+ * @brief Function for clearing GPIO pins.
+ *
+ * Note that pins must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_mask Specifies the pins to clear.
+ * set.
+ */
+__STATIC_INLINE void nrf_gpio_pins_clear(uint32_t pin_mask);
+
+/**
+ * @brief Function for toggling a GPIO pin.
+ *
+ * Note that the pin must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * toggle.
+ */
+__STATIC_INLINE void nrf_gpio_pin_toggle(uint32_t pin_number);
+
+/**
+ * @brief Function for writing a value to a GPIO pin.
+ *
+ * Note that the pin must be configured as an output for this
+ * function to have any effect.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * write.
+ *
+ * @param value specifies the value to be written to the pin.
+ * @arg 0 clears the pin
+ * @arg >=1 sets the pin.
+ */
+__STATIC_INLINE void nrf_gpio_pin_write(uint32_t pin_number, uint32_t value);
+
+/**
+ * @brief Function for reading the input level of a GPIO pin.
+ *
+ * Note that the pin must have input connected for the value
+ * returned from this function to be valid.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * read.
+ *
+ * @return
+ * @retval 0 if the pin input level is low.
+ * @retval 1 if the pin input level is high.
+ * @retval > 1 should never occur.
+ */
+__STATIC_INLINE uint32_t nrf_gpio_pin_read(uint32_t pin_number);
+
+/**
+ * @brief Function for reading the input level of all GPIO pins.
+ *
+ * Note that the pin must have input connected for the value
+ * returned from this function to be valid.
+ *
+ * @retval Status of input of all pins
+ */
+__STATIC_INLINE uint32_t nrf_gpio_pins_read(void);
+
+/**
+ * @brief Function for reading the sense configuration of a GPIO pin.
+ *
+ * @param pin_number specifies the pin number [0:31] to
+ * read.
+ *
+ * @retval Sense configuration
+ */
+__STATIC_INLINE nrf_gpio_pin_sense_t nrf_gpio_pin_sense_get(uint32_t pin_number);
+
+/**
+ * @brief Generic function for writing a single byte of a 32 bit word at a given
+ * address.
+ *
+ * This function should not be called from outside the nrf_gpio
+ * abstraction layer.
+ *
+ * @param word_address is the address of the word to be written.
+ *
+ * @param byte_no is the word byte number (0-3) to be written.
+ *
+ * @param value is the value to be written to byte "byte_no" of word
+ * at address "word_address"
+ */
+__STATIC_INLINE void nrf_gpio_word_byte_write(volatile uint32_t * word_address, uint8_t byte_no, uint8_t value);
+
+/**
+ * @brief Generic function for reading a single byte of a 32 bit word at a given
+ * address.
+ *
+ * This function should not be called from outside the nrf_gpio
+ * abstraction layer.
+ *
+ * @param word_address is the address of the word to be read.
+ *
+ * @param byte_no is the byte number (0-3) of the word to be read.
+ *
+ * @return byte "byte_no" of word at address "word_address".
+ */
+__STATIC_INLINE uint8_t nrf_gpio_word_byte_read(const volatile uint32_t* word_address, uint8_t byte_no);
+
+/**
+ * @brief Function for setting the direction of a port.
+ *
+ * @param port is the port for which to set the direction.
+ *
+ * @param dir direction to be set for this port.
+ */
+__STATIC_INLINE void nrf_gpio_port_dir_set(nrf_gpio_port_select_t port, nrf_gpio_port_dir_t dir);
+
+/**
+ * @brief Function for reading a GPIO port.
+ *
+ * @param port is the port to read.
+ *
+ * @return the input value on this port.
+ */
+__STATIC_INLINE uint8_t nrf_gpio_port_read(nrf_gpio_port_select_t port);
+
+/**
+ * @brief Function for writing to a GPIO port.
+ *
+ * @param port is the port to write.
+ *
+ * @param value is the value to write to this port.
+ *
+ * @sa nrf_gpio_port_dir_set()
+ */
+__STATIC_INLINE void nrf_gpio_port_write(nrf_gpio_port_select_t port, uint8_t value);
+
+/**
+ * @brief Function for setting individual pins on GPIO port.
+ *
+ * @param port is the port for which to set the pins.
+ *
+ * @param set_mask is a mask specifying which pins to set. A bit
+ * set to 1 indicates that the corresponding port pin shall be
+ * set.
+ *
+ * @sa nrf_gpio_port_dir_set()
+ */
+__STATIC_INLINE void nrf_gpio_port_set(nrf_gpio_port_select_t port, uint8_t set_mask);
+
+/**
+ * @brief Function for clearing individual pins on GPIO port.
+ *
+ * @param port is the port for which to clear the pins.
+ *
+ * @param clr_mask is a mask specifying which pins to clear. A bit
+ * set to 1 indicates that the corresponding port pin shall be
+ * cleared.
+ *
+ * @sa nrf_gpio_port_dir_set()
+ */
+__STATIC_INLINE void nrf_gpio_port_clear(nrf_gpio_port_select_t port, uint8_t clr_mask);
+
+#ifndef SUPPRESS_INLINE_IMPLEMENTATION
+__STATIC_INLINE void nrf_gpio_range_cfg_output(uint32_t pin_range_start, uint32_t pin_range_end)
+{
+    /*lint -e{845} // A zero has been given as right argument to operator '|'" */
+    for (; pin_range_start <= pin_range_end; pin_range_start++)
+    {
+        nrf_gpio_cfg_output(pin_range_start);
+    }
+}
+
+__STATIC_INLINE void nrf_gpio_range_cfg_input(uint32_t pin_range_start, uint32_t pin_range_end, nrf_gpio_pin_pull_t pull_config)
+{
+    /*lint -e{845} // A zero has been given as right argument to operator '|'" */
+    for (; pin_range_start <= pin_range_end; pin_range_start++)
+    {
+        nrf_gpio_cfg_input(pin_range_start, pull_config);
+    }
+}
+
+__STATIC_INLINE void nrf_gpio_cfg(
+        uint32_t             pin_number,
+        nrf_gpio_pin_dir_t   dir,
+        nrf_gpio_pin_input_t input,
+        nrf_gpio_pin_pull_t  pull,
+        nrf_gpio_pin_drive_t drive,
+        nrf_gpio_pin_sense_t sense)
+{
+    NRF_GPIO->PIN_CNF[pin_number] = ((uint32_t)dir   << GPIO_PIN_CNF_DIR_Pos)
+                                  | ((uint32_t)input << GPIO_PIN_CNF_INPUT_Pos)
+                                  | ((uint32_t)pull  << GPIO_PIN_CNF_PULL_Pos)
+                                  | ((uint32_t)drive << GPIO_PIN_CNF_DRIVE_Pos)
+                                  | ((uint32_t)sense << GPIO_PIN_CNF_SENSE_Pos);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_output(uint32_t pin_number)
+{
+    nrf_gpio_cfg(
+            pin_number,
+            NRF_GPIO_PIN_DIR_OUTPUT,
+            NRF_GPIO_PIN_INPUT_DISCONNECT,
+            NRF_GPIO_PIN_NOPULL,
+            NRF_GPIO_PIN_S0S1,
+            NRF_GPIO_PIN_NOSENSE);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config)
+{
+    nrf_gpio_cfg(
+            pin_number,
+            NRF_GPIO_PIN_DIR_INPUT,
+            NRF_GPIO_PIN_INPUT_CONNECT,
+            pull_config,
+            NRF_GPIO_PIN_S0S1,
+            NRF_GPIO_PIN_NOSENSE);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_default(uint32_t pin_number)
+{
+    nrf_gpio_cfg(
+            pin_number,
+            NRF_GPIO_PIN_DIR_INPUT,
+            NRF_GPIO_PIN_INPUT_DISCONNECT,
+            NRF_GPIO_PIN_NOPULL,
+            NRF_GPIO_PIN_S0S1,
+            NRF_GPIO_PIN_NOSENSE);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_watcher(uint32_t pin_number)
+{
+    /*lint -e{845} // A zero has been given as right argument to operator '|'" */
+    uint32_t cnf = NRF_GPIO->PIN_CNF[pin_number] & ~GPIO_PIN_CNF_INPUT_Msk;
+    NRF_GPIO->PIN_CNF[pin_number] = cnf | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos);
+}
+
+__STATIC_INLINE void nrf_gpio_input_disconnect(uint32_t pin_number)
+{
+    /*lint -e{845} // A zero has been given as right argument to operator '|'" */
+    uint32_t cnf = NRF_GPIO->PIN_CNF[pin_number] & ~GPIO_PIN_CNF_INPUT_Msk;
+    NRF_GPIO->PIN_CNF[pin_number] = cnf | (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_sense_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config, nrf_gpio_pin_sense_t sense_config)
+{
+    nrf_gpio_cfg(
+            pin_number,
+            NRF_GPIO_PIN_DIR_INPUT,
+            NRF_GPIO_PIN_INPUT_CONNECT,
+            pull_config,
+            NRF_GPIO_PIN_S0S1,
+            sense_config);
+}
+
+__STATIC_INLINE void nrf_gpio_cfg_sense_set(uint32_t pin_number, nrf_gpio_pin_sense_t sense_config)
+{
+    /*lint -e{845} // A zero has been given as right argument to operator '|'" */
+    //uint32_t cnf = NRF_GPIO->PIN_CNF[pin_number] & ~GPIO_PIN_CNF_SENSE_Msk;
+    NRF_GPIO->PIN_CNF[pin_number] &= ~GPIO_PIN_CNF_SENSE_Msk;
+    NRF_GPIO->PIN_CNF[pin_number] |= (sense_config << GPIO_PIN_CNF_SENSE_Pos);
+}
+
+__STATIC_INLINE void nrf_gpio_pin_dir_set(uint32_t pin_number, nrf_gpio_pin_dir_t direction)
+{
+    if(direction == NRF_GPIO_PIN_DIR_INPUT)
+    {
+        nrf_gpio_cfg(
+                pin_number,
+                NRF_GPIO_PIN_DIR_INPUT,
+                NRF_GPIO_PIN_INPUT_CONNECT,
+                NRF_GPIO_PIN_NOPULL,
+                NRF_GPIO_PIN_S0S1,
+                NRF_GPIO_PIN_NOSENSE);
+    }
+    else
+    {
+        NRF_GPIO->DIRSET = (1UL << pin_number);
+    }
+}
+
+__STATIC_INLINE void nrf_gpio_pin_set(uint32_t pin_number)
+{
+    NRF_GPIO->OUTSET = (1UL << pin_number);
+}
+
+__STATIC_INLINE void nrf_gpio_pins_set(uint32_t pin_mask)
+{
+    NRF_GPIO->OUTSET = pin_mask;
+}
+
+__STATIC_INLINE void nrf_gpio_pin_clear(uint32_t pin_number)
+{
+    NRF_GPIO->OUTCLR = (1UL << pin_number);
+}
+
+__STATIC_INLINE void nrf_gpio_pins_clear(uint32_t pin_mask)
+{
+    NRF_GPIO->OUTCLR = pin_mask;
+}
+
+__STATIC_INLINE void nrf_gpio_pin_toggle(uint32_t pin_number)
+{
+    const uint32_t pin_bit   = 1UL << pin_number;
+    const uint32_t pin_state = ((NRF_GPIO->OUT >> pin_number) & 1UL);
+
+    if (pin_state == 0)
+    {
+        // Current state low, set high.
+        NRF_GPIO->OUTSET = pin_bit;
+    }
+    else
+    {
+        // Current state high, set low.
+        NRF_GPIO->OUTCLR = pin_bit;
+    }
+}
+
+__STATIC_INLINE void nrf_gpio_pin_write(uint32_t pin_number, uint32_t value)
+{
+    if (value == 0)
+    {
+        nrf_gpio_pin_clear(pin_number);
+    }
+    else
+    {
+        nrf_gpio_pin_set(pin_number);
+    }
+}
+
+__STATIC_INLINE uint32_t nrf_gpio_pin_read(uint32_t pin_number)
+{
+    return  ((NRF_GPIO->IN >> pin_number) & 1UL);
+}
+
+__STATIC_INLINE uint32_t nrf_gpio_pins_read(void)
+{
+    return NRF_GPIO->IN;
+}
+
+__STATIC_INLINE nrf_gpio_pin_sense_t nrf_gpio_pin_sense_get(uint32_t pin_number)
+{
+    return (nrf_gpio_pin_sense_t)((NRF_GPIO->PIN_CNF[pin_number] & GPIO_PIN_CNF_SENSE_Msk) >> GPIO_PIN_CNF_SENSE_Pos);
+}
+
+__STATIC_INLINE void nrf_gpio_word_byte_write(volatile uint32_t * word_address, uint8_t byte_no, uint8_t value)
+{
+    *((volatile uint8_t*)(word_address) + byte_no) = value;
+}
+
+__STATIC_INLINE uint8_t nrf_gpio_word_byte_read(const volatile uint32_t* word_address, uint8_t byte_no)
+{
+    return (*((const volatile uint8_t*)(word_address) + byte_no));
+}
+
+__STATIC_INLINE void nrf_gpio_port_dir_set(nrf_gpio_port_select_t port, nrf_gpio_port_dir_t dir)
+{
+    if (dir == NRF_GPIO_PORT_DIR_OUTPUT)
+    {
+        nrf_gpio_word_byte_write(&NRF_GPIO->DIRSET, port, 0xFF);
+    }
+    else
+    {
+        nrf_gpio_range_cfg_input(port*8, (port+1)*8-1, NRF_GPIO_PIN_NOPULL);
+    }
+}
+
+__STATIC_INLINE uint8_t nrf_gpio_port_read(nrf_gpio_port_select_t port)
+{
+    return nrf_gpio_word_byte_read(&NRF_GPIO->IN, port);
+}
+
+__STATIC_INLINE void nrf_gpio_port_write(nrf_gpio_port_select_t port, uint8_t value)
+{
+    nrf_gpio_word_byte_write(&NRF_GPIO->OUT, port, value);
+}
+
+__STATIC_INLINE void nrf_gpio_port_set(nrf_gpio_port_select_t port, uint8_t set_mask)
+{
+    nrf_gpio_word_byte_write(&NRF_GPIO->OUTSET, port, set_mask);
+}
+
+__STATIC_INLINE void nrf_gpio_port_clear(nrf_gpio_port_select_t port, uint8_t clr_mask)
+{
+    nrf_gpio_word_byte_write(&NRF_GPIO->OUTCLR, port, clr_mask);
+}
+#endif //SUPPRESS_INLINE_IMPLEMENTATION
+/** @} */
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpiote.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_gpiote.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,366 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef NRF_GPIOTE_H__
+#define NRF_GPIOTE_H__
+
+#include "nrf.h"
+#include <stdint.h>
+#include <stddef.h>
+#include <stdbool.h>
+
+/**
+* @defgroup nrf_gpiote_abs GPIOTE abstraction
+* @{
+* @ingroup nrf_gpiote
+* @brief GPIOTE abstraction for configuration of channels.
+*/
+#ifdef NRF51
+#define NUMBER_OF_GPIO_TE 4
+#elif defined NRF52
+#define NUMBER_OF_GPIO_TE 8
+#else
+#error "Chip family not specified"
+#endif
+
+ /**
+ * @enum nrf_gpiote_polarity_t
+ * @brief Polarity for the GPIOTE channel.
+ */
+typedef enum
+{
+  NRF_GPIOTE_POLARITY_LOTOHI = GPIOTE_CONFIG_POLARITY_LoToHi,       ///<  Low to high.
+  NRF_GPIOTE_POLARITY_HITOLO = GPIOTE_CONFIG_POLARITY_HiToLo,       ///<  High to low.
+  NRF_GPIOTE_POLARITY_TOGGLE = GPIOTE_CONFIG_POLARITY_Toggle        ///<  Toggle.
+} nrf_gpiote_polarity_t;
+
+
+ /**
+ * @enum nrf_gpiote_outinit_t
+ * @brief Initial output value for the GPIOTE channel.
+ */
+typedef enum
+{
+  NRF_GPIOTE_INITIAL_VALUE_LOW  = GPIOTE_CONFIG_OUTINIT_Low,       ///<  Low to high.
+  NRF_GPIOTE_INITIAL_VALUE_HIGH = GPIOTE_CONFIG_OUTINIT_High       ///<  High to low.
+} nrf_gpiote_outinit_t;
+
+/**
+ * @brief Tasks.
+ */
+typedef enum /*lint -save -e30 -esym(628,__INTADDR__) */
+{
+    NRF_GPIOTE_TASKS_OUT_0     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[0]), /**< Out task 0.*/
+    NRF_GPIOTE_TASKS_OUT_1     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[1]), /**< Out task 1.*/
+    NRF_GPIOTE_TASKS_OUT_2     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[2]), /**< Out task 2.*/
+    NRF_GPIOTE_TASKS_OUT_3     = offsetof(NRF_GPIOTE_Type, TASKS_OUT[3]), /**< Out task 3.*/
+    /*lint -restore*/
+} nrf_gpiote_tasks_t;
+
+/**
+ * @brief Events.
+ */
+typedef enum /*lint -save -e30 -esym(628,__INTADDR__) */
+{
+    NRF_GPIOTE_EVENTS_IN_0     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[0]), /**< In event 0.*/
+    NRF_GPIOTE_EVENTS_IN_1     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[1]), /**< In event 1.*/
+    NRF_GPIOTE_EVENTS_IN_2     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[2]), /**< In event 2.*/
+    NRF_GPIOTE_EVENTS_IN_3     = offsetof(NRF_GPIOTE_Type, EVENTS_IN[3]), /**< In event 3.*/
+    NRF_GPIOTE_EVENTS_PORT     = offsetof(NRF_GPIOTE_Type, EVENTS_PORT), /**<  Port event.*/
+    /*lint -restore*/
+} nrf_gpiote_events_t;
+
+/**
+ * @enum nrf_gpiote_int_t
+ * @brief GPIOTE interrupts.
+ */
+typedef enum
+{
+    NRF_GPIOTE_INT_IN0_MASK  = GPIOTE_INTENSET_IN0_Msk,  /**< GPIOTE interrupt from IN0. */
+    NRF_GPIOTE_INT_IN1_MASK  = GPIOTE_INTENSET_IN1_Msk,  /**< GPIOTE interrupt from IN1. */
+    NRF_GPIOTE_INT_IN2_MASK  = GPIOTE_INTENSET_IN2_Msk,  /**< GPIOTE interrupt from IN2. */
+    NRF_GPIOTE_INT_IN3_MASK  = GPIOTE_INTENSET_IN3_Msk,  /**< GPIOTE interrupt from IN3. */
+    NRF_GPIOTE_INT_PORT_MASK = (int)GPIOTE_INTENSET_PORT_Msk, /**< GPIOTE interrupt from PORT event. */
+} nrf_gpiote_int_t;
+
+#define NRF_GPIOTE_INT_IN_MASK (NRF_GPIOTE_INT_IN0_MASK | NRF_GPIOTE_INT_IN1_MASK |\
+                                NRF_GPIOTE_INT_IN2_MASK | NRF_GPIOTE_INT_IN3_MASK)
+/**
+ * @brief Function for activating a specific GPIOTE task.
+ *
+ * @param[in]  task Task.
+ */
+__STATIC_INLINE void nrf_gpiote_task_set(nrf_gpiote_tasks_t task);
+
+/**
+ * @brief Function for getting the address of a specific GPIOTE task.
+ *
+ * @param[in] task Task.
+ *
+ * @returns Address.
+ */
+__STATIC_INLINE uint32_t nrf_gpiote_task_addr_get(nrf_gpiote_tasks_t task);
+
+/**
+ * @brief Function for getting the state of a specific GPIOTE event.
+ *
+ * @param[in] event Event.
+ */
+__STATIC_INLINE bool nrf_gpiote_event_is_set(nrf_gpiote_events_t event);
+
+/**
+ * @brief Function for clearing a specific GPIOTE event.
+ *
+ * @param[in] event Event.
+ */
+__STATIC_INLINE void nrf_gpiote_event_clear(nrf_gpiote_events_t event);
+
+/**
+ * @brief Function for getting the address of a specific GPIOTE event.
+ *
+ * @param[in] event Event.
+ *
+ * @return Address
+ */
+__STATIC_INLINE uint32_t nrf_gpiote_event_addr_get(nrf_gpiote_events_t event);
+
+/**@brief Function for enabling interrupts.
+ *
+ * @param[in]  mask          Interrupt mask to be enabled.
+ */
+__STATIC_INLINE void nrf_gpiote_int_enable(uint32_t mask);
+
+/**@brief Function for disabling interrupts.
+ *
+ * @param[in]  mask          Interrupt mask to be disabled.
+ */
+__STATIC_INLINE void nrf_gpiote_int_disable(uint32_t mask);
+
+/**@brief Function for checking if interrupts are enabled.
+ *
+ * @param[in]  mask          Mask of interrupt flags to check.
+ *
+ * @return                   Mask with enabled interrupts.
+ */
+__STATIC_INLINE uint32_t nrf_gpiote_int_is_enabled(uint32_t mask);
+
+/**@brief Function for enabling a GPIOTE event.
+ *
+ * @param[in]  idx        Task-Event index.
+ */
+__STATIC_INLINE void nrf_gpiote_event_enable(uint32_t idx);
+
+/**@brief Function for disabling a GPIOTE event.
+ *
+ * @param[in]  idx        Task-Event index.
+ */
+__STATIC_INLINE void nrf_gpiote_event_disable(uint32_t idx);
+
+/**@brief Function for configuring a GPIOTE event.
+ *
+ * @param[in]  idx        Task-Event index.
+ * @param[in]  pin        Pin associated with event.
+ * @param[in]  polarity   Transition that should generate an event.
+ */
+__STATIC_INLINE void nrf_gpiote_event_configure(uint32_t idx, uint32_t pin,
+                                                nrf_gpiote_polarity_t polarity);
+
+/**@brief Function for getting the pin associated with a GPIOTE event.
+ *
+ * @param[in]  idx        Task-Event index.
+ *
+ * @return Pin number.
+ */
+__STATIC_INLINE uint32_t nrf_gpiote_event_pin_get(uint32_t idx);
+
+/**@brief Function for getting the polarity associated with a GPIOTE event.
+ *
+ * @param[in]  idx        Task-Event index.
+ *
+ * @return Polarity.
+ */
+__STATIC_INLINE nrf_gpiote_polarity_t nrf_gpiote_event_polarity_get(uint32_t idx);
+
+/**@brief Function for enabling a GPIOTE task.
+ *
+ * @param[in]  idx        Task-Event index.
+ */
+__STATIC_INLINE void nrf_gpiote_task_enable(uint32_t idx);
+
+/**@brief Function for disabling a GPIOTE task.
+ *
+ * @param[in]  idx        Task-Event index.
+ */
+__STATIC_INLINE void nrf_gpiote_task_disable(uint32_t idx);
+
+/**@brief Function for configuring a GPIOTE task.
+ * @note  Function is not configuring mode field so task is disabled after this function is called.
+ *
+ * @param[in]  idx        Task-Event index.
+ * @param[in]  pin        Pin associated with event.
+ * @param[in]  polarity   Transition that should generate an event.
+ * @param[in]  init_val   Initial value of pin.
+ */
+__STATIC_INLINE void nrf_gpiote_task_configure(uint32_t idx, uint32_t pin,
+                                               nrf_gpiote_polarity_t polarity,
+                                               nrf_gpiote_outinit_t  init_val);
+
+/**@brief Function for forcing a specific state on the pin connected to GPIOTE.
+ *
+ * @param[in]  idx        Task-Event index.
+ * @param[in]  init_val   Pin state.
+ */
+__STATIC_INLINE void nrf_gpiote_task_force(uint32_t idx, nrf_gpiote_outinit_t init_val);
+
+/**@brief Function for resetting a GPIOTE task event configuration to the default state.
+ *
+ * @param[in]  idx        Task-Event index.
+ */
+__STATIC_INLINE void nrf_gpiote_te_default(uint32_t idx);
+
+#ifndef SUPPRESS_INLINE_IMPLEMENTATION
+__STATIC_INLINE void nrf_gpiote_task_set(nrf_gpiote_tasks_t task)
+{
+    *(__IO uint32_t *)((uint32_t)NRF_GPIOTE + task) = 0x1UL;
+}
+
+__STATIC_INLINE uint32_t nrf_gpiote_task_addr_get(nrf_gpiote_tasks_t task)
+{
+    return ((uint32_t)NRF_GPIOTE + task);
+}
+
+__STATIC_INLINE bool nrf_gpiote_event_is_set(nrf_gpiote_events_t event)
+{
+    return (*(uint32_t *)nrf_gpiote_event_addr_get(event) == 0x1UL) ? true : false;
+}
+
+__STATIC_INLINE void nrf_gpiote_event_clear(nrf_gpiote_events_t event)
+{
+    *(uint32_t *)nrf_gpiote_event_addr_get(event) = 0;
+#if __CORTEX_M == 0x04
+    volatile uint32_t dummy = *((volatile uint32_t *)nrf_gpiote_event_addr_get(event));
+    (void)dummy;
+#endif
+}
+
+__STATIC_INLINE uint32_t nrf_gpiote_event_addr_get(nrf_gpiote_events_t event)
+{
+    return ((uint32_t)NRF_GPIOTE + event);
+}
+
+__STATIC_INLINE void nrf_gpiote_int_enable(uint32_t mask)
+{
+    NRF_GPIOTE->INTENSET = mask;
+}
+
+__STATIC_INLINE void nrf_gpiote_int_disable(uint32_t mask)
+{
+    NRF_GPIOTE->INTENCLR = mask;
+}
+
+__STATIC_INLINE uint32_t nrf_gpiote_int_is_enabled(uint32_t mask)
+{
+    return (NRF_GPIOTE->INTENSET & mask);
+}
+
+__STATIC_INLINE void nrf_gpiote_event_enable(uint32_t idx)
+{
+   NRF_GPIOTE->CONFIG[idx] |= GPIOTE_CONFIG_MODE_Event;
+}
+
+__STATIC_INLINE void nrf_gpiote_event_disable(uint32_t idx)
+{
+   NRF_GPIOTE->CONFIG[idx] &= ~GPIOTE_CONFIG_MODE_Event;
+}
+
+__STATIC_INLINE void nrf_gpiote_event_configure(uint32_t idx, uint32_t pin, nrf_gpiote_polarity_t polarity)
+{
+  NRF_GPIOTE->CONFIG[idx] &= ~(GPIOTE_CONFIG_PSEL_Msk | GPIOTE_CONFIG_POLARITY_Msk);
+  NRF_GPIOTE->CONFIG[idx] |= ((pin << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PSEL_Msk) |
+                              ((polarity << GPIOTE_CONFIG_POLARITY_Pos) & GPIOTE_CONFIG_POLARITY_Msk);
+}
+
+__STATIC_INLINE uint32_t nrf_gpiote_event_pin_get(uint32_t idx)
+{
+    return ((NRF_GPIOTE->CONFIG[idx] & GPIOTE_CONFIG_PSEL_Msk) >> GPIOTE_CONFIG_PSEL_Pos);
+}
+
+__STATIC_INLINE nrf_gpiote_polarity_t nrf_gpiote_event_polarity_get(uint32_t idx)
+{
+    return (nrf_gpiote_polarity_t)((NRF_GPIOTE->CONFIG[idx] & GPIOTE_CONFIG_POLARITY_Msk) >> GPIOTE_CONFIG_POLARITY_Pos);
+}
+
+__STATIC_INLINE void nrf_gpiote_task_enable(uint32_t idx)
+{
+    uint32_t final_config = NRF_GPIOTE->CONFIG[idx] | GPIOTE_CONFIG_MODE_Task;
+    /* Workaround for the OUTINIT PAN. When nrf_gpiote_task_config() is called a glitch happens
+    on the GPIO if the GPIO in question is already assigned to GPIOTE and the pin is in the
+    correct state in GPIOTE but not in the OUT register. */
+    /* Configure channel to Pin31, not connected to the pin, and configure as a tasks that will set it to proper level */
+    NRF_GPIOTE->CONFIG[idx] = final_config | ((31 << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PSEL_Msk);
+    __NOP();
+    __NOP();
+    __NOP();
+    NRF_GPIOTE->CONFIG[idx] = final_config;
+}
+
+__STATIC_INLINE void nrf_gpiote_task_disable(uint32_t idx)
+{
+    NRF_GPIOTE->CONFIG[idx] &= ~GPIOTE_CONFIG_MODE_Task;
+}
+
+__STATIC_INLINE void nrf_gpiote_task_configure(uint32_t idx, uint32_t pin,
+                                                nrf_gpiote_polarity_t polarity,
+                                                nrf_gpiote_outinit_t  init_val)
+{
+  NRF_GPIOTE->CONFIG[idx] &= ~(GPIOTE_CONFIG_PSEL_Msk |
+                               GPIOTE_CONFIG_POLARITY_Msk |
+                               GPIOTE_CONFIG_OUTINIT_Msk);
+
+  NRF_GPIOTE->CONFIG[idx] |= ((pin << GPIOTE_CONFIG_PSEL_Pos) & GPIOTE_CONFIG_PSEL_Msk) |
+                             ((polarity << GPIOTE_CONFIG_POLARITY_Pos) & GPIOTE_CONFIG_POLARITY_Msk) |
+                             ((init_val << GPIOTE_CONFIG_OUTINIT_Pos) & GPIOTE_CONFIG_OUTINIT_Msk);
+}
+
+__STATIC_INLINE void nrf_gpiote_task_force(uint32_t idx, nrf_gpiote_outinit_t init_val)
+{
+    NRF_GPIOTE->CONFIG[idx] = (NRF_GPIOTE->CONFIG[idx] & ~GPIOTE_CONFIG_OUTINIT_Msk) 
+                              | ((init_val << GPIOTE_CONFIG_OUTINIT_Pos) & GPIOTE_CONFIG_OUTINIT_Msk);
+}
+
+__STATIC_INLINE void nrf_gpiote_te_default(uint32_t idx)
+{
+    NRF_GPIOTE->CONFIG[idx] = 0;
+}
+#endif //SUPPRESS_INLINE_IMPLEMENTATION
+/** @} */
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */ 
+
+/** 
+ *@file
+ *@brief NMVC driver implementation 
+ */
+
+#include "stdbool.h"
+#include "nrf.h"
+#include "nrf_nvmc.h"
+
+
+void nrf_nvmc_page_erase(uint32_t address)
+{ 
+  // Enable erase.
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+
+  // Erase the page
+  NRF_NVMC->ERASEPAGE = address;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+  
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+}
+
+
+void nrf_nvmc_write_byte(uint32_t address, uint8_t value)
+{
+  uint32_t byte_shift = address & (uint32_t)0x03;
+  uint32_t address32 = address & ~byte_shift; // Address to the word this byte is in.
+  uint32_t value32 = (*(uint32_t*)address32 & ~((uint32_t)0xFF << (byte_shift << (uint32_t)3)));
+  value32 = value32 + ((uint32_t)value << (byte_shift << 3));
+
+  // Enable write.
+  NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+
+  *(uint32_t*)address32 = value32;
+  while(NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+
+  NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);
+  {
+  }
+}
+
+void nrf_nvmc_write_word(uint32_t address, uint32_t value)
+{
+  // Enable write.
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy){
+  }
+
+  *(uint32_t*)address = value;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy){
+  }
+
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+}
+
+void nrf_nvmc_write_bytes(uint32_t address, const uint8_t * src, uint32_t num_bytes)
+{
+  uint32_t i;
+  for(i=0;i<num_bytes;i++)
+  {
+     nrf_nvmc_write_byte(address+i,src[i]);
+  }
+}
+
+void nrf_nvmc_write_words(uint32_t address, const uint32_t * src, uint32_t num_words)
+{
+  uint32_t i;
+
+  // Enable write.
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+
+  for(i=0;i<num_words;i++)
+  {
+    ((uint32_t*)address)[i] = src[i];
+    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+    {
+    }
+  }
+
+  NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
+  while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
+  {
+  }
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_nvmc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * @file
+ * @brief NMVC driver API.
+ */
+
+#ifndef NRF_NVMC_H__
+#define NRF_NVMC_H__
+
+#include <stdint.h>
+
+
+/**
+ * @defgroup nrf_nvmc Non-volatile memory controller
+ * @{
+ * @ingroup nrf_drivers
+ * @brief Driver for the NVMC peripheral.
+ *
+ * This driver allows writing to the non-volatile memory (NVM) regions
+ * of the chip. In order to write to NVM the controller must be powered
+ * on and the relevant page must be erased.
+ *
+ */
+
+
+/**
+ * @brief Erase a page in flash. This is required before writing to any
+ * address in the page.
+ *
+ * @param address Start address of the page. 
+ */
+void nrf_nvmc_page_erase(uint32_t address);
+
+
+/**
+ * @brief Write a single byte to flash.
+ *
+ * The function reads the word containing the byte, and then
+ * rewrites the entire word.
+ *
+ * @param address Address to write to.
+ * @param value   Value to write.
+ */
+void nrf_nvmc_write_byte(uint32_t address , uint8_t value);
+
+
+/**
+ * @brief Write a 32-bit word to flash. 
+ * @param address Address to write to.
+ * @param value   Value to write.
+ */
+void nrf_nvmc_write_word(uint32_t address, uint32_t value);
+
+
+/**
+ * @brief Write consecutive bytes to flash.
+ *
+ * @param address   Address to write to.
+ * @param src       Pointer to data to copy from.
+ * @param num_bytes Number of bytes in src to write.
+ */
+void nrf_nvmc_write_bytes(uint32_t  address, const uint8_t * src, uint32_t num_bytes);
+
+
+/**
+ * @brief Write consecutive words to flash.
+ * 
+ * @param address   Address to write to.
+ * @param src       Pointer to data to copy from.
+ * @param num_words Number of bytes in src to write.
+ */
+void nrf_nvmc_write_words(uint32_t address, const uint32_t * src, uint32_t num_words);
+
+
+#endif // NRF_NVMC_H__
+/** @} */
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_temp.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_temp.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef NRF_TEMP_H__
+#define NRF_TEMP_H__
+
+#include "nrf.h"
+
+/**
+* @defgroup nrf_temperature TEMP (temperature) abstraction
+* @{
+* @ingroup nrf_drivers temperature_example
+* @brief Temperature module init and read functions.
+*
+*/
+
+/**@cond NO_DOXYGEN */
+#define MASK_SIGN           (0x00000200UL)
+#define MASK_SIGN_EXTENSION (0xFFFFFC00UL)
+
+/**
+ * @brief Function for preparing the temp module for temperature measurement.
+ *
+ * This function initializes the TEMP module and writes to the hidden configuration register.
+ */
+static __INLINE void nrf_temp_init(void)
+{
+    /**@note Workaround for PAN_028 rev2.0A anomaly 31 - TEMP: Temperature offset value has to be manually loaded to the TEMP module */
+    *(uint32_t *) 0x4000C504 = 0;
+}
+
+/**
+ * @brief Function for reading temperature measurement.
+ *
+ * The function reads the 10 bit 2's complement value and transforms it to a 32 bit 2's complement value.
+ */
+static __INLINE int32_t nrf_temp_read(void)
+{    
+    /**@note Workaround for PAN_028 rev2.0A anomaly 28 - TEMP: Negative measured values are not represented correctly */
+    return ((NRF_TEMP->TEMP & MASK_SIGN) != 0) ? (NRF_TEMP->TEMP | MASK_SIGN_EXTENSION) : (NRF_TEMP->TEMP);    
+}
+/**@endcond */
+
+/** @} */
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_wdt.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/hal/nrf_wdt.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,319 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * @defgroup nrf_wdt_hal WDT HAL
+ * @{
+ * @ingroup nrf_wdt
+ *
+ * @brief Hardware access layer for accessing the watchdog timer (WDT) peripheral.
+ */
+
+#ifndef NRF_WDT_H__
+#define NRF_WDT_H__
+
+#include <stddef.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "nrf.h"
+
+#define NRF_WDT_CHANNEL_NUMBER 0x8UL
+#define NRF_WDT_RR_VALUE       0x6E524635UL /* Fixed value, shouldn't be modified.*/
+
+#define NRF_WDT_TASK_SET       1UL
+#define NRF_WDT_EVENT_CLEAR    0UL
+
+/**
+ * @enum nrf_wdt_task_t
+ * @brief WDT tasks.
+ */
+typedef enum
+{
+    /*lint -save -e30 -esym(628,__INTADDR__)*/
+    NRF_WDT_TASK_START = offsetof(NRF_WDT_Type, TASKS_START), /**< Task for starting WDT. */
+    /*lint -restore*/
+} nrf_wdt_task_t;
+
+/**
+ * @enum nrf_wdt_event_t
+ * @brief WDT events.
+ */
+typedef enum
+{
+    /*lint -save -e30*/
+    NRF_WDT_EVENT_TIMEOUT = offsetof(NRF_WDT_Type, EVENTS_TIMEOUT), /**< Event from WDT time-out. */
+    /*lint -restore*/
+} nrf_wdt_event_t;
+
+/**
+ * @enum nrf_wdt_behaviour_t
+ * @brief WDT behavior in CPU SLEEP or HALT mode.
+ */
+typedef enum
+{
+    NRF_WDT_BEHAVIOUR_RUN_SLEEP        = WDT_CONFIG_SLEEP_Msk,                       /**< WDT will run when CPU is in SLEEP mode. */
+    NRF_WDT_BEHAVIOUR_RUN_HALT         = WDT_CONFIG_HALT_Msk,                        /**< WDT will run when CPU is in HALT mode. */
+    NRF_WDT_BEHAVIOUR_RUN_SLEEP_HALT   = WDT_CONFIG_SLEEP_Msk | WDT_CONFIG_HALT_Msk, /**< WDT will run when CPU is in SLEEP or HALT mode. */
+    NRF_WDT_BEHAVIOUR_PAUSE_SLEEP_HALT = 0,                                          /**< WDT will be paused when CPU is in SLEEP or HALT mode. */
+} nrf_wdt_behaviour_t;
+
+/**
+ * @enum nrf_wdt_rr_register_t
+ * @brief WDT reload request registers.
+ */
+typedef enum
+{
+    NRF_WDT_RR0 = 0, /**< Reload request register 0. */
+    NRF_WDT_RR1,     /**< Reload request register 1. */
+    NRF_WDT_RR2,     /**< Reload request register 2. */
+    NRF_WDT_RR3,     /**< Reload request register 3. */
+    NRF_WDT_RR4,     /**< Reload request register 4. */
+    NRF_WDT_RR5,     /**< Reload request register 5. */
+    NRF_WDT_RR6,     /**< Reload request register 6. */
+    NRF_WDT_RR7      /**< Reload request register 7. */
+} nrf_wdt_rr_register_t;
+
+/**
+ * @enum nrf_wdt_int_mask_t
+ * @brief WDT interrupts.
+ */
+typedef enum
+{
+    NRF_WDT_INT_TIMEOUT_MASK = WDT_INTENSET_TIMEOUT_Msk, /**< WDT interrupt from time-out event. */
+} nrf_wdt_int_mask_t;
+
+/**
+ * @brief Function for configuring the watchdog behavior when the CPU is sleeping or halted.
+ *
+ * @param behaviour Watchdog behavior when CPU is in SLEEP or HALT mode.
+ */
+__STATIC_INLINE void nrf_wdt_behaviour_set(nrf_wdt_behaviour_t behaviour)
+{
+    NRF_WDT->CONFIG = behaviour;
+}
+
+
+/**
+ * @brief Function for starting the watchdog.
+ *
+ * @param[in]  task             Task.
+ */
+__STATIC_INLINE void nrf_wdt_task_trigger(nrf_wdt_task_t task)
+{
+    *((volatile uint32_t *)((uint8_t *)NRF_WDT + task)) = NRF_WDT_TASK_SET;
+}
+
+
+/**
+ * @brief Function for clearing the WDT event.
+ *
+ * @param[in]  event       Event.
+ */
+__STATIC_INLINE void nrf_wdt_event_clear(nrf_wdt_event_t event)
+{
+    *((volatile uint32_t *)((uint8_t *)NRF_WDT + (uint32_t)event)) = NRF_WDT_EVENT_CLEAR;
+}
+
+
+/**
+ * @brief Function for retrieving the state of the WDT event.
+ *
+ * @param[in]  event       Event.
+ *
+ * @retval     true              If the event is set.
+ * @retval     false             If the event is not set.
+ */
+__STATIC_INLINE bool nrf_wdt_event_check(nrf_wdt_event_t event)
+{
+    return (bool)*((volatile uint32_t *)((uint8_t *)NRF_WDT + event));
+}
+
+
+/**
+ * @brief Function for enabling a specific interrupt.
+ *
+ * @param[in]  int_mask         Interrupt.
+ */
+__STATIC_INLINE void nrf_wdt_int_enable(uint32_t int_mask)
+{
+    NRF_WDT->INTENSET = int_mask;
+}
+
+
+/**
+ * @brief Function for retrieving the state of given interrupt.
+ *
+ * @param[in]  int_mask         Interrupt.
+ *
+ * @retval     true                   Interrupt is enabled.
+ * @retval     false                  Interrupt is not enabled.
+ */
+__STATIC_INLINE bool nrf_wdt_int_enable_check(uint32_t int_mask)
+{
+    return (bool)(NRF_WDT->INTENSET & int_mask);
+}
+
+
+/**
+ * @brief Function for disabling a specific interrupt.
+ *
+ * @param[in]  int_mask         Interrupt.
+ */
+__STATIC_INLINE void nrf_wdt_int_disable(uint32_t int_mask)
+{
+    NRF_WDT->INTENCLR = int_mask;
+}
+
+
+/**
+ * @brief Function for returning the address of a specific WDT task register.
+ *
+ * @param[in]  task             Task.
+ */
+__STATIC_INLINE uint32_t nrf_wdt_task_address_get(nrf_wdt_task_t task)
+{
+    return ((uint32_t)NRF_WDT + task);
+}
+
+
+/**
+ * @brief Function for returning the address of a specific WDT event register.
+ *
+ * @param[in]  event       Event.
+ *
+ * @retval     address of requested event register
+ */
+__STATIC_INLINE uint32_t nrf_wdt_event_address_get(nrf_wdt_event_t event)
+{
+    return ((uint32_t)NRF_WDT + event);
+}
+
+
+/**
+ * @brief Function for retrieving the watchdog status.
+ *
+ * @retval     true             If the watchdog is started.
+ * @retval     false            If the watchdog is not started.
+ */
+__STATIC_INLINE bool nrf_wdt_started(void)
+{
+    return (bool)(NRF_WDT->RUNSTATUS);
+}
+
+
+/**
+ * @brief Function for retrieving the watchdog reload request status.
+ *
+ * @param[in]  rr_register      Reload request register to check.
+ *
+ * @retval     true             If a reload request is running.
+ * @retval     false            If no reload request is running.
+ */
+__STATIC_INLINE bool nrf_wdt_request_status(nrf_wdt_rr_register_t rr_register)
+{
+    return (bool)(((NRF_WDT->REQSTATUS) >> rr_register) & 0x1UL);
+}
+
+
+/**
+ * @brief Function for setting the watchdog reload value.
+ *
+ * @param[in]  reload_value     Watchdog counter initial value.
+ */
+__STATIC_INLINE void nrf_wdt_reload_value_set(uint32_t reload_value)
+{
+    NRF_WDT->CRV = reload_value;
+}
+
+
+/**
+ * @brief Function for retrieving the watchdog reload value.
+ *
+ * @retval                      Reload value.
+ */
+__STATIC_INLINE uint32_t nrf_wdt_reload_value_get(void)
+{
+    return (uint32_t)NRF_WDT->CRV;
+}
+
+
+/**
+ * @brief Function for enabling a specific reload request register.
+ *
+ * @param[in]  rr_register       Reload request register to enable.
+ */
+__STATIC_INLINE void nrf_wdt_reload_request_enable(nrf_wdt_rr_register_t rr_register)
+{
+    NRF_WDT->RREN |= 0x1UL << rr_register;
+}
+
+
+/**
+ * @brief Function for disabling a specific reload request register.
+ *
+ * @param[in]  rr_register       Reload request register to disable.
+ */
+__STATIC_INLINE void nrf_wdt_reload_request_disable(nrf_wdt_rr_register_t rr_register)
+{
+    NRF_WDT->RREN &= ~(0x1UL << rr_register);
+}
+
+
+/**
+ * @brief Function for retrieving the status of a specific reload request register.
+ *
+ * @param[in]  rr_register       Reload request register to check.
+ *
+ * @retval     true              If the reload request register is enabled.
+ * @retval     false             If the reload request register is not enabled.
+ */
+__STATIC_INLINE bool nrf_wdt_reload_request_is_enabled(nrf_wdt_rr_register_t rr_register)
+{
+    return (bool)(NRF_WDT->RREN & (0x1UL << rr_register));
+}
+
+
+/**
+ * @brief Function for setting a specific reload request register.
+ *
+ * @param[in]  rr_register       Reload request register to set.
+ */
+__STATIC_INLINE void nrf_wdt_reload_request_set(nrf_wdt_rr_register_t rr_register)
+{
+    NRF_WDT->RR[rr_register] = NRF_WDT_RR_VALUE;
+}
+
+
+#endif
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/config/pstorage_platform.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/config/pstorage_platform.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+ /** @cond To make doxygen skip this file */
+
+/** @file
+ *  This header contains defines with respect persistent storage that are specific to
+ *  persistent storage implementation and application use case.
+ */
+#ifndef PSTORAGE_PL_H__
+#define PSTORAGE_PL_H__
+
+#include <stdint.h>
+#include "nrf.h"
+
+static __INLINE uint16_t pstorage_flash_page_size()
+{
+  return (uint16_t)NRF_FICR->CODEPAGESIZE;
+}
+
+#define PSTORAGE_FLASH_PAGE_SIZE     pstorage_flash_page_size()          /**< Size of one flash page. */
+#define PSTORAGE_FLASH_EMPTY_MASK    0xFFFFFFFF                          /**< Bit mask that defines an empty address in flash. */
+
+#ifdef NRF51
+#define BOOTLOADER_ADDRESS           (NRF_UICR->BOOTLOADERADDR)
+#elif defined NRF52
+#define BOOTLOADER_ADDRESS           (PSTORAGE_FLASH_EMPTY_MASK)
+#endif 
+
+static __INLINE uint32_t pstorage_flash_page_end()
+{
+   uint32_t bootloader_addr = BOOTLOADER_ADDRESS;
+  
+   return ((bootloader_addr != PSTORAGE_FLASH_EMPTY_MASK) ?
+           (bootloader_addr/ PSTORAGE_FLASH_PAGE_SIZE) : NRF_FICR->CODESIZE);
+}
+
+#define PSTORAGE_FLASH_PAGE_END     pstorage_flash_page_end()
+
+#define PSTORAGE_NUM_OF_PAGES       1                                                           /**< Number of flash pages allocated for the pstorage module excluding the swap page, configurable based on system requirements. */
+#define PSTORAGE_MIN_BLOCK_SIZE     0x0010                                                      /**< Minimum size of block that can be registered with the module. Should be configured based on system requirements, recommendation is not have this value to be at least size of word. */
+
+#define PSTORAGE_DATA_START_ADDR    ((PSTORAGE_FLASH_PAGE_END - PSTORAGE_NUM_OF_PAGES - 1) \
+                                    * PSTORAGE_FLASH_PAGE_SIZE)                                 /**< Start address for persistent data, configurable according to system requirements. */
+#define PSTORAGE_DATA_END_ADDR      ((PSTORAGE_FLASH_PAGE_END - 1) * PSTORAGE_FLASH_PAGE_SIZE)  /**< End address for persistent data, configurable according to system requirements. */
+#define PSTORAGE_SWAP_ADDR          PSTORAGE_DATA_END_ADDR                                      /**< Top-most page is used as swap area for clear and update. */
+
+#define PSTORAGE_MAX_BLOCK_SIZE     PSTORAGE_FLASH_PAGE_SIZE                                    /**< Maximum size of block that can be registered with the module. Should be configured based on system requirements. And should be greater than or equal to the minimum size. */
+#define PSTORAGE_CMD_QUEUE_SIZE     2                                                           /**< Maximum number of flash access commands that can be maintained by the module for all applications. Configurable. */
+
+
+/** Abstracts persistently memory block identifier. */
+typedef uint32_t pstorage_block_t;
+
+typedef struct
+{
+    uint32_t            module_id;      /**< Module ID.*/
+    pstorage_block_t    block_id;       /**< Block ID.*/
+} pstorage_handle_t;
+
+typedef uint16_t pstorage_size_t;      /** Size of length and offset fields. */
+
+/**@brief Handles Flash Access Result Events. To be called in the system event dispatcher of the application. */
+void pstorage_sys_event_handler (uint32_t sys_evt);
+
+#endif // PSTORAGE_PL_H__
+
+/** @} */
+/** @endcond */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,1592 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "pstorage.h"
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include "nordic_common.h"
+#include "nrf_error.h"
+#include "nrf_assert.h"
+#include "nrf.h"
+#include "nrf_soc.h"
+#include "app_util.h"
+#include "app_error.h"
+
+#define INVALID_OPCODE             0x00                                /**< Invalid op code identifier. */
+#define SOC_MAX_WRITE_SIZE         PSTORAGE_FLASH_PAGE_SIZE            /**< Maximum write size allowed for a single call to \ref sd_flash_write as specified in the SoC API. */
+#define RAW_MODE_APP_ID            (PSTORAGE_NUM_OF_PAGES + 1)         /**< Application id for raw mode. */
+
+#if defined(NRF52)
+#define SD_CMD_MAX_TRIES           1000                                /**< Number of times to try a softdevice flash operatoion, specific for nRF52 to account for longest time of flash page erase*/
+#else
+#define SD_CMD_MAX_TRIES           3                                   /**< Number of times to try a softdevice flash operation when the @ref NRF_EVT_FLASH_OPERATION_ERROR sys_evt is received. */
+#endif /* defined(NRF52) */
+
+#define MASK_TAIL_SWAP_DONE        (1 << 0)                            /**< Flag for checking if the tail restore area has been written to swap page. */     
+#define MASK_SINGLE_PAGE_OPERATION (1 << 1)                            /**< Flag for checking if command is a single flash page operation. */
+#define MASK_MODULE_INITIALIZED    (1 << 2)                            /**< Flag for checking if the module has been initialized. */
+#define MASK_FLASH_API_ERR_BUSY    (1 << 3)                            /**< Flag for checking if flash API returned NRF_ERROR_BUSY. */
+
+/**
+ * @defgroup api_param_check API Parameters check macros.
+ *
+ * @details Macros that verify parameters passed to the module in the APIs. These macros
+ *          could be mapped to nothing in final code versions to save execution and size.
+ *
+ * @{
+ */
+
+/**@brief Check if the input pointer is NULL, if so it returns NRF_ERROR_NULL.
+ */
+#define NULL_PARAM_CHECK(PARAM)                                                                   \
+        if ((PARAM) == NULL)                                                                      \
+        {                                                                                         \
+            return NRF_ERROR_NULL;                                                                \
+        }
+
+/**@brief Verifies that the module identifier supplied by the application is within permissible
+ *        range.
+ */
+#define MODULE_ID_RANGE_CHECK(ID)                                                                 \
+        if ((((ID)->module_id) >= PSTORAGE_NUM_OF_PAGES) ||                                       \
+            (m_app_table[(ID)->module_id].cb == NULL))                                            \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+/**@brief Verifies that the block identifier supplied by the application is within the permissible
+ *        range.
+ */
+#define BLOCK_ID_RANGE_CHECK(ID)                                                                  \
+        if (((ID)->block_id) >= (m_app_table[(ID)->module_id].base_id +                           \
+            (m_app_table[(ID)->module_id].block_count * MODULE_BLOCK_SIZE(ID))))                  \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+/**@brief Verifies that the block size requested by the application can be supported by the module.
+ */
+#define BLOCK_SIZE_CHECK(X)                                                                       \
+        if (((X) > PSTORAGE_MAX_BLOCK_SIZE) || ((X) < PSTORAGE_MIN_BLOCK_SIZE))                   \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+/**@brief Verifies the block size requested by the application in registration API.
+ */
+#define BLOCK_COUNT_CHECK(COUNT, SIZE)                                                            \
+        if (((COUNT) == 0) ||                                                                     \
+            ((m_next_page_addr + ((COUNT) *(SIZE)) > PSTORAGE_SWAP_ADDR)))                        \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }        
+
+/**@brief Verifies the size parameter provided by the application in API.
+ */
+#define SIZE_CHECK(ID, SIZE)                                                                      \
+        if(((SIZE) == 0) || ((SIZE) > MODULE_BLOCK_SIZE(ID)))                                     \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+/**@brief Verifies the offset parameter provided by the application in API.
+ */
+#define OFFSET_CHECK(ID, OFFSET, SIZE)                                                            \
+        if(((SIZE) + (OFFSET)) > MODULE_BLOCK_SIZE(ID))                                           \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+
+/**@brief Verifies the module identifier supplied by the application.
+ */
+#define MODULE_RAW_HANDLE_CHECK(ID)                                                               \
+        if ((((ID)->module_id) != RAW_MODE_APP_ID))                                               \
+        {                                                                                         \
+            return NRF_ERROR_INVALID_PARAM;                                                       \
+        }
+
+#endif // PSTORAGE_RAW_MODE_ENABLE
+
+/**@} */
+
+
+/**@brief Verify module's initialization status.
+ *
+ * @details  Verify module's initialization status. Returns NRF_ERROR_INVALID_STATE when a
+ *           module API is called without initializing the module.
+ */
+#define VERIFY_MODULE_INITIALIZED()                                                               \
+        do                                                                                        \
+        {                                                                                         \
+            if (!(m_flags & MASK_MODULE_INITIALIZED))                                             \
+            {                                                                                     \
+                 return NRF_ERROR_INVALID_STATE;                                                  \
+            }                                                                                     \
+        } while(0)
+
+/**@brief Macro to fetch the block size registered for the module. */
+#define MODULE_BLOCK_SIZE(ID) (m_app_table[(ID)->module_id].block_size)
+
+/**@brief Main state machine of the component. */
+typedef enum
+{
+    STATE_IDLE,                                                        /**< State for being idle (no command execution in progress). */
+    STATE_STORE,                                                       /**< State for storing data when using store/update API. */
+    STATE_DATA_ERASE_WITH_SWAP,                                        /**< State for erasing the data page when using update/clear API when use of swap page is required. */
+    STATE_DATA_ERASE,                                                  /**< State for erasing the data page when using update/clear API without the need to use the swap page. */
+    STATE_ERROR                                                        /**< State entered when command processing is terminated abnormally. */
+} pstorage_state_t;  
+
+/**@brief Sub state machine contained by @ref STATE_DATA_ERASE_WITH_SWAP super state machine. */
+typedef enum
+{
+    STATE_ERASE_SWAP,                                                  /**< State for erasing the swap page when using the update/clear API. */   
+    STATE_WRITE_DATA_TO_SWAP,                                          /**< State for writing the data page into the swap page when using update/clear API. */
+    STATE_ERASE_DATA_PAGE,                                             /**< State for erasing data page when using update/clear API. */
+    STATE_RESTORE_TAIL,                                                /**< State for restoring tail (end) of backed up data from swap to data page when using update/clear API. */
+    STATE_RESTORE_HEAD,                                                /**< State for restoring head (beginning) of backed up data from swap to data page when using update/clear API. */
+    SWAP_SUB_STATE_MAX                                                 /**< Enumeration upper bound. */   
+} flash_swap_sub_state_t;
+
+/**@brief Application registration information.
+ *
+ * @details Defines application specific information that the application needs to maintain to be able 
+ *          to process requests from each one of them.
+ */
+typedef struct
+{
+    pstorage_ntf_cb_t cb;                                              /**< Callback registered with the module to be notified of result of flash access.  */
+    pstorage_block_t  base_id;                                         /**< Base block ID assigned to the module. */
+    pstorage_size_t   block_size;                                      /**< Size of block for the module. */
+    pstorage_size_t   block_count;                                     /**< Number of blocks requested by the application. */
+} pstorage_module_table_t;
+
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+/**@brief Application registration information.
+ *
+ * @details Defines application specific information that the application registered for raw mode.
+ */
+typedef struct
+{
+    pstorage_ntf_cb_t cb;                                              /**< Callback registered with the module to be notified of the result of flash access.  */
+} pstorage_raw_module_table_t;
+#endif // PSTORAGE_RAW_MODE_ENABLE
+
+
+/**@brief Defines command queue element.
+ *
+ * @details Defines command queue element. Each element encapsulates needed information to process
+ *          a flash access command.
+ */
+typedef struct
+{
+    uint8_t           op_code;                                         /**< Identifies the flash access operation being queued. Element is free if op-code is INVALID_OPCODE. */
+    pstorage_size_t   size;                                            /**< Identifies the size in bytes requested for the operation. */
+    pstorage_size_t   offset;                                          /**< Offset requested by the application for the access operation. */
+    pstorage_handle_t storage_addr;                                    /**< Address/Identifier for persistent memory. */
+    uint8_t *         p_data_addr;                                     /**< Address/Identifier for data memory. This is assumed to be resident memory. */
+} cmd_queue_element_t;
+
+
+/**@brief   Defines command queue, an element is free if the op_code field is not invalid.
+ *
+ * @details Defines commands enqueued for flash access. At any point in time, this queue has one or
+ *          more flash access operations pending if the count field is not zero. When the queue is
+ *          not empty, the rp (read pointer) field points to the flash access command in progress 
+ *          or, if none is in progress, the command to be requested next. The queue implements a 
+ *          simple first in first out algorithm. Data addresses are assumed to be resident.
+ */
+typedef struct
+{
+    uint8_t             rp;                                            /**< Read pointer, pointing to flash access that is ongoing or to be requested next. */
+    uint8_t             count;                                         /**< Number of elements in the queue.  */
+    cmd_queue_element_t cmd[PSTORAGE_CMD_QUEUE_SIZE];                  /**< Array to maintain flash access operation details. */
+} cmd_queue_t;
+
+static cmd_queue_t             m_cmd_queue;                            /**< Flash operation request queue. */
+static pstorage_size_t         m_next_app_instance;                    /**< Points to the application module instance that can be allocated next. */
+static uint32_t                m_next_page_addr;                       /**< Points to the flash address that can be allocated to a module next. This is needed as blocks of a module that can span across flash pages. */
+static pstorage_state_t        m_state;                                /**< Main state tracking variable. */
+static flash_swap_sub_state_t  m_swap_sub_state;                       /**< Flash swap erase when swap used state tracking variable. */
+static uint32_t                m_head_word_size;                       /**< Head restore area size in words. */
+static uint32_t                m_tail_word_size;                       /**< Tail restore area size in words. */
+static uint32_t                m_current_page_id;                      /**< Variable for tracking the flash page being processed. */
+static uint32_t                m_num_of_command_retries;               /**< Variable for tracking flash operation retries upon flash operation failures. */
+static pstorage_module_table_t m_app_table[PSTORAGE_NUM_OF_PAGES];     /**< Registered application information table. */
+static uint32_t                m_num_of_bytes_written;                 /**< Variable for tracking the number of bytes written by the store operation. */
+static uint32_t                m_app_data_size;                        /**< Variable for storing the application command size parameter internally. */
+static uint32_t                m_flags = 0;                            /**< Storage for boolean flags for state tracking. */
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+static pstorage_raw_module_table_t m_raw_app_table;                    /**< Registered application information table for raw mode. */
+#endif // PSTORAGE_RAW_MODE_ENABLE
+
+// Required forward declarations.
+static void cmd_process(void);
+static void store_operation_execute(void);
+static void app_notify(uint32_t result, cmd_queue_element_t * p_elem);
+static void cmd_queue_element_init(uint32_t index);
+static void cmd_queue_dequeue(void);
+static void sm_state_change(pstorage_state_t new_state);
+static void swap_sub_state_state_change(flash_swap_sub_state_t new_state); 
+
+/**@brief Function for consuming a command queue element.
+ *
+ * @details Function for consuming a command queue element, which has been fully processed.
+ */
+static void command_queue_element_consume(void)
+{
+    // Initialize/free the element as it is now processed.    
+    cmd_queue_element_init(m_cmd_queue.rp);
+
+    // Adjust command queue state tracking variables.
+    --(m_cmd_queue.count);   
+    if (++(m_cmd_queue.rp) == PSTORAGE_CMD_QUEUE_SIZE)
+    {
+        m_cmd_queue.rp = 0;
+    }    
+}
+
+
+/**@brief Function for executing the finalization procedure for the command executed.
+ *
+ * @details Function for executing the finalization procedure for command executed, which includes 
+ *          notifying the application of command completion, consuming the command queue element, 
+ *          and changing the internal state.
+ */
+static void command_end_procedure_run(void)
+{    
+    app_notify(NRF_SUCCESS, &m_cmd_queue.cmd[m_cmd_queue.rp]);
+    
+    command_queue_element_consume();
+    
+    sm_state_change(STATE_IDLE);
+}
+
+
+/**@brief Function for idle state entry actions.
+ *
+ * @details Function for idle state entry actions, which include resetting relevant state data and 
+ *          scheduling any possible queued flash access operation.
+ */
+static void state_idle_entry_run(void)
+{
+    m_num_of_command_retries = 0;
+    m_num_of_bytes_written   = 0;
+    
+    // Schedule any possible queued flash access operation.
+    cmd_queue_dequeue();
+}
+
+
+/**@brief Function for notifying an application of command completion and transitioning to an error 
+ *        state.
+ *
+ * @param[in] result Result code of the operation for the application.
+ */
+static void app_notify_error_state_transit(uint32_t result)
+{
+    app_notify(result, &m_cmd_queue.cmd[m_cmd_queue.rp]);
+    sm_state_change(STATE_ERROR);                
+}
+
+
+/**@brief Function for processing flash API error code.
+ *
+ * @param[in] err_code Error code from the flash API.
+ */
+static void flash_api_err_code_process(uint32_t err_code)
+{
+    switch (err_code)
+    {
+        case NRF_SUCCESS:
+            break;
+            
+        case NRF_ERROR_BUSY:
+            // Flash access operation was not accepted and must be reissued upon flash operation 
+            // complete event.
+            m_flags |= MASK_FLASH_API_ERR_BUSY;        
+            break;
+            
+        default:
+            // Complete the operation with appropriate result code and transit to an error state. 
+            app_notify_error_state_transit(err_code);
+            break;
+    }
+}
+
+/**@brief Function for writing data to flash.
+ *
+ * @param[in] p_dst         Pointer to start of flash location to be written.
+ * @param[in] p_src         Pointer to buffer with data to be written.
+ * @param[in] size_in_words Number of 32-bit words to write. 
+ */
+static void flash_write(uint32_t * const       p_dst, 
+                        uint32_t const * const p_src, 
+                        uint32_t               size_in_words)
+{
+    flash_api_err_code_process(sd_flash_write(p_dst, p_src, size_in_words));    
+}
+
+
+/**@brief Function for writing data to flash upon store command.
+ *
+ * @details Function for writing data to flash upon executing store command. Data is written to 
+ *          flash in reverse order, meaning starting at the end. If the data that is to be written 
+ *          is greater than the flash page size, it will be fragmented to fit the flash page size.
+ */
+static void store_cmd_flash_write_execute(void)
+{
+    const cmd_queue_element_t * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    
+    if (p_cmd->size > SOC_MAX_WRITE_SIZE)    
+    {
+        const uint32_t offset = p_cmd->size - PSTORAGE_FLASH_PAGE_SIZE;
+        flash_write((uint32_t *)(p_cmd->storage_addr.block_id + p_cmd->offset + offset),
+                    (uint32_t *)(p_cmd->p_data_addr + offset), 
+                    PSTORAGE_FLASH_PAGE_SIZE / sizeof(uint32_t));   
+
+        m_num_of_bytes_written = PSTORAGE_FLASH_PAGE_SIZE;    
+    }
+    else
+    {
+        flash_write((uint32_t *)(p_cmd->storage_addr.block_id + p_cmd->offset),
+                    (uint32_t *)(p_cmd->p_data_addr), 
+                    p_cmd->size / sizeof(uint32_t));   
+
+        m_num_of_bytes_written = p_cmd->size;        
+    }    
+}
+
+
+/**@brief Function for store state entry action.
+ *
+ * @details Function for store state entry action, which includes writing data to a flash page.
+ */
+static void state_store_entry_run(void)
+{
+    store_cmd_flash_write_execute();    
+}
+
+
+/**@brief Function for data erase with swap state entry actions.
+ *
+ * @details Function for data erase with swap state entry actions. This includes adjusting relevant 
+ *          state and data variables and transitioning to the correct sub state.
+ */
+static void state_data_erase_swap_entry_run(void)
+{
+    m_flags &= ~MASK_TAIL_SWAP_DONE;
+    
+    const cmd_queue_element_t * p_cmd        = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    const pstorage_block_t      cmd_block_id = p_cmd->storage_addr.block_id;
+    
+    const uint32_t clear_start_page_id = cmd_block_id / PSTORAGE_FLASH_PAGE_SIZE;
+    m_current_page_id                  = clear_start_page_id;      
+        
+    // @note: No need to include p_cmd->offset when calculating clear_end_page_id as:
+    // - clear API does not include offset parameter
+    // - update and store APIs are limited to operate on single block boundary thus the boolean 
+    // clause ((m_head_word_size == 0) && is_more_than_one_page) below in this function  will never 
+    // evaluate as true as if is_more_than_one_page == true m_head_word_size is always != 0        
+    const uint32_t clear_end_page_id  = (cmd_block_id + p_cmd->size - 1u) / 
+                                        PSTORAGE_FLASH_PAGE_SIZE;
+
+    if (clear_start_page_id == clear_end_page_id)
+    {
+        m_flags |= MASK_SINGLE_PAGE_OPERATION;
+    }
+    else
+    {
+        m_flags &= ~MASK_SINGLE_PAGE_OPERATION;
+    }
+                            
+    if ((m_head_word_size == 0) && !(m_flags & MASK_SINGLE_PAGE_OPERATION))
+    {        
+        // No head restore required and clear/update area is shared by multiple flash pages, which 
+        // means the current flash page does not have any tail area to restore. You can proceed with 
+        // data page erase directly as no swap is needed for the current flash page.
+        swap_sub_state_state_change(STATE_ERASE_DATA_PAGE);        
+    }
+    else
+    {     
+        swap_sub_state_state_change(STATE_ERASE_SWAP);
+    }               
+}
+
+
+/**@brief Function for erasing flash page.
+ *
+ * @param[in] page_number Page number of the page to be erased.
+ */
+static void flash_page_erase(uint32_t page_number)
+{
+    flash_api_err_code_process(sd_flash_page_erase(page_number));
+}
+
+
+/**@brief Function for data erase state entry action.
+ *
+ * @details Function for data erase state entry action, which includes erasing the data flash page.
+ */
+static void state_data_erase_entry_run(void)
+{
+    flash_page_erase(m_current_page_id);                          
+}
+
+
+/**@brief Function for dispatching the correct application main state entry action.
+ */
+static void state_entry_action_run(void)
+{
+    switch (m_state)
+    {
+        case STATE_IDLE:
+            state_idle_entry_run();
+            break;
+
+        case STATE_STORE:
+            state_store_entry_run();
+            break;
+            
+        case STATE_DATA_ERASE_WITH_SWAP:
+            state_data_erase_swap_entry_run();
+            break;
+            
+        case STATE_DATA_ERASE:
+            state_data_erase_entry_run();        
+            break;
+                        
+        default:
+            // No action needed.
+            break;
+    }
+}
+
+
+/**@brief Function for changing application main state and dispatching state entry action.
+ *
+ * @param[in] new_state New application main state to transit to.
+ */
+static void sm_state_change(pstorage_state_t new_state)
+{
+    m_state = new_state;
+    state_entry_action_run();
+}
+
+
+/**@brief Function for swap erase state entry action.
+ *
+ * @details Function for swap erase state entry action, which includes erasing swap flash 
+ *          page.
+ */
+static void state_swap_erase_entry_run(void)
+{
+    flash_page_erase(PSTORAGE_SWAP_ADDR / PSTORAGE_FLASH_PAGE_SIZE);                
+}
+
+
+/**@brief Function for write data to the swap state entry action.
+ *
+ * @details Function for write data to the swap state entry action, which includes writing the 
+ *          current data page to the swap flash page.
+ */
+static void state_write_data_swap_entry_run(void)
+{
+    // @note: There is room for further optimization here as there is only need to write the
+    // whole flash page to swap area if there is both head and tail area to be restored. In any 
+    // other case we can omit some data from the head or end of the page as that is the clear area.
+    flash_write((uint32_t *)(PSTORAGE_SWAP_ADDR), 
+                (uint32_t *)(m_current_page_id * PSTORAGE_FLASH_PAGE_SIZE), 
+                PSTORAGE_FLASH_PAGE_SIZE / sizeof(uint32_t));    
+}
+
+
+/**@brief Function for erase data page state entry action.
+ *
+ * @details Function for erase data page state entry action, which includes erasing the data flash 
+ *          page.
+ */
+static void state_erase_data_page_entry_run(void)
+{
+    flash_page_erase(m_current_page_id);
+}
+
+
+/**@brief Function for restore tail state entry action.
+ *
+ * @details Function for restore tail state entry action, which includes writing the tail section 
+ *          back from swap to the data page.
+ */
+static void state_restore_tail_entry_run(void)
+{
+    const cmd_queue_element_t * p_cmd        = &m_cmd_queue.cmd[m_cmd_queue.rp];    
+    const pstorage_block_t      cmd_block_id = p_cmd->storage_addr.block_id;                            
+    
+    const uint32_t tail_offset = (cmd_block_id + p_cmd->size + p_cmd->offset) % 
+                                 PSTORAGE_FLASH_PAGE_SIZE; 
+                                 
+    flash_write((uint32_t *)(cmd_block_id + p_cmd->size + p_cmd->offset),
+                (uint32_t *)(PSTORAGE_SWAP_ADDR + tail_offset),
+                m_tail_word_size);
+}
+
+
+/**@brief Function for restore head state entry action.
+ *
+ * @details Function for restore head state entry action, which includes writing the head section 
+ *          back from swap to the data page.
+ */
+static void state_restore_head_entry_run(void)
+{
+    flash_write((uint32_t *)((m_current_page_id - 1u) * PSTORAGE_FLASH_PAGE_SIZE),
+                (uint32_t *)PSTORAGE_SWAP_ADDR,
+                m_head_word_size);
+}
+
+
+/**@brief Function for dispatching the correct swap sub state entry action.
+ */
+static void swap_sub_state_entry_action_run(void)
+{
+    static void (* const swap_sub_state_sm_lut[SWAP_SUB_STATE_MAX])(void) = 
+    {
+        state_swap_erase_entry_run,
+        state_write_data_swap_entry_run,
+        state_erase_data_page_entry_run,
+        state_restore_tail_entry_run,
+        state_restore_head_entry_run
+    };
+    
+    swap_sub_state_sm_lut[m_swap_sub_state]();
+}
+
+
+/**@brief Function for changing the swap sub state and dispatching state entry action.
+ *
+ * @param[in] new_state New swap sub state to transit to.
+ */   
+static void swap_sub_state_state_change(flash_swap_sub_state_t new_state)
+{
+    m_swap_sub_state = new_state;
+    swap_sub_state_entry_action_run();    
+}
+
+
+/**@brief Function for initializing the command queue element.
+ *
+ * @param[in] index Index of the element to be initialized.
+ */
+static void cmd_queue_element_init(uint32_t index)
+{
+    // Internal function and checks on range of index can be avoided.
+    m_cmd_queue.cmd[index].op_code                = INVALID_OPCODE;
+    m_cmd_queue.cmd[index].size                   = 0;
+    m_cmd_queue.cmd[index].storage_addr.module_id = PSTORAGE_NUM_OF_PAGES;
+    m_cmd_queue.cmd[index].storage_addr.block_id  = 0;
+    m_cmd_queue.cmd[index].p_data_addr            = NULL;
+    m_cmd_queue.cmd[index].offset                 = 0;
+}
+
+
+/**@brief Function for initializing the command queue.
+ */
+static void cmd_queue_init(void)
+{
+    m_cmd_queue.rp    = 0;
+    m_cmd_queue.count = 0;
+
+    for (uint32_t cmd_index = 0; cmd_index < PSTORAGE_CMD_QUEUE_SIZE; ++cmd_index)
+    {
+        cmd_queue_element_init(cmd_index);
+    }
+}
+
+
+/**@brief Function for enqueuing, and possibly dispatching, a flash access operation.
+ *
+ * @param[in] opcode         Identifies the operation requested to be enqueued.
+ * @param[in] p_storage_addr Identifies the module and flash address on which the operation is 
+ *                           requested.
+ * @param[in] p_data_addr    Identifies the data address for flash access.
+ * @param[in] size           Size in bytes of data requested for the access operation.
+ * @param[in] offset         Offset within the flash memory block at which operation is requested.
+ *
+ * @retval    NRF_SUCCESS      Upon success.
+ * @retval    NRF_ERROR_NO_MEM Upon failure, when no space is available in the command queue. 
+ */
+static uint32_t cmd_queue_enqueue(uint8_t             opcode,
+                                  pstorage_handle_t * p_storage_addr,
+                                  uint8_t           * p_data_addr,
+                                  pstorage_size_t     size,
+                                  pstorage_size_t     offset)
+{
+    uint32_t err_code;
+
+    if (m_cmd_queue.count != PSTORAGE_CMD_QUEUE_SIZE)
+    {
+        // Enqueue the command if it the queue is not full.
+        uint32_t write_index = m_cmd_queue.rp + m_cmd_queue.count;
+
+        if (write_index >= PSTORAGE_CMD_QUEUE_SIZE) 
+        {
+            write_index -= PSTORAGE_CMD_QUEUE_SIZE;
+        }
+
+        m_cmd_queue.cmd[write_index].op_code      = opcode;
+        m_cmd_queue.cmd[write_index].p_data_addr  = p_data_addr;
+        m_cmd_queue.cmd[write_index].storage_addr = (*p_storage_addr);
+        m_cmd_queue.cmd[write_index].size         = size;
+        m_cmd_queue.cmd[write_index].offset       = offset;
+               
+        m_cmd_queue.count++;
+                                
+        if (m_state == STATE_IDLE)
+        {
+            cmd_process(); 
+        }            
+        
+        err_code = NRF_SUCCESS;        
+    }
+    else
+    {
+        err_code = NRF_ERROR_NO_MEM;
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for dequeing a possible pending flash access operation.
+ */
+static void cmd_queue_dequeue(void)
+{
+    if ((m_cmd_queue.count != 0)) 
+    {
+        cmd_process();
+    }
+}
+
+
+/**@brief Function for notifying an application of command completion.
+ *
+ * @param[in] result Result code of the operation for the application.
+ * @param[in] p_elem Pointer to the command queue element for which this result was received. 
+ */
+static void app_notify(uint32_t result, cmd_queue_element_t * p_elem)
+{
+    pstorage_ntf_cb_t ntf_cb;
+    const uint8_t     op_code = p_elem->op_code;
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+    if (p_elem->storage_addr.module_id == RAW_MODE_APP_ID)
+    {
+        ntf_cb = m_raw_app_table.cb;
+    }
+    else
+#endif // PSTORAGE_RAW_MODE_ENABLE
+    {
+        ntf_cb = m_app_table[p_elem->storage_addr.module_id].cb;
+    }
+
+    ntf_cb(&p_elem->storage_addr, op_code, result, p_elem->p_data_addr, m_app_data_size);
+}
+
+
+/**@brief Function for evaluating if a data page swap is required for the tail section on the 
+ *        current page.
+ *
+ * @retval true  If data page swap is required.
+ * @retval false If data page swap is not required.
+ */
+static bool is_tail_data_page_swap_required(void)
+{
+    bool ret_value;
+
+    // Extract id of the last page command is executed upon.
+    const cmd_queue_element_t * p_cmd        = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    const pstorage_block_t      cmd_block_id = p_cmd->storage_addr.block_id;        
+    const uint32_t              last_page_id = (cmd_block_id + p_cmd->size + p_cmd->offset - 1u) / 
+                                               PSTORAGE_FLASH_PAGE_SIZE;    
+        
+    // If tail section area exists and the current page is the last page then tail data page swap is 
+    // required.    
+    if ((m_tail_word_size != 0) && (m_current_page_id == last_page_id))
+    {
+        ret_value = true;
+    }
+    else
+    {
+        ret_value = false;    
+    }
+    
+    return ret_value;
+}
+
+
+/**@brief Function for performing post processing for the update and clear commands.
+ *
+ * @details Function for performing post processing for the update and clear commands, which implies 
+ *          executing the correct execution path depending on the command. 
+ */
+static void clear_post_processing_run(void)
+{
+    const cmd_queue_element_t * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp]; 
+    
+    if (p_cmd->op_code != PSTORAGE_UPDATE_OP_CODE)
+    {
+        command_end_procedure_run();    
+    }
+    else
+    {
+        store_operation_execute();                    
+    }
+}
+
+
+/**@brief Function for doing swap sub state exit action.
+ */
+static void swap_sub_sm_exit_action_run(void)
+{
+    clear_post_processing_run();
+}
+
+
+/**@brief Function for evaluating if the page erase operation is required for the current page.
+ *
+ * @retval true  If page erase is required.
+ * @retval false If page erase is not required. 
+ */
+static bool is_page_erase_required(void)
+{
+    bool ret;
+    
+    const cmd_queue_element_t * p_cmd                      = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    const pstorage_block_t      cmd_block_id               = p_cmd->storage_addr.block_id;        
+    const uint32_t              id_last_page_to_be_cleared = (cmd_block_id + p_cmd->size + 
+                                                             p_cmd->offset - 1u) / 
+                                                             PSTORAGE_FLASH_PAGE_SIZE;
+
+    // True if:
+    // - current page is not the last page OR
+    // - current page is the last page AND no tail exists
+    if ((m_current_page_id < id_last_page_to_be_cleared) ||
+        ((m_current_page_id == id_last_page_to_be_cleared) && (m_tail_word_size == 0)))         
+    {
+        ret = true;
+    }
+    else
+    {
+        ret = false;
+    }
+    
+    return ret;
+}
+
+
+/**@brief Function for reissuing the last flash operation request, which was rejected by the flash 
+ *        API, in swap sub sate.
+ */
+static void swap_sub_state_err_busy_process(void)
+{
+    // Reissue the request by doing a self transition to the current state.    
+    m_flags &= ~MASK_FLASH_API_ERR_BUSY;
+    swap_sub_state_state_change(m_swap_sub_state);        
+}
+
+
+/**@brief Function for doing restore head state action upon flash operation success event.
+ *
+ * @details Function for doing restore head state action upon flash operation success event, which 
+ *          includes making a state transition depending on the current state.
+ */
+static void head_restore_state_run(void)
+{
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {            
+        if (is_tail_data_page_swap_required())
+        {
+            // Additional data page needs to be swapped for tail section as we are clearing a block, 
+            // which is shared between 2 flash pages.
+                    
+            // Adjust variables to ensure correct state transition path is taken after the tail 
+            // section swap has completed.
+            m_head_word_size = 0;   
+            m_flags         |= MASK_TAIL_SWAP_DONE;        
+                  
+            swap_sub_state_state_change(STATE_ERASE_SWAP);        
+        }
+        else if (is_page_erase_required())
+        {
+            // Additional page erase operation is required.
+                    
+            // Adjust variable to ensure correct state transition path is taken after the additional 
+            // page erase operation has completed.
+            m_head_word_size = 0;
+            swap_sub_state_state_change(STATE_ERASE_DATA_PAGE);        
+        }            
+        else if (m_tail_word_size != 0)
+        {
+            // Proceed with restoring tail from swap to data page. 
+            swap_sub_state_state_change(STATE_RESTORE_TAIL);
+        }
+        else
+        {            
+            // Swap statemachine execution end reached.
+            swap_sub_sm_exit_action_run();        
+        }
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        swap_sub_state_err_busy_process();        
+    }
+}
+
+
+/**@brief Function for doing restore tail state action upon flash operation success event.
+ */
+static void tail_restore_state_run(void)
+{
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {
+        swap_sub_sm_exit_action_run();        
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        swap_sub_state_err_busy_process();        
+    }    
+}
+
+
+/**@brief Function for doing data page erase state action upon a flash operation success event.
+ *
+ * @details Function for doing data page erase state action upon a flash operation success event, 
+ *          which includes making a state transit to a new state depending on the current state.
+ */
+static void data_page_erase_state_run(void)
+{            
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {
+        ++m_current_page_id;   
+                    
+        if (m_head_word_size != 0)
+        {            
+            swap_sub_state_state_change(STATE_RESTORE_HEAD);
+        }
+        else if (is_page_erase_required())
+        {
+            // Additional page erase operation is required.    
+            swap_sub_state_state_change(STATE_ERASE_DATA_PAGE);                
+        }                
+        else if (m_tail_word_size != 0)
+        {                    
+            if (!(m_flags & MASK_TAIL_SWAP_DONE)) 
+            {
+                // Tail area restore is required and we have not yet written the relevant data page 
+                // to swap area. Start the process of writing the data page to swap.
+                m_flags |= MASK_TAIL_SWAP_DONE;            
+
+                swap_sub_state_state_change(STATE_ERASE_SWAP);            
+            }
+            else
+            {
+                // Tail area restore is required and we have already written the relevant data page 
+                // to swap area. Proceed by restoring the tail area.
+                swap_sub_state_state_change(STATE_RESTORE_TAIL);            
+            }
+        }            
+        else
+        {
+            swap_sub_sm_exit_action_run();        
+        }        
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        swap_sub_state_err_busy_process();        
+    }
+}
+
+
+/**@brief Function for doing data to swap write state action upon flash operation success event.
+ */
+static void data_to_swap_write_state_run(void)
+{        
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {
+        // If the operation is executed only on 1 single flash page it automatically means that tail 
+        // area is written to the swap, which we store to flags.     
+        if (m_flags & MASK_SINGLE_PAGE_OPERATION)
+        {
+            m_flags |= MASK_TAIL_SWAP_DONE;        
+        }
+
+        swap_sub_state_state_change(STATE_ERASE_DATA_PAGE);    
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        swap_sub_state_err_busy_process();        
+    }        
+}
+
+
+/**@brief Function for doing swap erase state action upon flash operation success event.
+ */
+static void swap_erase_state_run(void)
+{
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {        
+        swap_sub_state_state_change(STATE_WRITE_DATA_TO_SWAP);
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        swap_sub_state_err_busy_process();        
+    }
+}
+
+
+/**@brief Function for dispatching the correct state action for data erase with a swap composite 
+*         state upon a flash operation success event.
+ */
+static void swap_sub_state_sm_run(void)
+{  
+    static void (* const swap_sub_state_sm_lut[SWAP_SUB_STATE_MAX])(void) = 
+    {
+        swap_erase_state_run,
+        data_to_swap_write_state_run,
+        data_page_erase_state_run,
+        tail_restore_state_run,
+        head_restore_state_run
+    };
+    
+    swap_sub_state_sm_lut[m_swap_sub_state]();    
+}
+
+
+/**@brief Function for reissuing the last flash operation request, which was rejected by the flash 
+ *        API, in main sate.
+ */
+static void main_state_err_busy_process(void)
+{
+    // Reissue the request by doing a self transition to the current state.    
+    m_flags &= ~MASK_FLASH_API_ERR_BUSY;
+    sm_state_change(m_state);                    
+}
+
+
+/**@brief Function for doing erase state action upon flash operation success event.
+ *
+ * @details Function for doing erase state action upon flash operation success event, which includes 
+ *          making a state transition depending on the current state.
+ */
+static void erase_sub_state_sm_run(void)
+{
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {        
+        // Clear operation request has succeeded.
+        ++m_current_page_id;                        
+                
+        if (!is_page_erase_required())
+        {
+            clear_post_processing_run();
+        }
+        else
+        {   
+            // All required flash pages have not yet been erased, issue erase by doing a self 
+            // transit. 
+            sm_state_change(m_state);        
+        }                              
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        main_state_err_busy_process();
+    }
+}
+
+
+/**@brief Function for doing store state action upon flash operation success event.
+ */
+static void store_sub_state_sm_run(void)
+{
+    if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+    {        
+        // As write operation request has succeeded, adjust the size tracking state information 
+        // accordingly.
+        cmd_queue_element_t * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];    
+        p_cmd->size                -= m_num_of_bytes_written;
+
+        if (p_cmd->size == 0)
+        {
+            command_end_procedure_run();
+        }
+        else
+        {
+            store_cmd_flash_write_execute();
+        }
+    }
+    else
+    {
+        // As operation request was rejected by the flash API reissue the request.
+        main_state_err_busy_process();
+    }
+}
+
+
+/**@brief Function for doing action upon flash operation success event.
+ */
+static void flash_operation_success_run(void)
+{    
+    switch (m_state)
+    {                   
+        case STATE_STORE:
+            store_sub_state_sm_run();
+            break;
+                        
+        case STATE_DATA_ERASE:
+            erase_sub_state_sm_run();
+            break;
+                        
+        case STATE_DATA_ERASE_WITH_SWAP:
+            swap_sub_state_sm_run();                        
+            break;                        
+            
+        default:
+            // No implementation needed.
+            break;
+    }                    
+}
+
+
+/**@brief Function for doing action upon flash operation failure event.
+ *
+ * @details Function for doing action upon flash operation failure event, which includes retrying 
+ *          the last operation or if retry count has been reached completing the operation with 
+ *          appropriate result code and transitioning to an error state.
+ *
+ * @note    The command is not removed from the command queue, which will result to stalling of the 
+ *          command pipeline and the appropriate application recovery procedure for this is to reset 
+ *          the system by issuing @ref pstorage_init which will also result to flushing of the 
+ *          command queue.
+ */
+static void flash_operation_failure_run(void)
+{   
+    if (++m_num_of_command_retries != SD_CMD_MAX_TRIES)
+    {
+        // Retry the last operation by doing a self transition to the current state.
+            
+        if (m_state != STATE_DATA_ERASE_WITH_SWAP)
+        {
+            sm_state_change(m_state);        
+        }
+        else
+        {
+            swap_sub_state_state_change(m_swap_sub_state);
+        }
+    }
+    else
+    {
+        // Complete the operation with appropriate result code and transit to an error state.     
+        app_notify_error_state_transit(NRF_ERROR_TIMEOUT);        
+    }   
+}
+
+
+/**@brief Function for handling flash access result events.
+ *
+ * @param[in] sys_evt System event to be handled.
+ */
+void pstorage_sys_event_handler(uint32_t sys_evt)
+{  
+    if (m_state != STATE_IDLE && m_state != STATE_ERROR)
+    {        
+        switch (sys_evt)
+        {
+            case NRF_EVT_FLASH_OPERATION_SUCCESS:
+                flash_operation_success_run();
+                break;
+            
+            case NRF_EVT_FLASH_OPERATION_ERROR:            
+                if (!(m_flags & MASK_FLASH_API_ERR_BUSY))
+                {
+                    flash_operation_failure_run();
+                }
+                else
+                {
+                    // As our last flash operation request was rejected by the flash API reissue the 
+                    // request by doing same code execution path as for flash operation sucess 
+                    // event. This will promote code reuse in the implementation.                    
+                    flash_operation_success_run();
+                }                
+                break;
+                
+            default:
+                // No implementation needed.
+                break;
+        }
+
+    }
+}
+
+
+/**@brief Function for calculating the tail area size in number of 32-bit words.
+ *
+ * @param[in] cmd_end_of_storage_address End of storage area within the scope of the command.
+ * @param[in] end_of_storage_address     End of allocated storage area for the application.
+ */
+static void tail_word_size_calculate(pstorage_size_t cmd_end_of_storage_address, 
+                                     pstorage_size_t end_of_storage_address)
+{ 
+    // Two different cases to resolve when calculating correct size for restore tail section:
+    // 1) End of storage area and command end area are in the same page.
+    // 2) End of storage area and command end area are not in the same page.
+    
+    const uint32_t end_of_storage_area_page         = end_of_storage_address     / 
+                                                      PSTORAGE_FLASH_PAGE_SIZE;
+    const uint32_t command_end_of_storage_area_page = cmd_end_of_storage_address / 
+                                                      PSTORAGE_FLASH_PAGE_SIZE;
+
+    if (end_of_storage_area_page == command_end_of_storage_area_page)
+    {
+        //lint -e{573} suppress "Signed-unsigned mix with divide".
+        m_tail_word_size = (end_of_storage_address - cmd_end_of_storage_address) / sizeof(uint32_t);                                           
+    }
+    else
+    {
+        //lint -e{573} suppress "Signed-unsigned mix with divide".    
+        m_tail_word_size = (PSTORAGE_FLASH_PAGE_SIZE - 
+                           (cmd_end_of_storage_address % PSTORAGE_FLASH_PAGE_SIZE)) / 
+                           sizeof(uint32_t);               
+    }            
+}
+
+
+/**@brief Function for executing the clear operation.
+ */
+static void clear_operation_execute(void)
+{    
+    const cmd_queue_element_t * p_cmd        = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    const pstorage_block_t      cmd_block_id = p_cmd->storage_addr.block_id;
+
+    const pstorage_size_t  block_size    = m_app_table[p_cmd->storage_addr.module_id].block_size;
+    const pstorage_size_t  block_count   = m_app_table[p_cmd->storage_addr.module_id].block_count;
+    const pstorage_block_t block_base_id = m_app_table[p_cmd->storage_addr.module_id].base_id;  
+      
+    const bool is_start_address_page_aligned = (cmd_block_id % PSTORAGE_FLASH_PAGE_SIZE) == 0;
+    
+    // Calculate the end (1 beyond allocated area) for complete storage area and to the area only 
+    // within scope of this command.
+    const pstorage_block_t end_of_storage_address     = block_base_id + (block_size * block_count); 
+    const pstorage_block_t cmd_end_of_storage_address = cmd_block_id + p_cmd->size + p_cmd->offset;
+
+    // Zero tail to make sure no extra erase is done erroneously.
+    m_tail_word_size = 0;        
+        
+    // If the following is true no swap access is needed:
+    // - 1st logical test covers the case of: clear/update 1 complete single page.
+    // - 2nd logical test covers the case of: 
+    //   1) Clear/update last allocated page and page is not full (page can't be shared between 
+    //      multiple clients so the end of the page is unused area).
+    //   2) Clear/update all allocated storage.
+    if ((is_start_address_page_aligned && (p_cmd->size == PSTORAGE_FLASH_PAGE_SIZE)) ||
+        (is_start_address_page_aligned && (cmd_end_of_storage_address == end_of_storage_address) && 
+        (p_cmd->offset == 0)) || (p_cmd->storage_addr.module_id == RAW_MODE_APP_ID)) 
+    {
+        // Nothing to put to the swap and we can just erase the pages(s).         
+        
+        m_current_page_id = cmd_block_id / PSTORAGE_FLASH_PAGE_SIZE;
+        
+        sm_state_change(STATE_DATA_ERASE);                        
+    }
+    else
+    {
+        // Not all the blocks for the module can be cleared, we need to use swap page for storing 
+        // data temporarily.                        
+        
+        m_head_word_size = ((cmd_block_id + p_cmd->offset) % PSTORAGE_FLASH_PAGE_SIZE) / 
+                           sizeof(uint32_t);
+        
+        const bool is_cmd_end_address_page_aligned = ((cmd_end_of_storage_address % 
+                                                      PSTORAGE_FLASH_PAGE_SIZE) == 0);
+        if ((cmd_end_of_storage_address != end_of_storage_address) && 
+            !is_cmd_end_address_page_aligned)
+        {
+            // When command area is not equal to end of the storage allocation area and not ending 
+            // to page boundary there is a need to restore the tail area.
+            tail_word_size_calculate(cmd_end_of_storage_address, end_of_storage_address);
+        }
+
+        sm_state_change(STATE_DATA_ERASE_WITH_SWAP);         
+    }        
+}
+
+
+/**@brief Function for executing the store operation.
+ */
+static void store_operation_execute(void)
+{    
+    sm_state_change(STATE_STORE);
+}
+ 
+
+/**@brief Function for executing the update operation.
+ */ 
+static void update_operation_execute(void)
+{
+    clear_operation_execute();
+}
+
+
+/**@brief Function for dispatching the flash access operation.
+ */  
+static void cmd_process(void)
+{
+    const cmd_queue_element_t * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    m_app_data_size                   = p_cmd->size;
+
+    switch (p_cmd->op_code)
+    {
+        case PSTORAGE_STORE_OP_CODE:                   
+            store_operation_execute();       
+            break;
+
+        case PSTORAGE_CLEAR_OP_CODE:
+            clear_operation_execute();
+            break;
+
+        case PSTORAGE_UPDATE_OP_CODE:
+            update_operation_execute();
+            break;
+
+        default:
+            // No action required.
+            break;
+    }
+}
+
+
+uint32_t pstorage_init(void)
+{
+    cmd_queue_init();
+
+    m_next_app_instance = 0;
+    m_next_page_addr    = PSTORAGE_DATA_START_ADDR;
+    m_current_page_id   = 0;
+    
+    for (uint32_t index = 0; index < PSTORAGE_NUM_OF_PAGES; index++)
+    {
+        m_app_table[index].cb           = NULL;
+        m_app_table[index].block_size   = 0;
+        m_app_table[index].block_count  = 0;
+    }
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+    m_raw_app_table.cb           = NULL;
+#endif //PSTORAGE_RAW_MODE_ENABLE
+
+    m_state                     = STATE_IDLE;
+    m_num_of_command_retries    = 0;
+    m_flags                     = 0;
+    m_num_of_bytes_written      = 0;
+    m_flags                    |= MASK_MODULE_INITIALIZED;
+       
+    return NRF_SUCCESS;
+}
+
+
+uint32_t pstorage_register(pstorage_module_param_t * p_module_param,
+                           pstorage_handle_t       * p_block_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_module_param);
+    NULL_PARAM_CHECK(p_block_id);
+    NULL_PARAM_CHECK(p_module_param->cb);
+    BLOCK_SIZE_CHECK(p_module_param->block_size);    
+    BLOCK_COUNT_CHECK(p_module_param->block_count, p_module_param->block_size);
+
+    if (!((p_module_param->block_size % sizeof(uint32_t)) == 0))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+    
+    if (m_next_app_instance == PSTORAGE_NUM_OF_PAGES)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    p_block_id->module_id = m_next_app_instance;
+    p_block_id->block_id  = m_next_page_addr;
+
+    m_app_table[m_next_app_instance].base_id     = p_block_id->block_id;
+    m_app_table[m_next_app_instance].cb          = p_module_param->cb;
+    m_app_table[m_next_app_instance].block_size  = p_module_param->block_size;
+    m_app_table[m_next_app_instance].block_count = p_module_param->block_count;
+
+    // Calculate number of flash pages allocated for the device and adjust next free page address.
+    /*lint -save -e666 */
+    const uint32_t page_count = CEIL_DIV((p_module_param->block_size * p_module_param->block_count), 
+                                         PSTORAGE_FLASH_PAGE_SIZE);
+    /*lint -restore */
+    m_next_page_addr         += page_count * PSTORAGE_FLASH_PAGE_SIZE;
+    
+    ++m_next_app_instance;
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t pstorage_block_identifier_get(pstorage_handle_t * p_base_id,
+                                       pstorage_size_t     block_num,
+                                       pstorage_handle_t * p_block_id)
+{
+    pstorage_handle_t temp_id;
+
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_base_id);
+    NULL_PARAM_CHECK(p_block_id);
+    MODULE_ID_RANGE_CHECK(p_base_id);
+
+    temp_id           = (*p_base_id);
+    temp_id.block_id += (block_num * MODULE_BLOCK_SIZE(p_base_id));
+
+    BLOCK_ID_RANGE_CHECK(&temp_id);
+
+    (*p_block_id) = temp_id;
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t pstorage_store(pstorage_handle_t * p_dest,
+                        uint8_t           * p_src,
+                        pstorage_size_t     size,
+                        pstorage_size_t     offset)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_src);
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_ID_RANGE_CHECK(p_dest);
+    BLOCK_ID_RANGE_CHECK(p_dest);
+    SIZE_CHECK(p_dest, size);    
+    OFFSET_CHECK(p_dest, offset, size);
+    
+    if ((!is_word_aligned(p_src))                    || 
+        (!is_word_aligned((void *)(uint32_t)offset)) || 
+        (!is_word_aligned((uint32_t *)p_dest->block_id)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    return cmd_queue_enqueue(PSTORAGE_STORE_OP_CODE, p_dest, p_src, size, offset);
+}
+
+
+uint32_t pstorage_update(pstorage_handle_t * p_dest,
+                         uint8_t           * p_src,
+                         pstorage_size_t     size,
+                         pstorage_size_t     offset)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_src);
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_ID_RANGE_CHECK(p_dest);
+    BLOCK_ID_RANGE_CHECK(p_dest);
+    SIZE_CHECK(p_dest, size);
+    OFFSET_CHECK(p_dest, offset, size);
+
+    if ((!is_word_aligned(p_src))                    || 
+        (!is_word_aligned((void *)(uint32_t)offset)) || 
+        (!is_word_aligned((uint32_t *)p_dest->block_id)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    return cmd_queue_enqueue(PSTORAGE_UPDATE_OP_CODE, p_dest, p_src, size, offset);
+}
+
+
+uint32_t pstorage_load(uint8_t           * p_dest,
+                       pstorage_handle_t * p_src,
+                       pstorage_size_t     size,
+                       pstorage_size_t     offset)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_src);
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_ID_RANGE_CHECK(p_src);
+    BLOCK_ID_RANGE_CHECK(p_src);
+    SIZE_CHECK(p_src, size);
+    OFFSET_CHECK(p_src, offset, size);
+
+    if ((!is_word_aligned(p_dest))                   || 
+        (!is_word_aligned((void *)(uint32_t)offset)) || 
+        (!is_word_aligned((uint32_t *)p_src->block_id)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    memcpy(p_dest, (((uint8_t *)p_src->block_id) + offset), size);
+
+    m_app_table[p_src->module_id].cb(p_src, PSTORAGE_LOAD_OP_CODE, NRF_SUCCESS, p_dest, size);
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t pstorage_clear(pstorage_handle_t * p_dest, pstorage_size_t size)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_ID_RANGE_CHECK(p_dest);
+    BLOCK_ID_RANGE_CHECK(p_dest);
+
+    if ((!is_word_aligned((uint32_t *)p_dest->block_id)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    // Check is the area starting from block_id multiple of block_size.
+    if (
+        !(
+            ((p_dest->block_id - m_app_table[p_dest->module_id].base_id) %
+             m_app_table[p_dest->module_id].block_size) == 0
+            )
+        )
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Check is requested size multiple of registered block size or 0.
+    if (((size % m_app_table[p_dest->module_id].block_size) != 0) || (size == 0))    
+    {        
+        return NRF_ERROR_INVALID_PARAM;        
+    }
+
+    const uint32_t registered_allocation_size = m_app_table[p_dest->module_id].block_size * 
+                                                m_app_table[p_dest->module_id].block_count;
+    
+    const pstorage_block_t clear_request_end_address = p_dest->block_id + size;
+    const pstorage_block_t allocation_end_address    = m_app_table[p_dest->module_id].base_id + 
+                                                       registered_allocation_size;
+    // Check if request would lead to a buffer overrun.                                                       
+    if (clear_request_end_address > allocation_end_address)
+    {        
+        return NRF_ERROR_INVALID_PARAM;            
+    }
+    
+    return cmd_queue_enqueue(PSTORAGE_CLEAR_OP_CODE, p_dest, NULL, size, 0);
+}
+
+
+uint32_t pstorage_access_status_get(uint32_t * p_count)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_count);
+
+    (*p_count) = m_cmd_queue.count;
+
+    return NRF_SUCCESS;
+}
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+
+uint32_t pstorage_raw_register(pstorage_module_param_t * p_module_param,
+                               pstorage_handle_t       * p_block_id)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_module_param);
+    NULL_PARAM_CHECK(p_block_id);
+    NULL_PARAM_CHECK(p_module_param->cb);
+
+    if (m_raw_app_table.cb != NULL)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    p_block_id->module_id = RAW_MODE_APP_ID;
+    m_raw_app_table.cb    = p_module_param->cb;
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t pstorage_raw_store(pstorage_handle_t * p_dest,
+                            uint8_t           * p_src,
+                            pstorage_size_t     size,
+                            pstorage_size_t     offset)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_src);
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_RAW_HANDLE_CHECK(p_dest);
+    
+    if (size == 0)
+    {
+        return NRF_ERROR_INVALID_PARAM;        
+    }
+    
+    // Verify word alignment.
+    if ((!is_word_aligned(p_src))                    || 
+        (!is_word_aligned((void *)(uint32_t)size))   ||     
+        (!is_word_aligned((void *)(uint32_t)offset)) || 
+        (!is_word_aligned((void *)(p_dest->block_id))))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+       
+    return cmd_queue_enqueue(PSTORAGE_STORE_OP_CODE, p_dest, p_src, size, offset);
+}
+
+
+uint32_t pstorage_raw_clear(pstorage_handle_t * p_dest, pstorage_size_t size)
+{
+    VERIFY_MODULE_INITIALIZED();
+    NULL_PARAM_CHECK(p_dest);
+    MODULE_RAW_HANDLE_CHECK(p_dest);
+    
+    if ((!is_word_aligned((uint32_t *)p_dest->block_id)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }    
+
+    return cmd_queue_enqueue(PSTORAGE_CLEAR_OP_CODE, p_dest, NULL, size, 0);
+}
+
+#endif // PSTORAGE_RAW_MODE_ENABLE
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/drivers_nrf/pstorage/pstorage.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,401 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup persistent_storage Persistent Storage Interface
+ * @{
+ * @ingroup app_common
+ * @brief Abstracted flash interface.
+ *
+ * @details  An abstracted interface is provided by the module to easily port the application and 
+ *           SDK modules to an alternate option. This ensures that the SDK and application are moved 
+ *           to alternate persistent storage instead of the one provided by default.
+ */
+
+#ifndef PSTORAGE_H__
+#define PSTORAGE_H__
+
+#include "pstorage_platform.h"
+
+
+/**@defgroup ps_opcode Persistent Storage Access Operation Codes
+ * @{
+ * @brief    Persistent Storage Access Operation Codes. 
+ *
+ * @details  Persistent Storage Access Operation Codes are used by Persistent storage operation 
+ *           completion callback @ref pstorage_ntf_cb_t to identify the operation type requested by 
+ *           the application.
+ */
+#define PSTORAGE_STORE_OP_CODE    0x01  /**< Store Operation type. */
+#define PSTORAGE_LOAD_OP_CODE     0x02  /**< Load Operation type. */
+#define PSTORAGE_CLEAR_OP_CODE    0x03  /**< Clear Operation type. */
+#define PSTORAGE_UPDATE_OP_CODE   0x04  /**< Update Operation type. */
+
+/**@} */
+
+/**@defgroup pstorage_data_types Persistent Memory Interface Data Types
+ * @{
+ * @brief Data Types needed for interfacing with persistent memory.
+ *
+ * @details Data Types needed for interfacing with persistent memory.
+ */
+
+/**@brief Persistent storage operation completion callback function type.
+ *
+ * @details The persistent storage operation completion callback is used by the interface to report
+ *          success or failure of a flash operation. Since data is not copied for a store operation, 
+ *          a callback is an indication that the resident memory can now be reused or freed.
+ * 
+ * @param[in] handle   Identifies the module and block for the callback that is received.
+ * @param[in] op_code  Identifies the operation for the event that is notified.
+ * @param[in] result   Identifies the result of a flash access operation. NRF_SUCCESS implies 
+ *                     operation succeeded.
+ *
+ *                     @note Unmanaged (abnormal behaviour) error codes from the SoftDevice flash 
+ *                     access API are forwarded as is and are expected to be handled by the 
+ *                     application. For details refer to the implementation file and corresponding 
+ *                     SoftDevice flash API documentation.
+ *                     
+ * @param[in] p_data   Identifies the application data pointer. For a store operation, this points 
+ *                     to the resident source of application memory that the application can now 
+ *                     free or reuse. When there is a clear operation, this is NULL since no 
+ *                     application pointer is needed for this operation.
+ * @param[in] data_len Length data the application provided for the operation. 
+ */
+typedef void (*pstorage_ntf_cb_t)(pstorage_handle_t * p_handle,
+                                  uint8_t             op_code,
+                                  uint32_t            result,
+                                  uint8_t *           p_data,
+                                  uint32_t            data_len);
+
+/**@brief Struct containing module registration context. */
+typedef struct
+{
+    pstorage_ntf_cb_t cb;             /**< Persistent storage operation completion callback function @ref pstorage_ntf_cb_t.  */
+    pstorage_size_t   block_size;     /**< Desired block size for persistent memory storage. For example, if a module has a table with 10 entries, and each entry is 64 bytes in size,
+                                       *   it can request 10 blocks with a block size of 64 bytes. The module can also request one block that is 640 bytes depending 
+                                       *   on how it would like to access or alter the memory in persistent memory.
+                                       *   The first option is preferred when it is a single entry that needs to be updated often and doesn't impact the other entries.
+                                       *   The second option is preferred when table entries are not changed individually but have a common point of loading and storing
+                                       *   data. */
+    pstorage_size_t   block_count;    /** Number of blocks requested by the module; minimum values is 1. */
+} pstorage_module_param_t;
+
+/**@} */
+
+/**@defgroup pstorage_routines Persistent Storage Access Routines
+ * @{
+ * @brief Functions/Interface SDK modules used to persistently store data.
+ *
+ * @details Interface for the Application and SDK modules to load/store information persistently.
+ *          Note: While implementation of each of the persistent storage access functions
+ *          depends on the system and is specific to system/solution, the signature of the
+ *          interface routines should not be altered.
+ */
+
+/**@brief Function for initializing the module.
+ *
+ * @details Function for initializing the module. This function is called once before any other APIs 
+ *          of the module are used.
+ *
+ * @retval     NRF_SUCCESS             Operation success.
+ */
+uint32_t pstorage_init(void);
+
+/**@brief Function for registering with persistent storage interface.
+ *
+ * @param[in]  p_module_param Module registration parameter.
+ * @param[out] p_block_id     Block identifier to identify persistent memory blocks when 
+ *                            registration succeeds. Application is expected to use the block IDs 
+ *                            for subsequent operations on requested persistent memory. Maximum 
+ *                            registrations permitted is determined by the configuration of the 
+ *                            parameter PSTORAGE_NUM_OF_PAGES. If more than one memory block is 
+ *                            requested, the identifier provided here is the base identifier for the 
+ *                            first block and used to identify the subsequent block. The application 
+ *                            uses \@ref pstorage_block_identifier_get with this base identifier and 
+ *                            block number. Therefore if 10 blocks of size 64 are requested and the 
+ *                            application wishes to store memory in the 6th block, it shall use
+ *                            \@ref pstorage_block_identifier_get with the base ID and provide a 
+ *                            block number of 5. This way the application is only expected to 
+ *                            remember the base block identifier.
+ *
+ * @retval     NRF_SUCCESS             Operation success.
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. Additional registrations can't be 
+ *                                     supported.
+ */
+uint32_t pstorage_register(pstorage_module_param_t * p_module_param,
+                           pstorage_handle_t *       p_block_id);
+
+/**@brief Function for getting block ID with reference to base block identifier provided at the time 
+ *        of registration.
+ *
+ * @details Function to get the block ID with reference to base block identifier provided at the 
+ *          time of registration.
+ *          If more than one memory block was requested when registering, the identifier provided 
+ *          here is the base identifier for the first block which is used to identify subsequent
+ *          blocks. The application shall use this routine to get the block identifier, providing 
+ *          input as base identifier and block number. Therefore, if 10 blocks of size 64 are 
+ *          requested and the application wishes to store memory in the 6th block, it shall use
+ *          \@ref pstorage_block_identifier_get with the base ID and provide a block number of 5.
+ *          This way the application is only expected to remember the base block identifier.
+ *
+ * @param[in]  p_base_id  Base block ID received at the time of registration.
+ * @param[in]  block_num  Block Number, with first block numbered zero.
+ * @param[out] p_block_id Block identifier for the block number requested when the API succeeds.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ */
+uint32_t pstorage_block_identifier_get(pstorage_handle_t * p_base_id,
+                                       pstorage_size_t     block_num,
+                                       pstorage_handle_t * p_block_id);
+
+/**@brief Function for persistently storing data of length 'size' contained in the 'p_src' address
+ *        in the storage module at 'p_dest' address. Equivalent to Storage Write.
+ *
+ * @param[in]  p_dest Destination address where data is to be stored persistently.
+ * @param[in]  p_src  Source address containing data to be stored. API assumes this to be resident
+ *                    memory and no intermediate copy of data is made by the API. Must be word 
+ *                    aligned.
+ * @param[in]  size   Size of data to be stored expressed in bytes. Must be word aligned and size + 
+ *                    offset must be <= block size.                      
+ * @param[in]  offset Offset in bytes to be applied when writing to the block.
+ *                    For example, if within a block of 100 bytes, the application wishes to
+ *                    write 20 bytes at an offset of 12, then this field should be set to 12.
+ *                    Must be word aligned.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_ADDR  Operation failure. Parameter is not aligned.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ *
+ * @warning    No copy of the data is made, meaning memory provided for the data source that is to 
+ *             be written to flash cannot be freed or reused by the application until this procedure
+ *             is complete. The application is notified when the procedure is finished using the
+ *             notification callback registered by the application.
+ */
+uint32_t pstorage_store(pstorage_handle_t * p_dest,
+                        uint8_t *           p_src,
+                        pstorage_size_t     size,
+                        pstorage_size_t     offset);
+
+/**@brief Function for updating persistently stored data of length 'size' contained in the 'p_src' 
+ *        address in the storage module at 'p_dest' address.
+ *
+ * @param[in]  p_dest Destination address where data is to be updated.
+ * @param[in]  p_src  Source address containing data to be stored. API assumes this to be resident
+ *                    memory and no intermediate copy of data is made by the API.
+ * @param[in]  size   Size of data to be stored expressed in bytes. Must be word aligned and size + 
+ *                    offset must be <= block size.
+ * @param[in]  offset Offset in bytes to be applied when writing to the block.
+ *                    For example, if within a block of 100 bytes, the application wishes to
+ *                    write 20 bytes at an offset of 12 bytes, then this field should be set to 12.
+ *                    Must be word aligned.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_ADDR  Operation failure. Parameter is not aligned.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ *
+ * @warning    No copy of the data is made, meaning memory provided for the data source that is to 
+ *             be written to flash cannot be freed or reused by the application until this procedure
+ *             is complete. The application is notified when the procedure is finished using the
+ *             notification callback registered by the application.
+ */
+uint32_t pstorage_update(pstorage_handle_t * p_dest,
+                         uint8_t *           p_src,
+                         pstorage_size_t     size,
+                         pstorage_size_t     offset);
+
+/**@brief Function for loading persistently stored data of length 'size' from 'p_src' address
+ *        to 'p_dest' address. Equivalent to Storage Read.
+ *
+ * @param[in]  p_dest Destination address where persistently stored data is to be loaded.
+ * @param[in]  p_src  Source where data is loaded from persistent memory.
+ * @param[in]  size   Size of data to be loaded from persistent memory expressed in bytes.
+ *                    Should be word aligned.
+ * @param[in]  offset Offset in bytes, to be applied when loading from the block.
+ *                    For example, if within a block of 100 bytes, the application wishes to
+ *                    load 20 bytes from offset of 12 bytes, then this field should be set to 12.
+ *                    Should be word aligned.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_ADDR  Operation failure. Parameter is not aligned.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ */
+uint32_t pstorage_load(uint8_t *           p_dest,
+                       pstorage_handle_t * p_src,
+                       pstorage_size_t     size,
+                       pstorage_size_t     offset);
+
+/**@brief Function for clearing data in persistent memory.
+ *
+ * @param[in]  p_base_id Base block identifier in persistent memory that needs to be cleared;
+ *                       equivalent to an Erase Operation.
+ * @param[in]  size      Size of data to be cleared from persistent memory expressed in bytes.
+ *                       This parameter is to provision for clearing of certain blocks
+ *                       of memory, or all memory blocks in a registered module. If the total size 
+ *                       of the application module is used (blocks * block size) in combination with
+ *                       the identifier for the first block in the module, all blocks in the 
+ *                       module will be erased. Must be multiple of block size.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_ADDR  Operation failure. Parameter is not aligned.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ *
+ * @note       Clear operations may take time. This API however, does not block until the clear
+ *             procedure is complete. The application is notified of procedure completion using
+ *             a notification callback registered by the application. The 'result' parameter of the
+ *             callback indicates if the procedure was successful or not.
+ */
+uint32_t pstorage_clear(pstorage_handle_t * p_base_id, pstorage_size_t size);
+
+/**@brief Function for getting the number of pending operations with the module.
+ *
+ * @param[out] p_count Number of storage operations pending with the module. If 0, there are no 
+ *                     outstanding requests.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ */
+uint32_t pstorage_access_status_get(uint32_t * p_count);
+
+#ifdef PSTORAGE_RAW_MODE_ENABLE
+
+/**@brief Function for registering with the persistent storage interface.
+ *
+ * @param[in]  p_module_param Module registration parameter.
+ * @param[out] p_block_id     Block identifier used to identify persistent memory blocks upon 
+ *                            successful registration. The application is expected to use the block 
+ *                            IDs for subsequent operations on requested persistent memory. When 
+ *                            more than one memory block is requested, this identifier is the base 
+ *                            identifier for the first block and used to identify subsequent blocks. 
+ *                            The application shall use \@ref pstorage_block_identifier_get with 
+ *                            this base identifier and block number. Therefore if 10 blocks of size 
+ *                            64 are requested and the application wishes to store memory in the 6th 
+ *                            block, it shall use \@ref pstorage_block_identifier_get with the base 
+ *                            ID and provide a block number of 5. Therefore, the application is only 
+ *                            expected to remember the base block identifier.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ */
+uint32_t pstorage_raw_register(pstorage_module_param_t * p_module_param,
+                               pstorage_handle_t *       p_block_id);
+
+/**@brief Function for persistently storing data of length 'size' contained in 'p_src' address in 
+ *        storage module at 'p_dest' address. Equivalent to Storage Write.
+ *
+ * @param[in]  p_dest Destination address where data is to be stored persistently.
+ * @param[in]  p_src  Source address containing data to be stored. The API assumes this is resident
+ *                    memory and no intermediate copy of data is made by the API. Must be word 
+ *                    aligned.
+ * @param[in]  size   Size of data to be stored expressed in bytes. Must be word aligned.
+ * @param[in]  offset Offset in bytes to be applied when writing to the block.
+ *                    For example, if within a block of 100 bytes, the application wishes to
+ *                    write 20 bytes at an offset of 12 bytes, this field should be set to 12.
+ *                    Must be word aligned.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_ADDR  Operation failure. Parameter is not aligned.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ *
+ * @warning    No copy of the data is made, meaning memory provided for data source that is to be 
+ *             written to flash cannot be freed or reused by the application until this procedure
+ *             is complete. The application is notified when the procedure is finished using the
+ *             notification callback registered by the application.
+ */
+uint32_t pstorage_raw_store(pstorage_handle_t * p_dest,
+                            uint8_t *           p_src,
+                            pstorage_size_t     size,
+                            pstorage_size_t     offset);
+
+/**@brief Function for clearing data in persistent memory in raw mode.
+ *
+ * @param[in]  p_dest Base block identifier in persistent memory that needs to be cleared.
+ *                    Equivalent to an Erase Operation.
+ * @param[in]  size   Size of data to be cleared from persistent memory expressed in bytes. 
+ *                    Not used.
+ *
+ * @retval     NRF_SUCCESS             Operation success. 
+ * @retval     NRF_ERROR_INVALID_STATE Operation failure. API is called without module 
+ *                                     initialization.
+ * @retval     NRF_ERROR_NULL          Operation failure. NULL parameter has been passed.
+ * @retval     NRF_ERROR_INVALID_PARAM Operation failure. Invalid parameter has been passed.
+ * @retval     NRF_ERROR_NO_MEM        Operation failure. No storage space available.
+ *
+ * @note       Clear operations may take time. This API, however, does not block until the clear
+ *             procedure is complete. The application is notified of procedure completion using
+ *             a notification callback registered by the application. The 'result' parameter of the
+ *             callback indicates if the procedure was successful or not.
+ */
+uint32_t pstorage_raw_clear(pstorage_handle_t * p_dest, pstorage_size_t size);
+
+#endif // PSTORAGE_RAW_MODE_ENABLE
+
+/**@} */
+/**@} */
+
+#endif // PSTORAGE_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/**@file
+ *
+ * @defgroup nrf_bootloader Bootloader API.
+ * @{     
+ *
+ * @brief Bootloader module interface.
+ */
+
+#ifndef BOOTLOADER_H__
+#define BOOTLOADER_H__
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "bootloader_types.h"
+#include <dfu_types.h>
+
+/**@brief Function for initializing the Bootloader.
+ * 
+ * @retval     NRF_SUCCESS If bootloader was succesfully initialized. 
+ */
+uint32_t bootloader_init(void);
+
+/**@brief Function for validating application region in flash.
+ * 
+ * @param[in]  app_addr      Address to the region in flash where the application is stored.
+ * 
+ * @retval     true          If Application region is valid.
+ * @retval     false         If Application region is not valid.
+ */
+bool bootloader_app_is_valid(uint32_t app_addr);
+
+/**@brief Function for starting the Device Firmware Update.
+ * 
+ * @retval     NRF_SUCCESS If new application image was successfully transferred.
+ */
+uint32_t bootloader_dfu_start(void);
+
+/**@brief Function for exiting bootloader and booting into application.
+ *
+ * @details This function will disable SoftDevice and all interrupts before jumping to application.
+ *          The SoftDevice vector table base for interrupt forwarding will be set the application
+ *          address.
+ *
+ * @param[in]  app_addr      Address to the region where the application is stored.
+ */
+void bootloader_app_start(uint32_t app_addr);
+
+/**@brief Function for retrieving the bootloader settings.
+ *
+ * @param[out] p_settings    A copy of the current bootloader settings is returned in the structure
+ *                           provided.
+ */
+void bootloader_settings_get(bootloader_settings_t * const p_settings);
+
+/**@brief Function for processing DFU status update.
+ *
+ * @param[in]  update_status DFU update status.
+ */
+void bootloader_dfu_update_process(dfu_update_status_t update_status);
+
+/**@brief Function getting state of SoftDevice update in progress.
+ *        After a successfull SoftDevice transfer the system restarts in orderto disable SoftDevice
+ *        and complete the update.
+ *
+ * @retval     true          A SoftDevice update is in progress. This indicates that second stage 
+ *                           of a SoftDevice update procedure can be initiated.
+ * @retval     false         No SoftDevice update is in progress.
+ */
+bool bootloader_dfu_sd_in_progress(void);
+
+/**@brief Function for continuing the Device Firmware Update of a SoftDevice.
+ * 
+ * @retval     NRF_SUCCESS If the final stage of SoftDevice update was successful. 
+ */
+uint32_t bootloader_dfu_sd_update_continue(void);
+
+/**@brief Function for finalizing the Device Firmware Update of a SoftDevice.
+ * 
+ * @retval     NRF_SUCCESS If the final stage of SoftDevice update was successful. 
+ */
+uint32_t bootloader_dfu_sd_update_finalize(void);
+
+#endif // BOOTLOADER_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/**@file
+ *
+ * @defgroup nrf_bootloader_types Types and definitions.
+ * @{     
+ *  
+ * @ingroup nrf_bootloader
+ * 
+ * @brief Bootloader module type and definitions.
+ */
+ 
+#ifndef BOOTLOADER_TYPES_H__
+#define BOOTLOADER_TYPES_H__
+
+#include <stdint.h>
+
+#define BOOTLOADER_DFU_START 0xB1
+
+#define BOOTLOADER_SVC_APP_DATA_PTR_GET 0x02
+
+/**@brief DFU Bank state code, which indicates wether the bank contains: A valid image, invalid image, or an erased flash.
+  */
+typedef enum
+{
+    BANK_VALID_APP   = 0x01,
+    BANK_VALID_SD    = 0xA5,
+    BANK_VALID_BOOT  = 0xAA,
+    BANK_ERASED      = 0xFE,
+    BANK_INVALID_APP = 0xFF,
+} bootloader_bank_code_t;
+
+/**@brief Structure holding bootloader settings for application and bank data.
+ */
+typedef struct
+{
+    bootloader_bank_code_t bank_0;          /**< Variable to store if bank 0 contains a valid application. */
+    uint16_t               bank_0_crc;      /**< If bank is valid, this field will contain a valid CRC of the total image. */
+    bootloader_bank_code_t bank_1;          /**< Variable to store if bank 1 has been erased/prepared for new image. Bank 1 is only used in Banked Update scenario. */
+    uint32_t               bank_0_size;     /**< Size of active image in bank0 if present, otherwise 0. */
+    uint32_t               sd_image_size;   /**< Size of SoftDevice image in bank0 if bank_0 code is BANK_VALID_SD. */
+    uint32_t               bl_image_size;   /**< Size of Bootloader image in bank0 if bank_0 code is BANK_VALID_SD. */
+    uint32_t               app_image_size;  /**< Size of Application image in bank0 if bank_0 code is BANK_VALID_SD. */
+    uint32_t               sd_image_start;  /**< Location in flash where SoftDevice image is stored for SoftDevice update. */
+} bootloader_settings_t;
+
+#endif // BOOTLOADER_TYPES_H__ 
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "bootloader_util.h"
+#include <stdint.h>
+#include <string.h>
+
+
+/**
+ * @brief Function for aborting current application/bootloader jump to to other app/bootloader.
+ *
+ * @details This functions will use the address provide to swap the stack pointer and then load 
+ *          the address of the reset handler to be executed. It will check current system mode 
+ *          (thread/handler) and if in thread mode it will reset into other application.
+ *          If in handler mode \ref isr_abort will be executed to ensure correct exit of handler 
+ *          mode and jump into reset handler of other application.
+ *
+ * @param[in]  start_addr  Start address of other application. This address must point to the 
+               initial stack pointer of the application.
+ *
+ * @note This function will never return but issue a reset into provided application.
+ */
+#if defined ( __CC_ARM )
+__asm static void bootloader_util_reset(uint32_t start_addr)
+{
+    LDR   R5, [R0]              ; Get App initial MSP for bootloader.
+    MSR   MSP, R5               ; Set the main stack pointer to the applications MSP.
+    LDR   R0, [R0, #0x04]       ; Load Reset handler into R0. This will be first argument to branch instruction (BX).
+
+    MOVS  R4, #0xFF             ; Load ones to R4.
+    SXTB  R4, R4                ; Sign extend R4 to obtain 0xFFFFFFFF instead of 0xFF.
+    MRS   R5, IPSR              ; Load IPSR to R5 to check for handler or thread mode.
+    CMP   R5, #0x00             ; Compare, if 0 then we are in thread mode and can continue to reset handler of bootloader.
+    BNE   isr_abort             ; If not zero we need to exit current ISR and jump to reset handler of bootloader.
+
+    MOV   LR, R4                ; Clear the link register and set to ones to ensure no return, R4 = 0xFFFFFFFF.
+    BX    R0                    ; Branch to reset handler of bootloader.
+
+isr_abort
+                                ; R4 contains ones from line above. Will be popped as R12 when exiting ISR (Cleaning up the registers).
+    MOV   R5, R4                ; Fill with ones before jumping to reset handling. We be popped as LR when exiting ISR. Ensures no return to application.
+    MOV   R6, R0                ; Move address of reset handler to R6. Will be popped as PC when exiting ISR. Ensures the reset handler will be executed when exist ISR.
+    MOVS  r7, #0x21             ; Move MSB reset value of xPSR to R7. Will be popped as xPSR when exiting ISR. xPSR is 0x21000000 thus MSB is 0x21.
+    REV   r7, r7                ; Reverse byte order to put 0x21 as MSB.
+    PUSH  {r4-r7}               ; Push everything to new stack to allow interrupt handler to fetch it on exiting the ISR.
+
+    MOVS  R4, #0x00             ; Fill with zeros before jumping to reset handling. We be popped as R0 when exiting ISR (Cleaning up of the registers).
+    MOVS  R5, #0x00             ; Fill with zeros before jumping to reset handling. We be popped as R1 when exiting ISR (Cleaning up of the registers).
+    MOVS  R6, #0x00             ; Fill with zeros before jumping to reset handling. We be popped as R2 when exiting ISR (Cleaning up of the registers).
+    MOVS  R7, #0x00             ; Fill with zeros before jumping to reset handling. We be popped as R3 when exiting ISR (Cleaning up of the registers).
+    PUSH  {r4-r7}               ; Push zeros (R4-R7) to stack to prepare for exiting the interrupt routine.
+
+    MOVS  R0, #0xF9             ; Move the execution return command into register, 0xFFFFFFF9.
+    SXTB  R0, R0                ; Sign extend R0 to obtain 0xFFFFFFF9 instead of 0xF9.
+    BX    R0                    ; No return - Handler mode will be exited. Stack will be popped and execution will continue in reset handler initializing other application.
+    ALIGN
+}
+#elif defined ( __GNUC__ )
+static inline void bootloader_util_reset(uint32_t start_addr)
+{
+    __asm volatile(
+        "ldr   r0, [%0]\t\n"            // Get App initial MSP for bootloader.
+        "msr   msp, r0\t\n"             // Set the main stack pointer to the applications MSP.
+        "ldr   r0, [%0, #0x04]\t\n"     // Load Reset handler into R0.
+
+        "movs  r4, #0xFF\t\n"           // Move ones to R4.
+        "sxtb  r4, r4\t\n"              // Sign extend R4 to obtain 0xFFFFFFFF instead of 0xFF.
+
+        "mrs   r5, IPSR\t\n"            // Load IPSR to R5 to check for handler or thread mode.
+        "cmp   r5, #0x00\t\n"           // Compare, if 0 then we are in thread mode and can continue to reset handler of bootloader.
+        "bne   isr_abort\t\n"           // If not zero we need to exit current ISR and jump to reset handler of bootloader.
+
+        "mov   lr, r4\t\n"              // Clear the link register and set to ones to ensure no return.
+        "bx    r0\t\n"                  // Branch to reset handler of bootloader.
+
+        "isr_abort:  \t\n"
+
+        "mov   r5, r4\t\n"              // Fill with ones before jumping to reset handling. Will be popped as LR when exiting ISR. Ensures no return to application.
+        "mov   r6, r0\t\n"              // Move address of reset handler to R6. Will be popped as PC when exiting ISR. Ensures the reset handler will be executed when exist ISR.
+        "movs  r7, #0x21\t\n"           // Move MSB reset value of xPSR to R7. Will be popped as xPSR when exiting ISR. xPSR is 0x21000000 thus MSB is 0x21.
+        "rev   r7, r7\t\n"              // Reverse byte order to put 0x21 as MSB.
+        "push  {r4-r7}\t\n"             // Push everything to new stack to allow interrupt handler to fetch it on exiting the ISR.
+
+        "movs  r4, #0x00\t\n"           // Fill with zeros before jumping to reset handling. We be popped as R0 when exiting ISR (Cleaning up of the registers).
+        "movs  r5, #0x00\t\n"           // Fill with zeros before jumping to reset handling. We be popped as R1 when exiting ISR (Cleaning up of the registers).
+        "movs  r6, #0x00\t\n"           // Fill with zeros before jumping to reset handling. We be popped as R2 when exiting ISR (Cleaning up of the registers).
+        "movs  r7, #0x00\t\n"           // Fill with zeros before jumping to reset handling. We be popped as R3 when exiting ISR (Cleaning up of the registers).
+        "push  {r4-r7}\t\n"             // Push zeros (R4-R7) to stack to prepare for exiting the interrupt routine.
+
+        "movs  r0, #0xF9\t\n"           // Move the execution return command into register, 0xFFFFFFF9.
+        "sxtb  r0, r0\t\n"              // Sign extend R0 to obtain 0xFFFFFFF9 instead of 0xF9.
+        "bx    r0\t\n"                  // No return - Handler mode will be exited. Stack will be popped and execution will continue in reset handler initializing other application.
+        ".align\t\n"
+        :: "r" (start_addr)             // Argument list for the gcc assembly. start_addr is %0.
+        :  "r0", "r4", "r5", "r6", "r7" // List of register maintained manually.
+    );
+}
+#elif defined ( __ICCARM__ )
+static inline void bootloader_util_reset(uint32_t start_addr)
+{
+    asm("ldr   r5, [%0]\n"                    // Get App initial MSP for bootloader.
+        "msr   msp, r5\n"                     // Set the main stack pointer to the applications MSP.
+        "ldr   r0, [%0, #0x04]\n"             // Load Reset handler into R0.
+
+        "movs  r4, #0x00\n"                   // Load zero into R4.
+        "mvns  r4, r4\n"                      // Invert R4 to ensure it contain ones.
+
+        "mrs   r5, IPSR\n"                    // Load IPSR to R5 to check for handler or thread mode 
+        "cmp   r5, #0x00\n"                   // Compare, if 0 then we are in thread mode and can continue to reset handler of bootloader.
+        "bne   isr_abort\n"                   // If not zero we need to exit current ISR and jump to reset handler of bootloader.
+
+        "mov   lr, r4\n"                      // Clear the link register and set to ones to ensure no return.
+        "bx    r0\n"                          // Branch to reset handler of bootloader.
+
+        "isr_abort: \n"
+                                              // R4 contains ones from line above. We be popped as R12 when exiting ISR (Cleaning up the registers).
+        "mov   r5, r4\n"                      // Fill with ones before jumping to reset handling. Will be popped as LR when exiting ISR. Ensures no return to application.
+        "mov   r6, r0\n"                      // Move address of reset handler to R6. Will be popped as PC when exiting ISR. Ensures the reset handler will be executed when exist ISR.
+        "movs  r7, #0x21\n"                   // Move MSB reset value of xPSR to R7. Will be popped as xPSR when exiting ISR. xPSR is 0x21000000 thus MSB is 0x21.
+        "rev   r7, r7\n"                      // Reverse byte order to put 0x21 as MSB.
+        "push  {r4-r7}\n"                     // Push everything to new stack to allow interrupt handler to fetch it on exiting the ISR.
+
+        "movs  r4, #0x00\n"                   // Fill with zeros before jumping to reset handling. We be popped as R0 when exiting ISR (Cleaning up of the registers).
+        "movs  r5, #0x00\n"                   // Fill with zeros before jumping to reset handling. We be popped as R1 when exiting ISR (Cleaning up of the registers).
+        "movs  r6, #0x00\n"                   // Fill with zeros before jumping to reset handling. We be popped as R2 when exiting ISR (Cleaning up of the registers).
+        "movs  r7, #0x00\n"                   // Fill with zeros before jumping to reset handling. We be popped as R3 when exiting ISR (Cleaning up of the registers).
+        "push  {r4-r7}\n"                     // Push zeros (R4-R7) to stack to prepare for exiting the interrupt routine.
+
+        "movs  r0, #0x06\n"                   // Load 0x06 into R6 to prepare for exec return command.
+        "mvns  r0, r0\n"                      // Invert 0x06 to obtain EXEC_RETURN, 0xFFFFFFF9.
+        "bx    r0\n"                          // No return - Handler mode will be exited. Stack will be popped and execution will continue in reset handler initializing other application.
+        :: "r" (start_addr)                   // Argument list for the IAR assembly. start_addr is %0.
+        :  "r0", "r4", "r5", "r6", "r7");     // List of register maintained manually.
+}
+#else
+#error Compiler not supported.
+#endif
+
+
+void bootloader_util_app_start(uint32_t start_addr)
+{
+    bootloader_util_reset(start_addr);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/bootloader_util.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+ /**@file
+ *
+ * @defgroup nrf_bootloader_util Bootloader util API.
+ * @{     
+ *  
+ * @brief Bootloader util module interface.
+ */
+ 
+#ifndef BOOTLOADER_UTIL_H__
+#define BOOTLOADER_UTIL_H__
+
+#include <stdint.h>
+#include "bootloader_types.h"
+
+/**@brief Function for starting the application (or bootloader) at the provided address.
+ * 
+ * @param[in]  start_addr             Start address.
+ *
+ * @note This function will never retrun. Instead it will reset into the application of the 
+ *       provided address.
+ */
+void bootloader_util_app_start(uint32_t start_addr);
+
+#endif // BOOTLOADER_UTIL_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/**@file
+ *
+ * @defgroup nrf_dfu Device Firmware Update API.
+ * @{     
+ *
+ * @brief Device Firmware Update module interface.
+ */
+
+#ifndef DFU_H__
+#define DFU_H__
+
+#include <dfu_types.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+
+/**@brief DFU event callback for asynchronous calls.
+ *
+ * @param[in] packet  Packet type for which this callback is related. START_PACKET, DATA_PACKET.
+ * @param[in] result  Operation result code. NRF_SUCCESS when a queued operation was successful.
+ * @param[in] p_data  Pointer to the data to which the operation is related.
+ */
+typedef void (*dfu_callback_t)(uint32_t packet, uint32_t  result, uint8_t * p_data);
+
+/**@brief Function for initializing the Device Firmware Update module.
+ * 
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_init(void);
+
+/**@brief Function for registering a callback listener for \ref dfu_data_pkt_handle callbacks.
+ *
+ * @param[in] callback_handler  Callback handler for receiving DFU events on completed operations
+ *                              of DFU packets.
+ */
+void dfu_register_callback(dfu_callback_t callback_handler);
+
+/**@brief Function for setting the DFU image size. 
+ *
+ * @details Function sets the DFU image size. This function must be called when an update is started 
+ *          in order to notify the DFU of the new image size. If multiple images are to be 
+ *          transferred within the same update context then this function must be called with size 
+ *          information for each image being transfered.
+ *          If an image type is not being transfered, e.g. SoftDevice but no Application , then the
+ *          image size for application must be zero.
+ * 
+ * @param[in] p_packet   Pointer to the DFU packet containing information on DFU update process to
+ *                       be started.
+ *
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_start_pkt_handle(dfu_update_packet_t * p_packet);
+
+/**@brief Function for handling DFU data packets.
+ *
+ * @param[in] p_packet   Pointer to the DFU packet.
+ *
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_data_pkt_handle(dfu_update_packet_t * p_packet);
+
+/**@brief Function for handling DFU init packets.
+ *
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_init_pkt_handle(dfu_update_packet_t * p_packet);
+
+/**@brief Function for validating a transferred image after the transfer has completed.
+ * 
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_image_validate(void);
+
+/**@brief Function for activating the transfered image after validation has successfully completed.
+ *
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_image_activate(void);
+
+/**@brief Function for reseting the current update procedure and return to initial state.
+ *        
+ * @details This function call will result in a system reset to ensure correct system behavior.
+ *          The reset will might be scheduled to execute at a later point in time to ensure pending 
+ *          flash operations has completed.
+ */
+void dfu_reset(void);
+
+/**@brief Function for validating that new bootloader has been correctly installed.
+ *        
+ * @return NRF_SUCCESS if install was successful. NRF_ERROR_NULL if the images differs.
+ */
+uint32_t dfu_bl_image_validate(void);
+
+/**@brief Function for validating that new SoftDevicehas been correctly installed.
+ *        
+ * @return NRF_SUCCESS if install was successful. NRF_ERROR_NULL if the images differs.
+ */
+uint32_t dfu_sd_image_validate(void);
+
+/**@brief Function for swapping existing bootloader with newly received.
+ *        
+ * @return NRF_SUCCESS on succesfull swapping. For error code please refer to 
+ *         \ref sd_mbr_command_copy_bl_t.
+ */
+uint32_t dfu_bl_image_swap(void);
+
+/**@brief Function for swapping existing SoftDevice with newly received.
+ *        
+ * @return NRF_SUCCESS on succesfull swapping. For error code please refer to 
+ *         \ref sd_mbr_command_copy_sd_t.
+ */
+uint32_t dfu_sd_image_swap(void);
+
+/**@brief Function for handling DFU init packet complete.
+ *
+ * @return    NRF_SUCCESS on success, an error_code otherwise.
+ */
+uint32_t dfu_init_pkt_complete(void);
+
+#endif // DFU_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "dfu_app_handler.h"
+#include <string.h>
+#include "bootloader_util.h"
+#include "nrf.h"
+#include "nrf_sdm.h"
+#include "ble_gatt.h"
+#include "ble_gatts.h"
+#include "app_error.h"
+#include "dfu_ble_svc.h"
+#include "device_manager.h"
+#include "nrf_delay.h"
+
+#define IRQ_ENABLED            0x01                                     /**< Field that identifies if an interrupt is enabled. */
+#define MAX_NUMBER_INTERRUPTS  32                                       /**< Maximum number of interrupts available. */
+
+static void                    dfu_app_reset_prepare(void);             /**< Forward declaration of default reset handler. */
+static dfu_app_reset_prepare_t m_reset_prepare = dfu_app_reset_prepare; /**< Callback function to application to prepare for system reset. Allows application to clean up service and memory before reset. */
+static dfu_ble_peer_data_t     m_peer_data;                             /**< Peer data to be used for data exchange when resetting into DFU mode. */
+static dm_handle_t             m_dm_handle;                             /**< Device Manager handle with instance IDs of current BLE connection. */
+
+
+/**@brief Function for reset_prepare handler if the application has not registered a handler.
+ */
+static void dfu_app_reset_prepare(void)
+{
+    // Reset prepare should be handled by application.
+    // This function can be extended to include default handling if application does not implement
+    // own handler.
+}
+
+
+/**@brief Function for disabling all interrupts before jumping from bootloader to application.
+ */
+static void interrupts_disable(void)
+{
+    uint32_t interrupt_setting_mask;
+    uint32_t irq;
+
+    // Fetch the current interrupt settings.
+    interrupt_setting_mask = NVIC->ISER[0];
+
+    // Loop from interrupt 0 for disabling of all interrupts.
+    for (irq = 0; irq < MAX_NUMBER_INTERRUPTS; irq++)
+    {
+        if (interrupt_setting_mask & (IRQ_ENABLED << irq))
+        {
+            // The interrupt was enabled, hence disable it.
+            NVIC_DisableIRQ((IRQn_Type)irq);
+        }
+    }
+}
+
+
+/**@brief Function for providing peer information to DFU for re-establishing a bonded connection in
+ *        DFU mode.
+ *
+ * @param[in] conn_handle   Connection handle for the connection requesting DFU mode.
+ */
+static void dfu_app_peer_data_set(uint16_t conn_handle)
+{
+    uint32_t                 err_code;
+    dm_sec_keyset_t          key_set;
+    uint32_t                 app_context_data = 0;
+    dm_application_context_t app_context;
+
+
+/** [DFU bond sharing] */
+    err_code = dm_handle_get(conn_handle, &m_dm_handle);
+    if (err_code == NRF_SUCCESS)
+    {
+        err_code = dm_distributed_keys_get(&m_dm_handle, &key_set);
+        if (err_code == NRF_SUCCESS)
+        {
+            APP_ERROR_CHECK(err_code);
+
+            m_peer_data.addr              = key_set.keys_central.p_id_key->id_addr_info;
+            m_peer_data.irk               = key_set.keys_central.p_id_key->id_info;
+            m_peer_data.enc_key.enc_info  = key_set.keys_periph.enc_key.p_enc_key->enc_info;
+            m_peer_data.enc_key.master_id = key_set.keys_periph.enc_key.p_enc_key->master_id;
+
+            err_code = dfu_ble_svc_peer_data_set(&m_peer_data);
+            APP_ERROR_CHECK(err_code);
+
+            app_context_data   = (DFU_APP_ATT_TABLE_CHANGED << DFU_APP_ATT_TABLE_POS);
+            app_context.len    = sizeof(app_context_data);
+            app_context.p_data = (uint8_t *)&app_context_data;
+            app_context.flags  = 0;
+
+            err_code = dm_application_context_set(&m_dm_handle, &app_context);
+            APP_ERROR_CHECK(err_code);
+        }
+        else
+        {
+            // Keys were not available, thus we have a non-encrypted connection.
+            err_code = dm_peer_addr_get(&m_dm_handle, &m_peer_data.addr);
+            APP_ERROR_CHECK(err_code);
+
+            err_code = dfu_ble_svc_peer_data_set(&m_peer_data);
+            APP_ERROR_CHECK(err_code);
+        }
+    }
+/** [DFU bond sharing] */
+}
+
+
+/**@brief Function for preparing the reset, disabling SoftDevice, and jumping to the bootloader.
+ *
+ * @param[in] conn_handle Connection handle for peer requesting to enter DFU mode.
+ */
+static void bootloader_start(uint16_t conn_handle)
+{
+    uint32_t err_code;
+    uint16_t sys_serv_attr_len = sizeof(m_peer_data.sys_serv_attr);
+
+    err_code = sd_ble_gatts_sys_attr_get(conn_handle,
+                                         m_peer_data.sys_serv_attr,
+                                         &sys_serv_attr_len,
+                                         BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS);
+    if (err_code != NRF_SUCCESS)
+    {
+        // Any error at this stage means the system service attributes could not be fetched.
+        // This means the service changed indication cannot be sent in DFU mode, but connection
+        // is still possible to establish.
+    }
+
+    m_reset_prepare();
+
+    err_code = sd_power_gpregret_set(BOOTLOADER_DFU_START);
+    APP_ERROR_CHECK(err_code);
+
+    err_code = sd_softdevice_disable();
+    APP_ERROR_CHECK(err_code);
+
+    err_code = sd_softdevice_vector_table_base_set(NRF_UICR->BOOTLOADERADDR);
+    APP_ERROR_CHECK(err_code);
+
+    dfu_app_peer_data_set(conn_handle);
+
+    NVIC_ClearPendingIRQ(SWI2_IRQn);
+    interrupts_disable();
+    bootloader_util_app_start(NRF_UICR->BOOTLOADERADDR);
+}
+
+
+void dfu_app_on_dfu_evt(ble_dfu_t * p_dfu, ble_dfu_evt_t * p_evt)
+{
+    switch (p_evt->ble_dfu_evt_type)
+    {
+        case BLE_DFU_START:
+            // Starting the bootloader - will cause reset.
+            bootloader_start(p_dfu->conn_handle);
+            break;
+
+        default:
+            {
+                // Unsupported event received from DFU Service. 
+                // Send back BLE_DFU_RESP_VAL_NOT_SUPPORTED message to peer.
+                uint32_t err_code = ble_dfu_response_send(p_dfu,
+                                                          BLE_DFU_START_PROCEDURE,
+                                                          BLE_DFU_RESP_VAL_NOT_SUPPORTED);
+                APP_ERROR_CHECK(err_code);
+            }
+            break;
+    }
+}
+
+
+void dfu_app_reset_prepare_set(dfu_app_reset_prepare_t reset_prepare_func)
+{
+    m_reset_prepare = reset_prepare_func;
+}
+
+
+void dfu_app_dm_appl_instance_set(dm_application_instance_t app_instance)
+{
+    uint32_t err_code;
+    
+    err_code = dm_application_instance_set(&app_instance, &m_dm_handle);
+    APP_ERROR_CHECK(err_code);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_app_handler.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+  
+/** @file
+ *
+ * @defgroup nrf_dfu_app_handler DFU BLE packet handling in application
+ * @{
+ *
+ * @brief Handling of DFU BLE packets in the application.
+ *
+ * @details This module implements the handling of DFU packets for switching 
+ *          from an application to the bootloader and start DFU mode. The DFU
+ *          packets are transmitted over BLE. 
+ *          This module handles only the StartDFU packet, which allows a BLE 
+ *          application to expose support for the DFU Service.
+ *          The actual DFU Service runs in a dedicated environment after a BLE 
+ *          disconnect and reset of the \nRFXX device. 
+ *          The host must reconnect and continue the update procedure with 
+ *          access to the full DFU Service.
+ *
+ * @note The application must propagate DFU events to this module by calling
+ *       @ref dfu_app_on_dfu_evt from the @ref ble_dfu_evt_handler_t callback.
+ */
+ 
+#ifndef DFU_APP_HANDLER_H__
+#define DFU_APP_HANDLER_H__
+
+#include "ble_dfu.h"
+#include "nrf_svc.h"
+#include "bootloader_types.h"
+#include "device_manager.h"
+
+#define DFU_APP_ATT_TABLE_POS     0                     /**< Position for the ATT table changed setting. */
+#define DFU_APP_ATT_TABLE_CHANGED 1                     /**< Value indicating that the ATT table might have changed. This value will be set in the application-specific context in Device Manager when entering DFU mode. */
+
+/**@brief DFU application reset_prepare function. This function is a callback that allows the 
+ *        application to prepare for an upcoming application reset. 
+ */
+typedef void (*dfu_app_reset_prepare_t)(void);
+
+/**@brief   Function for handling events from the DFU Service. 
+ *
+ * @details The application must inject this function into the DFU Service or propagate DFU events 
+ *          to the dfu_app_handler module by calling this function in the application-specific DFU event 
+ *          handler.
+ * 
+ * @param[in] p_dfu  Pointer to the DFU Service structure to which the include event relates.
+ * @param[in] p_evt  Pointer to the DFU event.
+ */
+void dfu_app_on_dfu_evt(ble_dfu_t * p_dfu, ble_dfu_evt_t * p_evt);
+
+/**@brief Function for registering a function to prepare a reset.
+ *
+ * @details The provided function is executed before resetting the system into bootloader/DFU
+ *          mode. By registering this function, the caller is notified before the reset and can
+ *          thus prepare the application for reset. For example, the application can gracefully
+ *          disconnect any peers on BLE, turn of LEDS, ensure that all pending flash operations
+ *          have completed, and so on.
+ *
+ * @param[in] reset_prepare_func  Function to be executed before a reset.
+ */
+void dfu_app_reset_prepare_set(dfu_app_reset_prepare_t reset_prepare_func);
+
+/**@brief Function for setting the Device Manager application instance.
+ *
+ * @details This function allows to set the @ref dm_application_instance_t value that is returned by the 
+ *          Device Manager when the application registers using @ref dm_register.
+ *          If this function is not called, it is not be possible to share bonding information
+ *          from the application to the bootloader/DFU when entering DFU mode.
+ *
+ * @param[in] app_instance Value for the application instance in use.
+ */
+void dfu_app_dm_appl_instance_set(dm_application_instance_t app_instance);
+
+#endif // DFU_APP_HANDLER_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_bank_internal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_bank_internal.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/**@file
+ *
+ * @defgroup dfu_bank_internal Device Firmware Update internal header for bank handling in DFU.
+ * @{     
+ *
+ * @brief Device Firmware Update Bank handling module interface.
+ *
+ * @details This header is intended for shared definition and functions between single and dual bank 
+ *         implementations used for DFU support. It is not supposed to be used for external access 
+ *         to the DFU module.
+ *  
+ */
+#ifndef DFU_BANK_INTERNAL_H__
+#define DFU_BANK_INTERNAL_H__
+
+#include <dfu_types.h>
+
+/**@brief States of the DFU state machine. */
+typedef enum
+{
+    DFU_STATE_INIT_ERROR,                                                           /**< State for: dfu_init(...) error. */
+    DFU_STATE_IDLE,                                                                 /**< State for: idle. */
+    DFU_STATE_PREPARING,                                                            /**< State for: preparing, indicates that the flash is being erased and no data packets can be processed. */
+    DFU_STATE_RDY,                                                                  /**< State for: ready. */
+    DFU_STATE_RX_INIT_PKT,                                                          /**< State for: receiving initialization packet. */
+    DFU_STATE_RX_DATA_PKT,                                                          /**< State for: receiving data packet. */
+    DFU_STATE_VALIDATE,                                                             /**< State for: validate. */
+    DFU_STATE_WAIT_4_ACTIVATE                                                       /**< State for: waiting for dfu_image_activate(). */
+} dfu_state_t;
+
+#define APP_TIMER_PRESCALER         0                                               /**< Value of the RTC1 PRESCALER register. */
+#define DFU_TIMEOUT_INTERVAL        APP_TIMER_TICKS(120000, APP_TIMER_PRESCALER)    /**< DFU timeout interval in units of timer ticks. */     
+
+#define IS_UPDATING_SD(START_PKT)   ((START_PKT).dfu_update_mode & DFU_UPDATE_SD)   /**< Macro for determining if a SoftDevice update is ongoing. */
+#define IS_UPDATING_BL(START_PKT)   ((START_PKT).dfu_update_mode & DFU_UPDATE_BL)   /**< Macro for determining if a Bootloader update is ongoing. */
+#define IS_UPDATING_APP(START_PKT)  ((START_PKT).dfu_update_mode & DFU_UPDATE_APP)  /**< Macro for determining if a Application update is ongoing. */
+#define IMAGE_WRITE_IN_PROGRESS()   (m_data_received > 0)                           /**< Macro for determining if an image write is in progress. */
+#define IS_WORD_SIZED(SIZE)         ((SIZE & (sizeof(uint32_t) - 1)) == 0)          /**< Macro for checking that the provided is word sized. */
+
+/**@cond NO_DOXYGEN */
+static uint32_t                     m_data_received;                                /**< Amount of received data. */
+/**@endcond */
+
+/**@brief     Type definition of function used for preparing of the bank before receiving of a
+ *            software image.
+ *
+ * @param[in] image_size  Size of software image being received.
+ */
+typedef void (*dfu_bank_prepare_t)(uint32_t image_size);
+
+/**@brief     Type definition of function used for handling clear complete of the bank before 
+ *            receiving of a software image.
+ */
+typedef void (*dfu_bank_cleared_t)(void);
+
+/**@brief    Type definition of function used for activating of the software image received.
+ *
+ * @return  NRF_SUCCESS If the image has been successfully activated any other NRF_ERROR code in
+ *          case of a failure.
+ */
+typedef uint32_t (*dfu_bank_activate_t)(void);
+
+/**@brief Structure for holding of function pointers for needed prepare and activate procedure for
+ *        the requested update procedure. 
+ */
+typedef struct
+{
+    dfu_bank_prepare_t  prepare;                                                    /**< Function pointer to the prepare function called on start of update procedure. */
+    dfu_bank_cleared_t  cleared;                                                    /**< Function pointer to the cleared function called after prepare function completes. */
+    dfu_bank_activate_t activate;                                                   /**< Function pointer to the activate function called on finalizing the update procedure. */
+} dfu_bank_func_t;
+
+#endif // DFU_BANK_INTERNAL_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+  
+/** @file
+ *
+ * @defgroup nrf_dfu_ble_svc DFU BLE SVC 
+ * @{
+ *
+ * @brief DFU BLE SVC in bootloader. The DFU BLE SuperVisor Calls allow an application to execute
+ *        functions in the installed bootloader. 
+ *
+ * @details This module implements handling of SuperVisor Calls in the bootloader. 
+ *          SuperVisor Calls allow for an application to execute calls into the bootloader.
+ *          Currently, it is possible to exchange bonding information (like keys) from the 
+ *          application to a bootloader supporting DFU OTA using BLE, so the update process can be 
+ *          done through an already existing bond.
+ *
+ * @note The application must make sure that all SuperVisor Calls (SVC) are forwarded to the 
+ *       bootloader to ensure correct behavior. Forwarding of SVCs to the bootloader is 
+ *       done using the SoftDevice SVC @ref sd_softdevice_vector_table_base_set with the value 
+ *       present in @c NRF_UICR->BOOTLOADERADDR.
+ */
+ 
+#ifndef DFU_BLE_SVC_H__
+#define DFU_BLE_SVC_H__
+
+#include "nrf_svc.h"
+#include <stdint.h>
+#include "ble_gap.h"
+#include "nrf.h"
+#include "nrf_soc.h"
+#include "nrf_error_sdm.h"
+
+#define BOOTLOADER_SVC_BASE     0x0     /**< The number of the lowest SVC number reserved for the bootloader. */
+#define SYSTEM_SERVICE_ATT_SIZE 8       /**< Size of the system service attribute length including CRC-16 at the end. */  
+
+/**@brief The SVC numbers used by the SVC functions in the SoC library. */
+enum BOOTLOADER_SVCS
+{
+    DFU_BLE_SVC_PEER_DATA_SET = BOOTLOADER_SVC_BASE,    /**< SVC number for the setting of peer data call. */
+    BOOTLOADER_SVC_LAST
+};
+
+/**@brief   DFU Peer data structure.
+ *
+ * @details This structure contains peer data needed for connection to a bonded device during DFU.
+ *          The peer data must be provided by the application to the bootloader during buttonless
+ *          update. See @ref dfu_ble_svc_peer_data_set. It contains bond information about the
+ *          desired DFU peer.
+ */
+typedef struct
+{
+    ble_gap_addr_t      addr;                                   /**< BLE GAP address of the device that initiated the DFU process. */
+    ble_gap_irk_t       irk;                                    /**< IRK of the device that initiated the DFU process if this device uses Private Resolvable Addresses. */
+    ble_gap_enc_key_t   enc_key;                                /**< Encryption key structure containing encrypted diversifier and LTK for re-establishing the bond. */
+    uint8_t             sys_serv_attr[SYSTEM_SERVICE_ATT_SIZE]; /**< System service attributes for restoring of Service Changed Indication setting in DFU mode. */
+} dfu_ble_peer_data_t;
+
+/**@brief   SVC Function for setting peer data containing address, IRK, and LTK to establish bonded
+ *          connection in DFU mode.
+ *
+ * @param[in] p_peer_data  Pointer to the peer data containing keys for the connection.
+ *
+ * @retval NRF_ERROR_NULL If a NULL pointer was provided as argument.
+ * @retval NRF_SUCCESS    If the function completed successfully.
+ */
+SVCALL(DFU_BLE_SVC_PEER_DATA_SET, uint32_t, dfu_ble_svc_peer_data_set(dfu_ble_peer_data_t * p_peer_data));
+
+#endif // DFU_BLE_SVC_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc_internal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_ble_svc_internal.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+  
+/** @file
+ *
+ * @defgroup nrf_dfu_ble_svc_internal DFU BLE SVC internal
+ * @{
+ *
+ * @brief DFU BLE SVC internal functions in bootloader. The DFU BLE SuperVisor Calls allow an 
+ *        application to execute functions in the installed bootloader. This interface provides 
+ *        internal Bootloader DFU functions for retrieving data exchanged through SuperVisor Calls.
+ *
+ */
+
+#ifndef DFU_BLE_SVC_INTERNAL_H__
+#define DFU_BLE_SVC_INTERNAL_H__
+
+#include <stdint.h>
+#include "dfu_ble_svc.h"
+#include "ble_gap.h"
+
+/**@brief Internal bootloader/DFU function for retrieving peer data provided from application.
+ *
+ * @param[out] p_peer_data Peer data set by application to be used for DFU connection.
+ *
+ * @retval NRF_SUCCESS            If peer data is valid and can be used for connection.
+ * @retval NRF_ERROR_NULL         If p_peer_data is a NULL pointer.
+ * @retval NRF_ERROR_INVALID_DATA If peer data is not available or invalid.
+ */
+uint32_t dfu_ble_peer_data_get(dfu_ble_peer_data_t * p_peer_data);
+
+#endif // DFU_BLE_SVC_INTERNAL_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup nrf_dfu_init Init packet handling in DFU
+ * @{
+ *
+ * @brief Device Firmware Update module type and function declaration for init packet handling.
+ *
+ * @details This header contains basic functionality for performing safety checks on software 
+ *          updates for \nRFXX based devices. It provides a skeleton for pre-checking an init packet
+ *          to ensure the following image is compatible with this device. A safety check should 
+ *          always be performed to prevent accidental flashing of unsupported applications or a
+ *          wrong combination of application and SoftDevice.
+ *          The device information contains information such as:
+ *          - Device type (2 bytes), for example Heart Rate. The device type is a number defined by
+ *            the customer. It can be located in UICR or FICR.
+ *          - Device revision (2 bytes), for example major revision 1, minor revision 0. The device
+ *            revision is a number defined by the customer. It can be located in UICR or FICR.
+ *          - List of SoftDevices supported by this application, for example 
+ *              0x0049 = S110v6_0_0 
+ *              0xFFFE = S110 development (any SoftDevice accepted),
+ *          - CRC or hash of firmware image
+ *
+ * @note This module does not support security features such as image signing, but the corresponding
+ *       implementation allows for such extensions.
+ *       If the init packet is signed by a trusted source, it must be decrypted before it can be 
+ *       processed.
+ */
+
+#ifndef DFU_INIT_H__
+#define DFU_INIT_H__
+
+#include <stdint.h>
+#include "nrf.h"
+
+/**@brief Structure contained in an init packet. Contains information on device type, revision, and 
+ *        supported SoftDevices.
+ */
+typedef struct
+{
+    uint16_t device_type;                                                                   /**< Device type (2 bytes), for example Heart Rate. This number must be defined by the customer before production. It can be located in UICR or FICR. */
+    uint16_t device_rev;                                                                    /**< Device revision (2 bytes), for example major revision 1, minor revision 0. This number must be defined by the customer before production. It can be located in UICR or FICR. */
+    uint32_t app_version;                                                                   /**< Application version for the image software. This field allows for additional checking, for example ensuring that a downgrade is not allowed. */
+    uint16_t softdevice_len;                                                                /**< Number of different SoftDevice revisions compatible with this application. The list of SoftDevice firmware IDs is defined in @ref softdevice. */
+    uint16_t softdevice[1];                                                                 /**< Variable length array of SoftDevices compatible with this application. The length of the array is specified in the length field. SoftDevice firmware id 0xFFFE indicates any SoftDevice. */
+} dfu_init_packet_t;
+
+/**@brief Structure holding basic device information settings.
+ */
+typedef struct
+{
+    uint16_t device_type;                                                                   /**< Device type (2 bytes), for example Heart Rate. This number must be defined by the customer before production. It can be located in UICR or FICR. */
+    uint16_t device_rev;                                                                    /**< Device revision (2 bytes), for example major revision 1, minor revision 0. This number must be defined by the customer before production. It can be located in UICR or FICR. */
+} dfu_device_info_t;
+
+/** The device info offset can be modified to place the device info settings at a different location.
+  * If the customer reserved UICR location is used for other application specific data, the offset
+  * must be updated to avoid collision with that data.
+  */
+/** [DFU UICR DEV offset] */
+#define UICR_CUSTOMER_DEVICE_INFO_OFFSET    0x0                                             /**< Device info offset inside the customer UICR reserved area. Customers may change this value to place the device information in a user-preferred location. */
+/** [DFU UICR DEV offset] */
+
+#define UICR_CUSTOMER_RESERVED_OFFSET       0x80                                            /**< Customer reserved area in the UICR. The area from UICR + 0x80 is reserved for customer usage. */
+#define DFU_DEVICE_INFO_BASE                (NRF_UICR_BASE + \
+                                             UICR_CUSTOMER_RESERVED_OFFSET + \
+                                             UICR_CUSTOMER_DEVICE_INFO_OFFSET)              /**< The device information base address inside of UICR. */
+#define DFU_DEVICE_INFO                     ((dfu_device_info_t *)DFU_DEVICE_INFO_BASE)     /**< The memory mapped structure for device information data. */
+
+#define DFU_DEVICE_TYPE_EMPTY               ((uint16_t)0xFFFF)                              /**< Mask indicating no device type is present in UICR. 0xFFFF is default flash pattern when not written with data. */
+#define DFU_DEVICE_REVISION_EMPTY           ((uint16_t)0xFFFF)                              /**< Mask indicating no device revision is present in UICR. 0xFFFF is default flash pattern when not written with data. */
+#define DFU_SOFTDEVICE_ANY                  ((uint16_t)0xFFFE)                              /**< Mask indicating that any SoftDevice is allowed for updating this application. Allows for easy development. Not to be used in production images. */
+
+
+/**@brief DFU prevalidate call for pre-checking the received init packet.
+ *
+ * @details  Pre-validation will safety check the firmware image to be transfered in second stage.
+ *           The function currently checks the device type, device revision, application firmware 
+ *           version, and supported SoftDevices. More checks should be added according to 
+ *           customer-specific requirements.
+ * 
+ * @param[in] p_init_data    Pointer to the init packet. If the init packet is encrypted or signed,
+ *                           it must first be decrypted before being checked.
+ * @param[in] init_data_len  Length of the init data.
+ *
+ * @retval NRF_SUCCESS              If the pre-validation succeeded, that means the image is 
+ *                                  supported by the device and it is considered to come from a 
+ *                                  trusted source (signing).
+ * @retval NRF_ERROR_INVALID_DATA   If the pre-validation failed, that means the image is not 
+ *                                  supported by the device or comes from an un-trusted source 
+ *                                  (signing).
+ * @retval NRF_ERROR_INVALID_LENGTH If the size of the init packet is not within the limits of 
+ *                                  the init packet handler.
+ */
+uint32_t dfu_init_prevalidate(uint8_t * p_init_data, uint32_t init_data_len);
+
+/**@brief DFU postvalidate call for post-checking the received image using the init packet.
+ *
+ * @details  Post-validation can verify the integrity check the firmware image received before 
+ *           activating the image.
+ *           Checks performed can be: 
+ *           - A simple CRC as shown in the corresponding implementation of this API in the file
+ *             dfu_init_template.c
+ *           - A hash for better verification of the image.
+ *           - A signature to ensure the image originates from a trusted source.
+ *           Checks are intended to be expanded for customer-specific requirements.
+ * 
+ * @param[in] p_image    Pointer to the received image. The init data provided in the call 
+ *                       \ref dfu_init_prevalidate will be used for validating the image.
+ * @param[in] image_len  Length of the image data.
+ *
+ * @retval NRF_SUCCESS             If the post-validation succeeded, that meant the integrity of the
+ *                                 image has been verified and the image originates from a trusted 
+ *                                 source (signing).
+ * @retval NRF_ERROR_INVALID_DATA  If the post-validation failed, that meant the post check of the 
+ *                                 image failed such as the CRC is not matching the image transfered
+ *                                 or the verification of the image fails (signing).
+ */
+uint32_t dfu_init_postvalidate(uint8_t * p_image, uint32_t image_len);
+
+#endif // DFU_INIT_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init_template.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_init_template.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup nrf_dfu_init_template Template file with an DFU init packet handling example.
+ * @{
+ *
+ * @ingroup nrf_dfu
+ *
+ * @brief This file contains a template on how to implement DFU init packet handling.
+ *
+ * @details The template shows how device type and revision can be used for a safety check of the 
+ *          received image. It shows how validation can be performed in two stages:
+ *          - Stage 1: Pre-check of firmware image before transfer to ensure the firmware matches:
+ *                     - Device Type.
+ *                     - Device Revision.
+ *                     Installed SoftDevice.
+ *                     This template can be extended with additional checks according to needs.
+ *                     For example, such a check could be the origin of the image (trusted source) 
+ *                     based on a signature scheme.
+ *          - Stage 2: Post-check of the image after image transfer but before installing firmware.
+ *                     For example, such a check could be an integrity check in form of hashing or 
+ *                     verification of a signature.
+ *                     In this template, a simple CRC check is carried out.
+ *                     The CRC check can be replaced with other mechanisms, like signing.
+ *
+ * @note This module does not support security features such as image signing, but the 
+ *       implementation allows for such extension.
+ *       If the init packet is signed by a trusted source, it must be decrypted before it can be
+ *       processed.
+ */
+
+#include "dfu_init.h"
+#include <stdint.h>
+#include <string.h>
+#include <dfu_types.h>
+#include "nrf_error.h"
+#include "crc16.h"
+
+#define DFU_INIT_PACKET_EXT_LENGTH_MIN      2                       //< Minimum length of the extended init packet. The extended init packet may contain a CRC, a HASH, or other data. This value must be changed according to the requirements of the system. The template uses a minimum value of two in order to hold a CRC. */
+#define DFU_INIT_PACKET_EXT_LENGTH_MAX      10                      //< Maximum length of the extended init packet. The extended init packet may contain a CRC, a HASH, or other data. This value must be changed according to the requirements of the system. The template uses a maximum value of 10 in order to hold a CRC and any padded data on transport layer without overflow. */
+
+static uint8_t m_extended_packet[DFU_INIT_PACKET_EXT_LENGTH_MAX];   //< Data array for storage of the extended data received. The extended data follows the normal init data of type \ref dfu_init_packet_t. Extended data can be used for a CRC, hash, signature, or other data. */
+static uint8_t m_extended_packet_length;                            //< Length of the extended data received with init packet. */
+
+
+uint32_t dfu_init_prevalidate(uint8_t * p_init_data, uint32_t init_data_len)
+{
+    uint32_t i = 0;
+    
+    // In order to support signing or encryption then any init packet decryption function / library
+    // should be called from here or implemented at this location.
+
+    // Length check to ensure valid data are parsed.
+    if (init_data_len < sizeof(dfu_init_packet_t))
+    {
+        return NRF_ERROR_INVALID_LENGTH;
+    }
+
+    // Current template uses clear text data so they can be casted for pre-check.
+    dfu_init_packet_t * p_init_packet = (dfu_init_packet_t *)p_init_data;
+
+    m_extended_packet_length = ((uint32_t)p_init_data + init_data_len) -
+                               (uint32_t)&p_init_packet->softdevice[p_init_packet->softdevice_len];
+    if (m_extended_packet_length < DFU_INIT_PACKET_EXT_LENGTH_MIN)
+    {
+        return NRF_ERROR_INVALID_LENGTH;
+    }
+
+    if (((uint32_t)p_init_data + init_data_len) < 
+        (uint32_t)&p_init_packet->softdevice[p_init_packet->softdevice_len])
+    {
+        return NRF_ERROR_INVALID_LENGTH;
+    }
+
+    memcpy(m_extended_packet,
+           &p_init_packet->softdevice[p_init_packet->softdevice_len],
+           m_extended_packet_length);
+
+/** [DFU init application version] */
+    // To support application versioning, this check should be updated.
+    // This template allows for any application to be installed. However, 
+    // customers can place a revision number at the bottom of the application 
+    // to be verified by the bootloader. This can be done at a location 
+    // relative to the application, for example the application start 
+    // address + 0x0100.
+/** [DFU init application version] */
+    
+    // First check to verify the image to be transfered matches the device type.
+    // If no Device type is present in DFU_DEVICE_INFO then any image will be accepted.
+    if ((DFU_DEVICE_INFO->device_type != DFU_DEVICE_TYPE_EMPTY) &&
+        (p_init_packet->device_type != DFU_DEVICE_INFO->device_type))
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+    
+    // Second check to verify the image to be transfered matches the device revision.
+    // If no Device revision is present in DFU_DEVICE_INFO then any image will be accepted.
+    if ((DFU_DEVICE_INFO->device_rev != DFU_DEVICE_REVISION_EMPTY) &&
+        (p_init_packet->device_rev != DFU_DEVICE_INFO->device_rev))
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    // Third check: Check the array of supported SoftDevices by this application.
+    //              If the installed SoftDevice does not match any SoftDevice in the list then an
+    //              error is returned.
+    while (i < p_init_packet->softdevice_len)
+    {
+        if (p_init_packet->softdevice[i]   == DFU_SOFTDEVICE_ANY ||
+            p_init_packet->softdevice[i++] == SD_FWID_GET(MBR_SIZE))
+        {
+            return NRF_SUCCESS;
+        }
+    }
+    
+    // No matching SoftDevice found - Return NRF_ERROR_INVALID_DATA.
+    return NRF_ERROR_INVALID_DATA;
+}
+
+
+uint32_t dfu_init_postvalidate(uint8_t * p_image, uint32_t image_len)
+{
+#if NEED_CRC_CHECK /* disabled for now */
+    uint16_t image_crc;
+    uint16_t received_crc;
+    
+    // In order to support hashing (and signing) then the (decrypted) hash should be fetched and
+    // the corresponding hash should be calculated over the image at this location.
+    // If hashing (or signing) is added to the system then the CRC validation should be removed.
+
+    // calculate CRC from active block.
+    image_crc = crc16_compute(p_image, image_len, NULL);
+
+    // Decode the received CRC from extended data.    
+    received_crc = uint16_decode((uint8_t *)&m_extended_packet[0]);
+
+    // Compare the received and calculated CRC.
+    if (image_crc != received_crc)
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+#endif /* NEED_CRC_CHECK */
+
+    return NRF_SUCCESS;
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_transport.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_transport.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup nrf_dfu_transport DFU transport API.
+ * @{     
+ *  
+ * @brief DFU transport module interface.
+ */
+ 
+#ifndef DFU_TRANSPORT_H__
+#define DFU_TRANSPORT_H__
+
+#include <stdint.h>
+
+/**@brief Function for starting the update of Device Firmware.
+ *
+ * @retval NRF_SUCCESS Operation success.   
+ */
+uint32_t dfu_transport_update_start(void);
+
+/**@brief Function for closing the transport layer.
+ *
+ * @retval NRF_SUCCESS Operation success.    
+ */
+uint32_t dfu_transport_close(void);
+
+#endif // DFU_TRANSPORT_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/dfu_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup nrf_dfu_types Types and definitions.
+ * @{
+ *
+ * @ingroup nrf_dfu
+ *
+ * @brief Device Firmware Update module type and definitions.
+ */
+
+#ifndef DFU_TYPES_H__
+#define DFU_TYPES_H__
+
+#include <stdint.h>
+#include "nrf_sdm.h"
+#include "nrf.h"
+#include "app_util.h"
+
+#define NRF_UICR_BOOT_START_ADDRESS     (NRF_UICR_BASE + 0x14)                                          /**< Register where the bootloader start address is stored in the UICR register. */
+
+#define CODE_REGION_1_START             SD_SIZE_GET(MBR_SIZE)                                           /**< This field should correspond to the size of Code Region 0, (which is identical to Start of Code Region 1), found in UICR.CLEN0 register. This value is used for compile safety, as the linker will fail if application expands into bootloader. Runtime, the bootloader will use the value found in UICR.CLEN0. */
+#define SOFTDEVICE_REGION_START         MBR_SIZE                                                        /**< This field should correspond to start address of the bootloader, found in UICR.RESERVED, 0x10001014, register. This value is used for sanity check, so the bootloader will fail immediately if this value differs from runtime value. The value is used to determine max application size for updating. */
+
+#ifdef NRF51
+#ifdef SIGNING
+#define BOOTLOADER_REGION_START         0x00039C00                                                    /**< This field should correspond to start address of the bootloader, found in UICR.RESERVED, 0x10001014, register. This value is used for sanity check, so the bootloader will fail immediately if this value differs from runtime value. The value is used to determine max application size for updating. */
+#define BOOTLOADER_SETTINGS_ADDRESS     0x0003D800                                                    /**< The field specifies the page location of the bootloader settings address. */
+#else
+#define BOOTLOADER_REGION_START         0x0003C000                                                      /**< This field should correspond to start address of the bootloader, found in UICR.RESERVED, 0x10001014, register. This value is used for sanity check, so the bootloader will fail immediately if this value differs from runtime value. The value is used to determine max application size for updating. */
+#define BOOTLOADER_SETTINGS_ADDRESS     0x0003FC00                                                      /**< The field specifies the page location of the bootloader settings address. */
+#endif
+
+#define CODE_PAGE_SIZE                  0x0400                                                          /**< Size of a flash codepage. Used for size of the reserved flash space in the bootloader region. Will be runtime checked against NRF_UICR->CODEPAGESIZE to ensure the region is correct. */
+#elif NRF52
+#define BOOTLOADER_REGION_START         0x0007B000                                                      /**< This field should correspond to start address of the bootloader, found in UICR.RESERVED, 0x10001014, register. This value is used for sanity check, so the bootloader will fail immediately if this value differs from runtime value. The value is used to determine max application size for updating. */
+#define BOOTLOADER_SETTINGS_ADDRESS     0x0007F000                                                      /**< The field specifies the page location of the bootloader settings address. */
+#define CODE_PAGE_SIZE                  0x1000                                                          /**< Size of a flash codepage. Used for size of the reserved flash space in the bootloader region. Will be runtime checked against NRF_UICR->CODEPAGESIZE to ensure the region is correct. */
+#else
+#error No target defined
+#endif
+
+#define DFU_REGION_TOTAL_SIZE           (BOOTLOADER_REGION_START - CODE_REGION_1_START)                 /**< Total size of the region between SD and Bootloader. */
+
+#define DFU_APP_DATA_RESERVED           0x0000                                                          /**< Size of Application Data that must be preserved between application updates. This value must be a multiple of page size. Page size is 0x400 (1024d) bytes, thus this value must be 0x0000, 0x0400, 0x0800, 0x0C00, 0x1000, etc. */
+#define DFU_BANK_PADDING                (DFU_APP_DATA_RESERVED % (2 * CODE_PAGE_SIZE))                  /**< Padding to ensure that image size banked is always page sized. */
+#define DFU_IMAGE_MAX_SIZE_FULL         (DFU_REGION_TOTAL_SIZE - DFU_APP_DATA_RESERVED)                 /**< Maximum size of an application, excluding save data from the application. */
+#define DFU_IMAGE_MAX_SIZE_BANKED       ((DFU_REGION_TOTAL_SIZE - \
+                                          DFU_APP_DATA_RESERVED - \
+                                          DFU_BANK_PADDING) / 2)                                        /**< Maximum size of an application, excluding save data from the application. */
+
+#define DFU_BL_IMAGE_MAX_SIZE           (BOOTLOADER_SETTINGS_ADDRESS - BOOTLOADER_REGION_START)         /**< Maximum size of a bootloader, excluding save data from the current bootloader. */
+
+#define DFU_BANK_0_REGION_START         CODE_REGION_1_START                                             /**< Bank 0 region start. */
+#define DFU_BANK_1_REGION_START         (DFU_BANK_0_REGION_START + DFU_IMAGE_MAX_SIZE_BANKED)           /**< Bank 1 region start. */
+
+#define EMPTY_FLASH_MASK                0xFFFFFFFF                                                      /**< Bit mask that defines an empty address in flash. */
+
+#define INVALID_PACKET                  0x00                                                            /**< Invalid packet identifies. */
+#define INIT_PACKET                     0x01                                                            /**< Packet identifies for initialization packet. */
+#define STOP_INIT_PACKET                0x02                                                            /**< Packet identifies for stop initialization packet. Used when complete init packet has been received so that the init packet can be used for pre validaiton. */
+#define START_PACKET                    0x03                                                            /**< Packet identifies for the Data Start Packet. */
+#define DATA_PACKET                     0x04                                                            /**< Packet identifies for a Data Packet. */
+#define STOP_DATA_PACKET                0x05                                                            /**< Packet identifies for the Data Stop Packet. */
+
+#define DFU_UPDATE_SD                   0x01                                                            /**< Bit field indicating update of SoftDevice is ongoing. */
+#define DFU_UPDATE_BL                   0x02                                                            /**< Bit field indicating update of bootloader is ongoing. */
+#define DFU_UPDATE_APP                  0x04                                                            /**< Bit field indicating update of application is ongoing. */
+
+#define DFU_INIT_RX                     0x00                                                            /**< Op Code identifies for receiving init packet. */
+#define DFU_INIT_COMPLETE               0x01                                                            /**< Op Code identifies for transmission complete of init packet. */
+
+// Safe guard to ensure during compile time that the DFU_APP_DATA_RESERVED is a multiple of page size.
+STATIC_ASSERT((((DFU_APP_DATA_RESERVED) & (CODE_PAGE_SIZE - 1)) == 0x00));
+
+/**@brief Structure holding a start packet containing update mode and image sizes.
+ */
+typedef struct
+{
+    uint8_t  dfu_update_mode;                                                                           /**< Packet type, used to identify the content of the received packet referenced by data packet. */
+    uint32_t sd_image_size;                                                                             /**< Size of the SoftDevice image to be transferred. Zero if no SoftDevice image will be transfered. */
+    uint32_t bl_image_size;                                                                             /**< Size of the Bootloader image to be transferred. Zero if no Bootloader image will be transfered. */
+    uint32_t app_image_size;                                                                            /**< Size of the application image to be transmitted. Zero if no Bootloader image will be transfered. */
+} dfu_start_packet_t;
+
+/**@brief Structure holding a bootloader init/data packet received.
+ */
+typedef struct
+{
+    uint32_t   packet_length;                                                                           /**< Packet length of the data packet. Each data is word size, meaning length of 4 is 4 words, not bytes. */
+    uint32_t * p_data_packet;                                                                           /**< Data Packet received. Each data is a word size entry. */
+} dfu_data_packet_t;
+
+/**@brief Structure for holding dfu update packet. Packet type indicate the type of packet.
+ */
+typedef struct
+{
+    uint32_t   packet_type;                                                                             /**< Packet type, used to identify the content of the received packet referenced by data packet. */
+    union
+    {
+        dfu_data_packet_t    data_packet;                                                               /**< Used when packet type is INIT_PACKET or DATA_PACKET. Packet contains data received for init or data. */
+        dfu_start_packet_t * start_packet;                                                              /**< Used when packet type is START_DATA_PACKET. Will contain information on software to be updtaed, i.e. SoftDevice, Bootloader and/or Application along with image sizes. */
+    } params;
+} dfu_update_packet_t;
+
+/**@brief DFU status error codes.
+*/
+typedef enum
+{
+    DFU_UPDATE_APP_COMPLETE,                                                                            /**< Status update of application complete.*/
+    DFU_UPDATE_SD_COMPLETE,                                                                             /**< Status update of SoftDevice update complete. Note that this solely indicates that a new SoftDevice has been received and stored in bank 0 and 1. */
+    DFU_UPDATE_SD_SWAPPED,                                                                              /**< Status update of SoftDevice update complete. Note that this solely indicates that a new SoftDevice has been received and stored in bank 0 and 1. */
+    DFU_UPDATE_BOOT_COMPLETE,                                                                           /**< Status update complete.*/
+    DFU_BANK_0_ERASED,                                                                                  /**< Status bank 0 erased.*/
+    DFU_TIMEOUT,                                                                                        /**< Status timeout.*/
+    DFU_RESET                                                                                           /**< Status Reset to indicate current update procedure has been aborted and system should reset. */
+} dfu_update_status_code_t;
+
+/**@brief Structure holding DFU complete event.
+*/
+typedef struct
+{
+    dfu_update_status_code_t status_code;                                                               /**< Device Firmware Update status. */
+    uint16_t                 app_crc;                                                                   /**< CRC of the recieved application. */
+    uint32_t                 sd_size;                                                                   /**< Size of the recieved SoftDevice. */
+    uint32_t                 bl_size;                                                                   /**< Size of the recieved BootLoader. */
+    uint32_t                 app_size;                                                                  /**< Size of the recieved Application. */
+    uint32_t                 sd_image_start;                                                            /**< Location in flash where the received SoftDevice image is stored. */
+} dfu_update_status_t;
+
+/**@brief Update complete handler type. */
+typedef void (*dfu_complete_handler_t)(dfu_update_status_t dfu_update_status);
+
+#endif // DFU_TYPES_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/** @file
+ *
+ * @defgroup memory_pool_internal Memory Pool Internal
+ * @{
+ * @ingroup memory_pool
+ *
+ * @brief Memory pool internal definitions
+ */
+ 
+#ifndef MEM_POOL_INTERNAL_H__
+#define MEM_POOL_INTERNAL_H__
+
+#define TX_BUF_SIZE       4u    /**< TX buffer size in bytes. */
+#define RX_BUF_SIZE       32u   /**< RX buffer size in bytes. */
+
+#define RX_BUF_QUEUE_SIZE 8u     /**< RX buffer element size. */
+ 
+#endif // MEM_POOL_INTERNAL_H__
+ 
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "crc16.h"
+#include <stdio.h>
+
+uint16_t crc16_compute(const uint8_t * p_data, uint32_t size, const uint16_t * p_crc)
+{
+    uint32_t i;
+    uint16_t crc = (p_crc == NULL) ? 0xffff : *p_crc;
+
+    for (i = 0; i < size; i++)
+    {
+        crc  = (unsigned char)(crc >> 8) | (crc << 8);
+        crc ^= p_data[i];
+        crc ^= (unsigned char)(crc & 0xff) >> 4;
+        crc ^= (crc << 8) << 4;
+        crc ^= ((crc & 0xff) << 4) << 1;
+    }
+
+    return crc;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/crc16/crc16.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/** @file
+ *
+ * @defgroup crc_compute CRC compute
+ * @{
+ * @ingroup hci_transport
+ *
+ * @brief    This module implements the CRC-16 calculation in the blocks.
+ */
+ 
+#ifndef CRC16_H__
+#define CRC16_H__
+
+#include <stdint.h>
+
+/**@brief Function for calculating CRC-16 in blocks.
+ *
+ * Feed each consecutive data block into this function, along with the current value of p_crc as 
+ * returned by the previous call of this function. The first call of this function should pass NULL 
+ * as the initial value of the crc in p_crc.
+ *
+ * @param[in] p_data The input data block for computation.
+ * @param[in] size   The size of the input data block in bytes.
+ * @param[in] p_crc  The previous calculated CRC-16 value or NULL if first call.  
+ *
+ * @return The updated CRC-16 value, based on the input supplied.
+ */
+uint16_t crc16_compute(const uint8_t * p_data, uint32_t size, const uint16_t * p_crc);
+
+#endif // CRC16_H__
+ 
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/experimental_section_vars/section_vars.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/experimental_section_vars/section_vars.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,323 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SECTION_VARS_H__
+#define SECTION_VARS_H__
+
+#include "app_util.h"
+
+#if defined __ICC_ARM__
+
+// turn on language extensions for iar
+#pragma language=extended
+
+#endif
+
+/**
+ * @defgroup section_vars Section variables
+ * @ingroup app_common
+ * @{
+ * @brief Section variables.
+ */
+
+/**@brief Macro to delay macro expression of pragma
+ *
+ */
+#define NRF_PRAGMA(x) _Pragma(#x)
+
+
+/**@brief Macro to register section by name in code
+ *
+ * @param[in]   section_name    Name of the section to register
+ **/
+#if defined __CC_ARM
+
+// Not required by this compiler
+#define NRF_SECTION_VARS_REGISTER_SECTION(section_name)
+
+#elif defined __GNUC__
+
+// Not required by this compiler
+#define NRF_SECTION_VARS_REGISTER_SECTION(section_name)
+
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_REGISTER_SECTION(section_name) NRF_PRAGMA(section = ## #section_name )
+
+#else
+
+#error TODO
+
+#endif
+
+/*lint -save -e27 */
+
+/**@brief Macro for accessing start of a named data section by symbol 
+ *
+ * @details     The symbol that this macro resolves to is used to access the section 
+ *              by start address.
+ *
+ * @param[in]   section_name    Name of the section
+ */
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_START_SYMBOL(section_name)         section_name ## $$Base
+
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_START_SYMBOL(section_name)         __start_ ## section_name
+
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_START_SYMBOL(section_name)         __section_begin(#section_name)
+
+#else
+
+#error TODO
+
+#endif
+
+
+/**@brief Macro for accessing end of a named data section by symbol
+ *
+ * @details     The symbol that this macro resolves to is used to access the section
+ *              by end address.
+ *
+ * @param[in]   section_name    Name of the section    
+ */
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_END_SYMBOL(section_name)           section_name ## $$Limit
+
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_END_SYMBOL(section_name)           __stop_ ## section_name
+
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_END_SYMBOL(section_name)           __section_end(#section_name)
+
+#endif
+
+/*lint -restore */
+
+
+/**@brief Macro for accessing Length of a named section
+ *
+ * @details     This macro is used to get the size of a named section.
+ *
+ * @param[in]   section_name    Name of the section
+ */
+
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_LENGTH(section_name) \
+    ((uint32_t)&NRF_SECTION_VARS_END_SYMBOL(section_name) - (uint32_t)&NRF_SECTION_VARS_START_SYMBOL(section_name))
+
+#elif defined __GNUC__
+
+ #define NRF_SECTION_VARS_LENGTH(section_name) \
+    ((uint32_t)&NRF_SECTION_VARS_END_SYMBOL(section_name) - (uint32_t)&NRF_SECTION_VARS_START_SYMBOL(section_name))
+
+#elif defined __ICCARM__
+
+ #define NRF_SECTION_VARS_LENGTH(section_name) \
+    ((uint32_t)NRF_SECTION_VARS_END_SYMBOL(section_name) - (uint32_t)NRF_SECTION_VARS_START_SYMBOL(section_name))
+
+#else
+
+#error TODO
+
+#endif
+      
+
+/**@brief Macro for accessing the start address of a named section
+ *
+ * param[in]    section_name    Name of the section to get the start address from
+ */
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_START_ADDR(section_name)       (uint32_t)&NRF_SECTION_VARS_START_SYMBOL(section_name)
+      
+#elif defined __GNUC__
+      
+#define NRF_SECTION_VARS_START_ADDR(section_name)       (uint32_t)&NRF_SECTION_VARS_START_SYMBOL(section_name)
+      
+#elif defined __ICCARM__
+      
+#define NRF_SECTION_VARS_START_ADDR(section_name)       (uint32_t)iar_ ## section_name ## _start
+
+#else
+      
+#error TODO
+      
+#endif
+
+      
+/*@brief Macro for accessing the end address of a named section
+ *
+ * @param[in]   section_name    Name of the section to get end address from
+ */
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_END_ADDR(section_name)         (uint32_t)&NRF_SECTION_VARS_END_SYMBOL(section_name)
+      
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_END_ADDR(section_name)         (uint32_t)&NRF_SECTION_VARS_END_SYMBOL(section_name)
+      
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_END_ADDR(section_name)         (uint32_t)iar_ ## section_name ## _end
+
+#else
+      
+#error TODO
+      
+#endif
+
+
+/**@brief Macro for declaring symbols for named sections
+ *
+ * @note    These external declarations of section specific symbols are required for the linker in GCC and Keil (not IAR)
+ *
+ * @param[in]   type_name       Name of the type stored in the section
+ * @param[in]   section_name    Name of the section
+ */
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_REGISTER_SYMBOLS(type_name, section_name)      \
+    extern type_name* NRF_SECTION_VARS_START_SYMBOL(section_name);      \
+    extern void* NRF_SECTION_VARS_END_SYMBOL(section_name)
+
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_REGISTER_SYMBOLS(type_name, section_name)      \
+    extern type_name* NRF_SECTION_VARS_START_SYMBOL(section_name);      \
+    extern void* NRF_SECTION_VARS_END_SYMBOL(section_name)
+
+#elif defined __ICCARM__
+
+// No symbol registration required for IAR      
+#define NRF_SECTION_VARS_REGISTER_SYMBOLS(type_name, section_name)                              \
+    extern void*   iar_ ## section_name ## _start   = __section_begin(#section_name);            \
+    extern void*   iar_ ## section_name ## _end     = __section_end(#section_name)
+      
+#else
+      
+#error TODO
+
+#endif
+
+
+/**@brief Macro to add symbols to a named section
+ *
+ * @details     The symbols are placed in a named section. All calls to this macro
+ *              will result in symbols being placed in a contiguous manner in the named section. 
+ *              This macro ensures that the symbol is not removed because of optimization level.
+ *
+ * @warning     There is no guarantee for ordering of placement. If ordering is required
+ *
+ * @warning     The symbols added in the named section must be word aligned to
+ *              ensure that compilers do not pad the section during symbol placement.
+ *
+ * @param[in]   section_name    Name of the section
+ * @param[in]   type_def        Datatype of the symbol to place in the given section
+ */
+#if defined __CC_ARM
+    
+#define NRF_SECTION_VARS_ADD(section_name, type_def) \
+    static type_def __attribute__((section( #section_name ))) __attribute__((used))
+
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_ADD(section_name, type_def) \
+    static type_def __attribute__ ((section( #section_name ))) __attribute__ ((used))
+
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_ADD(section_name, type_def) \
+    __root type_def @ #section_name
+
+#else
+      
+#error    TODO
+      
+#endif    
+
+      
+/**@brief Macro to get symbol from named section
+ *
+ * @warning     The stored symbol can only be resolved using this macro if the 
+ *              type of the data is word aligned. The operation of acquiring 
+ *              the stored symbol relies on sizeof of the stored type, no 
+ *              padding can exist in the named section in between individual 
+ *              stored items or this macro will fail.
+ *
+ * @param[in]   i               Index of item in section
+ * @param[in]   type_name       Type name of item in section
+ * @param[in]   section_name    Name of the section
+ */
+      
+#if defined __CC_ARM
+
+#define NRF_SECTION_VARS_GET(i, type_name, section_name) \
+    (type_name*)(NRF_SECTION_VARS_START_ADDR(section_name) + i * sizeof(type_name))
+      
+#elif defined __GNUC__
+
+#define NRF_SECTION_VARS_GET(i, type_name, section_name) \
+    (type_name*)(NRF_SECTION_VARS_START_ADDR(section_name) + i * sizeof(type_name))
+      
+#elif defined __ICCARM__
+
+#define NRF_SECTION_VARS_GET(i, type_name, section_name) \
+      (type_name*)iar_ ## section_name ## _start + (i * sizeof(type_name))
+
+#else
+
+#error TODO
+
+#endif
+
+
+/**@brief Macro to get number of items in named section
+ *
+ * @param[in]   type_name       Type name of item in section
+ * @param[in]   section_name    Name of the section
+ */
+#define NRF_SECTION_VARS_COUNT(type_name, section_name) \
+    NRF_SECTION_VARS_LENGTH(section_name) / sizeof(type_name)
+
+/** @} */
+
+#endif // SECTION_VARS_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,2090 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "fds.h"
+#include <stdint.h>
+#include <string.h>
+#include <stdbool.h>
+#include "fds_config.h"
+#include "fds_types_internal.h"
+#include "fstorage.h"
+#include "nrf_error.h"
+#include "app_util.h"
+
+
+/** Our fstorage configuration.
+ *  The other fields will be assigned automatically during compilation. */
+FS_SECTION_VARS_ADD(fs_config_t fs_config) = { .cb = fs_callback, .num_pages = FDS_MAX_PAGES };
+
+static uint32_t const fds_page_tag_swap[]   = {FDS_PAGE_TAG_WORD_0_SWAP, FDS_PAGE_TAG_WORD_1,
+                                               FDS_PAGE_TAG_WORD_2,      FDS_PAGE_TAG_WORD_3};
+
+static uint32_t const fds_page_tag_valid[]  = {FDS_PAGE_TAG_WORD_0_VALID, FDS_PAGE_TAG_WORD_1,
+                                               FDS_PAGE_TAG_WORD_2,       FDS_PAGE_TAG_WORD_3};
+
+static uint32_t const fds_page_tag_gc       = FDS_PAGE_TAG_WORD_3_GC;
+
+static fds_tl_t const m_fds_tl_invalid      = { .type = FDS_TYPE_ID_INVALID,
+                                                .length_words = 0xFFFF };
+
+/**@brief Internal status flags. */
+static uint8_t           volatile m_flags;       
+
+static uint8_t                    m_users;
+static fds_cb_t                   m_cb_table[FDS_MAX_USERS];
+
+/**@brief The last record ID. Setup page by page_scan() during pages_init(). */
+static fds_record_id_t            m_last_rec_id;
+
+/**@brief The internal queues. */
+static fds_cmd_queue_t            m_cmd_queue;   
+static fds_chunk_queue_t          m_chunk_queue;
+
+/**@brief Holds the state of pages. Setup by fds_init(). */
+static fds_page_t                 m_pages[FDS_MAX_PAGES];
+static bool                       m_swap_page_avail = false;
+
+static fds_gc_data_t              m_gc;
+static uint16_t                   m_gc_runs;
+
+static uint8_t          volatile  m_counter;
+
+
+static void app_notify(ret_code_t       result,
+                       fds_cmd_id_t     cmd,
+                       fds_record_id_t  record_id,
+                       fds_record_key_t record_key)
+{
+    for (uint8_t user = 0; user < FDS_MAX_USERS; user++)
+    {
+        if (m_cb_table[user] != NULL)
+        {
+            m_cb_table[user](result, cmd, record_id, record_key);
+        }
+    }
+}
+
+
+static void atomic_counter_inc()
+{
+    CRITICAL_SECTION_ENTER();
+    m_counter++;
+    CRITICAL_SECTION_EXIT();
+}
+
+
+static void atomic_counter_dec()
+{
+    CRITICAL_SECTION_ENTER();
+    m_counter--;
+    CRITICAL_SECTION_EXIT();
+}
+
+
+static bool atomic_counter_is_zero()
+{
+    bool ret;
+    CRITICAL_SECTION_ENTER();
+    ret = (m_counter == 0);
+    CRITICAL_SECTION_EXIT();
+    return ret;
+}
+
+
+static void flag_set(fds_flags_t flag)
+{
+    CRITICAL_SECTION_ENTER();
+    m_flags |= flag;
+    CRITICAL_SECTION_EXIT();
+}
+
+
+static void flag_clear(fds_flags_t flag)
+{
+    CRITICAL_SECTION_ENTER();
+    m_flags &= ~(flag);
+    CRITICAL_SECTION_EXIT();
+}
+
+
+static bool flag_is_set(fds_flags_t flag)
+{
+    bool ret;
+    CRITICAL_SECTION_ENTER();
+    ret = (m_flags & flag);
+    CRITICAL_SECTION_EXIT();
+    return ret;
+}
+
+
+/**@brief Function to check if a header has valid information. */
+static __INLINE bool header_is_valid(fds_header_t const * const p_header)
+{
+    return ((p_header->tl.type     != FDS_TYPE_ID_INVALID) &&
+            (p_header->ic.instance != FDS_INSTANCE_ID_INVALID));
+}
+
+
+static bool address_within_page_bounds(uint32_t const * const p_addr)
+{
+    return (p_addr >= fs_config.p_start_addr) &&
+           (p_addr <= fs_config.p_end_addr) &&
+           (is_word_aligned(p_addr));
+}
+
+
+/**@brief Internal function to identify the page type. */
+static fds_page_type_t page_identify(uint16_t page_number)
+{
+    uint32_t const * const p_page_addr = m_pages[page_number].start_addr;
+
+    uint32_t const word0 = *(p_page_addr);
+    uint32_t const word1 = *(p_page_addr + 1);
+    uint32_t const word2 = *(p_page_addr + 2);
+    uint32_t const word3 = *(p_page_addr + 3);
+
+    if (word1 != FDS_PAGE_TAG_WORD_1)
+    {
+        return FDS_PAGE_UNDEFINED;
+    }
+
+    if (word2 != FDS_PAGE_TAG_WORD_2)
+    {
+        return FDS_PAGE_UNDEFINED;
+    }
+
+    if (word3 == FDS_PAGE_TAG_WORD_3)
+    {
+        if (word0 == FDS_PAGE_TAG_WORD_0_SWAP)
+        {
+            return FDS_PAGE_SWAP;
+        }
+
+        if (word0 == FDS_PAGE_TAG_WORD_0_VALID)
+        {
+            return FDS_PAGE_VALID;
+        }
+    }
+    else if (word3 == FDS_PAGE_TAG_WORD_3_GC)
+    {
+        if (word0 == FDS_PAGE_TAG_WORD_0_SWAP || word0 == FDS_PAGE_TAG_WORD_0_VALID)
+        {
+            return FDS_PAGE_GC;
+        }
+    }
+
+    return FDS_PAGE_UNDEFINED;
+}
+
+
+static uint16_t page_by_addr(uint32_t const * const p_addr)
+{
+    if (p_addr == NULL)
+    {
+        return 0;
+    }
+
+    // Compute the BYTES offset from the beginning of the first page.
+    uint32_t const byte_offset = (uint32_t)p_addr - (uint32_t)m_pages[0].start_addr;
+
+// See nrf.h.
+#if defined (NRF51)
+    return byte_offset >> 10; // Divide by page size (1024).
+#elif defined (NRF52)
+    return byte_offset >> 12; // Divide by page size (4096).
+#else
+    #error "Device family must be defined. See nrf.h."
+#endif
+}
+
+
+// NOTE: depends on m_pages.write_offset to function.
+static bool page_has_space(uint16_t page, fds_length_t length_words)
+{
+    if (page >= FDS_MAX_PAGES)
+    {
+        return false;
+    }
+
+    CRITICAL_SECTION_ENTER();
+    length_words +=  m_pages[page].write_offset;
+    length_words +=  m_pages[page].words_reserved;
+    CRITICAL_SECTION_EXIT();
+
+    return (length_words < FS_PAGE_SIZE_WORDS);
+}
+
+
+/**@brief This function scans a page to determine how many words have
+ *        been written to it. This information is used to set the page
+ *        write offset during initialization (mount). Additionally, this
+ *        function will update the last known record ID as it proceeds.
+ */
+static void page_scan(uint16_t page, uint16_t volatile * words_written)
+{
+    uint32_t const * p_addr = (m_pages[page].start_addr + FDS_PAGE_TAG_SIZE);
+
+    *words_written = FDS_PAGE_TAG_SIZE;
+
+    // A corrupt TL might cause problems.
+    while ((p_addr < m_pages[page].start_addr + FS_PAGE_SIZE_WORDS) &&
+           (*p_addr != FDS_ERASED_WORD))
+    {
+        fds_header_t const * const p_header = (fds_header_t*)p_addr;
+
+        /** Note: DO NOT check for the validity of the header using
+         *  header_is_valid() here. If an header has an invalid type (0x0000)
+         *  or a missing instance (0xFFFF) then we WANT to skip it.
+         */
+
+         // Update the last known record id.
+         if (p_header->id > m_last_rec_id)
+         {
+            m_last_rec_id = p_header->id;
+         }
+
+         // Jump to the next record.
+         p_addr         += (FDS_HEADER_SIZE + p_header->tl.length_words);
+         *words_written += (FDS_HEADER_SIZE + p_header->tl.length_words);
+    }
+}
+
+
+static bool page_is_empty(uint16_t page)
+{
+    uint32_t const * const p_addr = m_pages[page].start_addr;
+
+    for (uint16_t i = 0; i < FS_PAGE_SIZE_WORDS; i++)
+    {
+        if (*(p_addr + i) != FDS_ERASED_WORD)
+        {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+
+static ret_code_t page_id_from_virtual_id(uint16_t vpage_id, uint16_t * p_page_id)
+{
+    for (uint16_t i = 0; i < FDS_MAX_PAGES; i++)
+    {
+        if (m_pages[i].vpage_id == vpage_id)
+        {
+            *p_page_id = i;
+            return NRF_SUCCESS;
+        }
+    }
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static ret_code_t page_from_virtual_id(uint16_t vpage_id, fds_page_t ** p_page)
+{
+    for (uint16_t i = 0; i < FDS_MAX_PAGES; i++)
+    {
+        if (m_pages[i].vpage_id == vpage_id)
+        {
+            *p_page = &m_pages[i];
+            return NRF_SUCCESS;
+        }
+    }
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static uint32_t record_id_new()
+{
+    return ++m_last_rec_id;
+}
+
+
+/**@brief Tags a page as swap, i.e., reserved for GC. */
+static ret_code_t page_tag_write_swap(uint16_t page)
+{
+    return fs_store(&fs_config,
+                    m_pages[page].start_addr,
+                    (uint32_t const *)&fds_page_tag_swap,
+                    FDS_PAGE_TAG_SIZE);
+}
+
+
+/**@brief Tags a page as valid, i.e, ready for storage. */
+static ret_code_t page_tag_write_valid(uint16_t page)
+{
+    return fs_store(&fs_config,
+                    m_pages[page].start_addr,
+                    (uint32_t const *)&fds_page_tag_valid,
+                    FDS_PAGE_TAG_SIZE);
+}
+
+
+/**@brief Tags a valid page as being garbage collected. */
+static ret_code_t page_tag_write_gc(uint16_t page)
+{
+    return fs_store(&fs_config,
+                    m_pages[page].start_addr + 3,
+                    (uint32_t const *)&fds_page_tag_gc,
+                    1 /*Words*/);
+}
+
+
+/**@brief Given a page and a record, finds the next valid record. */
+static ret_code_t scan_next_valid(uint16_t page, uint32_t const ** p_record)
+{
+    uint32_t const * p_next_rec = (*p_record);
+
+    if (p_next_rec == NULL)
+    {
+        // This if the first invocation on this page, start from the beginning.
+        p_next_rec = m_pages[page].start_addr + FDS_PAGE_TAG_SIZE;
+    }
+    else
+    {
+        // Jump to the next record.
+        p_next_rec += (FDS_HEADER_SIZE + ((fds_header_t*)(*p_record))->tl.length_words);
+    }
+
+    // Scan until we find a valid record or until the end of the page.
+
+    /** README: We might seek until the write_offset is reached, but it might not
+     *  known at this point. */
+    while ((p_next_rec < (m_pages[page].start_addr + FS_PAGE_SIZE_WORDS)) &&
+           (*p_next_rec != FDS_ERASED_WORD)) // Did we jump to an erased word?
+    {
+        fds_header_t const * const p_header = (fds_header_t*)p_next_rec;
+
+        if (header_is_valid(p_header))
+        {
+            // Bingo!
+            *p_record = p_next_rec;
+            return NRF_SUCCESS;
+        }
+        else
+        {
+            // The item is not valid, jump to the next.
+            p_next_rec += (FDS_HEADER_SIZE + (p_header->tl.length_words));
+        }
+    }
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static ret_code_t seek_record(fds_record_desc_t * const p_desc)
+{
+    uint32_t const * p_record;
+    uint16_t         page;
+    bool             seek_all_pages = false;
+
+    if ((p_desc->ptr_magic == FDS_MAGIC_HWORD) &&
+        (p_desc->gc_magic  == m_gc_runs))
+    {
+        // No need to seek the file.
+        return NRF_SUCCESS;
+    }
+
+    /** The pointer in the descriptor is not initialized, or GC
+     *  has been run since the last time it was retrieved.
+     *  We must seek the record again. */
+
+    // Obtain the physical page ID.
+    if (page_id_from_virtual_id(p_desc->vpage_id, &page) != NRF_SUCCESS)
+    {
+        page = 0;
+        seek_all_pages = true;
+    }
+
+    do {
+        // Let's find the address from where we should start seeking the record.
+        p_record = m_pages[page].start_addr + FDS_PAGE_TAG_SIZE;
+
+        /** Seek for a record with matching ID.
+         *  We might get away with seeking to the page write offset, if it is known. */
+
+        while ((p_record < (m_pages[page].start_addr + FS_PAGE_SIZE_WORDS)) &&
+               (*p_record != FDS_ERASED_WORD))
+        {
+            fds_header_t const * const p_header = (fds_header_t*)p_record;
+
+            if ((p_header->id != p_desc->record_id) ||
+                (!header_is_valid(p_header)))
+            {
+                // ID doesnt't match or the record has been cleared. Jump to the next record.
+                p_record += FDS_HEADER_SIZE + p_header->tl.length_words;
+            }
+            else
+            {
+                // Update the pointer in the descriptor.
+                p_desc->p_rec     = p_record;
+                p_desc->ptr_magic = FDS_MAGIC_HWORD;
+                p_desc->gc_magic  = m_gc_runs;
+
+                return NRF_SUCCESS;
+            }
+        }
+    } while (seek_all_pages ? page++ < FDS_MAX_PAGES : 0);
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static ret_code_t find_record(fds_type_id_t     const * const p_type,
+                              fds_instance_id_t const * const p_inst,
+                              fds_record_desc_t       * const p_desc,
+                              fds_find_token_t        * const p_token)
+{
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    // Here we distinguish between the first invocation and the and the others.
+    if ((p_token->magic != FDS_MAGIC_WORD) ||
+        !address_within_page_bounds(p_token->p_addr)) // Is the address is really okay?
+    {
+        // Initialize the token.
+        p_token->magic    = FDS_MAGIC_WORD;
+        p_token->vpage_id = 0;
+        p_token->p_addr   = NULL;
+    }
+    else
+    {
+        // Look past the last record address.
+         p_token->p_addr += (FDS_HEADER_SIZE + ((fds_header_t*)p_token->p_addr)->tl.length_words);
+    }
+
+    // Begin (or resume) searching for a record.
+    for (; p_token->vpage_id < FDS_MAX_PAGES; p_token->vpage_id++)
+    {
+        uint16_t page = 0;
+
+        // Obtain the physical page ID.
+        page_id_from_virtual_id(p_token->vpage_id, &page);
+
+        if (m_pages[page].page_type != FDS_PAGE_VALID)
+        {
+            // Skip this page.
+            continue;
+        }
+
+        if (p_token->p_addr == NULL)
+        {
+            // If it's the first time the function is run, initialize the pointer.
+            p_token->p_addr = m_pages[page].start_addr + FDS_PAGE_TAG_SIZE;
+        }
+
+        // Seek a valid record on this page, starting from the address stored in the token.
+        while ((p_token->p_addr < (m_pages[page].start_addr + FS_PAGE_SIZE_WORDS)) &&
+               (*p_token->p_addr != FDS_ERASED_WORD)) // Did we jump to an erased word?
+        {
+            fds_header_t const * const p_header = (fds_header_t*)p_token->p_addr;
+
+            if (header_is_valid(p_header))
+            {
+                // A valid record was found, check its header for a match.
+                bool item_match = false;
+
+                if (p_type != NULL)
+                {
+                    if (p_header->tl.type == *p_type)
+                    {
+                        item_match = true;
+                    }
+                }
+
+                if (p_inst != NULL)
+                {
+                    if (p_header->ic.instance == *p_inst)
+                    {
+                        item_match = (p_type == NULL) ? true : item_match && true;
+                    }
+                    else
+                    {
+                        item_match = false;
+                    }
+                }
+
+                if (item_match)
+                {
+                    // We found the record! Update the descriptor.
+                    p_desc->vpage_id  = m_pages[page].vpage_id;
+                    p_desc->record_id = p_header->id;
+
+                    p_desc->p_rec     = p_token->p_addr;
+                    p_desc->ptr_magic = FDS_MAGIC_HWORD;
+                    p_desc->gc_magic  = m_gc_runs;
+
+                    return NRF_SUCCESS;
+                }
+            }
+            // Jump to the next record.
+            p_token->p_addr += (FDS_HEADER_SIZE + (p_header->tl.length_words));
+        }
+
+        /** We have seeked an entire page. Set the address in the token to NULL
+         *  so that it will be set again on the next iteration. */
+        p_token->p_addr = NULL;
+    }
+
+    /** If we couldn't find the record, zero the token structure
+     *  so that it can be reused. */
+    p_token->magic = 0x00;
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static void gc_init()
+{
+    // Set which pages to GC.
+    for (uint16_t i = 0; i < FDS_MAX_PAGES; i++)
+    {
+        m_gc.do_gc_page[i] = (m_pages[i].page_type == FDS_PAGE_VALID);
+    }
+}
+
+
+static void gc_reset()
+{
+    m_gc.state       = BEGIN;
+    m_gc.cur_page    = 0;
+    m_gc.p_scan_addr = NULL;
+}
+
+
+static void gc_set_state(fds_gc_state_t new_state)
+{
+    m_gc.state = new_state;
+}
+
+
+static ret_code_t gc_get_next_page(uint16_t * const next_page)
+{
+    for (uint16_t i = 0; i < FDS_MAX_PAGES; i++)
+    {        
+        if (m_gc.do_gc_page[i])
+        {
+            uint16_t records_open;
+
+            CRITICAL_SECTION_ENTER();
+            records_open = m_pages[i].records_open;
+            CRITICAL_SECTION_EXIT();
+
+            // Do not attempt to GC this page anymore.
+            m_gc.do_gc_page[i] = false;
+
+            // Only GC pages with no open records.
+            if (records_open == 0)
+            {
+                *next_page = i;
+                return NRF_SUCCESS;
+            }   
+        }
+    }
+
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+static ret_code_t gc_page()
+{
+    ret_code_t ret;
+
+    ret = gc_get_next_page(&m_gc.cur_page);
+
+    // No pages left to GC. GC has terminated. Reset GC data.
+    if (ret != NRF_SUCCESS)
+    {    
+        gc_reset();
+
+        return COMMAND_COMPLETED;
+    }
+
+    // Prepare to GC the page.
+    gc_set_state(GC_PAGE);
+
+    // Flag the page as being garbage collected.
+    ret = page_tag_write_gc(m_gc.cur_page);
+
+    if (ret != NRF_SUCCESS)
+    {
+        return ret;
+    }
+
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t gc_copy_record()
+{
+    ret_code_t fs_ret;
+
+    // We have found a record to copy.
+    fds_record_t const * const p_record = (fds_record_t*)m_gc.p_scan_addr;
+
+    gc_set_state(COPY_RECORD);
+
+    // Copy the item to swap.
+    fs_ret = fs_store(&fs_config,
+                      m_pages[m_gc.swap_page].start_addr + m_pages[m_gc.swap_page].write_offset,
+                      (uint32_t*)p_record,
+                      FDS_HEADER_SIZE + p_record->header.tl.length_words);
+
+    if (fs_ret != NRF_SUCCESS)
+    {
+        // Oops :(
+        // This is an error. Can we recover?
+    }
+
+    // Remember to update the swap page write offset.
+    m_pages[m_gc.swap_page].write_offset += (FDS_HEADER_SIZE + p_record->header.tl.length_words);
+
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t gc_ready_swap_page()
+{
+    ret_code_t fs_ret;
+
+    /** A page has been scanned through. All valid records found were copied to swap.
+     *  The swap page can now be flagged as a valid page. */
+    gc_set_state(READY_SWAP);
+
+    fs_ret = page_tag_write_valid(m_gc.swap_page);
+    if (fs_ret != NRF_SUCCESS)
+    {
+        return fs_ret;
+    }
+
+    /** Do not update the page type in the internal page structure (m_pages)
+     *  right away. (why?) */
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t gc_seek_record()
+{
+    // Let's find a valid record which has not been copied yet.
+    if (scan_next_valid(m_gc.cur_page, &m_gc.p_scan_addr) == NRF_SUCCESS)
+    {
+        /** The record is guaranteed to fit in the destination page,
+         *  so we don't need to check its size. */
+        return gc_copy_record();
+    }
+    else
+    {
+        /** No more (uncopied) records left on this page.
+         *  The swap page can now be marked as a valid page. */
+        return gc_ready_swap_page();
+    }
+}
+
+
+static ret_code_t gc_new_swap_page()
+{
+    ret_code_t fs_ret;
+    uint16_t   vpage_id;
+
+    gc_set_state(NEW_SWAP);
+
+    // Save the swap page virtual page ID.
+    vpage_id = m_pages[m_gc.swap_page].vpage_id;
+
+    /** The swap page has been marked as valid in Flash. We copy the GC'ed page
+     *  write_offset and virtual page ID. */
+    m_pages[m_gc.swap_page].page_type      = FDS_PAGE_VALID;
+    m_pages[m_gc.swap_page].vpage_id       = m_pages[m_gc.cur_page].vpage_id;
+    m_pages[m_gc.swap_page].words_reserved = m_pages[m_gc.cur_page].words_reserved;
+
+    // The new swap page is now the page we just GC.
+    m_gc.swap_page = m_gc.cur_page;
+
+    // Update the write_offset, words_reserved and vpage_id fields for the new swap page.
+    m_pages[m_gc.swap_page].page_type      = FDS_PAGE_SWAP;
+    m_pages[m_gc.swap_page].vpage_id       = vpage_id;
+    m_pages[m_gc.swap_page].write_offset   = FDS_PAGE_TAG_SIZE;
+    m_pages[m_gc.swap_page].words_reserved = 0;
+
+    /** Finally, erase the new swap page. Remember we still have to flag this
+     *  new page as swap, but we'll wait the callback for this operation to do so. */
+    fs_ret = fs_erase(&fs_config,
+                      (uint32_t*)m_pages[m_gc.swap_page].start_addr,
+                      FS_PAGE_SIZE_WORDS);
+
+    if (fs_ret != NRF_SUCCESS)
+    {
+        return fs_ret;
+    }
+
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t gc_new_swap_page_init()
+{
+    ret_code_t fs_ret;
+
+    gc_set_state(INIT_SWAP);
+
+    fs_ret = page_tag_write_swap(m_gc.swap_page);
+    if (fs_ret != NRF_SUCCESS)
+    {
+        return fs_ret;
+    }
+
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t gc_execute(uint32_t result)
+{
+    // TODO: Handle resuming GC.
+
+    ret_code_t ret;
+
+    if (result != NRF_SUCCESS)
+    {
+        // An operation failed. Report to the application.
+        return result;
+    }
+
+    switch (m_gc.state)
+    {
+        case BEGIN:
+        {
+            // Increment the number of times the GC has been run.
+            m_gc_runs++;
+            // Sets up a list of pages to GC.
+            gc_init();
+            // Go !
+            ret = gc_page();
+        } break;
+
+        case GC_PAGE:
+            /** A page has been successfully flagged as being GC.
+             *  Look for valid records to copy. */
+            ret = gc_seek_record();
+            break;
+
+        case COPY_RECORD:
+            /** A record has been copied to swap.
+             *  Look for more records to copy. */
+            ret = gc_seek_record();
+            break;
+
+        case READY_SWAP:
+            /** The swap page has been flagged as 'valid' (ready).
+             *  Let's prepare a new swap page. */
+            ret = gc_new_swap_page();
+            break;
+
+        case NEW_SWAP:
+            // A new swap page has been prepared. Let's flag it as swap.
+            ret = gc_new_swap_page_init();
+            break;
+
+        case INIT_SWAP:
+            /** The swap was flagged as swap in flash. Let's compress another page.
+             *  Be sure to update the address where to scan from. */
+            m_gc.p_scan_addr = NULL;
+            ret = gc_page();
+            break;
+
+        default:
+            // Should really not happen.
+            ret = NRF_ERROR_INTERNAL;
+            break;
+    }
+
+    return ret;
+}
+
+
+/**@brief Function for initializing the command queue. */
+static void queues_init(void)
+{
+    memset(&m_cmd_queue,   0, sizeof(fds_cmd_queue_t));
+    memset(&m_chunk_queue, 0, sizeof(fds_chunk_queue_t));
+}
+
+
+void cmd_queue_next(fds_cmd_t ** pp_cmd)
+{
+    if (*pp_cmd != &m_cmd_queue.cmd[FDS_CMD_QUEUE_SIZE - 1])
+    {
+        (*pp_cmd)++;
+        return;
+    }
+
+    *pp_cmd = &m_cmd_queue.cmd[0];
+}
+
+
+void chunk_queue_next(fds_record_chunk_t ** pp_chunk)
+{
+    if ((*pp_chunk) != &m_chunk_queue.chunk[FDS_CHUNK_QUEUE_SIZE - 1])
+    {
+        (*pp_chunk)++;
+        return;
+    }
+
+    *pp_chunk = &m_chunk_queue.chunk[0];
+}
+
+
+/**@brief Advances one position in the command queue. Returns true if the queue is not empty. */
+static bool cmd_queue_advance(void)
+{
+    // Reset the current element.
+    memset(&m_cmd_queue.cmd[m_cmd_queue.rp], 0, sizeof(fds_cmd_t));
+
+    CRITICAL_SECTION_ENTER();
+    if (m_cmd_queue.count != 0)
+    {
+        // Advance in the queue, wrapping around if necessary.
+        m_cmd_queue.rp = (m_cmd_queue.rp + 1) % FDS_CMD_QUEUE_SIZE;
+        m_cmd_queue.count--;
+    }
+    CRITICAL_SECTION_EXIT();
+
+    return m_cmd_queue.count != 0;
+}
+
+
+/**@brief Returns the current chunk, and advances to the next in the queue. */
+static bool chunk_queue_get_and_advance(fds_record_chunk_t ** pp_chunk)
+{
+    bool chunk_popped = false;
+
+    CRITICAL_SECTION_ENTER();
+    if (m_chunk_queue.count != 0)
+    {
+        // Point to the current chunk and advance the queue.
+        *pp_chunk = &m_chunk_queue.chunk[m_chunk_queue.rp];
+
+        m_chunk_queue.rp = (m_chunk_queue.rp + 1) % FDS_CHUNK_QUEUE_SIZE;
+        m_chunk_queue.count--;
+
+        chunk_popped = true;
+    }
+    CRITICAL_SECTION_EXIT();
+
+    return chunk_popped;
+}
+
+
+static bool chunk_queue_skip(uint8_t num_op)
+{
+    bool chunk_skipped = false;
+
+    CRITICAL_SECTION_ENTER();
+    if (num_op <= m_chunk_queue.count)
+    {
+        m_chunk_queue.count -= num_op;
+        chunk_skipped = true;
+    }
+    CRITICAL_SECTION_EXIT();
+
+    return chunk_skipped;
+}
+
+
+/**@brief Reserves resources on both queues. */
+static ret_code_t queue_reserve(uint8_t               num_cmd,
+                                uint8_t               num_chunks,
+                                fds_cmd_t          ** pp_cmd,
+                                fds_record_chunk_t ** pp_chunk)
+{
+    uint8_t cmd_index;
+    uint8_t chunk_index;
+
+    // This is really just being safe.
+    if (pp_cmd == NULL || ((pp_chunk == NULL) && (num_chunks != 0)))
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if (num_cmd == 0)
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    CRITICAL_SECTION_ENTER();
+
+    // Ensure there is enough space in the queues.
+    if ((m_cmd_queue.count   > FDS_CMD_QUEUE_SIZE - num_cmd) ||
+        (m_chunk_queue.count > FDS_CHUNK_QUEUE_SIZE - num_chunks))
+    {
+        CRITICAL_SECTION_EXIT();
+        return NRF_ERROR_BUSY;
+    }
+
+    // Find the write position in the commands queue.
+    cmd_index  = m_cmd_queue.count;
+    cmd_index += m_cmd_queue.rp;
+    cmd_index  = cmd_index % FDS_CMD_QUEUE_SIZE;
+
+    *pp_cmd = &m_cmd_queue.cmd[cmd_index];
+    m_cmd_queue.count += num_cmd;
+
+    /* If no operations are associated with the command, such as is the case 
+     * for initialization and compression, pp_chunk can be NULL. */
+    if (num_chunks != 0)
+    {
+        chunk_index  = m_chunk_queue.count;
+        chunk_index += m_chunk_queue.rp;
+        chunk_index  = chunk_index % FDS_CHUNK_QUEUE_SIZE;
+
+        *pp_chunk = &m_chunk_queue.chunk[chunk_index];
+        m_chunk_queue.count += num_chunks;
+    }
+
+    CRITICAL_SECTION_EXIT();
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief Cancel the reservation on resources on queues. */
+static void queue_reserve_cancel(uint8_t num_cmd, uint8_t num_chunks)
+{
+    CRITICAL_SECTION_ENTER();
+    m_cmd_queue.count   -= num_cmd;
+    m_chunk_queue.count -= num_chunks;
+    CRITICAL_SECTION_EXIT();
+}
+
+
+static void pages_init(uint16_t * const p_pages_avail,
+                       bool     * const p_write_page_tag,
+                       bool     * const p_resume_comp)
+{
+    *p_pages_avail    = 0;
+    *p_write_page_tag = false;
+    *p_resume_comp    = false;
+
+    /** Scan pages and setup page data.
+     *  This function does NOT perform write operations in flash. */
+    for (uint16_t i = 0; i < FDS_MAX_PAGES; i++)
+    {
+        // Initialize page data. Note that start_addr must be set BEFORE invoking page_identify().
+        m_pages[i].start_addr     = fs_config.p_start_addr + (i * FS_PAGE_SIZE_WORDS);
+        m_pages[i].write_offset   = FDS_PAGE_TAG_SIZE;
+        m_pages[i].vpage_id       = i;
+        m_pages[i].records_open   = 0;
+        m_pages[i].words_reserved = 0;
+
+        m_pages[i].page_type      = page_identify(i);
+
+        switch (m_pages[i].page_type)
+        {
+            case FDS_PAGE_UNDEFINED:
+            {
+                if (page_is_empty(i))
+                {
+                    /* We have found an erased page, which can be initialized.
+                     * This will require a write in flash. */
+                    m_pages[i].page_type = FDS_PAGE_ERASED;
+                    *p_write_page_tag = true;
+                }
+            } break;
+
+            case FDS_PAGE_VALID:
+            {
+                /** If a page is valid, we update its write offset.
+                 *  Additionally, page_scan will update the last known record ID. */
+                page_scan(i, &m_pages[i].write_offset);
+                (*p_pages_avail)++;
+            } break;
+
+            case FDS_PAGE_SWAP:
+            {
+                m_gc.swap_page    = i;
+                m_swap_page_avail = true;
+            } break;
+
+            case FDS_PAGE_GC:
+            {
+                /** There is an ongoing garbage collection.
+                 *  We should resume the operation, which we don't yet. */
+                m_gc.cur_page   = i;
+                m_gc.state      = GC_PAGE;
+                *p_resume_comp  = true;
+            } break;
+
+            default:
+                break;
+        }
+    }
+}
+
+
+// NOTE: Adds FDS_HEADER_SIZE automatically.
+static ret_code_t write_space_reserve(uint16_t length_words, uint16_t * vpage_id)
+{
+    bool     space_reserved  = false;
+    uint16_t total_len_words = length_words + FDS_HEADER_SIZE;
+
+    if (total_len_words >= FS_PAGE_SIZE_WORDS - FDS_PAGE_TAG_SIZE)
+    {
+        return NRF_ERROR_INVALID_LENGTH;
+    }
+
+    for (uint16_t page = 0; page < FDS_MAX_PAGES; page++)
+    {
+        if ((m_pages[page].page_type == FDS_PAGE_VALID) &&
+            (page_has_space(page, total_len_words)))
+        {
+            space_reserved = true;
+            *vpage_id      = m_pages[page].vpage_id;
+
+            CRITICAL_SECTION_ENTER();
+            m_pages[page].words_reserved += total_len_words;
+            CRITICAL_SECTION_EXIT();
+            
+            break;
+        }
+    }
+
+    return space_reserved ? NRF_SUCCESS : NRF_ERROR_NO_MEM;
+}
+
+
+static bool chunk_is_aligned(fds_record_chunk_t const * const p_chunk, uint8_t num_parts)
+{
+    for (uint8_t i = 0; i < num_parts; i++)
+    {
+        if (!is_word_aligned(p_chunk[i].p_data))
+        {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+
+static ret_code_t init_execute(uint32_t result, uint32_t const * p_page_addr)
+{
+    uint16_t   cur_page;
+    bool       page_tag_written = false;
+
+    if (result != NRF_SUCCESS)
+    {
+        // Oops. Error.
+        return result;
+    }
+
+    // Here we just distinguish between the first invocation and the others.
+    cur_page = p_page_addr == NULL ? 0 : page_by_addr(p_page_addr) + 1;
+
+    if (cur_page == FDS_MAX_PAGES)
+    {
+        // We have finished. We'd need to set some flags.
+        flag_set(FDS_FLAG_INITIALIZED);
+        flag_clear(FDS_FLAG_INITIALIZING);
+
+        return COMMAND_COMPLETED;
+    }
+
+    while (cur_page < FDS_MAX_PAGES && !page_tag_written)
+    {
+        if (m_pages[cur_page].page_type == FDS_PAGE_ERASED)
+        {
+            page_tag_written = true;
+
+            if (m_swap_page_avail)
+            {
+                if (page_tag_write_valid(cur_page) != NRF_SUCCESS)
+                {
+                    // Oops. Error.
+                }
+                // Update the page type.
+                m_pages[cur_page].page_type = FDS_PAGE_VALID;
+            }
+            else
+            {
+                if (page_tag_write_swap(cur_page) != NRF_SUCCESS)
+                {
+                    // Oops. Error.
+                }
+                // Update the page type.
+                m_pages[cur_page].page_type = FDS_PAGE_SWAP;
+
+                /** Update compression data. We set this information in init_pages
+                 *  if it is available, otherwise, we should set it here. */
+                m_swap_page_avail = true;
+                m_gc.swap_page = cur_page;
+            }
+        }
+
+        cur_page++;
+    }
+
+    if (!page_tag_written)
+    {
+        if (m_swap_page_avail)
+        {
+            return COMMAND_COMPLETED;
+        }
+        else
+        {
+            // There is no empty space to use as swap.
+            // Notify user that no compression is available?
+        }
+    }
+
+    return COMMAND_EXECUTING;
+}
+
+
+/**@brief Function to execute write and update commands.
+ *
+ */
+static ret_code_t store_execute(uint32_t result, fds_cmd_t * const p_cmd)
+{
+    ret_code_t           fs_ret;
+    fds_record_chunk_t * p_chunk = NULL;
+    fds_page_t         * p_page  = NULL;
+    uint32_t           * p_write_addr;
+
+    // Using virtual page IDs allows other operations to be queued even if GC has been requested.
+    page_from_virtual_id(p_cmd->vpage_id, &p_page);
+
+    if (result != NRF_SUCCESS)
+    {
+        // The previous operation has failed, update the page data.
+        p_page->write_offset   += (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+        p_page->words_reserved -= (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+
+        return result;
+    }
+
+    // Compute the write address (just syntatic sugar).
+    p_write_addr = (uint32_t*)(p_page->start_addr + p_page->write_offset);
+
+    // Execute the operation.
+    switch (p_cmd->op_code)
+    {
+        case FDS_OP_WRITE_TL:
+        {
+            fs_ret = fs_store(&fs_config,
+                              p_write_addr + FDS_WRITE_OFFSET_TL,
+                              (uint32_t*)&p_cmd->record_header.tl,
+                              FDS_HEADER_SIZE_TL /*Words*/);
+
+            // Set the next operation to be executed.
+            p_cmd->op_code = FDS_OP_WRITE_ID;
+
+        } break;
+
+        case FDS_OP_WRITE_ID:
+        {
+            fs_ret = fs_store(&fs_config,
+                              p_write_addr + FDS_WRITE_OFFSET_ID,
+                              (uint32_t*)&p_cmd->record_header.id,
+                              FDS_HEADER_SIZE_ID /*Words*/);
+
+            p_cmd->op_code = FDS_OP_WRITE_CHUNK;
+
+        } break;
+
+        case FDS_OP_WRITE_CHUNK:
+        {
+            // Decrement the number of chunks left to write.
+            p_cmd->num_chunks--;
+
+            // Retrieve the chunk to be written.
+            chunk_queue_get_and_advance(&p_chunk);
+
+            fs_ret = fs_store(&fs_config,
+                              p_write_addr + p_cmd->chunk_offset,
+                              p_chunk->p_data,
+                              p_chunk->length_words);
+
+            // Accumulate the offset.
+            p_cmd->chunk_offset += p_chunk->length_words;
+
+            if (p_cmd->num_chunks == 0)
+            {
+                /** We have written all the record chunks; we'll write
+                 *  IC last as a mean to 'validate' the record. */
+                p_cmd->op_code = FDS_OP_WRITE_IC;
+            }
+
+        } break;
+
+        case FDS_OP_WRITE_IC:
+        {
+            fs_ret = fs_store(&fs_config,
+                              p_write_addr + FDS_WRITE_OFFSET_IC,
+                              (uint32_t*)&p_cmd->record_header.ic,
+                              FDS_HEADER_SIZE_IC /*Words*/);
+
+            // This is the final operation.
+            p_cmd->op_code = FDS_OP_DONE;
+
+        } break;
+
+        case FDS_OP_DONE:
+        {
+            // We have successfully written down the IC. The command has completed successfully.
+            p_page->write_offset   += (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+            p_page->words_reserved -= (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+
+            return COMMAND_COMPLETED;
+
+        };
+
+        default:
+            fs_ret = NRF_ERROR_INTERNAL;
+            break;
+    }
+
+    // If fs_store did not succeed, the command has failed.
+    if (fs_ret != NRF_SUCCESS)
+    {
+        /** We're not going to receive a callback from fstorage
+         *  so we update the page data right away. */
+        p_page->write_offset   += (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+        p_page->words_reserved -= (FDS_HEADER_SIZE + (p_cmd->chunk_offset - FDS_WRITE_OFFSET_DATA));
+
+        // We should propagate the error from fstorage.
+        return fs_ret;
+    }
+
+    // An operation has successfully been executed. Wait for the callback.
+    return COMMAND_EXECUTING;
+}
+
+
+static ret_code_t clear_execute(ret_code_t result, fds_cmd_t * const p_cmd)
+{
+    ret_code_t        ret;
+    fds_record_desc_t desc;
+
+    // This must persist across calls.
+    static fds_find_token_t tok;
+
+    if (result != NRF_SUCCESS)
+    {
+        // A previous operation has failed. Propagate the error.
+        return result;
+    }
+
+    switch (p_cmd->op_code)
+    {
+        case FDS_OP_CLEAR_TL:
+        {
+            // We were provided a descriptor for the record.
+            desc.vpage_id  = p_cmd->vpage_id;
+            desc.record_id = p_cmd->record_header.id;
+
+            /** Unfortunately, we always seek the record in this case,
+             *  because we don't buffer an entire record descriptor in the
+             *  fds_cmd_t structure. Keep in mind though, that we will
+             *  seek one page at most. */
+            if (seek_record(&desc) != NRF_SUCCESS)
+            {
+                // The record never existed, or it is already cleared.
+                ret = NRF_ERROR_NOT_FOUND;
+            }
+            else
+            {
+                // Copy the record key, so that it may be returned in the callback.
+                p_cmd->record_header.tl.type     = ((fds_header_t*)desc.p_rec)->tl.type;
+                p_cmd->record_header.ic.instance = ((fds_header_t*)desc.p_rec)->ic.instance;
+
+                ret = fs_store(&fs_config,
+                               desc.p_rec,
+                               (uint32_t*)&m_fds_tl_invalid,
+                               FDS_HEADER_SIZE_TL);
+            }
+
+            p_cmd->op_code = FDS_OP_DONE;
+
+        } break;
+
+        case FDS_OP_CLEAR_INSTANCE:
+        {
+            if (find_record(NULL, &p_cmd->record_header.ic.instance,
+                            &desc, &tok) != NRF_SUCCESS)
+            {
+                // No more records to be found.
+                p_cmd->op_code = FDS_OP_DONE;
+
+                // Zero the token, so that we may reuse it.
+                memset(&tok, 0, sizeof(fds_find_token_t));
+
+                /** We won't receive a callback, since no flash operation
+                 *  was initiated. The command has finished. */
+                ret = COMMAND_COMPLETED;
+            }
+            else
+            {
+                ret = fs_store(&fs_config,
+                               desc.p_rec,
+                               (uint32_t*)&m_fds_tl_invalid,
+                               FDS_HEADER_SIZE_TL);
+            }
+        } break;
+
+        case FDS_OP_DONE:
+        {
+            /** The last operation completed successfully.
+             *  The command has finished. Return. */
+            ret = COMMAND_COMPLETED;
+        } break;
+
+        default:
+            ret = NRF_ERROR_INVALID_DATA;
+            break;
+    }
+
+    // Await for the operation result.
+    return ret;
+}
+
+
+static ret_code_t cmd_queue_process(void)
+{
+    ret_code_t        ret;
+    fds_cmd_t * const p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+
+    switch (p_cmd->id)
+    {
+        case FDS_CMD_INIT:
+            ret = init_execute(NRF_SUCCESS, NULL);
+            break;
+
+        case FDS_CMD_WRITE:
+        case FDS_CMD_UPDATE:
+            ret = store_execute(NRF_SUCCESS, p_cmd);
+            break;
+
+        case FDS_CMD_CLEAR:
+        case FDS_CMD_CLEAR_INST:
+            ret = clear_execute(NRF_SUCCESS, p_cmd);
+            break;
+
+        case FDS_CMD_GC:
+            ret = gc_execute(NRF_SUCCESS);
+            break;
+
+        default:
+            ret = NRF_ERROR_FORBIDDEN;
+            break;
+    }
+
+    if ((ret == COMMAND_EXECUTING) || (ret == COMMAND_COMPLETED))
+    {
+        return NRF_SUCCESS;
+    }
+
+    // This is an error.
+    return ret;
+}
+
+
+static ret_code_t cmd_queue_process_start(void)
+{
+    bool start_processing = false;
+
+    if (!flag_is_set(FDS_FLAG_PROCESSING))
+    {
+        flag_set(FDS_FLAG_PROCESSING);
+        start_processing = true;
+    }
+
+    if (!start_processing)
+    {
+        // We are awaiting a callback, so there is no need to manually start queue processing.
+        return NRF_SUCCESS;
+    }
+
+    return cmd_queue_process();
+}
+
+
+static void fs_callback(uint8_t           op_code,
+                        uint32_t          result,
+                        uint32_t  const * p_data,
+                        fs_length_t       length)
+{
+    ret_code_t         ret;
+    fds_cmd_t        * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+    fds_record_key_t   record_key;
+
+    switch (p_cmd->id)
+    {
+        case FDS_CMD_INIT:
+            ret = init_execute(result, p_data);
+            break;
+
+        case FDS_CMD_WRITE:
+        case FDS_CMD_UPDATE:
+            ret = store_execute(result, p_cmd);
+            break;
+
+        case FDS_CMD_CLEAR:
+        case FDS_CMD_CLEAR_INST:
+            ret = clear_execute(result, p_cmd);
+            break;
+
+        case FDS_CMD_GC:
+            ret = gc_execute(result);
+            break;
+
+        default:
+            // Should not happen.
+            ret = NRF_ERROR_INTERNAL;
+            break;
+    }
+
+    if (ret == COMMAND_EXECUTING /*=NRF_SUCCESS*/)
+    {
+        /** The current command is still being processed.
+         *  The command queue does not need to advance. */
+        return;
+    }
+
+    // Initialize the fds_record_key_t structure needed for the callback.
+    record_key.type     = p_cmd->record_header.tl.type;
+    record_key.instance = p_cmd->record_header.ic.instance;
+
+    // The command has either completed or an operation (and thus the command) has failed.
+    if (ret == COMMAND_COMPLETED)
+    {
+        // The command has completed successfully. Notify the application.
+        app_notify(NRF_SUCCESS, p_cmd->id, p_cmd->record_header.id, record_key);
+    }
+    else
+    {
+        /** An operation has failed. This is fatal for the execution of a command.
+         *  Skip other operations associated with the current command.
+         *  Notify the user of the failure.  */
+        chunk_queue_skip(p_cmd->num_chunks);
+        app_notify(ret /*=result*/, p_cmd->id, p_cmd->record_header.id, record_key);
+    }
+
+    // Advance the command queue, and if there is still something in the queue, process it.
+    if (cmd_queue_advance())
+    {
+        /** Only process the queue if there are no pending commands being queued, since they
+         *  will begin to process the queue on their own. Be sure to clear
+         *  the flag FDS_FLAG_PROCESSING though ! */
+        if (atomic_counter_is_zero())
+        {
+            cmd_queue_process();
+        }
+        else
+        {
+            flag_clear(FDS_FLAG_PROCESSING);
+        }
+    }
+    else
+    {
+        /** No more elements in the queue. Clear the FDS_FLAG_PROCESSING flag,
+         *  so that new commands can start the queue processing. */
+        flag_clear(FDS_FLAG_PROCESSING);
+    }
+}
+
+
+ret_code_t fds_init()
+{
+    ret_code_t   fs_ret;
+    fds_cmd_t  * p_cmd;
+    uint16_t     pages_avail;
+    bool         write_page_tag;
+    bool         resume_compression;
+
+    fds_record_key_t const dummy_key = {.type     = FDS_TYPE_ID_INVALID,
+                                        .instance = FDS_INSTANCE_ID_INVALID};
+
+    if (flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        // Notify immediately.
+        app_notify(NRF_SUCCESS, FDS_CMD_INIT, 0 /*unused*/, dummy_key /*unused*/);
+        return NRF_SUCCESS;
+    }
+
+    if (flag_is_set(FDS_FLAG_INITIALIZING))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    fs_ret = fs_init();
+    if (fs_ret != NRF_SUCCESS)
+    {
+        // fs_init() failed, propagate the error.
+        return fs_ret;
+    }
+
+    queues_init();
+
+    /** Initialize the last known record to zero.
+     *  Its value will be updated by page_scan() called in pages_init(). */
+    m_last_rec_id = 0;
+
+    // Initialize the page table containing all info on pages (address, type etc).
+    pages_init(&pages_avail, &write_page_tag, &resume_compression);
+
+    if (pages_avail == 0 && !write_page_tag)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    /** This flag means fds_init() has been called. However,
+     *  the module is NOT yet initialized. */
+    flag_set(FDS_FLAG_INITIALIZING);
+
+    if (resume_compression)
+    {
+        return NRF_SUCCESS;
+    }
+
+    if (write_page_tag)
+    {
+        if (queue_reserve(FDS_CMD_QUEUE_SIZE_INIT, 0, &p_cmd, NULL) != NRF_SUCCESS)
+        {
+            // Should never happen.
+            return NRF_ERROR_BUSY;
+        }
+
+        // Initialize the command in the queue.
+        p_cmd->id = FDS_CMD_INIT;
+
+        return cmd_queue_process_start();
+    }
+    else
+    {
+        /* No flash operation is necessary for initialization.
+         * We can notify the application immediately. */
+        flag_set  (FDS_FLAG_INITIALIZED);
+        flag_clear(FDS_FLAG_INITIALIZING);
+        app_notify(NRF_SUCCESS, FDS_CMD_INIT, 0 /*unused*/, dummy_key /*unused*/);
+    }
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t fds_open(fds_record_desc_t * const p_desc,
+                    fds_record_t      * const p_record)
+{
+    uint16_t page;
+
+    if (p_desc == NULL || p_record == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if (page_id_from_virtual_id(p_desc->vpage_id, &page) != NRF_SUCCESS)
+    {
+        // Should not happen.
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    // Seek the record if necessary.
+    if (seek_record(p_desc) == NRF_SUCCESS)
+    {
+        if (header_is_valid((fds_header_t*)p_desc->p_rec))
+        {
+            CRITICAL_SECTION_ENTER();
+            m_pages[page].records_open++;
+            CRITICAL_SECTION_EXIT();
+
+            p_record->header = *((fds_header_t*)p_desc->p_rec);
+            p_record->p_data = (p_desc->p_rec + FDS_HEADER_SIZE);
+
+            return NRF_SUCCESS;
+        }
+    }
+
+    /** The record could not be found.
+     *  It either never existed or it has been cleared. */
+    return NRF_ERROR_NOT_FOUND;
+}
+
+
+ret_code_t fds_close(fds_record_desc_t const * const p_desc)
+{
+    uint16_t page;
+
+    if (p_desc == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if (page_id_from_virtual_id(p_desc->vpage_id, &page) != NRF_SUCCESS)
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    CRITICAL_SECTION_ENTER();
+    m_pages[page].records_open--;
+    CRITICAL_SECTION_EXIT();
+
+    return NRF_SUCCESS;
+}
+
+
+static ret_code_t write_enqueue(fds_record_desc_t        * const p_desc,
+                                fds_record_key_t                 key,
+                                uint8_t                          num_chunks,
+                                fds_record_chunk_t               chunks[],
+                                fds_write_token_t  const * const p_tok,
+                                bool                             do_update)
+{
+    ret_code_t           ret;
+    fds_cmd_t          * p_cmd;
+    fds_record_chunk_t * p_chunk = NULL;
+    uint16_t             vpage_id;
+    uint16_t             length_words = 0;
+    uint8_t              cmd_queue_elems;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if ((key.type     == FDS_TYPE_ID_INVALID) ||
+        (key.instance == FDS_INSTANCE_ID_INVALID))
+    {
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    if (!chunk_is_aligned(chunks, num_chunks))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    cmd_queue_elems = do_update ? FDS_CMD_QUEUE_SIZE_UPDATE : FDS_CMD_QUEUE_SIZE_WRITE;
+
+    // Reserve space on both queues, and obtain pointers to the first elements reserved.
+    ret = queue_reserve(cmd_queue_elems,
+                        num_chunks,
+                        &p_cmd,
+                        &p_chunk);
+
+    if (ret != NRF_SUCCESS)
+    {
+        return ret;
+    }
+
+    // No space was previously reserved for this operation.
+    if (p_tok == NULL)
+    {
+        // Compute the total length of the record.
+        for (uint8_t i = 0; i < num_chunks; i++)
+        {
+            length_words += chunks[i].length_words;
+        }
+
+        /** Find a page where we can write the data. Reserve the space necessary
+         *  to write the metadata as well. */
+        ret = write_space_reserve(length_words, &vpage_id);
+        if (ret != NRF_SUCCESS)
+        {
+            // If there is no space available, cancel the queue reservation.
+            queue_reserve_cancel(cmd_queue_elems, num_chunks);
+            return ret;
+        }
+    }
+    else
+    {
+        length_words = p_tok->length_words;
+        vpage_id     = p_tok->vpage_id;
+    }
+
+    // Initialize the command.
+    p_cmd->id           = do_update ? FDS_CMD_UPDATE : FDS_CMD_WRITE;
+    p_cmd->op_code      = FDS_OP_WRITE_TL;
+    p_cmd->num_chunks   = num_chunks;
+    p_cmd->chunk_offset = FDS_WRITE_OFFSET_DATA;
+    p_cmd->vpage_id     = vpage_id;
+
+    // Fill in the header information.
+    p_cmd->record_header.id              = record_id_new();
+    p_cmd->record_header.tl.type         = key.type;
+    p_cmd->record_header.tl.length_words = length_words;
+    p_cmd->record_header.ic.instance     = key.instance;
+    p_cmd->record_header.ic.checksum     = 0;
+
+    // Buffer the record chunks in the queue.
+    for (uint8_t i = 0; i < num_chunks; i++)
+    {
+        p_chunk->p_data       = chunks[i].p_data;
+        p_chunk->length_words = chunks[i].length_words;
+        chunk_queue_next(&p_chunk);
+    }
+
+    if (do_update)
+    {
+        // Clear
+        cmd_queue_next(&p_cmd);
+        p_cmd->id      = FDS_CMD_CLEAR;
+        p_cmd->op_code = FDS_OP_CLEAR_TL;
+
+        p_cmd->vpage_id         = p_desc->vpage_id;
+        p_cmd->record_header.id = p_desc->record_id;
+    }
+
+    // Initialize the record descriptor, if provided.
+    if (p_desc != NULL)
+    {
+        p_desc->vpage_id  = vpage_id;
+        // Don't invoke record_id_new() again.
+        p_desc->record_id = p_cmd->record_header.id;
+    }
+
+    return cmd_queue_process_start();
+}
+
+
+ret_code_t fds_reserve(fds_write_token_t * const p_tok, uint16_t length_words)
+{
+    uint16_t vpage_id;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (p_tok == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    // Reserve space on the page. write_space_reserve() accounts for the header.
+    if (write_space_reserve(length_words, &vpage_id) == NRF_SUCCESS)
+    {
+        p_tok->vpage_id     = vpage_id;
+        p_tok->length_words = length_words;
+
+        return NRF_SUCCESS;
+    }
+
+    return NRF_ERROR_NO_MEM;
+}
+
+
+ret_code_t fds_reserve_cancel(fds_write_token_t * const p_tok)
+{
+    fds_page_t * p_page;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (p_tok == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    if (page_from_virtual_id(p_tok->vpage_id, &p_page) != NRF_SUCCESS)
+    {
+        // Could not find the virtual page. This shouldn't happen.
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    if ((p_page->words_reserved - p_tok->length_words) < 0)
+    {
+        /** We are trying to cancel a reservation for more words than how many are
+         *  currently reserved on the page. This is shouldn't happen. */
+        return NRF_ERROR_INVALID_DATA;
+    }
+
+    // Free the space which had been reserved.
+    p_page->words_reserved -= p_tok->length_words;
+
+    // Clean the token.
+    p_tok->vpage_id     = 0;
+    p_tok->length_words = 0;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t fds_write(fds_record_desc_t  * const p_desc,
+                     fds_record_key_t           key,
+                     uint8_t                    num_chunks,
+                     fds_record_chunk_t         chunks[])
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = write_enqueue(p_desc, key, num_chunks, chunks, NULL, false /*not an update*/);
+    atomic_counter_dec();
+    return ret;
+}
+
+
+ret_code_t fds_write_reserved(fds_write_token_t  const * const p_tok,
+                              fds_record_desc_t        * const p_desc,
+                              fds_record_key_t                 key,
+                              uint8_t                          num_chunks,
+                              fds_record_chunk_t               chunks[])
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = write_enqueue(p_desc, key, num_chunks, chunks, p_tok, false /*not an update*/);
+    atomic_counter_dec();
+    return ret;
+}
+
+
+static ret_code_t clear_enqueue(fds_record_desc_t * const p_desc)
+{
+    ret_code_t   ret;
+    fds_cmd_t  * p_cmd;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (p_desc == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    ret = queue_reserve(FDS_CMD_QUEUE_SIZE_CLEAR, 0, &p_cmd, NULL);
+
+    if (ret != NRF_SUCCESS)
+    {
+        return ret;
+    }
+
+    // Initialize the command.
+    p_cmd->id        = FDS_CMD_CLEAR;
+    p_cmd->op_code   = FDS_OP_CLEAR_TL;
+
+    p_cmd->record_header.id = p_desc->record_id;
+    p_cmd->vpage_id         = p_desc->vpage_id;
+
+    return cmd_queue_process_start();
+}
+
+
+ret_code_t fds_clear(fds_record_desc_t * const p_desc)
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = clear_enqueue(p_desc);
+    atomic_counter_dec();
+    return ret;
+}
+
+
+static ret_code_t clear_by_instance_enqueue(fds_instance_id_t instance)
+{
+    ret_code_t   ret;
+    fds_cmd_t  * p_cmd;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    ret  = queue_reserve(FDS_CMD_QUEUE_SIZE_CLEAR, 0, &p_cmd, NULL);
+
+    if (ret != NRF_SUCCESS)
+    {
+        return ret;
+    }
+
+    p_cmd->id      = FDS_CMD_CLEAR_INST;
+    p_cmd->op_code = FDS_OP_CLEAR_INSTANCE;
+
+    p_cmd->record_header.ic.instance = instance;
+
+    return cmd_queue_process_start();
+}
+
+ret_code_t fds_clear_by_instance(fds_instance_id_t instance)
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = clear_by_instance_enqueue(instance);
+    atomic_counter_dec();
+    return ret;
+}
+
+
+ret_code_t fds_update(fds_record_desc_t  * const p_desc,
+                      fds_record_key_t           key,
+                      uint8_t                    num_chunks,
+                      fds_record_chunk_t         chunks[])
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = write_enqueue(p_desc, key, num_chunks, chunks, NULL, true /*update*/);
+    atomic_counter_dec();
+    return ret;
+}
+
+
+static ret_code_t gc_enqueue()
+{
+    ret_code_t  ret;
+    fds_cmd_t * p_cmd;
+
+    if (!flag_is_set(FDS_FLAG_INITIALIZED))
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    ret = queue_reserve(FDS_CMD_QUEUE_SIZE_GC, 0, &p_cmd, NULL);
+    if (ret != NRF_SUCCESS)
+    {
+        return ret;
+    }
+
+    p_cmd->id = FDS_CMD_GC;
+
+    // Set compression parameters.
+    m_gc.state = BEGIN;
+
+    return cmd_queue_process_start();
+}
+
+
+ret_code_t fds_gc()
+{
+    ret_code_t ret;
+    atomic_counter_inc();
+    ret = gc_enqueue();
+    atomic_counter_dec();
+    return ret;   
+}
+
+
+ret_code_t fds_find(fds_type_id_t             type,
+                    fds_instance_id_t         instance,
+                    fds_record_desc_t * const p_desc,
+                    fds_find_token_t  * const p_token)
+{
+    if (p_desc == NULL || p_token == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    return find_record(&type, &instance, p_desc, p_token);
+}
+
+
+ret_code_t fds_find_by_type(fds_type_id_t             type,
+                            fds_record_desc_t * const p_desc,
+                            fds_find_token_t  * const p_token)
+{
+    if (p_desc == NULL || p_token == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    return find_record(&type, NULL, p_desc, p_token);
+}
+
+
+ret_code_t fds_find_by_instance(fds_instance_id_t         instance,
+                                fds_record_desc_t * const p_desc,
+                                fds_find_token_t  * const p_token)
+{
+    if (p_desc == NULL || p_token == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    return find_record(NULL, &instance, p_desc, p_token);
+}
+
+
+ret_code_t fds_register(fds_cb_t cb)
+{
+    if (m_users == FDS_MAX_USERS)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    m_cb_table[m_users] = cb;
+    m_users++;
+
+    return NRF_SUCCESS;
+}
+
+
+bool fds_descriptor_match(fds_record_desc_t const * const p_desc1,
+                          fds_record_desc_t const * const p_desc2)
+{
+    if ((p_desc1 == NULL) || (p_desc2 == NULL))
+    {
+        return false;
+    }
+
+    return (p_desc1->record_id == p_desc2->record_id);
+}
+
+
+ret_code_t fds_descriptor_from_rec_id(fds_record_desc_t * const p_desc,
+                                      fds_record_id_t           record_id)
+{
+    if (p_desc == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    p_desc->record_id = record_id;
+    p_desc->vpage_id  = FDS_VPAGE_ID_UNKNOWN;
+
+    return NRF_SUCCESS;
+}
+
+ret_code_t fds_record_id_from_desc(fds_record_desc_t const * const p_desc,
+                                   fds_record_id_t         * const p_record_id)
+{
+    if (p_desc == NULL || p_record_id == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    *p_record_id = p_desc->record_id;
+
+    return NRF_SUCCESS;
+}
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,566 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef FDS_H__
+#define FDS_H__
+
+/**
+ * @defgroup flash_data_storage Flash Data Storage
+ * @ingroup app_common
+ * @{
+ * @brief Flash Data Storage (FDS).
+ *
+ * @details Flash Data Storage (FDS) is a minimalistic filesystem for the on-chip flash.
+ *          It can be used to manipulate @e records, which consist of a piece of data, made up
+ *          of one or more chunks, and an associated key pair. 
+ */
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "sdk_errors.h"
+
+
+/**@brief */
+#define SIZEOF_WORDS(val)       (sizeof(val) / 4)
+
+/**@brief Reserved type key used to flag cleared records.
+ *        May not be used as a record key by the application. */
+#define FDS_TYPE_ID_INVALID     (0x0000)
+/**@brief Reserved instance key used to check for missing or corrupted metadata.
+ *        May not be used as a record key by the application. */
+#define FDS_INSTANCE_ID_INVALID (0xFFFF)
+
+
+typedef uint32_t fds_record_id_t;
+typedef uint16_t fds_type_id_t;
+typedef uint16_t fds_length_t;
+typedef uint16_t fds_instance_id_t;
+typedef uint16_t fds_checksum_t;
+
+
+/**@brief A piece of a record metadata, keeping information about one of its keys (type) and its
+ *        lenght, expressed in 4 byte words. */
+typedef struct 
+{
+    fds_type_id_t type;           /**< The record type ID. */
+    fds_length_t  length_words;   /**< Length of the record's data, in 4 byte words. */
+} fds_tl_t;
+
+
+/**@brief A piece of a record metadata, keeping information about one of its keys (instance) and
+ *        its checksum. */
+typedef struct
+{
+    fds_instance_id_t instance;       /**< The record instance ID. */
+    fds_checksum_t    checksum;       /**< Checksum of the entire record, including the metadata. */
+} fds_ic_t;
+
+
+/**@brief The record metadata. */
+typedef struct
+{
+    fds_tl_t        tl;     /**< See @ref fds_tl_t. */
+    fds_ic_t        ic;     /**< See @ref fds_ic_t. */
+    fds_record_id_t id;     /**< The unique record ID (32 bits). */
+} fds_header_t;
+
+
+typedef fds_header_t fds_record_header_t;
+
+/**@brief The record descriptor structure, used to manipulate a record.
+ * @note  This structure is meant to be opaque to the user, who does not need to access
+ *        any of its fields.
+ * @note    This structure does not need special initialization.
+ * @warning Do not reuse the same descriptor for different records. If you do, be sure to set
+ *          its fields to zero. */
+typedef struct
+{
+    uint32_t         record_id;     /**< The unique record ID. */
+    uint32_t const * p_rec;         /**< The last known record address in flash. */
+    uint16_t         vpage_id;      /**< The virtual page ID in which the record is stored. */
+    uint16_t         gc_magic;      /**< Number of times the GC algorithm has been run. */
+    uint16_t         ptr_magic;     /**< Used to verify the validity of p_rec. */
+} fds_record_desc_t;
+
+
+/**@brief The record key, used to lookup records.
+ * @note  The uniqueness of either field is not enforced by the system. */
+typedef struct
+{
+    uint16_t type;
+    uint16_t instance;
+} fds_record_key_t;
+
+
+/**@brief Structure used for reading a record back from flash memory. */
+typedef struct
+{
+    // TODO: the header should be a pointer.
+    fds_header_t         header;        /**< The record header (metadata), as stored in flash. */
+    uint32_t     const * p_data;        /**< The record data. */
+} fds_record_t;
+
+
+/**@brief A record chunk, containing a piece of data to be stored in a record.
+ *
+ * @note  p_data must be aligned on a (4 bytes) word boundary.
+ */
+typedef struct
+{
+    void         const * p_data;           /**< Pointer to the data to store. Must be word aligned. */
+    fds_length_t         length_words;     /**< Length of data pointed by p_data, in 4 byte words. */
+} fds_record_chunk_t;
+
+
+/**@brief A token to a reserved space in flash, created by @ref fds_reserve.
+ *        Use @ref fds_write_reserved to write the record in the reserved space,
+ *        or @ref fds_reserve_cancel to cancel the reservation.
+ */
+typedef struct
+{
+    uint16_t            vpage_id;       /**< The virtual ID of the page where space was reserved. */
+    fds_length_t        length_words;   /**< The amount of space reserved, in 4 byte words. */
+} fds_write_token_t;
+
+
+/**@brief A token to keep information about the progress of @ref fds_find, @ref fds_find_by_type
+ *        and @ref fds_find_by_instance operations.
+ * @note  This structure is meant to be opaque to the user, who does not need to access any of its
+ *        fields.
+ * @note  The token does not need special initialization.
+ * @warning Do not reuse the same token to search for different records. If you do, be sure to set
+ *          its fields to zero. */
+typedef struct
+{
+    uint32_t const * p_addr;
+    uint32_t         magic;
+    uint16_t         vpage_id;
+} fds_find_token_t;
+
+
+typedef enum
+{
+    FDS_CMD_NONE,       /**< No command. */
+    FDS_CMD_INIT,       /**< Module initialization commnad. Used in @ref fds_init */
+    FDS_CMD_WRITE,      /**< Write command. Used in @ref fds_write and @ref fds_write_reserved. */
+    FDS_CMD_UPDATE,     /**< Update command. Used in @ref fds_update. */
+    FDS_CMD_CLEAR,      /**< Clear record command. Used in @ref fds_clear and @ref fds_update. */
+    FDS_CMD_CLEAR_INST, /**< Clear instance command. Used in @ref fds_clear_by_instance. */
+    FDS_CMD_GC          /**< Garbage collection. Used in @ref fds_gc. */
+} fds_cmd_id_t;
+
+ 
+/**@brief Flash data storage callback function.
+ *
+ * @param result     Result of the command.
+ * @param cmd        The command associated with the callback.
+ * @param record_id  The unique ID of the record associated with the callback.
+ * @param record_key The key pair of the record associated with the callback.
+ */
+typedef void (*fds_cb_t)(ret_code_t       result,
+                         fds_cmd_id_t     cmd,
+                         fds_record_id_t  record_id,
+                         fds_record_key_t record_key);
+
+
+/**@brief       Function to register a callback for the module events.
+ * @details     The maximum amount of callback which can be registered can be configured by
+ *              changing the FDS_MAX_USERS macro in fds_config.h.
+ * 
+ * @param[in]   cb The callback function.
+ *
+ *
+ * @retval      NRF_SUCCESS      Success.
+ * @retval      NRF_ERROR_NO_MEM Error. Maximum number of registered callbacks reached.
+ */
+ret_code_t fds_register(fds_cb_t cb);
+
+
+/**@brief Function to initialize the module.
+ *
+ * @details This function initializes the module and installs the filesystem, if it is not
+ *          installed yet.
+ *
+ * @note    This function is asynchronous. Completion is reported with a callback through the
+ *          registered event handler. To be able to receive such callback, be sure to call
+ *          @ref fds_register before calling @ref fds_init.
+ *
+ * @retval  NRF_SUCCESS                 Success. The command was queued.
+ * @retval  NRF_ERROR_INVALID_STATE     Error. The module is currently undergoing initialization.
+ * @retval  NRF_ERROR_NO_MEM            Error. Insufficient space to install the filesystem, or
+ *                                      insufficient resources to perform the installation.
+ */
+ret_code_t fds_init(void);
+
+
+/**@brief Function to write a record to flash.
+ *
+ * @details This function can be used to write a record to flash. A record data consists of
+ *          multiple chunks and is supplied to the function as an array of fds_record_chunk_t
+ *          structures. The maximum lenght of a record data may not exceed the size of one flash
+ *          page minus FDS_HEADER_SIZE words.
+ *            
+ * @note This function is asynchronous, therefore, completion is reported with a callback
+ *       through the registered event handler.
+ *
+ * @note The record data must be aligned on a 4 byte boundary, and because it is not buffered
+ *       internally, it must be kept in memory by the application until the callback for the
+ *       command has been received, i.e., the command completed.
+ *
+ * @param[out] p_desc     The record descriptor. It may be NULL.
+ * @param[in]  key        The record key pair.
+ * @param[in]  num_chunks The number of elements in the chunks array.
+ * @param[in]  chunks     An array of chunks making up the record data.
+ *
+ * @retval NRF_SUCCESS               Success. The command was queued.
+ * @retval NRF_ERROR_INVALID_STATE   Error. The module is not initialized.
+ * @retval NRF_ERROR_INVALID_DATA    Error. The key contains an invalid type or instance.
+ * @retval NRF_ERROR_INVALID_ADDR    Error. The record data is not aligned on a 4 byte boundary.
+ * @retval NRF_ERROR_INVALID_LENGTH  Error. The record length exceeds the maximum lenght.
+ * @retval NRF_ERROR_BUSY            Error. Insufficient internal resources to queue the operation.
+ * @retval NRF_ERROR_NO_MEM          Error. No flash space available to store the record.
+ */
+ret_code_t fds_write(fds_record_desc_t * const p_desc,
+                     fds_record_key_t          key,
+                     uint8_t                   num_chunks,
+                     fds_record_chunk_t        chunks[]);
+
+
+/**@brief Function to reserve space for a record.
+ *
+ * @details This function can be used to reserve flash space to store a record, which can be
+ *          later written down using @ref fds_write_reserved. It is possible to cancel a
+ *          reservation by using @ref fds_reserve_cancel.
+ *
+ * @param[out] p_tok        A token which can be used to write a record in the reserved space
+ *                          using @ref fds_write_reserved.
+ * @param[in]  length_words The lenght of the record data, in 4 byte words.
+ *
+ * @retval  NRF_SUCCESS             Success. Flash space was successfully reserved.
+ * @retval  NRF_ERROR_NULL          Error. p_tok is NULL.
+ * @retval  NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval  NRF_ERROR_NO_MEM        Error. Insufficient space.
+ */
+ret_code_t fds_reserve(fds_write_token_t * const p_tok, uint16_t length_words);
+
+
+/**@brief Function to cancel a space reservation.
+ *
+ * @param[in] p_tok The token produced by @ref fds_reserve, identifying the reservation to cancel.
+ *
+ * @retval NRF_SUCCESS             Success. The reservation was canceled.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. p_tok is NULL.
+ * @retval NRF_ERROR_INVALID_DATA  Error. p_tok contains invalid data.
+ */
+ret_code_t fds_reserve_cancel(fds_write_token_t * const p_tok);
+
+
+/**@brief Function to write a record to flash, the space for which has been previously reserved
+ *        using @ref fds_reserve.
+ *
+ * @details This function behaves similarly to @ref fds_write, with the exception that it never
+ *          fails with NRF_ERROR_NO_MEM.
+ *
+ * @note This function is asynchronous, therefore, completion is reported with a callback
+ *       through the registered event handler.
+ *
+ * @note The record data must be aligned on a 4 byte boundary, and because it is not buffered
+ *       internally, it must be kept in memory by the application until the callback for the
+ *       command has been received, i.e., the command completed.
+ *
+ * @param[in]  p_tok      The token return by @ref fds_reserve.
+ * @param[out] p_desc     The record descriptor. It may be NULL.
+ * @param[in]  key        The record key pair.
+ * @param[in]  num_chunks The number of elements in the chunks array.
+ * @param[in]  chunks     An array of chunks making up the record data.
+ *
+ * @retval NRF_SUCCESS               Success. The command was queued.
+ * @retval NRF_ERROR_INVALID_STATE   Error. The module is not initialized.
+ * @retval NRF_ERROR_INVALID_DATA    Error. The key contains an invalid type or instance.
+ * @retval NRF_ERROR_INVALID_ADDR    Error. The record data is not aligned on a 4 byte boundary.
+ * @retval NRF_ERROR_INVALID_LENGTH  Error. The record length exceeds the maximum lenght.
+ * @retval NRF_ERROR_BUSY            Error. Insufficient internal resources to queue the operation.
+ */
+ret_code_t fds_write_reserved(fds_write_token_t  const * const p_tok,
+                              fds_record_desc_t        * const p_desc,
+                              fds_record_key_t                 key,
+                              uint8_t                          num_chunks,
+                              fds_record_chunk_t               chunks[]);
+
+
+/**@brief Function to clear a record.
+ *
+ * @details Clearing a record has the effect of preventing the system from retrieving the record
+ *          descriptor using the @ref fds_find, @ref fds_find_by_type and @ref fds_find_by_instance
+ *          functions. Additionally, @ref fds_open calls shall fail when supplied a descritpor for
+ *          a record which has been cleared. Clearing a record does not free the space it occupies
+ *          in flash. The reclaim flash space used by cleared records, use @ref fds_gc.
+ *
+ * @note    This function is asynchronous, therefore, completion is reported with a callback
+ *          through the registered event handler.
+ *
+ * @param[in] p_desc The descriptor of the record to clear.
+ *
+ * @retval NRF_SUCCESS             Success. The command was queued.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. p_desc is NULL.
+ * @retval NRF_ERROR_BUSY          Error. Insufficient internal resources to queue the operation.
+ */
+ret_code_t fds_clear(fds_record_desc_t * const p_desc);
+
+
+/**@brief Function to clear all records with a given instance.
+ *
+ * @details Clearing a record has the effect of preventing the system from retrieving the record
+ *          descriptor using the @ref fds_find, @ref fds_find_by_type and @ref fds_find_by_instance
+ *          functions. Additionally, @ref fds_open calls shall fail when supplied a descritpor for
+ *          a record which has been cleared. Clearing a record does not free the space it occupies
+ *          in flash. The reclaim flash space used by cleared records, use @ref fds_gc.
+ *
+ * @note This function is asynchronous, therefore, completion is reported with a callback
+ *       through the registered event handler. Only one callback will be issued. The record
+ *       instance ID in the key parameter of the callback will contain the instance ID passed as
+ *       parameter to this function. The record ID parameter will be zero, and the type ID equal
+ *       to FDS_TYPE_ID_INVALID.
+ *
+ * @param[in] instance The instance ID of the records to clear.
+ *
+ * @retval NRF_SUCCESS             Success. The command was queued.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. p_desc is NULL.
+ * @retval NRF_ERROR_BUSY          Error. Insufficient internal resources to queue the operation.
+ */
+ret_code_t fds_clear_by_instance(fds_instance_id_t instance);
+
+
+/**@brief Function to update an existing record.
+ *
+ * @details Updating a record writes a new record with the given key and data in flash, and then
+ *          clears the old record.
+ *
+ * @note This function is asynchronous, therefore, completion is reported with a callback
+ *       through the registered event handler. Two callbacks will be issued, one to signal that
+ *       the updated record has been written down, and another to signal that the old one has been
+ *       cleared.
+ *       
+ * @note The record data must be aligned on a 4 byte boundary, and because it is not buffered
+ *       internally, it must be kept in memory by the application until the callback for the
+ *       command has been received, i.e., the command completed.
+ * 
+ * @param[in, out] p_desc The descriptor of the record to update. The descriptor of the updated
+ *                        record, after the function has returned with NRF_SUCCESS.
+ * @param[in] key         The record new key pair.
+ * @param[in] num_chunks  The number of elements in the chunks array.
+ * @param[in] chunks      An array of chunks making up the record new data.
+ *
+ * @retval NRF_SUCCESS               Success. The command was queued.
+ * @retval NRF_ERROR_INVALID_STATE   Error. The module is not initialized.
+ * @retval NRF_ERROR_INVALID_DATA    Error. The key contains an invalid type or instance.
+ * @retval NRF_ERROR_INVALID_ADDR    Error. The record data is not aligned on a 4 byte boundary.
+ * @retval NRF_ERROR_INVALID_LENGTH  Error. The record length exceeds the maximum lenght.
+ * @retval NRF_ERROR_BUSY            Error. Insufficient internal resources to queue the operation.
+ * @retval NRF_ERROR_NO_MEM          Error. No flash space available to store the record.
+ */
+ret_code_t fds_update(fds_record_desc_t  * const p_desc,
+                      fds_record_key_t           key,
+                      uint8_t                    num_chunks,
+                      fds_record_chunk_t         chunks[]);
+
+
+/**@brief Function to search for records with a given key pair.
+ *
+ * @details Because types are not unique, to search for the next record with the given key call
+ *          the function again and supply the same fds_find_token_t structure to resume searching
+ *          from the last record found.
+ *
+ * @param[in]  type     The record type ID.
+ * @param[in]  instance The record instance ID.
+ * @param[out] p_desc   The descriptor of the record found.
+ * @param[out] p_token  A token containing information about the progress of the operation.
+ *
+ * @retval NRF_SUCCESS             Success. A record was found.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. Either p_desc or p_token are NULL.
+ * @retval NRF_ERROR_NOT_FOUND     Error. No record with the given key pair was found.
+ */
+ret_code_t fds_find(fds_type_id_t             type, 
+                    fds_instance_id_t         instance, 
+                    fds_record_desc_t * const p_desc,
+                    fds_find_token_t  * const p_token);
+
+
+/**@brief Function to search for records with a given type.
+ *
+ * @details Because types are not unique, to search for the next record with the given key call
+ *          the function again and supply the same fds_find_token_t structure to resume searching
+ *          from the last record found.
+ *
+ * @param[in]  type    The type ID in the record key.
+ * @param[out] p_desc  The descriptor of the record found.
+ * @param[out] p_token A token containing information about the progress of the operation.
+ *
+ * @retval NRF_SUCCESS             Success. A record was found.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. Either p_desc or p_token are NULL.
+ * @retval NRF_ERROR_NOT_FOUND     Error. No record with the given type was found.
+ */
+ ret_code_t fds_find_by_type(fds_type_id_t             type,
+                             fds_record_desc_t * const p_desc,
+                             fds_find_token_t  * const p_token);
+
+
+/**@brief Function to search for records with a given instance.
+ *
+ * @details Because types are not unique, to search for the next record with the given key call
+ *          the function again and supply the same fds_find_token_t structure to resume searching
+ *          from the last record found.
+ *
+ * @param[in]  instance The instance ID in the record key.
+ * @param[out] p_desc   The descriptor of the record found.
+ * @param[out] p_token  A token containing information about the progress of the operation.
+ *
+ * @retval NRF_SUCCESS             Success. A record was found.
+ * @retval NRF_ERROR_INVALID_STATE Error. The module is not initialized.
+ * @retval NRF_ERROR_NULL          Error. Either p_desc or p_token are NULL.
+ * @retval NRF_ERROR_NOT_FOUND     Error. No record with the given instance was found.
+ */
+ret_code_t fds_find_by_instance(fds_instance_id_t         instance,
+                                fds_record_desc_t * const p_desc,
+                                fds_find_token_t  * const p_token);
+
+
+/**@brief Function to open a record for reading.
+ *
+ * @details Function to read a record which has been written to flash. This function initializes
+ *          a fds_record_t structure which can be used to access the record data as well as
+ *          its associated metadata. The pointers provided in the fds_record_t structure are
+ *          pointers to flash memory. Opening a record with @ref fds_open prevents the garbage
+ *          collection to run on the flash page in which record is stored, therefore the contents
+ *          of the memory pointed by the fds_record_t p_data field is guaranteed to remain
+ *          unmodified, as long as the record is kept open.
+ *
+ * @note When you are done reading a record, close it using @ref fds_close so that successive
+ *       garbage collections can reclaim space on the page where the record is stored, if necessary.
+ *
+ * @param[in]  p_desc   The descriptor of the record to open.
+ * @param[out] p_record The record data and metadata, as stored in flash.
+ *
+ * @retval NRF_SUCCESS            Success. The record was opened.
+ * @retval NRF_ERROR_NOT_FOUND    Error. The record was not found. It may have been cleared, or it
+ *                                may have not been written yet.
+ * @retval NRF_ERROR_INVALID_DATA Error. The descriptor contains invalid data.
+ * @retval NRF_ERROR_NULL         Error. Either p_desc or p_record are NULL.
+ */
+ret_code_t fds_open(fds_record_desc_t * const p_desc,
+                    fds_record_t      * const p_record);
+
+
+/**@brief Function to close a record, after its contents have been read.
+ *
+ * @details Closing a record allows garbage collection to be run on the page in which the
+ *          record being closed is stored (if no other records remain open on that page).
+ *
+ * @note Closing a record, does NOT invalidate its descriptor, which can be safely supplied to
+ *       all functions which accept a descriptor as a parameter.
+ *
+ * @param[in] p_desc The descriptor of the record to close.
+ *
+ * @retval NRF_SUCCESS            Success. The record was closed.
+ * @retval NRF_ERROR_NULL         Error. p_desc is NULL.
+ * @retval NRF_ERROR_INVALID_DATA Error. The descriptor contains invalid data.
+ */
+ret_code_t fds_close(fds_record_desc_t const * const p_desc);
+
+
+/**@brief Function to perform a garbage collection.
+ *
+ * @details Garbage collection reclaims the flash space occupied by records which have been cleared
+ *          using @ref fds_clear.
+ *
+ * @note    This function is asynchronous, therefore, completion is reported with a callback
+ *          through the registered event handler.
+ */
+ret_code_t fds_gc(void);
+
+
+/**@brief Function to compare two record descriptors.
+ *
+ * @param[in] p_desc_one First descriptor.
+ * @param[in] p_desc_two Second descriptor.
+ *
+ * @retval true  If the descriptors identify the same record.
+ * @retval false Otherwise.
+ */
+bool fds_descriptor_match(fds_record_desc_t const * const p_desc_one,
+                          fds_record_desc_t const * const p_desc_two);
+
+
+/**@brief Function to obtain a descriptor from a record ID.
+ *
+ * @details This function can be used to reconstruct a descriptor from a record ID, such as the
+ *          one passed to the callback function.
+ *
+ * @warning This function does not check if a record with the given record ID exists or not. If a
+ *          non-existing record ID is supplied, the resulting descriptor will cause other functions
+ *          to fail when used as parameter.
+ *
+ * @param[out] p_desc    The descriptor of the record with given record ID.
+ * @param[in]  record_id The record ID for which to provide a descriptor.
+ *
+ * @retval NRF_SUCCESS         Success.
+ * @retval NRF_ERROR_NULL      Error. p_desc is NULL.
+ */
+ret_code_t fds_descriptor_from_rec_id(fds_record_desc_t * const p_desc,
+                                      fds_record_id_t           record_id);
+
+/**@brief Function to obtain a record ID from a record descriptor.
+ *
+ * @details This function can be used to extract a record ID from a descriptor. It may be used
+ *          in the callback function to determine which record the callback is associated to, if
+ *          you have its descriptor.
+ *
+ * @warning This function does not check the record descriptor sanity. If the descriptor is
+ *          uninitialized, or has been tampered with, the resulting record ID may be invalid.
+ *
+ * @param[in]  p_desc      The descriptor from which to extract the record ID.
+ * @param[out] p_record_id The record ID contained in the given descriptor.
+ *
+ * @retval NRF_SUCCESS    Success.
+ * @retval NRF_ERROR_NULL Error. Either p_desc is NULL or p_record_id is NULL.
+ */
+ret_code_t fds_record_id_from_desc(fds_record_desc_t const * const p_desc,
+                                   fds_record_id_t         * const p_record_id);
+
+/** @} */
+                                         
+#endif // FDS_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_config.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_config.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef FDS_CONFIG_H__
+#define FDS_CONFIG_H__
+
+ /**
+ * @file fds_config.h
+ *
+ * @addtogroup flash_data_storage
+ * @{
+ */
+
+/**@brief Configures the size of the internal queue. */
+#define FDS_CMD_QUEUE_SIZE          (8)
+/**@brief Determines how many @ref fds_record_chunk_t structures can be buffered at any time. */
+#define FDS_CHUNK_QUEUE_SIZE        (8)
+
+/**@brief Configures the number of physical flash pages to use. Out of the total, one is reserved
+ *        for garbage collection, hence, two pages is the minimum: one for the application data
+ *        and one for the system. */
+#define FDS_MAX_PAGES               (2)
+/**@brief Configures the maximum number of callbacks which can be registred. */
+#define FDS_MAX_USERS               (10)
+
+/** Page tag definitions. */
+#define FDS_PAGE_TAG_WORD_0_SWAP    (0xA5A5A5A5)
+#define FDS_PAGE_TAG_WORD_0_VALID   (0xA4A4A4A4)
+#define FDS_PAGE_TAG_WORD_1         (0xAABBCCDD)
+#define FDS_PAGE_TAG_WORD_2         (0xAABB01DD) /**< Includes version. */
+#define FDS_PAGE_TAG_WORD_3         (0x1CEB00DA)
+#define FDS_PAGE_TAG_WORD_3_GC      (0x1CEB00D8)
+
+/** @} */
+
+#endif // FDS_CONFIG_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_types_internal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fds/fds_types_internal.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef FDS_TYPES_INTERNAL__
+#define FDS_TYPES_INTERNAL__
+
+#include "fds.h"
+#include <stdint.h>
+#include <stdbool.h>
+#include "nrf_soc.h"
+
+
+#define COMMAND_EXECUTING           (NRF_SUCCESS)
+#define COMMAND_COMPLETED           (0x1234)
+//#define COMMAND_FAILED            (0x1236)
+
+#define FDS_MAGIC_HWORD             (0xF11E)
+#define FDS_MAGIC_WORD              (0x15ABE11A)
+#define FDS_ERASED_WORD             (0xFFFFFFFF)
+
+#define FDS_PAGE_TAG_SIZE           (4) /**< Page tag size, in 4 byte words. */
+
+#define FDS_VPAGE_ID_UNKNOWN        (0xFFFF)
+
+#define FDS_WRITE_OFFSET_TL         (0) /**< Offset of TL from the record base address, in 4 byte words. */
+#define FDS_WRITE_OFFSET_IC         (1) /**< Offset of IC from the record base address, in 4 byte words. */
+#define FDS_WRITE_OFFSET_ID         (2) /**< Offset of ID from the record base address, in 4 byte words. */
+#define FDS_WRITE_OFFSET_DATA       (3) /**< Offset of the data (chunks) from the record base address, in 4 byte words. */
+
+#define FDS_HEADER_SIZE_TL          (1) /**< Size of the TL part of the header, in 4 byte words. */
+#define FDS_HEADER_SIZE_ID          (1) /**< Size of the IC part of the header, in 4 byte words. */
+#define FDS_HEADER_SIZE_IC          (1) /**< Size of the IC part of the header, in 4 byte words. */
+#define FDS_HEADER_SIZE             (3) /**< Size of the whole header, in 4 byte words. */
+
+#define FDS_CMD_QUEUE_SIZE_INIT     (1)
+#define FDS_CMD_QUEUE_SIZE_WRITE    (1)
+#define FDS_CMD_QUEUE_SIZE_CLEAR    (1)
+#define FDS_CMD_QUEUE_SIZE_UPDATE   (2)
+#define FDS_CMD_QUEUE_SIZE_GC       (1)
+
+
+static uint8_t m_nested_critical;
+
+/** Macros to enable and disable application interrupts. */
+#define CRITICAL_SECTION_ENTER()    //sd_nvic_critical_region_enter(&m_nested_critical)
+#define CRITICAL_SECTION_EXIT()     //sd_nvic_critical_region_exit ( m_nested_critical)
+
+/**@brief Page types. */
+typedef enum
+{
+    FDS_PAGE_UNDEFINED, /**< Undefined page type. */
+    FDS_PAGE_ERASED,    /**< Page is erased. */
+    FDS_PAGE_VALID,     /**< Page is ready for storage. */
+    FDS_PAGE_SWAP,      /**< Page is reserved for GC. */
+    FDS_PAGE_GC         /**< Page is being garbage collected. */
+} fds_page_type_t;
+
+
+typedef enum
+{
+    FDS_OP_NONE         = 0x00, /**< No operation. */
+    FDS_OP_WRITE_TL,            /**< Write the type and length. */
+    FDS_OP_WRITE_ID,            /**< Write the record ID. */
+    FDS_OP_WRITE_CHUNK,         /**< Write the record value.  */
+    FDS_OP_WRITE_IC,            /**< Write the instance and checksum. */
+    FDS_OP_CLEAR_TL,
+    FDS_OP_CLEAR_INSTANCE,
+    FDS_OP_DONE,
+} fds_opcode_t;
+
+
+typedef enum
+{
+    FDS_FLAG_INITIALIZING       = (1 << 0),  /**< TODO: Not really needed atm? */
+    FDS_FLAG_INITIALIZED        = (1 << 1),  /**< Flag indicating that flash data storage has been initialized. */
+    FDS_FLAG_PROCESSING         = (1 << 2),  /**< Flag indicating that queue is being processed. */
+    FDS_FLAG_CAN_GC             = (1 << 3),  /**< Flag indicating that fds can regain data by performing garbage collection. */
+} fds_flags_t;
+
+
+typedef struct
+{
+    uint32_t const    * start_addr;
+    uint16_t            vpage_id;             /**< The page logical ID. */
+    uint16_t volatile   write_offset;         /**< The page write offset, in 4 bytes words. */
+    uint16_t volatile   words_reserved;       /**< The amount of words reserved by fds_write_reserve() on this page. */
+    uint16_t volatile   records_open;
+    fds_page_type_t     page_type        : 4; /**< The page type. */
+} fds_page_t;
+
+
+typedef struct
+{
+    fds_cmd_id_t        id            : 4;    /**< The ID of the command. */
+    fds_opcode_t        op_code       : 4;
+    uint8_t             num_chunks;           /**< Number of operations this command has left in the operation queue. */
+    uint16_t            chunk_offset;         /**< Offset used for writing the record value(s), in 4 byte words. */
+    uint16_t            vpage_id;             /**< The virtual page ID where we reserved the flash space for this command. */
+    fds_record_header_t record_header;
+} fds_cmd_t;
+
+
+/**@brief   Defines command queue, an element is free if the op_code field is not invalid.
+ *
+ * @details Defines commands enqueued for flash access. At any point in time, this queue has one or
+ *          more flash access operations pending if the count field is not zero. When the queue is
+ *          not empty, the rp (read pointer) field points to the flash access command in progress
+ *          or, if none is in progress, the command to be requested next. The queue implements a
+ *          simple first in first out algorithm. Data addresses are assumed to be resident. 
+ */
+typedef struct
+{
+    fds_cmd_t          cmd[FDS_CMD_QUEUE_SIZE];        /**< Array to maintain flash access operation details. */
+    uint8_t   volatile rp;                             /**< The index of the command being executed. */
+    uint8_t   volatile count;                          /**< Number of elements in the queue. */
+} fds_cmd_queue_t;
+
+
+typedef struct
+{
+    fds_record_chunk_t          chunk[FDS_CHUNK_QUEUE_SIZE];
+    uint8_t            volatile rp;
+    uint8_t            volatile count;
+} fds_chunk_queue_t;
+
+
+typedef enum
+{
+    NONE,
+    BEGIN,
+    RESUME,
+    GC_PAGE,
+    COPY_RECORD,
+    READY_SWAP,
+    NEW_SWAP,
+    INIT_SWAP
+} fds_gc_state_t;
+
+
+typedef struct
+{
+    uint16_t         cur_page;
+    uint16_t         swap_page;
+    uint32_t const * p_scan_addr;
+    fds_gc_state_t   state;
+    bool             do_gc_page[FDS_MAX_PAGES];
+} fds_gc_data_t;
+
+#endif // FDS_TYPES_INTERNAL__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,569 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "fstorage.h"
+#include <stdio.h>
+#include <string.h>
+#include <stdbool.h>
+#include "fstorage_config.h"
+#include "nrf_error.h"
+#include "nrf_soc.h"
+
+
+#define FS_FLAG_INIT                (1 << 0)    /**< fstorage has been initialized. */
+#define FS_FLAG_PROCESSING          (1 << 1)    /**< fstorage is executing queued flash operations. */
+#define FS_FLAG_FLASH_REQ_PENDING   (1 << 2)    /**< fstorage is waiting for a flash operation initiated by another module to complete. */
+
+
+/**@brief Macro invocation that registers section fs_data.
+ *
+ * @details Required for compilation.
+ */
+NRF_SECTION_VARS_REGISTER_SECTION(fs_data);
+
+
+/**@brief Macro invocation that declares symbols used to find the beginning and end of the section fs_data.
+ *
+ * @details Required for compilation.
+ */
+NRF_SECTION_VARS_REGISTER_SYMBOLS(fs_config_t, fs_data);
+
+
+/**@defgroup Section vars helper macros.
+ *
+ * @details Macros used to manipulate registered section variables.
+ */
+ /**@brief Get section variable with fstorage configuration by index. */
+#define FS_SECTION_VARS_GET(i)          NRF_SECTION_VARS_GET(i, fs_config_t, fs_data)
+ /**@brief Get the number of registered section variables. */
+#define FS_SECTION_VARS_COUNT           NRF_SECTION_VARS_COUNT(fs_config_t, fs_data)
+ /**@brief Get the start address of the registered section variables. */
+#define FS_SECTION_VARS_START_ADDR      NRF_SECTION_VARS_START_ADDR(fs_data)
+ /**@brief Get the end address of the registered section variables. */
+#define FS_SECTION_VARS_END_ADDR        NRF_SECTION_VARS_END_ADDR(fs_data)
+
+/** @} */
+
+
+/**@brief The command queue element.
+ *
+ * @details Encapsulate details of a command requested to this module.
+ */
+typedef struct
+{
+    fs_config_t const * p_config;           /**< The configuration of the user who requested the operation. */
+    uint8_t             op_code;            /**< Operation code. */
+    uint32_t const *    p_src;              /**< Pointer to the data to be written to flash. The data must be kept in memory until the operation has finished. */
+    uint32_t const *    p_addr;             /**< Destination of the data in flash. */
+    fs_length_t         length_words;       /**< Length of the operation */
+    fs_length_t         offset;             /**< Offset of the operation if operation is done in chunks */
+} fs_cmd_t;
+
+
+/**@brief Structure that defines the command queue
+ *
+ * @details This queue holds flash operations requested to the module. 
+ *          The data to be written must be kept in memory until the write operation is completed,
+ *          i.e., a callback indicating completion is received by the application.
+ */
+typedef struct
+{
+    uint8_t     rp;                         /**< The current element being processed. */
+    uint8_t     count;                      /**< Number of elements in the queue. */
+    fs_cmd_t    cmd[FS_CMD_QUEUE_SIZE];     /**< Array to maintain flash access operation details. */
+} fs_cmd_queue_t;
+
+
+static uint8_t          m_flags;            /**< FStorage status flags. */
+static fs_cmd_queue_t   m_cmd_queue;        /**< Flash operation request queue. */
+static uint16_t         m_retry_count = 0;  /**< Number of times a single flash operation was retried. */
+
+
+// Function prototypes
+static ret_code_t queue_process(void);
+static ret_code_t queue_process_impl(void);
+static void app_notify(uint32_t result, fs_cmd_t const * p_cmd);
+
+
+/**@brief Macro to check that the configuration is non-NULL and within
+*         valid section variable memory bounds.
+ *
+ * @param[in]   config    Configuration to check.
+ */
+#define FS_CHECK_CONFIG(config) \
+    ((FS_SECTION_VARS_START_ADDR < config) && (config < FS_SECTION_VARS_END_ADDR))
+
+
+/**@brief Function to check that the configuration is non-NULL and within
+*         valid section variable memory bounds.
+ *
+ * @param[in]   config    Configuration to check.
+ */
+static bool check_config(fs_config_t const * const config)
+{
+    if (config == NULL)
+    {
+        return false;
+    }
+
+    if ((FS_SECTION_VARS_START_ADDR <= (uint32_t)config) && ((uint32_t)config < FS_SECTION_VARS_END_ADDR))
+    {
+        return true;
+    }
+    else
+    {
+        return false;
+    }
+}
+
+
+/**@brief Function to initialize the queue. */
+static void queue_init(void)
+{
+    memset(&m_cmd_queue, 0, sizeof(fs_cmd_queue_t));
+}
+
+
+/**@brief Function to reset a queue item to its default values.
+ *
+ * @param	index	Index of the queue element.
+ */
+static void cmd_reset(uint32_t index)
+{
+    memset(&m_cmd_queue.cmd[index], 0, sizeof(fs_cmd_t));
+}
+
+
+/**@brief Function to enqueue flash access command
+ *
+ * @param[in]   config      Registered configuration.
+ * @param[in]   op_code     Operation code.
+ * @param[in]   address     Destination of the data.
+ * @param[in]   p_src       Source of data or NULL if n/a.
+ * @param[in]   length      Length of the data, in 4 byte words.
+ *
+ * @retval NRF_SUCCESS      Success. Command enqueued.
+ * @retval NRF_ERROR_NO_MEM Error. Queue is full.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+static ret_code_t cmd_enqueue(fs_config_t      const * p_config,
+                              uint8_t                  op_code,
+                              uint32_t         const * p_addr,
+                              uint32_t         const * p_src,
+                              fs_length_t              length_words)
+{
+    fs_cmd_t * p_cmd;
+    uint8_t    write_pos;
+
+    if (m_cmd_queue.count == FS_CMD_QUEUE_SIZE - 1)
+    {
+        return NRF_ERROR_NO_MEM;
+    }
+
+    write_pos = (m_cmd_queue.rp + m_cmd_queue.count) % FS_CMD_QUEUE_SIZE;
+
+    p_cmd = &m_cmd_queue.cmd[write_pos];
+
+    p_cmd->p_config     = p_config;
+    p_cmd->op_code      = op_code;
+    p_cmd->p_src        = p_src;
+    p_cmd->p_addr       = p_addr;
+    p_cmd->length_words = length_words;
+
+    m_cmd_queue.count++;
+
+    return queue_process();
+}
+
+
+/**@brief Function to consume queue item and notify the return value of the operation.
+ *
+ * @details This function will report the result and remove the command from the queue after
+ *          notification.
+ */
+static void cmd_consume(uint32_t result, const fs_cmd_t * p_cmd)
+{
+    // Consume the current item on the queue.
+    uint8_t rp = m_cmd_queue.rp;
+
+    m_cmd_queue.count--;
+    if (m_cmd_queue.count == 0)
+    {
+        // There are no elements left. Stop processing the queue.
+        m_flags &= ~FS_FLAG_PROCESSING;
+    }
+
+    if (++(m_cmd_queue.rp) == FS_CMD_QUEUE_SIZE)
+    {
+        m_cmd_queue.rp = 0;
+    }
+
+    // Notify upon successful operation.
+    app_notify(result, p_cmd);
+
+    // Reset the queue element.
+    cmd_reset(rp);
+}
+
+
+/**@brief Function to store data to flash.
+ *
+ * @param[in]   p_cmd   The queue element associated with the operation.
+ *
+ * @retval NRF_SUCCESS  Success. The request was sent to the SoftDevice.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+static __INLINE uint32_t store_execute(fs_cmd_t const * const p_cmd)
+{
+    // Write in chunks if write-size is larger than FS_MAX_WRITE_SIZE.
+    fs_length_t const length = ((p_cmd->length_words - p_cmd->offset) < FS_MAX_WRITE_SIZE_WORDS) ?
+        (p_cmd->length_words - p_cmd->offset) : FS_MAX_WRITE_SIZE_WORDS;
+
+    return sd_flash_write((uint32_t*)p_cmd->p_addr + p_cmd->offset /* destination */,
+                          (uint32_t*)p_cmd->p_src + p_cmd->offset  /* source */,
+                          length);
+}
+
+
+/**@brief Function to erase a page.
+ *
+ * @param[in]   p_cmd   The queue element associated with the operation.
+ *
+ * @retval NRF_SUCCESS  Success. The request was sent to the SoftDevice.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+static __INLINE uint32_t erase_execute(fs_cmd_t const * const p_cmd)
+{
+    // Erase the page.
+    return sd_flash_page_erase((uint32_t)(p_cmd->p_addr + p_cmd->offset) / FS_PAGE_SIZE);
+}
+
+
+/**@brief Function to process the current element in the queue and return the result.
+ *
+ * @retval NRF_SUCCESS          Success.
+ * @retval NRF_ERROR_FORBIDDEN  Error. Undefined command.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+static uint32_t queue_process_impl(void)
+{
+    uint32_t ret;
+    
+    fs_cmd_t const * const p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+
+    switch (p_cmd->op_code)
+    {
+        case FS_OP_STORE:
+            ret = store_execute(p_cmd);
+            break;
+
+        case FS_OP_ERASE:
+            ret = erase_execute(p_cmd);
+            break;
+
+        case FS_OP_NONE:
+            ret = NRF_SUCCESS;
+            break;
+
+        default:
+            ret = NRF_ERROR_FORBIDDEN;
+            break;
+    }
+
+    return ret;
+}
+
+
+/**@brief Starts processing the queue if there are no pending flash operations
+ *        for which we are awaiting a callback.
+ */
+static ret_code_t queue_process(void)
+{
+    ret_code_t ret = NRF_SUCCESS;
+
+    /** If the queue is not being processed, and there are still
+     *  some elements in it, then start processing. */
+    if ( !(m_flags & FS_FLAG_PROCESSING) &&
+          (m_cmd_queue.count > 0))
+    {
+        m_flags |= FS_FLAG_PROCESSING;
+
+        ret = queue_process_impl();
+
+        /** There is ongoing flash-operation which was not
+         *  initiated by fstorage. */
+        if (ret == NRF_ERROR_BUSY)
+        {
+            // Wait for a system callback.
+            m_flags |= FS_FLAG_FLASH_REQ_PENDING;
+
+            // Stop processing the queue.
+            m_flags &= ~FS_FLAG_PROCESSING;
+
+            ret = NRF_SUCCESS;
+        }
+        else if (ret != NRF_SUCCESS)
+        {
+            // Another error has occurred.
+            app_notify(ret, &m_cmd_queue.cmd[m_cmd_queue.rp]);
+        }
+    }
+
+    // If we are already processing the queue, return immediately.
+    return ret;
+}
+
+
+/**@brief Flash operation success callback handler.
+ *
+ * @details     This function updates read/write pointers.
+ *              This function resets retry count.
+ */
+static __INLINE void on_operation_success(void)
+{
+    fs_cmd_t * const p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+
+    m_retry_count = 0;
+
+    switch (p_cmd->op_code)
+    {
+        case FS_OP_STORE:
+            // Update the offset on successful write.
+            p_cmd->offset += FS_MAX_WRITE_SIZE_WORDS;
+            break;
+
+        case FS_OP_ERASE:
+            // Update the offset to correspond to the page that has been erased.
+            p_cmd->offset += FS_PAGE_SIZE_WORDS;
+            break;
+    }
+
+    // If offset is equal to or larger than length, then the operation has finished.
+    if (p_cmd->offset >= p_cmd->length_words)
+    {
+        cmd_consume(NRF_SUCCESS, p_cmd);
+    }
+
+    queue_process();
+}
+
+
+/**@brief Flash operation failure callback handler.
+ *
+ * @details Function to keep track of retries and notify failures.
+ */
+static __INLINE void on_operation_failure(uint32_t sys_evt)
+{
+    const fs_cmd_t * p_cmd;
+    
+    if (++m_retry_count > FS_CMD_MAX_RETRIES)
+    {
+        p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp];
+        cmd_consume(NRF_ERROR_TIMEOUT, p_cmd);
+    }
+
+    queue_process();
+}
+
+
+/**@brief Function to notify users.
+ *
+ * @param[in]   result      Result of the flash operation.
+ * @param[in]   p_cmd       The command associated with the callback.
+ */
+static void app_notify(uint32_t result, fs_cmd_t const * const p_cmd)
+{
+    p_cmd->p_config->cb(p_cmd->op_code, result, p_cmd->p_addr, p_cmd->length_words);
+}
+
+
+ret_code_t fs_init(void)
+{
+    uint16_t   lowest_index = 0;
+    uint16_t   lowest_order = 0xFFFF;
+    uint32_t * current_end  = (uint32_t*)FS_PAGE_END_ADDR;
+    uint32_t   num_left     = FS_SECTION_VARS_COUNT;
+
+    queue_init();
+
+    /** Assign pages to registered users, beginning with the ones with the lowest
+     *  order, which will be assigned pages with the lowest memory address. */
+    do
+    {
+        fs_config_t * p_config;
+        for (uint16_t i = 0; i < FS_SECTION_VARS_COUNT; i++)
+        {
+            p_config = FS_SECTION_VARS_GET(i);
+
+            // Skip the ones which have the end-address already set.
+            if (p_config->p_end_addr != NULL)
+                continue;
+
+            if (p_config->page_order < lowest_order)
+            {
+                lowest_order = p_config->page_order;
+                lowest_index = i;
+            }
+        }
+
+        p_config = FS_SECTION_VARS_GET(lowest_index);
+
+        p_config->p_end_addr   = current_end;
+        p_config->p_start_addr = p_config->p_end_addr - (p_config->num_pages * FS_PAGE_SIZE_WORDS);
+
+        current_end  = p_config->p_start_addr;
+        lowest_order = 0xFFFF;
+
+    } while ( --num_left > 0 );
+
+    m_flags |= FS_FLAG_INIT;
+
+    return NRF_SUCCESS;
+}
+
+
+ret_code_t fs_store(fs_config_t const *       p_config,
+                    uint32_t    const *       p_addr,
+                    uint32_t    const * const p_data,
+                    fs_length_t               length_words)
+{
+    if ((m_flags & FS_FLAG_INIT) == 0)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (!check_config(p_config))
+    {
+        return NRF_ERROR_FORBIDDEN;
+    }
+
+    if (!is_word_aligned(p_addr))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    // Check that the erase operation is on pages owned by this user (configuration).
+    if ((p_addr < p_config->p_start_addr) || ((p_addr + length_words) > p_config->p_end_addr))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    return cmd_enqueue(p_config, FS_OP_STORE, p_addr, p_data, length_words);
+}
+
+
+ret_code_t fs_erase(fs_config_t const *       p_config,
+                    uint32_t          * const p_addr,
+                    fs_length_t const         length_words)
+{
+    if ((m_flags & FS_FLAG_INIT) == 0)
+    {
+        return NRF_ERROR_INVALID_STATE;
+    }
+
+    if (!check_config(p_config))
+    {
+        return NRF_ERROR_FORBIDDEN;
+    }
+
+    /** Check that the address is aligned on a page boundary and the length to erase
+     *  is a multiple of the page size. */
+    if (((uint32_t)p_addr & (FS_PAGE_SIZE - 1)) ||
+        (length_words     & (FS_PAGE_SIZE_WORDS - 1)))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    // Check that the erase operation is on pages owned by this user (configuration).
+    if ((p_addr < p_config->p_start_addr) || ((p_addr + length_words) > p_config->p_end_addr))
+    {
+        return NRF_ERROR_INVALID_ADDR;
+    }
+
+    return cmd_enqueue(p_config, FS_OP_ERASE, p_addr, NULL, length_words);
+}
+
+
+/**@brief Function to handle system events from the SoftDevice.
+ *
+ * @details     This function should be dispatched system events if any of the modules used by
+ *              the application rely on FStorage. Examples include @ref Peer Manager and
+ *              @ref Flash Data Storage.
+ *
+ * @param[in]   sys_evt     System Event received.
+ */
+void fs_sys_event_handler(uint32_t sys_evt)
+{
+    if (m_flags & FS_FLAG_PROCESSING)
+    {
+        /** A flash operation was initiated by this module.
+         *  Handle its result. */
+        switch (sys_evt)
+        {
+            case NRF_EVT_FLASH_OPERATION_SUCCESS:
+                on_operation_success();
+                break;
+
+            case NRF_EVT_FLASH_OPERATION_ERROR:
+                on_operation_failure(sys_evt);
+                break;
+        }
+    }
+    else if ((m_flags & FS_FLAG_FLASH_REQ_PENDING))
+    {
+        /** A flash operation was initiated outside this module.
+         *  We have now receveid a callback which indicates it has
+         *  finished. Clear the FS_FLAG_FLASH_REQ_PENDING flag. */
+         m_flags &= ~FS_FLAG_FLASH_REQ_PENDING;
+
+         // Resume processing the queue, if necessary.
+         queue_process();
+    }
+}
+
+
+// Just for testing out section vars (across many compilers).
+void fs_debug_print()
+{
+    printf("fs start address: 0x%08lx\r\n", (unsigned long)FS_SECTION_VARS_START_ADDR);
+    printf("fs end address: 0x%08lx\r\n",   (unsigned long)FS_SECTION_VARS_END_ADDR);
+    printf("Num items: 0x%08lx\r\n",        (unsigned long)FS_SECTION_VARS_COUNT);
+    printf("===== ITEMS %lu =====\r\n",     (unsigned long)FS_SECTION_VARS_COUNT);
+
+    for(int i = 0; i < FS_SECTION_VARS_COUNT; i++)
+    {
+        fs_config_t* config = FS_SECTION_VARS_GET(i);
+        printf( "Address: 0x%08lx, CB: 0x%08lx\r\n",
+                (unsigned long)config, (unsigned long)config->cb );
+    }
+    printf("\r\n");
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+
+#ifndef FS_H__
+#define FS_H__
+
+ /** @file
+ *
+ * @defgroup fstorage FStorage
+ * @{
+ * @ingroup app_common
+ * @brief Module which provides low level functionality to store data to flash.
+ *
+ */
+
+
+#include <stdint.h>
+#include "section_vars.h"
+#include "fstorage_config.h"
+#include "sdk_errors.h"
+
+
+typedef uint16_t fs_length_t;
+
+
+typedef enum
+{
+    FS_OP_NONE          = 0,
+    FS_OP_STORE         = 1,
+    FS_OP_ERASE         = 2
+} fs_oper_t;
+
+
+/**@brief Callback for flash operations.
+ *
+ * @param[in]   op_code         Flash access operation code.
+ * @param[in]   result          Result of the operation.
+ * @param[in]   data            Pointer to resulting data (or NULL if not in use).
+ * @param[in]   length_words    Length of data in words.
+ */
+typedef void (*fs_cb_t)(uint8_t             op_code,
+                        uint32_t            result,
+                        uint32_t    const * p_data,
+                        fs_length_t         length_words);
+
+
+/**@brief Function prototype for a callback handler.
+ *
+ * @details This function is expected to be implemented by the module that 
+ *          registers for fstorage usage. Its usage is described
+ *          in the function pointer type fs_cb_t.
+ *
+ * @param[in]   op_code         Flash operation code.
+ * @param[in]   result          Result of the flash operation.
+ * @param[in]   p_data          Pointer to the resulting data (or NULL if not in use).
+ * @param[in]   length_words    Length of data in words.
+ */
+static void fs_callback(uint8_t             op_code,
+                        uint32_t            result,
+                        uint32_t    const * p_data,
+                        fs_length_t         length_words);
+
+
+/**@brief Flash storage config variable.
+ *
+ * @details     The fstorage module will update the start_addr and end_address according to 
+ *              ordering rules and the number of pages requested by the fstorage module user.
+ */
+typedef struct
+{
+    const fs_cb_t   cb;               /**< Callback to run when flash operation has completed. */
+    const uint8_t   num_pages;        /**< The number of pages to reserve for flash storage. */
+    const uint8_t   page_order;       /**< The order used to allocate pages. */
+    uint32_t      * p_start_addr;     /**< Pointer to the start address of the allocated flash storage. Set by running @ref fs_init. */
+    uint32_t *      p_end_addr;       /**< Pointer to the end address of the allcoated flash storage. Set by running @ref fs_init. */
+} fs_config_t;
+
+
+/**@brief Macro for registering of flash storage configuration variable.
+ *
+ * @details This macro is expected to be invoked in the code unit that that require
+ *          flash storage. Invoking this places the registered configuration variable
+ *          in a section named "fs_data" that the fstorage module uses during initialization
+ *          and regular operation.
+ */
+#define FS_SECTION_VARS_ADD(type_def) NRF_SECTION_VARS_ADD(fs_data, type_def)
+
+
+/**@brief Function to initialize FStorage.
+ *
+ * @details     This function allocates flash data pages according to the
+ *              number requested in the config variable. The data used to initialize.
+ *              the fstorage is section placed variables in the data section "fs_data".
+ */
+ret_code_t fs_init(void);
+
+
+/**@brief Function to store data in flash.
+ *
+ * @warning The data to be written to flash has to be kept in memory until the operation has
+ *          terminated, i.e., a callback is received.
+ *
+ * @param[in]   p_config        Const pointer to configiguration of module user that requests a store operation.
+ * @param[in]   p_addr          Write address of store operation.
+ * @param[in]   p_data          Pointer to the data to store.
+ * @param[in]   length_words    Length of the data to store.
+ *
+ * @retval NRF_SUCCESS                  Success. Command queued.
+ * @retval NRF_ERROR_INVALID_STATE      Error. The module is not initialized.
+ * @retval NRF_ERROR_INVALID_ADDR       Error. Data is unaligned or invalid configuration.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+ret_code_t fs_store(fs_config_t const *       p_config,
+                    uint32_t    const *       p_addr,
+                    uint32_t    const * const p_data,
+                    fs_length_t               length_words);
+
+
+/** Function to erase a page in flash.
+ *
+ * @note        The erase address must be aligned on a page boundary. The length in words must be 
+ *              equivalent to the page size.
+ *
+ * @param[in]   p_config        Pointer to the configuration of the user that requests the operation.
+ * @param[in]   p_addr          Address of page to erase (the same as first word in the page).
+ * @param[in]   length_words    Length (in 4 byte words) of the area to erase.
+ *
+ * @retval NRF_SUCCESS                  Success. Command queued.
+ * @retval NRF_ERROR_INVALID_STATE      Error. The module is not initialized.
+ * @retval NRF_ERROR_INVALID_ADDR       Error. Data is unaligned or invalid configuration.
+ * @retval Any error returned by the SoftDevice flash API.
+ */
+ret_code_t fs_erase(fs_config_t const *       p_config,
+                    uint32_t          * const p_addr,
+                    fs_length_t               length_words);
+
+
+/**@brief Function to call to handle events from the SoftDevice
+ *
+ * @param   sys_evt     System event from the SoftDevice
+ */
+void fs_sys_event_handler(uint32_t sys_evt);
+
+/** @} */
+
+#endif // FS_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_config.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_config.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef FS_CONFIG_H__
+#define FS_CONFIG_H__
+
+#include <stdint.h>
+#include "nrf.h"
+
+/**
+ * @defgroup fstorage_config FStorage configuration
+ * @ingroup fstorage
+ * @{
+ * @brief FStorage configuration.
+ */
+
+
+/**@brief Macro for max number of operations in the fs cmd queue.
+ */
+#define FS_CMD_QUEUE_SIZE   (8)
+
+
+/**@brief Macro for max number of retries for a flash command before it notifies as failed.
+ */
+#define FS_CMD_MAX_RETRIES  (3)
+
+
+/**@brief Macro for the content of a flash address that has not been written to.
+ */
+#define FS_EMPTY_MASK       (0xFFFFFFFF)
+
+
+/**@brief Macro for flash page size according to chip family
+ */
+#if defined (NRF51)
+    #define FS_PAGE_SIZE    (1024)
+#elif defined (NRF52)
+    #define FS_PAGE_SIZE    (4096)
+#else
+    #error "Device family must be defined. See nrf.h."
+#endif
+
+
+/*@brief Macro for flash page size according to chip family
+*/
+#define FS_PAGE_SIZE_WORDS  (FS_PAGE_SIZE/4)
+
+
+/**@brief Static inline function that provides last page address
+ *
+ * @note    If there is a bootloader present the bootloader address read from UICR
+ *          will act as the page beyond the end of the available flash storage
+ */
+static __INLINE uint32_t fs_flash_page_end_addr()
+{
+    uint32_t const bootloader_addr = NRF_UICR->NRFFW[0];
+    return  ((bootloader_addr != FS_EMPTY_MASK) ?
+             bootloader_addr : NRF_FICR->CODESIZE * FS_PAGE_SIZE);
+}
+
+
+/**@brief Macro for last page address
+ *
+ * @note    If there is a bootloader present the bootloader address read from UICR
+ *          will act as the page beyond the end of the available flash storage
+ */
+#define FS_PAGE_END_ADDR  fs_flash_page_end_addr()
+
+
+/**@brief Macro to describe the write
+ *
+ */
+#if defined (NRF51)
+    #define FS_MAX_WRITE_SIZE_WORDS	    (256)
+#elif defined (NRF52)
+    #define FS_MAX_WRITE_SIZE_WORDS     (1024)
+#else
+    #error "Device family must be defined. see nrf.h"
+#endif
+
+/** @} */
+
+#endif // FS_CONFIG_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_nosd.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/fstorage/fstorage_nosd.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+#include "hci_mem_pool.h"
+#include "hci_mem_pool_internal.h"
+#include <stdbool.h>
+#include <stdio.h>
+
+/**@brief RX buffer element instance structure. 
+ */
+typedef struct 
+{
+    uint8_t  rx_buffer[RX_BUF_SIZE];                                /**< RX buffer memory array. */  
+    uint32_t length;                                                /**< Length of the RX buffer memory array. */
+} rx_buffer_elem_t;
+
+/**@brief RX buffer queue element instance structure. 
+ */
+typedef struct 
+{
+    rx_buffer_elem_t * p_buffer;                                    /**< Pointer to RX buffer element. */
+    uint32_t           free_window_count;                           /**< Free space element count. */
+    uint32_t           free_available_count;                        /**< Free area element count. */
+    uint32_t           read_available_count;                        /**< Read area element count. */
+    uint32_t           write_index;                                 /**< Write position index. */                                      
+    uint32_t           read_index;                                  /**< Read position index. */                                                                            
+    uint32_t           free_index;                                  /**< Free position index. */                                                                                                                  
+} rx_buffer_queue_t;
+
+static bool              m_is_tx_allocated;                         /**< Boolean value to determine if the TX buffer is allocated. */
+static rx_buffer_elem_t  m_rx_buffer_elem_queue[RX_BUF_QUEUE_SIZE]; /**< RX buffer element instances. */
+static rx_buffer_queue_t m_rx_buffer_queue;                         /**< RX buffer queue element instance. */
+
+
+uint32_t hci_mem_pool_open(void)
+{
+    m_is_tx_allocated                      = false;    
+    m_rx_buffer_queue.p_buffer             = m_rx_buffer_elem_queue;
+    m_rx_buffer_queue.free_window_count    = RX_BUF_QUEUE_SIZE;
+    m_rx_buffer_queue.free_available_count = 0;
+    m_rx_buffer_queue.read_available_count = 0;
+    m_rx_buffer_queue.write_index          = 0;    
+    m_rx_buffer_queue.read_index           = 0;        
+    m_rx_buffer_queue.free_index           = 0;            
+    
+    return NRF_SUCCESS;
+}
+
+
+uint32_t hci_mem_pool_close(void)
+{    
+    return NRF_SUCCESS;
+}
+
+
+uint32_t hci_mem_pool_tx_alloc(void ** pp_buffer)
+{
+    static uint8_t tx_buffer[TX_BUF_SIZE];  
+
+    uint32_t err_code;
+    
+    if (pp_buffer == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+    
+    if (!m_is_tx_allocated)
+    {        
+            m_is_tx_allocated = true;
+            *pp_buffer        = tx_buffer;
+            err_code          = NRF_SUCCESS;
+    }
+    else
+    {
+        err_code              = NRF_ERROR_NO_MEM;
+    }
+    
+    return err_code;
+}
+
+
+uint32_t hci_mem_pool_tx_free(void)
+{
+    m_is_tx_allocated = false;
+    
+    return NRF_SUCCESS;
+}
+
+
+uint32_t hci_mem_pool_rx_produce(uint32_t length, void ** pp_buffer)
+{
+    uint32_t err_code; 
+
+    if (pp_buffer == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }    
+    *pp_buffer = NULL;
+    
+    if (m_rx_buffer_queue.free_window_count != 0)
+    {    
+        if (length <= RX_BUF_SIZE)
+        {    
+            --(m_rx_buffer_queue.free_window_count);            
+            ++(m_rx_buffer_queue.read_available_count);            
+
+            *pp_buffer                    = 
+                    m_rx_buffer_queue.p_buffer[m_rx_buffer_queue.write_index].rx_buffer;
+
+            m_rx_buffer_queue.free_index |= (1u << m_rx_buffer_queue.write_index);
+
+            // @note: Adjust the write_index making use of the fact that the buffer size is of 
+            // power of two and two's complement arithmetic. For details refer example to book 
+            // "Making embedded systems: Elicia White".
+            m_rx_buffer_queue.write_index = 
+                    (m_rx_buffer_queue.write_index + 1u) & (RX_BUF_QUEUE_SIZE - 1u);
+            
+            err_code                      = NRF_SUCCESS;
+        }
+        else
+        {
+            err_code = NRF_ERROR_DATA_SIZE;    
+        }        
+    }
+    else
+    {
+        err_code = NRF_ERROR_NO_MEM;    
+    }
+    
+    return err_code;
+}
+
+
+uint32_t hci_mem_pool_rx_consume(uint8_t * p_buffer)
+{
+    uint32_t err_code;
+    uint32_t consume_index;
+    uint32_t start_index;
+    
+    if (m_rx_buffer_queue.free_available_count != 0)
+    {
+        // Find the buffer that has been freed -
+        // Start at read_index minus free_available_count and then increment until read index.
+        err_code      = NRF_ERROR_INVALID_ADDR;
+        consume_index = (m_rx_buffer_queue.read_index - m_rx_buffer_queue.free_available_count) & 
+                        (RX_BUF_QUEUE_SIZE - 1u);
+        start_index   = consume_index;
+        
+        do
+        {
+            if (m_rx_buffer_queue.p_buffer[consume_index].rx_buffer == p_buffer)
+            {
+                m_rx_buffer_queue.free_index ^= (1u << consume_index);
+                err_code = NRF_SUCCESS;
+                break;
+            }
+            else
+            {
+                consume_index = (consume_index + 1u) & (RX_BUF_QUEUE_SIZE - 1u);
+            }
+        }
+        while (consume_index != m_rx_buffer_queue.read_index);
+
+        while (!(m_rx_buffer_queue.free_index & (1 << start_index)) && 
+                (m_rx_buffer_queue.free_available_count != 0))
+        {
+            --(m_rx_buffer_queue.free_available_count);
+            ++(m_rx_buffer_queue.free_window_count);            
+            start_index = (consume_index + 1u) & (RX_BUF_QUEUE_SIZE - 1u);
+        }
+    }
+    else
+    {
+        err_code = NRF_ERROR_NO_MEM;
+    }
+        
+    return err_code;    
+}
+
+
+uint32_t hci_mem_pool_rx_data_size_set(uint32_t length)
+{
+    // @note: Adjust the write_index making use of the fact that the buffer size is of power
+    // of two and two's complement arithmetic. For details refer example to book 
+    // "Making embedded systems: Elicia White".
+    const uint32_t index = (m_rx_buffer_queue.write_index - 1u) & (RX_BUF_QUEUE_SIZE - 1u);
+    m_rx_buffer_queue.p_buffer[index].length = length;    
+    
+    return NRF_SUCCESS;
+}
+
+
+uint32_t hci_mem_pool_rx_extract(uint8_t ** pp_buffer, uint32_t * p_length)
+{
+    uint32_t err_code;
+    
+    if ((pp_buffer == NULL) || (p_length == NULL))
+    {
+        return NRF_ERROR_NULL;
+    }
+    
+    if (m_rx_buffer_queue.read_available_count != 0)
+    {
+        --(m_rx_buffer_queue.read_available_count);
+        ++(m_rx_buffer_queue.free_available_count);        
+        
+        *pp_buffer                   = 
+            m_rx_buffer_queue.p_buffer[m_rx_buffer_queue.read_index].rx_buffer;
+        *p_length                    = 
+            m_rx_buffer_queue.p_buffer[m_rx_buffer_queue.read_index].length;
+        
+        // @note: Adjust the write_index making use of the fact that the buffer size is of power
+        // of two and two's complement arithmetic. For details refer example to book 
+        // "Making embedded systems: Elicia White".            
+        m_rx_buffer_queue.read_index = 
+            (m_rx_buffer_queue.read_index + 1u) & (RX_BUF_QUEUE_SIZE - 1u); 
+        
+        err_code                     = NRF_SUCCESS;
+    }
+    else
+    {
+        err_code                     = NRF_ERROR_NO_MEM;        
+    }
+    
+    return err_code;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/hci/hci_mem_pool.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/** @file
+ *
+ * @defgroup memory_pool Memory pool
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Memory pool implementation
+ *
+ * Memory pool implementation, based on circular buffer data structure, which supports asynchronous 
+ * processing of RX data. The current default implementation supports 1 TX buffer and 4 RX buffers.
+ * The memory managed by the pool is allocated from static storage instead of heap. The internal 
+ * design of the circular buffer implementing the RX memory layout is illustrated in the picture 
+ * below. 
+ *
+ * @image html memory_pool.png "Circular buffer design"
+ *
+ * The expected call order for the RX APIs is as follows:
+ * - hci_mem_pool_rx_produce
+ * - hci_mem_pool_rx_data_size_set
+ * - hci_mem_pool_rx_extract
+ * - hci_mem_pool_rx_consume
+ *
+ * @warning If the above mentioned expected call order is violated the end result can be undefined.
+ *
+ * \par Component specific configuration options
+ *
+ * The following compile time configuration options are available to suit various implementations:
+ * - TX_BUF_SIZE TX buffer size in bytes. 
+ * - RX_BUF_SIZE RX buffer size in bytes. 
+ * - RX_BUF_QUEUE_SIZE RX buffer element size.
+ */
+ 
+#ifndef HCI_MEM_POOL_H__
+#define HCI_MEM_POOL_H__
+
+#include <stdint.h>
+#include "nrf_error.h"
+
+/**@brief Function for opening the module.
+ *
+ * @retval NRF_SUCCESS          Operation success. 
+ */
+uint32_t hci_mem_pool_open(void);
+
+/**@brief Function for closing the module.
+ *
+ * @retval NRF_SUCCESS          Operation success. 
+ */
+uint32_t hci_mem_pool_close(void);
+
+/**@brief Function for allocating requested amount of TX memory.
+ *
+ * @param[out] pp_buffer        Pointer to the allocated memory.
+ *
+ * @retval NRF_SUCCESS          Operation success. Memory was allocated.
+ * @retval NRF_ERROR_NO_MEM     Operation failure. No memory available for allocation.
+ * @retval NRF_ERROR_NULL       Operation failure. NULL pointer supplied.  
+ */
+uint32_t hci_mem_pool_tx_alloc(void ** pp_buffer);
+ 
+/**@brief Function for freeing previously allocated TX memory.
+ *
+ * @note Memory management follows the FIFO principle meaning that free() order must match the 
+ *       alloc(...) order, which is the reason for omitting exact memory block identifier as an 
+ *       input parameter.
+ *
+ * @retval NRF_SUCCESS          Operation success. Memory was freed.
+ */
+uint32_t hci_mem_pool_tx_free(void);
+ 
+/**@brief Function for producing a free RX memory block for usage.
+ *
+ * @note Upon produce request amount being 0, NRF_SUCCESS is returned.   
+ *
+ * @param[in]  length           Amount, in bytes, of free memory to be produced.
+ * @param[out] pp_buffer        Pointer to the allocated memory.
+ *
+ * @retval NRF_SUCCESS          Operation success. Free RX memory block produced.
+ * @retval NRF_ERROR_NO_MEM     Operation failure. No suitable memory available for allocation.
+ * @retval NRF_ERROR_DATA_SIZE  Operation failure. Request size exceeds limit.  
+ * @retval NRF_ERROR_NULL       Operation failure. NULL pointer supplied.   
+ */
+uint32_t hci_mem_pool_rx_produce(uint32_t length, void ** pp_buffer);
+
+/**@brief Function for setting the length of the last produced RX memory block.
+ *
+ * @warning If call to this API is omitted the end result is that the following call to 
+ *          mem_pool_rx_extract will return incorrect data in the p_length output parameter.
+ *
+ * @param[in]  length           Amount, in bytes, of actual memory used.
+ *
+ * @retval NRF_SUCCESS          Operation success. Length was set.
+ */
+uint32_t hci_mem_pool_rx_data_size_set(uint32_t length);
+ 
+/**@brief Function for extracting a packet, which has been filled with read data, for further 
+ * processing.
+ *
+ * @param[out] pp_buffer        Pointer to the packet data.
+ * @param[out] p_length         Length of packet data in bytes.  
+ *
+ * @retval NRF_SUCCESS          Operation success. 
+ * @retval NRF_ERROR_NO_MEM     Operation failure. No packet available to extract.
+ * @retval NRF_ERROR_NULL       Operation failure. NULL pointer supplied.    
+ */
+uint32_t hci_mem_pool_rx_extract(uint8_t ** pp_buffer, uint32_t * p_length);
+ 
+/**@brief Function for freeing previously extracted packet, which has been filled with read data.
+ *
+ * @param[in] p_buffer             Pointer to consumed buffer.
+ *
+ * @retval NRF_SUCCESS             Operation success. 
+ * @retval NRF_ERROR_NO_MEM        Operation failure. No packet available to free. 
+ * @retval NRF_ERROR_INVALID_ADDR  Operation failure. Not a valid pointer. 
+ */
+uint32_t hci_mem_pool_rx_consume(uint8_t * p_buffer);
+ 
+#endif // HCI_MEM_POOL_H__
+ 
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "app_scheduler.h"
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include "nrf_soc.h"
+#include "nrf_assert.h"
+#include "app_util.h"
+#include "app_util_platform.h"
+
+/**@brief Structure for holding a scheduled event header. */
+typedef struct
+{
+    app_sched_event_handler_t handler;          /**< Pointer to event handler to receive the event. */
+    uint16_t                  event_data_size;  /**< Size of event data. */
+} event_header_t;
+
+STATIC_ASSERT(sizeof(event_header_t) <= APP_SCHED_EVENT_HEADER_SIZE);
+
+static event_header_t * m_queue_event_headers;  /**< Array for holding the queue event headers. */
+static uint8_t        * m_queue_event_data;     /**< Array for holding the queue event data. */
+static volatile uint8_t m_queue_start_index;    /**< Index of queue entry at the start of the queue. */
+static volatile uint8_t m_queue_end_index;      /**< Index of queue entry at the end of the queue. */
+static uint16_t         m_queue_event_size;     /**< Maximum event size in queue. */
+static uint16_t         m_queue_size;           /**< Number of queue entries. */
+
+/**@brief Function for incrementing a queue index, and handle wrap-around.
+ *
+ * @param[in]   index   Old index.
+ *
+ * @return      New (incremented) index.
+ */
+static __INLINE uint8_t next_index(uint8_t index)
+{
+    return (index < m_queue_size) ? (index + 1) : 0;
+}
+
+
+static __INLINE uint8_t app_sched_queue_full()
+{
+  uint8_t tmp = m_queue_start_index;
+  return next_index(m_queue_end_index) == tmp;
+}
+
+/**@brief Macro for checking if a queue is full. */
+#define APP_SCHED_QUEUE_FULL() app_sched_queue_full()
+
+
+static __INLINE uint8_t app_sched_queue_empty()
+{
+  uint8_t tmp = m_queue_start_index;
+  return m_queue_end_index == tmp;
+}
+
+/**@brief Macro for checking if a queue is empty. */
+#define APP_SCHED_QUEUE_EMPTY() app_sched_queue_empty()
+
+
+uint32_t app_sched_init(uint16_t event_size, uint16_t queue_size, void * p_event_buffer)
+{
+    uint16_t data_start_index = (queue_size + 1) * sizeof(event_header_t);
+
+    // Check that buffer is correctly aligned
+    if (!is_word_aligned(p_event_buffer))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    // Initialize event scheduler
+    m_queue_event_headers = p_event_buffer;
+    m_queue_event_data    = &((uint8_t *)p_event_buffer)[data_start_index];
+    m_queue_end_index     = 0;
+    m_queue_start_index   = 0;
+    m_queue_event_size    = event_size;
+    m_queue_size          = queue_size;
+
+    return NRF_SUCCESS;
+}
+
+
+uint32_t app_sched_event_put(void                    * p_event_data,
+                             uint16_t                  event_data_size,
+                             app_sched_event_handler_t handler)
+{
+    uint32_t err_code;
+
+    if (event_data_size <= m_queue_event_size)
+    {
+        uint16_t event_index = 0xFFFF;
+
+        CRITICAL_REGION_ENTER();
+
+        if (!APP_SCHED_QUEUE_FULL())
+        {
+            event_index       = m_queue_end_index;
+            m_queue_end_index = next_index(m_queue_end_index);
+        }
+
+        CRITICAL_REGION_EXIT();
+
+        if (event_index != 0xFFFF)
+        {
+            // NOTE: This can be done outside the critical region since the event consumer will
+            //       always be called from the main loop, and will thus never interrupt this code.
+            m_queue_event_headers[event_index].handler = handler;
+            if ((p_event_data != NULL) && (event_data_size > 0))
+            {
+                memcpy(&m_queue_event_data[event_index * m_queue_event_size],
+                       p_event_data,
+                       event_data_size);
+                m_queue_event_headers[event_index].event_data_size = event_data_size;
+            }
+            else
+            {
+                m_queue_event_headers[event_index].event_data_size = 0;
+            }
+
+            err_code = NRF_SUCCESS;
+        }
+        else
+        {
+            err_code = NRF_ERROR_NO_MEM;
+        }
+    }
+    else
+    {
+        err_code = NRF_ERROR_INVALID_LENGTH;
+    }
+
+    return err_code;
+}
+
+
+/**@brief Function for reading the next event from specified event queue.
+ *
+ * @param[out]  pp_event_data       Pointer to pointer to event data.
+ * @param[out]  p_event_data_size   Pointer to size of event data.
+ * @param[out]  p_event_handler     Pointer to event handler function pointer.
+ *
+ * @return      NRF_SUCCESS if new event, NRF_ERROR_NOT_FOUND if event queue is empty.
+ */
+static uint32_t app_sched_event_get(void                     ** pp_event_data,
+                                    uint16_t *                  p_event_data_size,
+                                    app_sched_event_handler_t * p_event_handler)
+{
+    uint32_t err_code = NRF_ERROR_NOT_FOUND;
+
+    if (!APP_SCHED_QUEUE_EMPTY())
+    {
+        uint16_t event_index;
+
+        // NOTE: There is no need for a critical region here, as this function will only be called
+        //       from app_sched_execute() from inside the main loop, so it will never interrupt
+        //       app_sched_event_put(). Also, updating of (i.e. writing to) the start index will be
+        //       an atomic operation.
+        event_index         = m_queue_start_index;
+        m_queue_start_index = next_index(m_queue_start_index);
+
+        *pp_event_data     = &m_queue_event_data[event_index * m_queue_event_size];
+        *p_event_data_size = m_queue_event_headers[event_index].event_data_size;
+        *p_event_handler   = m_queue_event_headers[event_index].handler;
+
+        err_code = NRF_SUCCESS;
+    }
+
+    return err_code;
+}
+
+
+void app_sched_execute(void)
+{
+    void                    * p_event_data;
+    uint16_t                  event_data_size;
+    app_sched_event_handler_t event_handler;
+
+    // Get next event (if any), and execute handler
+    while ((app_sched_event_get(&p_event_data, &event_data_size, &event_handler) == NRF_SUCCESS))
+    {
+        event_handler(p_event_data, event_data_size);
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/scheduler/app_scheduler.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup app_scheduler Scheduler
+ * @{
+ * @ingroup app_common
+ *
+ * @brief The scheduler is used for transferring execution from the interrupt context to the main
+ *        context.
+ *
+ * @details See @ref seq_diagrams_sched for sequence diagrams illustrating the flow of events
+ *          when using the Scheduler.
+ *
+ * @section app_scheduler_req Requirements:
+ *
+ * @subsection main_context_logic Logic in main context:
+ *
+ *   - Define an event handler for each type of event expected.
+ *   - Initialize the scheduler by calling the APP_SCHED_INIT() macro before entering the
+ *     application main loop.
+ *   - Call app_sched_execute() from the main loop each time the application wakes up because of an
+ *     event (typically when sd_app_evt_wait() returns).
+ *
+ * @subsection int_context_logic Logic in interrupt context:
+ *
+ *   - In the interrupt handler, call app_sched_event_put()
+ *     with the appropriate data and event handler. This will insert an event into the
+ *     scheduler's queue. The app_sched_execute() function will pull this event and call its
+ *     handler in the main context.
+ *
+ * @if (PERIPHERAL)
+ * For an example usage of the scheduler, see the implementations of
+ * @ref ble_sdk_app_hids_mouse and @ref ble_sdk_app_hids_keyboard.
+ * @endif
+ *
+ * @image html scheduler_working.jpg The high level design of the scheduler
+ */
+
+#ifndef APP_SCHEDULER_H__
+#define APP_SCHEDULER_H__
+
+#include <stdint.h>
+#include "app_error.h"
+#include "app_util.h"
+
+#define APP_SCHED_EVENT_HEADER_SIZE 8       /**< Size of app_scheduler.event_header_t (only for use inside APP_SCHED_BUF_SIZE()). */
+
+/**@brief Compute number of bytes required to hold the scheduler buffer.
+ *
+ * @param[in] EVENT_SIZE   Maximum size of events to be passed through the scheduler.
+ * @param[in] QUEUE_SIZE   Number of entries in scheduler queue (i.e. the maximum number of events
+ *                         that can be scheduled for execution).
+ *
+ * @return    Required scheduler buffer size (in bytes).
+ */
+#define APP_SCHED_BUF_SIZE(EVENT_SIZE, QUEUE_SIZE)                                                 \
+            (((EVENT_SIZE) + APP_SCHED_EVENT_HEADER_SIZE) * ((QUEUE_SIZE) + 1))
+            
+/**@brief Scheduler event handler type. */
+typedef void (*app_sched_event_handler_t)(void * p_event_data, uint16_t event_size);
+
+/**@brief Macro for initializing the event scheduler.
+ *
+ * @details It will also handle dimensioning and allocation of the memory buffer required by the
+ *          scheduler, making sure the buffer is correctly aligned.
+ *
+ * @param[in] EVENT_SIZE   Maximum size of events to be passed through the scheduler.
+ * @param[in] QUEUE_SIZE   Number of entries in scheduler queue (i.e. the maximum number of events
+ *                         that can be scheduled for execution).
+ *
+ * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it
+ *       several times as long as it is from the same location, e.g. to do a reinitialization).
+ */
+#define APP_SCHED_INIT(EVENT_SIZE, QUEUE_SIZE)                                                     \
+    do                                                                                             \
+    {                                                                                              \
+        static uint32_t APP_SCHED_BUF[CEIL_DIV(APP_SCHED_BUF_SIZE((EVENT_SIZE), (QUEUE_SIZE)),     \
+                                               sizeof(uint32_t))];                                 \
+        uint32_t ERR_CODE = app_sched_init((EVENT_SIZE), (QUEUE_SIZE), APP_SCHED_BUF);             \
+        APP_ERROR_CHECK(ERR_CODE);                                                                 \
+    } while (0)
+
+/**@brief Function for initializing the Scheduler.
+ *
+ * @details It must be called before entering the main loop.
+ *
+ * @param[in]   max_event_size   Maximum size of events to be passed through the scheduler.
+ * @param[in]   queue_size       Number of entries in scheduler queue (i.e. the maximum number of
+ *                               events that can be scheduled for execution).
+ * @param[in]   p_evt_buffer   Pointer to memory buffer for holding the scheduler queue. It must
+ *                               be dimensioned using the APP_SCHED_BUFFER_SIZE() macro. The buffer
+ *                               must be aligned to a 4 byte boundary.
+ *
+ * @note Normally initialization should be done using the APP_SCHED_INIT() macro, as that will both
+ *       allocate the scheduler buffer, and also align the buffer correctly.
+ *
+ * @retval      NRF_SUCCESS               Successful initialization.
+ * @retval      NRF_ERROR_INVALID_PARAM   Invalid parameter (buffer not aligned to a 4 byte
+ *                                        boundary).
+ */
+uint32_t app_sched_init(uint16_t max_event_size, uint16_t queue_size, void * p_evt_buffer);
+
+/**@brief Function for executing all scheduled events.
+ *
+ * @details This function must be called from within the main loop. It will execute all events
+ *          scheduled since the last time it was called.
+ */
+void app_sched_execute(void);
+
+/**@brief Function for scheduling an event.
+ *
+ * @details Puts an event into the event queue.
+ *
+ * @param[in]   p_event_data   Pointer to event data to be scheduled.
+ * @param[in]   event_size   Size of event data to be scheduled.
+ * @param[in]   handler        Event handler to receive the event.
+ *
+ * @return      NRF_SUCCESS on success, otherwise an error code.
+ */
+uint32_t app_sched_event_put(void *                    p_event_data,
+                             uint16_t                  event_size,
+                             app_sched_event_handler_t handler);
+
+#ifdef APP_SCHEDULER_WITH_PAUSE
+/**@brief A function to pause the scheduler.
+ *
+ * @details When the scheduler is paused events are not pulled from the scheduler queue for
+ *          processing. The function can be called multiple times. To unblock the scheduler the
+ *          function @ref app_sched_resume has to be called the same number of times.
+ */
+void app_sched_pause(void);
+
+/**@brief A function to resume a scheduler.
+ *
+ * @details To unblock the scheduler this function has to be called the same number of times as
+ *          @ref app_sched_pause function.
+ */
+void app_sched_resume(void);
+#endif
+#endif // APP_SCHEDULER_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/timer/app_timer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/timer/app_timer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,297 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup app_timer Application Timer
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Application timer functionality.
+ *
+ * @details This module enables the application to create multiple timer instances based on the RTC1
+ *          peripheral. Checking for time-outs and invokation of user time-out handlers is performed
+ *          in the RTC1 interrupt handler. List handling is done using a software interrupt (SWI0).
+ *          Both interrupt handlers are running in APP_LOW priority level.
+ *
+ * @details When calling app_timer_start() or app_timer_stop(), the timer operation is just queued,
+ *          and the software interrupt is triggered. The actual timer start/stop operation is
+ *          executed by the SWI0 interrupt handler. Since the SWI0 interrupt is running in APP_LOW,
+ *          if the application code calling the timer function is running in APP_LOW or APP_HIGH,
+ *          the timer operation will not be performed until the application handler has returned.
+ *          This will be the case, for example, when stopping a timer from a time-out handler when not using
+ *          the scheduler.
+ *
+ * @details Use the USE_SCHEDULER parameter of the APP_TIMER_INIT() macro to select if the
+ *          @ref app_scheduler should be used or not. Even if the scheduler is 
+ *          not used, app_timer.h will include app_scheduler.h, so when
+ *          compiling, app_scheduler.h must be available in one of the compiler include paths.
+ */
+
+#ifndef APP_TIMER_H__
+#define APP_TIMER_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include "app_error.h"
+#include "app_util.h"
+#include "compiler_abstraction.h"
+
+#define APP_TIMER_CLOCK_FREQ         32768                      /**< Clock frequency of the RTC timer used to implement the app timer module. */
+#define APP_TIMER_MIN_TIMEOUT_TICKS  5                          /**< Minimum value of the timeout_ticks parameter of app_timer_start(). */
+
+#define APP_TIMER_NODE_SIZE          32                         /**< Size of app_timer.timer_node_t (used to allocate data). */
+#define APP_TIMER_USER_OP_SIZE       24                         /**< Size of app_timer.timer_user_op_t (only for use inside APP_TIMER_BUF_SIZE()). */
+#define APP_TIMER_USER_SIZE          8                          /**< Size of app_timer.timer_user_t (only for use inside APP_TIMER_BUF_SIZE()). */
+#define APP_TIMER_INT_LEVELS         3                          /**< Number of interrupt levels from where timer operations may be initiated (only for use inside APP_TIMER_BUF_SIZE()). */
+
+/**@brief Compute number of bytes required to hold the application timer data structures.
+ *
+ * @param[in]  OP_QUEUE_SIZE   Size of queues holding timer operations that are pending execution.
+ *                             Note that due to the queue implementation, this size must be one more
+ *                             than the size that is actually needed.
+ *
+ * @return     Required application timer buffer size (in bytes).
+ */
+#define APP_TIMER_BUF_SIZE(OP_QUEUE_SIZE)                                              \
+    (                                                                                              \
+        (                                                                                          \
+            APP_TIMER_INT_LEVELS                                                                   \
+            *                                                                                      \
+            (APP_TIMER_USER_SIZE + ((OP_QUEUE_SIZE) + 1) * APP_TIMER_USER_OP_SIZE)                 \
+        )                                                                                          \
+    )
+
+/**@brief Convert milliseconds to timer ticks.
+ *
+ * This macro uses 64-bit integer arithmetic, but as long as the macro parameters are
+ *       constants (i.e. defines), the computation will be done by the preprocessor.
+ * 
+ * When using this macro, ensure that the 
+ *         values provided as input result in an output value that is supported by the
+ *         @ref app_timer_start function. For example, when the ticks for 1 ms is needed, the
+ *         maximum possible value of PRESCALER must be 6, when @ref APP_TIMER_CLOCK_FREQ is 32768.
+ *         This will result in a ticks value as 5. Any higher value for PRESCALER will result in a
+ *         ticks value that is not supported by this module.
+ *
+ * @param[in]  MS          Milliseconds.
+ * @param[in]  PRESCALER   Value of the RTC1 PRESCALER register (must be the same value that was
+ *                         passed to APP_TIMER_INIT()). 
+ *
+ * @return     Number of timer ticks.
+ */
+#define APP_TIMER_TICKS(MS, PRESCALER)\
+            ((uint32_t)ROUNDED_DIV((MS) * (uint64_t)APP_TIMER_CLOCK_FREQ, ((PRESCALER) + 1) * 1000))
+
+typedef struct app_timer_t { uint32_t data[CEIL_DIV(APP_TIMER_NODE_SIZE, sizeof(uint32_t))]; } app_timer_t;
+
+/**@brief Timer ID type.
+ * Never declare a variable of this type, but use the macro @ref APP_TIMER_DEF instead.*/
+typedef app_timer_t * app_timer_id_t;
+
+/**
+ * @brief Create a timer identifier and statically allocate memory for the timer.
+ *
+ * @param timer_id Name of the timer identifier variable that will be used to control the timer.
+ */
+#define APP_TIMER_DEF(timer_id)                                  \
+    static app_timer_t timer_id##_data = { {0} };                  \
+    static const app_timer_id_t timer_id = &timer_id##_data
+
+
+/**@brief Application time-out handler type. */
+typedef void (*app_timer_timeout_handler_t)(void * p_context);
+
+/**@brief Type of function for passing events from the timer module to the scheduler. */
+typedef uint32_t (*app_timer_evt_schedule_func_t) (app_timer_timeout_handler_t timeout_handler,
+                                                   void *                      p_context);
+
+/**@brief Timer modes. */
+typedef enum
+{
+    APP_TIMER_MODE_SINGLE_SHOT,                 /**< The timer will expire only once. */
+    APP_TIMER_MODE_REPEATED                     /**< The timer will restart each time it expires. */
+} app_timer_mode_t;
+
+/**@brief Initialize the application timer module.
+ *
+ * @details This macro handles dimensioning and allocation of the memory buffer required by the timer,
+ *          making sure that the buffer is correctly aligned. It will also connect the timer module
+ *          to the scheduler (if specified).
+ *
+ * @note    This module assumes that the LFCLK is already running. If it is not, the module will 
+ *          be non-functional, since the RTC will not run. If you do not use a SoftDevice, you 
+ *          must start the LFCLK manually. See the rtc_example's lfclk_config() function 
+ *          for an example of how to do this. If you use a SoftDevice, the LFCLK is started on 
+ *          SoftDevice init. 
+ *
+ *
+ * @param[in]  PRESCALER        Value of the RTC1 PRESCALER register. This will decide the
+ *                              timer tick rate. Set to 0 for no prescaling.
+ * @param[in]  OP_QUEUES_SIZE   Size of queues holding timer operations that are pending execution.
+ * @param[in]  SCHEDULER_FUNC   Pointer to scheduler event handler
+ *
+ * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it
+ *       several times as long as it is from the same location, for example, to do a re-initialization).
+ */
+/*lint -emacro(506, APP_TIMER_INIT) */ /* Suppress "Constant value Boolean */
+#define APP_TIMER_INIT(PRESCALER, OP_QUEUES_SIZE, SCHEDULER_FUNC)                                  \
+    do                                                                                             \
+    {                                                                                              \
+        static uint32_t APP_TIMER_BUF[CEIL_DIV(APP_TIMER_BUF_SIZE((OP_QUEUES_SIZE) + 1),           \
+                                               sizeof(uint32_t))];                                 \
+        uint32_t ERR_CODE = app_timer_init((PRESCALER),                                            \
+                                           (OP_QUEUES_SIZE) + 1,                                   \
+                                           APP_TIMER_BUF,                                          \
+                                           SCHEDULER_FUNC);                                        \
+        APP_ERROR_CHECK(ERR_CODE);                                                                 \
+    } while (0)
+
+
+
+/**@brief Function for initializing the timer module.
+ *
+ * Normally, initialization should be done using the APP_TIMER_INIT() macro, because that macro will both
+ *       allocate the buffers needed by the timer module (including aligning the buffers correctly)
+ *       and take care of connecting the timer module to the scheduler (if specified).
+ *
+ * @param[in]  prescaler           Value of the RTC1 PRESCALER register. Set to 0 for no prescaling.
+ * @param[in]  op_queues_size      Size of queues holding timer operations that are pending
+ *                                 execution. Note that due to the queue implementation, this size must
+ *                                 be one more than the size that is actually needed.
+ * @param[in]  p_buffer            Pointer to memory buffer for internal use in the app_timer
+ *                                 module. The size of the buffer can be computed using the
+ *                                 APP_TIMER_BUF_SIZE() macro. The buffer must be aligned to a
+ *                                 4 byte boundary.
+ * @param[in]  evt_schedule_func   Function for passing time-out events to the scheduler. Point to
+ *                                 app_timer_evt_schedule() to connect to the scheduler. Set to NULL
+ *                                 to make the timer module call the time-out handler directly from
+ *                                 the timer interrupt handler.
+ *
+ * @retval     NRF_SUCCESS               If the module was initialized successfully.
+ * @retval     NRF_ERROR_INVALID_PARAM   If a parameter was invalid (buffer not aligned to a 4 byte
+ *                                       boundary or NULL).
+ */
+uint32_t app_timer_init(uint32_t                      prescaler, 
+                        uint8_t                       op_queues_size,
+                        void *                        p_buffer,
+                        app_timer_evt_schedule_func_t evt_schedule_func);
+
+/**@brief Function for creating a timer instance.
+ *
+ * @param[in]  p_timer_id        Pointer to timer identifier.
+ * @param[in]  mode              Timer mode.
+ * @param[in]  timeout_handler   Function to be executed when the timer expires.
+ *
+ * @retval     NRF_SUCCESS               If the timer was successfully created.
+ * @retval     NRF_ERROR_INVALID_PARAM   If a parameter was invalid.
+ * @retval     NRF_ERROR_INVALID_STATE   If the application timer module has not been initialized or
+ *                                       the timer is running.
+ *
+ * @note This function does the timer allocation in the caller's context. It is also not protected
+ *       by a critical region. Therefore care must be taken not to call it from several interrupt
+ *       levels simultaneously.
+ * @note The function can be called again on the timer instance and will re-initialize the instance if
+ *       the timer is not running.
+ * @attention The FreeRTOS and RTX app_timer implementation does not allow app_timer_create to
+ *       be called on the previously initialized instance.
+ */
+uint32_t app_timer_create(app_timer_id_t const *      p_timer_id,
+                          app_timer_mode_t            mode,
+                          app_timer_timeout_handler_t timeout_handler);
+
+/**@brief Function for starting a timer.
+ *
+ * @param[in]       timer_id      Timer identifier.
+ * @param[in]       timeout_ticks Number of ticks (of RTC1, including prescaling) to time-out event
+ *                                (minimum 5 ticks).
+ * @param[in]       p_context     General purpose pointer. Will be passed to the time-out handler when
+ *                                the timer expires.
+ *
+ * @retval     NRF_SUCCESS               If the timer was successfully started.
+ * @retval     NRF_ERROR_INVALID_PARAM   If a parameter was invalid.
+ * @retval     NRF_ERROR_INVALID_STATE   If the application timer module has not been initialized or the timer
+ *                                       has not been created.
+ * @retval     NRF_ERROR_NO_MEM          If the timer operations queue was full.
+ *
+ * @note The minimum timeout_ticks value is 5.
+ * @note For multiple active timers, time-outs occurring in close proximity to each other (in the
+ *       range of 1 to 3 ticks) will have a positive jitter of maximum 3 ticks.
+ * @note When calling this method on a timer that is already running, the second start operation
+ *       is ignored.
+ */
+uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context);
+
+/**@brief Function for stopping the specified timer.
+ *
+ * @param[in]  timer_id                  Timer identifier.
+ *
+ * @retval     NRF_SUCCESS               If the timer was successfully stopped.
+ * @retval     NRF_ERROR_INVALID_PARAM   If a parameter was invalid.
+ * @retval     NRF_ERROR_INVALID_STATE   If the application timer module has not been initialized or the timer
+ *                                       has not been created.
+ * @retval     NRF_ERROR_NO_MEM          If the timer operations queue was full.
+ */
+uint32_t app_timer_stop(app_timer_id_t timer_id);
+
+/**@brief Function for stopping all running timers.
+ *
+ * @retval     NRF_SUCCESS               If all timers were successfully stopped.
+ * @retval     NRF_ERROR_INVALID_STATE   If the application timer module has not been initialized.
+ * @retval     NRF_ERROR_NO_MEM          If the timer operations queue was full.
+ */
+uint32_t app_timer_stop_all(void);
+
+/**@brief Function for returning the current value of the RTC1 counter.
+ *
+ * @param[out] p_ticks   Current value of the RTC1 counter.
+ *
+ * @retval     NRF_SUCCESS   If the counter was successfully read.
+ */
+uint32_t app_timer_cnt_get(uint32_t * p_ticks);
+
+/**@brief Function for computing the difference between two RTC1 counter values.
+ *
+ * @param[in]  ticks_to       Value returned by app_timer_cnt_get().
+ * @param[in]  ticks_from     Value returned by app_timer_cnt_get().
+ * @param[out] p_ticks_diff   Number of ticks from ticks_from to ticks_to.
+ *
+ * @retval     NRF_SUCCESS   If the counter difference was successfully computed.
+ */
+uint32_t app_timer_cnt_diff_compute(uint32_t   ticks_to,
+                                    uint32_t   ticks_from,
+                                    uint32_t * p_ticks_diff);
+
+#endif // APP_TIMER_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup app_error Common application error handler
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Common application error handler.
+ */
+
+#include "nrf.h"
+#include "app_error.h"
+#include "compiler_abstraction.h"
+#include "nordic_common.h"
+#ifdef DEBUG
+#include "bsp.h"
+
+/* global error variables - in order to prevent removal by optimizers */
+uint32_t m_error_code;
+uint32_t m_line_num;
+const uint8_t * m_p_file_name;
+#endif
+
+/**@brief Function for error handling, which is called when an error has occurred.
+ *
+ * @warning This handler is an example only and does not fit a final product. You need to analyze
+ *          how your product is supposed to react in case of error.
+ *
+ * @param[in] error_code  Error code supplied to the handler.
+ * @param[in] line_num    Line number where the handler is called.
+ * @param[in] p_file_name Pointer to the file name.
+ *
+ * Function is implemented as weak so that it can be overwritten by custom application error handler
+ * when needed.
+ */
+
+/*lint -save -e14 */
+__WEAK void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name)
+{
+    // On assert, the system can only recover with a reset.
+#ifndef DEBUG
+    NVIC_SystemReset();
+#else
+
+#ifdef BSP_DEFINES_ONLY 
+    LEDS_ON(LEDS_MASK);
+#else
+    UNUSED_VARIABLE(bsp_indication_set(BSP_INDICATE_FATAL_ERROR));
+    // This call can be used for debug purposes during application development.
+    // @note CAUTION: Activating this code will write the stack to flash on an error.
+    //                This function should NOT be used in a final product.
+    //                It is intended STRICTLY for development/debugging purposes.
+    //                The flash write will happen EVEN if the radio is active, thus interrupting
+    //                any communication.
+    //                Use with care. Uncomment the line below to use.
+    //ble_debug_assert_handler(error_code, line_num, p_file_name);
+#endif // BSP_DEFINES_ONLY
+
+    // The following variable helps Keil keep the call stack visible, in addition, it can be set to
+    // 0 in the debugger to continue executing code after the error check.
+    volatile bool loop = true;
+    UNUSED_VARIABLE(loop);
+
+    m_error_code = error_code;
+    m_line_num = line_num;
+    m_p_file_name = p_file_name;
+
+    UNUSED_VARIABLE(m_error_code);
+    UNUSED_VARIABLE(m_line_num);
+    UNUSED_VARIABLE(m_p_file_name);
+    __disable_irq();
+
+    while(loop);
+#endif // DEBUG
+}
+/*lint -restore */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/app_error.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+/** @file
+ *
+ * @defgroup app_error Common application error handler
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Common application error handler and macros for utilizing a common error handler.
+ */
+
+#ifndef APP_ERROR_H__
+#define APP_ERROR_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "nrf_error.h"
+
+/**@brief Function for error handling, which is called when an error has occurred. 
+ *
+ * @param[in] error_code  Error code supplied to the handler.
+ * @param[in] line_num    Line number where the handler is called.
+ * @param[in] p_file_name Pointer to the file name. 
+ */
+void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name);
+
+/**@brief Macro for calling error handler function. 
+ *
+ * @param[in] ERR_CODE Error code supplied to the error handler.
+ */
+#ifdef DEBUG
+#define APP_ERROR_HANDLER(ERR_CODE)                         \
+    do                                                      \
+    {                                                       \
+        app_error_handler((ERR_CODE), __LINE__, (uint8_t*) __FILE__);  \
+    } while (0)
+#else
+#define APP_ERROR_HANDLER(ERR_CODE)                         \
+    do                                                      \
+    {                                                       \
+        app_error_handler((ERR_CODE), 0, 0);  \
+    } while (0)
+#endif
+/**@brief Macro for calling error handler function if supplied error code any other than NRF_SUCCESS. 
+ *
+ * @param[in] ERR_CODE Error code supplied to the error handler.
+ */    
+#define APP_ERROR_CHECK(ERR_CODE)                           \
+    do                                                      \
+    {                                                       \
+        const uint32_t LOCAL_ERR_CODE = (ERR_CODE);         \
+        if (LOCAL_ERR_CODE != NRF_SUCCESS)                  \
+        {                                                   \
+            APP_ERROR_HANDLER(LOCAL_ERR_CODE);              \
+        }                                                   \
+    } while (0)    
+    
+/**@brief Macro for calling error handler function if supplied boolean value is false. 
+ *
+ * @param[in] BOOLEAN_VALUE Boolean value to be evaluated.
+ */
+#define APP_ERROR_CHECK_BOOL(BOOLEAN_VALUE)                   \
+    do                                                        \
+    {                                                         \
+        const uint32_t LOCAL_BOOLEAN_VALUE = (BOOLEAN_VALUE); \
+        if (!LOCAL_BOOLEAN_VALUE)                             \
+        {                                                     \
+            APP_ERROR_HANDLER(0);                             \
+        }                                                     \
+    } while (0)        
+
+#endif // APP_ERROR_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup app_util Utility Functions and Definitions
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Various types and definitions available to all applications.
+ */
+
+#ifndef APP_UTIL_H__
+#define APP_UTIL_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "compiler_abstraction.h"
+
+enum
+{
+    UNIT_0_625_MS = 625,                                /**< Number of microseconds in 0.625 milliseconds. */
+    UNIT_1_25_MS  = 1250,                               /**< Number of microseconds in 1.25 milliseconds. */
+    UNIT_10_MS    = 10000                               /**< Number of microseconds in 10 milliseconds. */
+};
+
+
+/**@brief Implementation specific macro for delayed macro expansion used in string concatenation
+*
+* @param[in]   lhs   Left hand side in concatenation
+* @param[in]   rhs   Right hand side in concatenation
+*/
+#define STRING_CONCATENATE_IMPL(lhs, rhs) lhs ## rhs
+
+
+/**@brief Macro used to concatenate string using delayed macro expansion
+*
+* @note This macro will delay concatenation until the expressions have been resolved
+*
+* @param[in]   lhs   Left hand side in concatenation
+* @param[in]   rhs   Right hand side in concatenation
+*/
+#define STRING_CONCATENATE(lhs, rhs) STRING_CONCATENATE_IMPL(lhs, rhs)
+
+
+// Disable lint-warnings/errors for STATIC_ASSERT
+//lint --emacro(10,STATIC_ASSERT)
+//lint --emacro(18,STATIC_ASSERT)
+//lint --emacro(19,STATIC_ASSERT)
+//lint --emacro(30,STATIC_ASSERT)
+//lint --emacro(37,STATIC_ASSERT)
+//lint --emacro(42,STATIC_ASSERT)
+//lint --emacro(26,STATIC_ASSERT)
+//lint --emacro(102,STATIC_ASSERT)
+//lint --emacro(533,STATIC_ASSERT)
+//lint --emacro(534,STATIC_ASSERT)
+//lint --emacro(132,STATIC_ASSERT)
+//lint --emacro(414,STATIC_ASSERT)
+//lint --emacro(578,STATIC_ASSERT)
+//lint --emacro(628,STATIC_ASSERT)
+//lint --emacro(648,STATIC_ASSERT)
+//lint --emacro(830,STATIC_ASSERT)
+
+
+/**@brief Macro for doing static (i.e. compile time) assertion.
+*
+* @note If the EXPR isn't resolvable, then the error message won't be shown.
+*
+* @note The output of STATIC_ASSERT_MSG will be different across different compilers.
+*
+* @param[in] EXPR Constant expression to be verified.
+*/
+#if defined ( __COUNTER__ )
+
+#define STATIC_ASSERT(EXPR) \
+    ;enum { STRING_CONCATENATE(static_assert_, __COUNTER__) = 1/(!!(EXPR)) }
+
+#else
+
+#define STATIC_ASSERT(EXPR) \
+    ;enum { STRING_CONCATENATE(assert_line_, __LINE__) = 1/(!!(EXPR)) }
+
+#endif
+
+
+
+/**@brief type for holding an encoded (i.e. little endian) 16 bit unsigned integer. */
+typedef uint8_t uint16_le_t[2];
+
+/**@brief type for holding an encoded (i.e. little endian) 32 bit unsigned integer. */
+typedef uint8_t uint32_le_t[4];
+
+/**@brief Byte array type. */
+typedef struct
+{
+    uint16_t  size;                 /**< Number of array entries. */
+    uint8_t * p_data;               /**< Pointer to array entries. */
+} uint8_array_t;
+    
+/**@brief Perform rounded integer division (as opposed to truncating the result).
+ *
+ * @param[in]   A   Numerator.
+ * @param[in]   B   Denominator.
+ *
+ * @return      Rounded (integer) result of dividing A by B.
+ */
+#define ROUNDED_DIV(A, B) (((A) + ((B) / 2)) / (B))
+
+/**@brief Check if the integer provided is a power of two.
+ *
+ * @param[in]   A   Number to be tested.
+ *
+ * @return      true if value is power of two.
+ * @return      false if value not power of two.
+ */
+#define IS_POWER_OF_TWO(A) ( ((A) != 0) && ((((A) - 1) & (A)) == 0) )
+
+/**@brief To convert milliseconds to ticks.
+ * @param[in] TIME          Number of milliseconds to convert.
+ * @param[in] RESOLUTION    Unit to be converted to in [us/ticks].
+ */
+#define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION))
+
+/**@brief Perform integer division, making sure the result is rounded up.
+ *
+ * @details One typical use for this is to compute the number of objects with size B is needed to
+ *          hold A number of bytes.
+ *
+ * @param[in]   A   Numerator.
+ * @param[in]   B   Denominator.
+ *
+ * @return      Integer result of dividing A by B, rounded up.
+ */
+#define CEIL_DIV(A, B)      \
+    (((A) + (B) - 1) / (B))
+
+/**@brief Function for creating a buffer aligned to 4 bytes.
+ *
+ * @param[in]   NAME        Name of the buffor.
+ * @param[in]   MIN_SIZE    Size of this buffor (it will be rounded up to multiples of 4 bytes).
+ */
+#define WORD_ALIGNED_MEM_BUFF(NAME, MIN_SIZE) static uint32_t NAME[CEIL_DIV(MIN_SIZE, sizeof(uint32_t))]
+
+/**@brief Function for changing the value unit.
+ *
+ * @param[in]   value               Value to be rescaled.
+ * @param[in]   old_unit_reversal   Reversal of the incoming unit.
+ * @param[in]   new_unit_reversal   Reversal of the desired unit.
+ *
+ * @return      Number of bytes written.
+ */
+static __INLINE uint64_t value_rescale(uint32_t value, uint32_t old_unit_reversal, uint16_t new_unit_reversal)
+{
+    return (uint64_t)ROUNDED_DIV((uint64_t)value * new_unit_reversal, old_unit_reversal);
+}
+
+/**@brief Function for encoding a uint16 value.
+ *
+ * @param[in]   value            Value to be encoded.
+ * @param[out]  p_encoded_data   Buffer where the encoded data is to be written.
+ *
+ * @return      Number of bytes written.
+ */
+static __INLINE uint8_t uint16_encode(uint16_t value, uint8_t * p_encoded_data)
+{
+    p_encoded_data[0] = (uint8_t) ((value & 0x00FF) >> 0);
+    p_encoded_data[1] = (uint8_t) ((value & 0xFF00) >> 8);
+    return sizeof(uint16_t);
+}
+
+/**@brief Function for encoding a three-byte value.
+ *
+ * @param[in]   value            Value to be encoded.
+ * @param[out]  p_encoded_data   Buffer where the encoded data is to be written.
+ *
+ * @return      Number of bytes written.
+ */
+static __INLINE uint8_t uint24_encode(uint32_t value, uint8_t * p_encoded_data)
+{
+    p_encoded_data[0] = (uint8_t) ((value & 0x000000FF) >> 0);
+    p_encoded_data[1] = (uint8_t) ((value & 0x0000FF00) >> 8);
+    p_encoded_data[2] = (uint8_t) ((value & 0x00FF0000) >> 16);
+    return 3;
+}
+
+/**@brief Function for encoding a uint32 value.
+ *
+ * @param[in]   value            Value to be encoded.
+ * @param[out]  p_encoded_data   Buffer where the encoded data is to be written.
+ *
+ * @return      Number of bytes written.
+ */
+static __INLINE uint8_t uint32_encode(uint32_t value, uint8_t * p_encoded_data)
+{
+    p_encoded_data[0] = (uint8_t) ((value & 0x000000FF) >> 0);
+    p_encoded_data[1] = (uint8_t) ((value & 0x0000FF00) >> 8);
+    p_encoded_data[2] = (uint8_t) ((value & 0x00FF0000) >> 16);
+    p_encoded_data[3] = (uint8_t) ((value & 0xFF000000) >> 24);
+    return sizeof(uint32_t);
+}
+
+/**@brief Function for decoding a uint16 value.
+ *
+ * @param[in]   p_encoded_data   Buffer where the encoded data is stored.
+ *
+ * @return      Decoded value.
+ */
+static __INLINE uint16_t uint16_decode(const uint8_t * p_encoded_data)
+{
+        return ( (((uint16_t)((uint8_t *)p_encoded_data)[0])) | 
+                 (((uint16_t)((uint8_t *)p_encoded_data)[1]) << 8 ));
+}
+
+/**@brief Function for decoding a three-byte value.
+ *
+ * @param[in]   p_encoded_data   Buffer where the encoded data is stored.
+ *
+ * @return      Decoded value (uint32_t).
+ */
+static __INLINE uint32_t uint24_decode(const uint8_t * p_encoded_data)
+{
+    return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 0)  |
+             (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 8)  |
+             (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 16));
+}
+
+/**@brief Function for decoding a uint32 value.
+ *
+ * @param[in]   p_encoded_data   Buffer where the encoded data is stored.
+ *
+ * @return      Decoded value.
+ */
+static __INLINE uint32_t uint32_decode(const uint8_t * p_encoded_data)
+{
+    return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 0)  |
+             (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 8)  |
+             (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 16) |
+             (((uint32_t)((uint8_t *)p_encoded_data)[3]) << 24 ));
+}
+
+/** @brief Function for converting the input voltage (in milli volts) into percentage of 3.0 Volts.
+ *
+ *  @details The calculation is based on a linearized version of the battery's discharge
+ *           curve. 3.0V returns 100% battery level. The limit for power failure is 2.1V and
+ *           is considered to be the lower boundary.
+ *
+ *           The discharge curve for CR2032 is non-linear. In this model it is split into
+ *           4 linear sections:
+ *           - Section 1: 3.0V - 2.9V = 100% - 42% (58% drop on 100 mV)
+ *           - Section 2: 2.9V - 2.74V = 42% - 18% (24% drop on 160 mV)
+ *           - Section 3: 2.74V - 2.44V = 18% - 6% (12% drop on 300 mV)
+ *           - Section 4: 2.44V - 2.1V = 6% - 0% (6% drop on 340 mV)
+ *
+ *           These numbers are by no means accurate. Temperature and
+ *           load in the actual application is not accounted for!
+ *
+ *  @param[in] mvolts The voltage in mV
+ *
+ *  @return    Battery level in percent.
+*/
+static __INLINE uint8_t battery_level_in_percent(const uint16_t mvolts)
+{
+    uint8_t battery_level;
+
+    if (mvolts >= 3000)
+    {
+        battery_level = 100;
+    }
+    else if (mvolts > 2900)
+    {
+        battery_level = 100 - ((3000 - mvolts) * 58) / 100;
+    }
+    else if (mvolts > 2740)
+    {
+        battery_level = 42 - ((2900 - mvolts) * 24) / 160;
+    }
+    else if (mvolts > 2440)
+    {
+        battery_level = 18 - ((2740 - mvolts) * 12) / 300;
+    }
+    else if (mvolts > 2100)
+    {
+        battery_level = 6 - ((2440 - mvolts) * 6) / 340;
+    }
+    else
+    {
+        battery_level = 0;
+    }
+
+    return battery_level;
+}
+
+/**@brief Function for checking if a pointer value is aligned to a 4 byte boundary.
+ *
+ * @param[in]   p   Pointer value to be checked.
+ *
+ * @return      TRUE if pointer is aligned to a 4 byte boundary, FALSE otherwise.
+ */
+static __INLINE bool is_word_aligned(void const* p)
+{
+    return (((uintptr_t)p & 0x03) == 0);
+}
+
+#endif // APP_UTIL_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "app_util_platform.h"
+
+static uint32_t m_in_critical_region = 0;
+
+void critical_region_enter(void)
+{
+    __disable_irq();    
+    m_in_critical_region++;    
+}
+
+void critical_region_exit(void)
+{
+    m_in_critical_region--;    
+    if (m_in_critical_region == 0)
+    {
+        __enable_irq();
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/app_util_platform.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup app_util_platform Utility Functions and Definitions (Platform)
+ * @{
+ * @ingroup app_common
+ *
+ * @brief Various types and definitions available to all applications when using SoftDevice.
+ */
+
+#ifndef APP_UTIL_PLATFORM_H__
+#define APP_UTIL_PLATFORM_H__
+
+#include <stdint.h>
+#include "compiler_abstraction.h"
+#include "nrf.h"
+#ifdef SOFTDEVICE_PRESENT
+#include "nrf_soc.h"
+#include "app_error.h"
+#endif
+/**@brief The interrupt priorities available to the application while the SoftDevice is active. */
+typedef enum
+{
+#ifndef SOFTDEVICE_PRESENT
+    APP_IRQ_PRIORITY_HIGHEST = 0,
+#endif
+    APP_IRQ_PRIORITY_HIGH    = 1,
+#ifndef SOFTDEVICE_PRESENT
+    APP_IRQ_PRIORITY_MID     = 2,
+#endif
+    APP_IRQ_PRIORITY_LOW     = 3
+} app_irq_priority_t;
+
+#define NRF_APP_PRIORITY_THREAD    4                    /**< "Interrupt level" when running in Thread Mode. */
+
+/**@cond NO_DOXYGEN */
+#define EXTERNAL_INT_VECTOR_OFFSET 16
+/**@endcond */
+
+#define PACKED(TYPE) __packed TYPE
+
+void critical_region_enter (void);
+void critical_region_exit (void);
+
+/**@brief Macro for entering a critical region.
+ *
+ * @note Due to implementation details, there must exist one and only one call to
+ *       CRITICAL_REGION_EXIT() for each call to CRITICAL_REGION_ENTER(), and they must be located
+ *       in the same scope.
+ */
+#ifdef SOFTDEVICE_PRESENT
+#define CRITICAL_REGION_ENTER()                                                             \
+    {                                                                                       \
+        uint8_t IS_NESTED_CRITICAL_REGION = 0;                                              \
+        uint32_t CURRENT_INT_PRI = current_int_priority_get();                              \
+        if (CURRENT_INT_PRI != APP_IRQ_PRIORITY_HIGH)                                       \
+        {                                                                                   \
+            uint32_t ERR_CODE = sd_nvic_critical_region_enter(&IS_NESTED_CRITICAL_REGION);  \
+            if (ERR_CODE == NRF_ERROR_SOFTDEVICE_NOT_ENABLED)                               \
+            {                                                                               \
+                __disable_irq();                                                            \
+            }                                                                               \
+            else                                                                            \
+            {                                                                               \
+                APP_ERROR_CHECK(ERR_CODE);                                                  \
+            }                                                                               \
+        }        
+#else
+#define CRITICAL_REGION_ENTER() critical_region_enter()
+#endif
+
+/**@brief Macro for leaving a critical region.
+ *
+ * @note Due to implementation details, there must exist one and only one call to
+ *       CRITICAL_REGION_EXIT() for each call to CRITICAL_REGION_ENTER(), and they must be located
+ *       in the same scope.
+ */
+#ifdef SOFTDEVICE_PRESENT
+#define CRITICAL_REGION_EXIT()                                                              \
+        if (CURRENT_INT_PRI != APP_IRQ_PRIORITY_HIGH)                                       \
+        {                                                                                   \
+            uint32_t ERR_CODE;                                                              \
+            __enable_irq();                                                                 \
+            ERR_CODE = sd_nvic_critical_region_exit(IS_NESTED_CRITICAL_REGION);             \
+            if (ERR_CODE != NRF_ERROR_SOFTDEVICE_NOT_ENABLED)                               \
+            {                                                                               \
+                APP_ERROR_CHECK(ERR_CODE);                                                  \
+            }                                                                               \
+        }                                                                                   \
+    }
+#else
+#define CRITICAL_REGION_EXIT() critical_region_exit()
+#endif 
+       
+/**@brief Function for finding the current interrupt level.
+ *
+ * @return   Current interrupt level.
+ * @retval   APP_IRQ_PRIORITY_HIGH    We are running in Application High interrupt level.
+ * @retval   APP_IRQ_PRIORITY_LOW     We are running in Application Low interrupt level.
+ * @retval   APP_IRQ_PRIORITY_THREAD  We are running in Thread Mode.
+ */
+static __INLINE uint8_t current_int_priority_get(void)
+{
+    uint32_t isr_vector_num = (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk);
+    if (isr_vector_num > 0)
+    {
+        int32_t irq_type = ((int32_t)isr_vector_num - EXTERNAL_INT_VECTOR_OFFSET);
+        return (NVIC_GetPriority((IRQn_Type)irq_type) & 0xFF);
+    }
+    else
+    {
+        return NRF_APP_PRIORITY_THREAD;
+    }
+}
+
+#endif // APP_UTIL_PLATFORM_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,58 @@
+ /*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef COMMON_H
+#define COMMON_H
+
+/*lint ++flb "Enter library region" */
+
+#include <stdbool.h>
+#include <stdint.h>
+
+/* @file
+* @brief Common header file for generic macros and definitions
+ *
+ */
+
+/*
+ * GPIO glue macros, this can be used to define a pin number in source/header file and use that macro for pin
+ * configuration using this expansion.
+ * example:
+ * #define RESET_PIN    8
+ * NRF_GPIO->PINCNF(RESET_PIN) = XXX  ;  // Expanded NRF_GPIO->PIN_CNF[8] = XXX
+ */
+#define PINX_GLUE(x, y, z)       x##y##_##z            /*!< first level glue for pin macros */
+#define PINCNF(p)                PINX_GLUE(PIN,p,CNF)  /*!< gpio configure pin number 'p' */
+#define PINOUT(p)                PINX_GLUE(PIN,p,OUT)  /*!< gpio out pin number 'p' */
+
+/*lint --flb "Leave library region" */
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/nordic_common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/nordic_common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ * @brief Common defines and macros for firmware developed by Nordic Semiconductor.
+ */
+
+#ifndef NORDIC_COMMON_H__
+#define NORDIC_COMMON_H__
+
+/** The upper 8 bits of a 32 bit value */
+//lint -emacro(572,MSB) // Suppress warning 572 "Excessive shift value"
+#define MSB(a) (((a) & 0xFF000000) >> 24)
+/** The lower 8 bits (of a 32 bit value) */
+#define LSB(a) ((a) & 0x000000FF)
+
+/** The upper 8 bits of a 16 bit value */
+//lint -emacro(572,MSB_16) // Suppress warning 572 "Excessive shift value"
+#define MSB_16(a) (((a) & 0xFF00) >> 8)
+/** The lower 8 bits (of a 16 bit value) */
+#define LSB_16(a) ((a) & 0x00FF)
+
+/** Leaves the minimum of the two 32-bit arguments */
+/*lint -emacro(506, MIN) */ /* Suppress "Constant value Boolean */
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+/** Leaves the maximum of the two 32-bit arguments */
+/*lint -emacro(506, MAX) */ /* Suppress "Constant value Boolean */
+#define MAX(a, b) ((a) < (b) ? (b) : (a))
+
+/** Concatenates two parameters. Useful as a second level of indirection,
+ *  when a parameter can be macro itself. */
+#define CONCAT_2(p1, p2)      p1##p2
+/** Concatenates three parameters. Useful as a second level of indirection,
+ *  when a parameter can be macro itself. */
+#define CONCAT_3(p1, p2, p3)  p1##p2##p3
+
+/**@brief Set a bit in the uint32 word.
+ *
+ * @param[in] W  Word whose bit is being set.
+ * @param[in] B  Bit number in the word to be set.
+ */
+#define SET_BIT(W,B)  ((W) |= (uint32_t)(1U << (B)))
+
+
+/**@brief Clears a bit in the uint32 word.
+ *
+ * @param[in] W   Word whose bit is to be cleared.
+ * @param[in] B   Bit number in the word to be cleared.
+ */
+#define CLR_BIT(W, B) ((W) &= (~((uint32_t)1 << (B))))
+
+
+/**@brief Checks if a bit is set.
+ *
+ * @param[in] W   Word whose bit is to be checked.
+ * @param[in] B   Bit number in the word to be checked.
+ *
+ * @retval 1 if bit is set.
+ * @retval 0 if bit is not set.
+ */
+#define IS_SET(W,B) (((W) >> (B)) & 1)
+
+#define BIT_0 0x01 /**< The value of bit 0 */
+#define BIT_1 0x02 /**< The value of bit 1 */
+#define BIT_2 0x04 /**< The value of bit 2 */
+#define BIT_3 0x08 /**< The value of bit 3 */
+#define BIT_4 0x10 /**< The value of bit 4 */
+#define BIT_5 0x20 /**< The value of bit 5 */
+#define BIT_6 0x40 /**< The value of bit 6 */
+#define BIT_7 0x80 /**< The value of bit 7 */
+#define BIT_8 0x0100 /**< The value of bit 8 */
+#define BIT_9 0x0200 /**< The value of bit 9 */
+#define BIT_10 0x0400 /**< The value of bit 10 */
+#define BIT_11 0x0800 /**< The value of bit 11 */
+#define BIT_12 0x1000 /**< The value of bit 12 */
+#define BIT_13 0x2000 /**< The value of bit 13 */
+#define BIT_14 0x4000 /**< The value of bit 14 */
+#define BIT_15 0x8000 /**< The value of bit 15 */
+#define BIT_16 0x00010000 /**< The value of bit 16 */
+#define BIT_17 0x00020000 /**< The value of bit 17 */
+#define BIT_18 0x00040000 /**< The value of bit 18 */
+#define BIT_19 0x00080000 /**< The value of bit 19 */
+#define BIT_20 0x00100000 /**< The value of bit 20 */
+#define BIT_21 0x00200000 /**< The value of bit 21 */
+#define BIT_22 0x00400000 /**< The value of bit 22 */
+#define BIT_23 0x00800000 /**< The value of bit 23 */
+#define BIT_24 0x01000000 /**< The value of bit 24 */
+#define BIT_25 0x02000000 /**< The value of bit 25 */
+#define BIT_26 0x04000000 /**< The value of bit 26 */
+#define BIT_27 0x08000000 /**< The value of bit 27 */
+#define BIT_28 0x10000000 /**< The value of bit 28 */
+#define BIT_29 0x20000000 /**< The value of bit 29 */
+#define BIT_30 0x40000000 /**< The value of bit 30 */
+#define BIT_31 0x80000000 /**< The value of bit 31 */
+
+#define UNUSED_VARIABLE(X)  ((void)(X))
+#define UNUSED_PARAMETER(X) UNUSED_VARIABLE(X)
+
+#endif // NORDIC_COMMON_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#include "nrf_assert.h"
+
+#if defined(DEBUG_NRF)
+void assert_nrf_callback(uint16_t line_num, const uint8_t * file_name)
+{
+    (void) file_name; /* Unused parameter */
+    (void) line_num;  /* Unused parameter */
+ 
+    while (1) ;
+}
+#endif /* DEBUG_NRF */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/nrf_assert.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ * @brief Utilities for verifying program logic
+ */
+
+#ifndef NRF_ASSERT_H_
+#define NRF_ASSERT_H_
+
+#include <stdint.h>
+#include "compiler_abstraction.h"
+
+#if defined(DEBUG_NRF) || defined(DEBUG_NRF_USER)
+
+/** @brief Function for handling assertions.
+ *
+ *
+ * @note
+ * This function is called when an assertion has triggered.
+ *
+ *
+ * @post
+ * All hardware is put into an idle non-emitting state (in particular the radio is highly
+ * important to switch off since the radio might be in a state that makes it send
+ * packets continiously while a typical final infinit ASSERT loop is executing).
+ *
+ *
+ * @param line_num The line number where the assertion is called
+ * @param file_name Pointer to the file name
+ */
+void assert_nrf_callback(uint16_t line_num, const uint8_t *file_name);
+
+/*lint -emacro(506, ASSERT) */ /* Suppress "Constant value Boolean */ 
+/*lint -emacro(774, ASSERT) */ /* Suppress "Boolean within 'if' always evaluates to True" */ \
+
+/** @brief Function for checking intended for production code.
+ *
+ * Check passes if "expr" evaluates to true. */
+#define ASSERT(expr) \
+if (expr)                                                                     \
+{                                                                             \
+}                                                                             \
+else                                                                          \
+{                                                                             \
+  assert_nrf_callback((uint16_t)__LINE__, (uint8_t *)__FILE__);               \
+}
+#else
+#define ASSERT(expr) //!< Assert empty when disabled
+__WEAK void assert_nrf_callback(uint16_t line_num, const uint8_t *file_name);
+#endif /* defined(DEBUG_NRF) || defined(DEBUG_NRF_USER) */
+
+#endif /* NRF_ASSERT_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @cond */
+/**@file
+ *
+ * @ingroup experimental_api
+ * @defgroup sdk_common SDK Common Header
+ * @breif All common headers needed for SDK examples will be included here so that application
+ *       developer does not have to include headers on him/herself.
+ * @{
+ */
+
+#ifndef SDK_COMMON_H__
+#define SDK_COMMON_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include "nordic_common.h"
+#include "compiler_abstraction.h"
+#include "sdk_os.h"
+#include "sdk_errors.h"
+#include "app_util.h"
+
+/** @} */
+/** @endcond */
+#endif // SDK_COMMON_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_errors.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_errors.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup sdk_error SDK Error codes
+ * @{
+ * @ingroup app_common
+ * @{
+ * @details Error codes are 32-bit unsigned integers with the most significant 16-bit reserved for
+ *          identifying the module where the error occurred while the least least significant LSB
+ *          are used to provide the cause or nature of error. Each module is assigned a 16-bit
+ *          unsigned integer. Which it will use to identify all errors that occurred in it. 16-bit
+ *          LSB range is with module id as the MSB in the 32-bit error code is reserved for the
+ *          module. As an example, if 0x8800 identifies a certain SDK module, all values from 
+ *          0x88000000 - 0x8800FFFF are reserved for this module.
+ *          It should be noted that common error reasons have been assigned values to make it 
+ *          possible to decode error reason easily. As an example, lets module uninitialized has
+ *          been assigned an error code 0x000A0. Then, if application encounters an error code
+ *          0xZZZZ00A0, it knows that it accessing a certain module without initializing it.
+ *          Apart from this, each module is allowed to define error codes that are not covered by
+ *          the common ones, however, these values are defined in a range that does not conflict
+ *          with common error values. For module, specific error however, it is possible that the
+ *          same error value is used by two different modules to indicated errors of very different
+ *          nature. If error is already defined by the NRF common error codes, these are reused.
+ *          A range is reserved for application as well, it can use this range for defining
+ *          application specific errors.
+ *
+ * @note Success code, NRF_SUCCESS, does not include any module identifier.          
+
+ */
+
+#ifndef SDK_ERRORS_H__
+#define SDK_ERRORS_H__
+
+#include <stdint.h>
+#include "nrf_error.h"
+
+/**
+ * @defgroup sdk_err_base Base defined for SDK Modules
+ * @{
+ */
+#define SDK_ERROR_BASE         (NRF_ERROR_BASE_NUM + 0x8000)   /**< Base value defined for SDK module identifiers. */
+#define SDK_COMMON_ERROR_BASE  (NRF_ERROR_BASE_NUM + 0x0080)   /**< Base error value to be used for SDK error values. */
+/* @} */
+
+/**
+ * @defgroup sdk_module_codes Codes reserved as identification for module where the error occurred.
+ * @{
+ */
+#define DEVICE_MANAGER_ERR_BASE   (0x8000)
+#define MEMORY_MANAGER_ERR_BASE   (0x8100)
+/* @} */
+
+
+/**
+ * @defgroup sdk_iot_errors Codes reserved as identification for IoT errors.
+ * @{
+ */
+#define IOT_ERR_BASE_START        (0xA000)
+#define IOT_ERR_BASE_STOP         (0xAFFF)
+/* @} */
+ 
+
+/**
+ * @defgroup sdk_common_errors Codes reserved as identification for common errors.
+ * @{
+ */
+#define MODULE_NOT_INITIALZED      (SDK_COMMON_ERROR_BASE + 0x0000)
+#define MUTEX_INIT_FAILED          (SDK_COMMON_ERROR_BASE + 0x0001)
+#define MUTEX_LOCK_FAILED          (SDK_COMMON_ERROR_BASE + 0x0002)
+#define MUTEX_UNLOCK_FAILED        (SDK_COMMON_ERROR_BASE + 0x0003)
+#define MUTEX_COND_INIT_FAILED     (SDK_COMMON_ERROR_BASE + 0x0004)
+#define MODULE_ALREADY_INITIALIZED (SDK_COMMON_ERROR_BASE + 0x0005)
+#define API_NOT_IMPLEMENTED        (SDK_COMMON_ERROR_BASE + 0x0010)
+#define FEATURE_NOT_ENABLED        (SDK_COMMON_ERROR_BASE + 0x0011)
+/* @} */
+
+
+/**
+ * @defgroup dm_specific_errors Error / status codes specific to device manager.
+ * @{
+ */
+#define DM_NO_APP_CONTEXT                (DEVICE_MANAGER_ERR_BASE + 0x0040)
+#define DM_SERVICE_CONTEXT_NOT_APPLIED   (DEVICE_MANAGER_ERR_BASE + 0x0041)
+#define DM_CONTEXT_INFO_LOST             (DEVICE_MANAGER_ERR_BASE + 0x0042)
+#define DM_DEVICE_CONTEXT_FULL           (DEVICE_MANAGER_ERR_BASE + 0x0043)
+/* @} */
+
+/**
+ * @brief API Result.
+ *
+ * @details Indicates success or failure of an API procedure. In case of failure, a comprehensive
+ *          error code indicating cause or reason for failure is provided.
+ *
+ *          Though called an API result, it could used in Asynchronous notifications callback along
+ *          with asynchronous callback as event result. This mechanism is employed when an event
+ *          marks the end of procedure initiated using API. API result, in this case, will only be
+ *          an indicative of whether the procedure has been requested successfully.
+ */
+typedef uint32_t ret_code_t;
+/** @} */
+/** @} */
+
+#endif // SDK_ERRORS_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "sdk_mapped_flags.h"
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include "compiler_abstraction.h"
+
+
+/**@brief Function for setting the state of a flag to true.
+ *
+ * @note This function does not check whether the index is valid.
+ *
+ * @param[in]  p_flags  The collection of flags to modify.
+ * @param[in]  index    The index of the flag to modify.
+ */
+static __INLINE void sdk_mapped_flags_set_by_index(sdk_mapped_flags_t * p_flags, uint16_t index)
+{
+    *p_flags |= (1U << index);
+}
+
+
+/**@brief Function for setting the state of a flag to false.
+ *
+ * @note This function does not check whether the index is valid.
+ *
+ * @param[in]  p_flags  The collection of flags to modify.
+ * @param[in]  index    The index of the flag to modify.
+ */
+static __INLINE void sdk_mapped_flags_clear_by_index(sdk_mapped_flags_t * p_flags, uint16_t index)
+{
+    *p_flags &= ~(1U << index);
+}
+
+
+/**@brief Function for getting the state of a flag.
+ *
+ * @note This function does not check whether the index is valid.
+ *
+ * @param[in]  p_flags  The collection of flags to read.
+ * @param[in]  index    The index of the flag to get.
+ */
+static __INLINE bool sdk_mapped_flags_get_by_index(sdk_mapped_flags_t flags, uint16_t index)
+{
+    return ((flags & (1 << index)) != 0);
+}
+
+
+
+uint16_t sdk_mapped_flags_first_key_index_get(sdk_mapped_flags_t flags)
+{
+    for (uint16_t i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++)
+    {
+        if (sdk_mapped_flags_get_by_index(flags, i))
+        {
+            return i;
+        }
+    }
+    return SDK_MAPPED_FLAGS_INVALID_INDEX;
+}
+
+
+void sdk_mapped_flags_update_by_key(uint16_t           * p_keys,
+                                    sdk_mapped_flags_t * p_flags,
+                                    uint16_t             key,
+                                    bool                 value)
+{
+    sdk_mapped_flags_bulk_update_by_key(p_keys, p_flags, 1, key, value);
+}
+
+
+void sdk_mapped_flags_bulk_update_by_key(uint16_t           * p_keys,
+                                         sdk_mapped_flags_t * p_flags,
+                                         uint32_t             n_flag_collections,
+                                         uint16_t             key,
+                                         bool                 value)
+{
+    if ((p_keys != NULL) && (p_flags != NULL) && (n_flag_collections > 0))
+    {
+        for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++)
+        {
+            if (p_keys[i] == key)
+            {
+                for (int j = 0; j < n_flag_collections; j++)
+                {
+                    if (value)
+                    {
+                        sdk_mapped_flags_set_by_index(&p_flags[j], i);
+                    }
+                    else
+                    {
+                        sdk_mapped_flags_clear_by_index(&p_flags[j], i);
+                    }
+                }
+                return;
+            }
+        }
+    }
+}
+
+
+bool sdk_mapped_flags_get_by_key(uint16_t * p_keys, sdk_mapped_flags_t flags, uint16_t key)
+{
+    if (p_keys != NULL)
+    {
+        for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++)
+        {
+            if (p_keys[i] == key)
+            {
+                return sdk_mapped_flags_get_by_index(flags, i);
+            }
+        }
+    }
+    return false;
+}
+
+
+sdk_mapped_flags_key_list_t sdk_mapped_flags_key_list_get(uint16_t           * p_keys,
+                                                          sdk_mapped_flags_t   flags)
+{
+    sdk_mapped_flags_key_list_t key_list;
+    key_list.len = 0;
+
+    if (p_keys != NULL)
+    {
+        for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++)
+        {
+            if (sdk_mapped_flags_get_by_index(flags, i))
+            {
+                key_list.flag_keys[key_list.len++] = p_keys[i];
+            }
+        }
+    }
+
+    return key_list;
+}
+
+
+uint32_t sdk_mapped_flags_n_flags_set(sdk_mapped_flags_t flags)
+{
+    uint32_t n_flags_set = 0;
+
+    for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++)
+    {
+        if (sdk_mapped_flags_get_by_index(flags, i))
+        {
+            n_flags_set += 1;
+        }
+    }
+    return n_flags_set;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_mapped_flags.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SDK_MAPPED_FLAGS_H__
+#define SDK_MAPPED_FLAGS_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "app_util.h"
+#include "compiler_abstraction.h"
+
+/**
+ * @file
+ * @defgroup sdk_mapped_flags Mapped flags
+ * @ingroup app_common
+ * @{
+ * @brief Module for writing and reading flags that are associated
+ *        with keys.
+ *
+ * @details The flags are represented as bits in a bitmap called a <i>flag collection</i>. The keys
+ *          are uint16_t. Each flag collection contains all flags of the same type, one flag for
+ *          each key.
+ *
+ *          The mapped flags module does not keep the flag states, nor the list of keys. These are
+ *          provided in the API calls. A key's index in the key list determines which bit in the
+ *          flag collection is associated with it. This module does not ever edit the key list, and
+ *          does not edit flags except in function calls that take the flag collection as a pointer.
+ *
+ */
+
+#define SDK_MAPPED_FLAGS_N_KEYS          8       /**< The number of keys to keep flags for. This is also the number of flags in a flag collection. If changing this value, you might also need change the width of the sdk_mapped_flags_t type. */
+#define SDK_MAPPED_FLAGS_N_KEYS_PER_BYTE 8       /**< The number of flags that fit in one byte. */
+#define SDK_MAPPED_FLAGS_INVALID_INDEX   0xFFFF  /**< A flag index guaranteed to be invalid. */
+
+typedef uint8_t sdk_mapped_flags_t; /**< The bitmap to hold flags. Each flag is one bit, and each bit represents the flag state associated with one key. */
+
+
+// Test whether the flag collection type is large enough to hold all the flags. If this fails,
+// reduce SDK_MAPPED_FLAGS_N_KEYS or increase the size of sdk_mapped_flags_t.
+STATIC_ASSERT((
+    sizeof(sdk_mapped_flags_t)*SDK_MAPPED_FLAGS_N_KEYS_PER_BYTE) >= SDK_MAPPED_FLAGS_N_KEYS);
+
+
+/**@brief Type used to present a subset of the registered keys.
+ */
+typedef struct
+{
+    uint32_t len;                                 /**< The length of the list. */
+    uint16_t flag_keys[SDK_MAPPED_FLAGS_N_KEYS];  /**< The list of keys. */
+} sdk_mapped_flags_key_list_t;
+
+
+/**@brief Function for getting the first index at which the flag is true in the provided
+ *        collection.
+ *
+ * @param[in]  flags   The flag collection to search for a flag set to true.
+ *
+ * @return  The first index that has its flag set to true. If none were found, the
+ *          function returns @ref SDK_MAPPED_FLAGS_INVALID_INDEX.
+ */
+uint16_t sdk_mapped_flags_first_key_index_get(sdk_mapped_flags_t flags);
+
+
+/**@brief Function for updating the state of a flag.
+ *
+ * @param[in]  p_keys   The list of associated keys (assumed to have a length of
+ *                      @ref SDK_MAPPED_FLAGS_N_KEYS).
+ * @param[out] p_flags  The flag collection to modify.
+ * @param[in]  key      The key to modify the flag of.
+ * @param[in]  value    The state to set the flag to.
+ */
+void sdk_mapped_flags_update_by_key(uint16_t           * p_keys,
+                                    sdk_mapped_flags_t * p_flags,
+                                    uint16_t             key,
+                                    bool                 value);
+
+
+/**@brief Function for updating the state of the same flag in multiple flag collections.
+ *
+ * @details The key and value are the same for all flag collections in the p_flags array.
+ *
+ * @param[in]  p_keys              The list of associated keys (assumed to have a length of
+ *                                 @ref SDK_MAPPED_FLAGS_N_KEYS).
+ * @param[out] p_flags             The flag collections to modify.
+ * @param[out] n_flag_collections  The number of flag collections in p_flags.
+ * @param[in]  key                 The key to modify the flag of.
+ * @param[in]  value               The state to set the flag to.
+ */
+void sdk_mapped_flags_bulk_update_by_key(uint16_t           * p_keys,
+                                         sdk_mapped_flags_t * p_flags,
+                                         uint32_t             n_flag_collections,
+                                         uint16_t             key,
+                                         bool                 value);
+
+
+/**@brief Function for getting the state of a specific flag.
+ *
+ * @param[in]  p_keys  The list of associated keys (assumed to have a length of
+ *                     @ref SDK_MAPPED_FLAGS_N_KEYS).
+ * @param[in]  flags   The flag collection to read from.
+ * @param[in]  key     The key to get the flag for.
+ *
+ * @return  The state of the flag.
+ */
+bool sdk_mapped_flags_get_by_key(uint16_t * p_keys, sdk_mapped_flags_t flags, uint16_t key);
+
+
+/**@brief Function for getting a list of all keys that have a specific flag set to true.
+ *
+ * @param[in]  p_keys  The list of associated keys (assumed to have a length of
+ *                     @ref SDK_MAPPED_FLAGS_N_KEYS).
+ * @param[in]  flags   The flag collection to search.
+ *
+ * @return  The list of keys.
+ */
+sdk_mapped_flags_key_list_t sdk_mapped_flags_key_list_get(uint16_t           * p_keys,
+                                                          sdk_mapped_flags_t   flags);
+
+
+/**@brief Function for getting the number of keys that have a specific flag set to true.
+ *
+ * @param[in]  flags  The flag collection to search.
+ *
+ * @return  The number of keys.
+ */
+uint32_t sdk_mapped_flags_n_flags_set(sdk_mapped_flags_t flags);
+
+
+/**@brief Function for querying whether any flags in the collection are set.
+ *
+ * @param[in]  flags  The flag collection to query.
+ *
+ * @retval  true If one or more flags are set to true.
+ * @retval  false Otherwise.
+ */
+static __INLINE bool sdk_mapped_flags_any_set(sdk_mapped_flags_t flags)
+{
+    return (flags != 0);
+}
+
+
+/** @} */
+
+#endif /* SDK_MAPPED_FLAGS_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_os.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/libraries/util/sdk_os.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+ /** @cond */
+/**@file
+ *
+ * @defgroup sdk_os SDK OS Abstraction
+ * @ingroup experimental_api
+ * @details In order to made SDK modules independent of use of an embedded OS, and permit
+ *          application with varied task architecture, SDK abstracts the OS specific
+ *          elements here in order to make all other modules agnostic to the OS or task
+ *          architecture.
+ * @{
+ */
+
+#ifndef SDK_OS_H__
+#define SDK_OS_H__
+
+#define SDK_MUTEX_DEFINE(X)
+#define SDK_MUTEX_INIT(X)
+#define SDK_MUTEX_LOCK(X)
+#define SDK_MUTEX_UNLOCK(X)
+
+/**
+ * @defgroup os_data_type Data types.
+ */
+ 
+/** @} */
+/** @endcond */
+#endif // SDK_OS_H__
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/prevent_bootloader_frame_pointer.cmake
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/prevent_bootloader_frame_pointer.cmake	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,21 @@
+# Copyright 2015 ARM Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+message("omit frame pointer for bootloader startup asm")
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+	set_source_files_properties(
+		"${CMAKE_CURRENT_LIST_DIR}/nordic_sdk/components/libraries/bootloader_dfu/bootloader_util.c"
+		PROPERTIES COMPILE_FLAGS -fomit-frame-pointer)
+endif()
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ant_stack_handler_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ant_stack_handler_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup ant_stack_handler_types Types definitions for ANT support in SoftDevice handler.
+ * @{
+ * @ingroup  softdevice_handler
+ * @brief    This file contains the declarations of types required for ANT stack support. These
+ *           types will be defined when the preprocessor define ANT_STACK_SUPPORT_REQD is defined.
+ */
+
+#ifndef ANT_STACK_HANDLER_TYPES_H__
+#define ANT_STACK_HANDLER_TYPES_H__
+
+#ifdef ANT_STACK_SUPPORT_REQD
+
+#include <stdlib.h>
+
+#define ANT_STACK_EVT_MSG_BUF_SIZE      32                                                /**< Size of ANT event message buffer. This will be provided to the SoftDevice while fetching an event. */
+#define ANT_STACK_EVT_STRUCT_SIZE       (sizeof(ant_evt_t))                               /**< Size of the @ref ant_evt_t structure. This will be used by the @ref softdevice_handler to internal event buffer size needed. */
+
+/**@brief ANT stack event type. */
+typedef struct
+{
+    uint8_t channel;                                                                      /**< Channel number. */
+    uint8_t event;                                                                        /**< Event code. */
+    uint8_t evt_buffer[ANT_STACK_EVT_MSG_BUF_SIZE];                                       /**< Event message buffer. */
+} ant_evt_t;
+
+/**@brief Application ANT stack event handler type. */
+typedef void (*ant_evt_handler_t) (ant_evt_t * p_ant_evt);
+
+/**@brief     Function for registering for ANT events.
+ *
+ * @details   The application should use this function to register for receiving ANT events from
+ *            the SoftDevice. If the application does not call this function, then any ANT event
+ *            that may be generated by the SoftDevice will NOT be fetched. Once the application has
+ *            registered for the events, it is not possible to  possible to cancel the registration.
+ *            However, it is possible to register a different function for handling the events at
+ *            any point of time.
+ *
+ * @param[in] ant_evt_handler Function to be called for each received ANT event.
+ *
+ * @retval    NRF_SUCCESS     Successful registration.
+ * @retval    NRF_ERROR_NULL  Null pointer provided as input.
+ */
+uint32_t softdevice_ant_evt_handler_set(ant_evt_handler_t ant_evt_handler);
+
+#else
+
+// The ANT Stack support is not required.
+
+#define ANT_STACK_EVT_STRUCT_SIZE       0                                                 /**< Since the ANT stack support is not required, this is equated to 0, so that the @ref softdevice_handler.h can compute the internal event buffer size without having to care for ANT events.*/
+
+#endif // ANT_STACK_SUPPORT_REQD
+
+#endif // ANT_STACK_HANDLER_TYPES_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ble_stack_handler_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/ble_stack_handler_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**@file
+ *
+ * @defgroup ble_stack_handler_types Types definitions for BLE support in SoftDevice handler.
+ * @{
+ * @ingroup  softdevice_handler
+ * @brief    This file contains the declarations of types required for BLE stack support. These
+ *           types will be defined when the preprocessor define BLE_STACK_SUPPORT_REQD is defined.
+ */
+
+#ifndef BLE_STACK_HANDLER_TYPES_H__
+#define BLE_STACK_HANDLER_TYPES_H__
+
+#define BLE_STACK_SUPPORT_REQD
+#ifdef BLE_STACK_SUPPORT_REQD
+
+#include <stdlib.h>
+#include "nrf_ble.h"
+#include "nrf_sdm.h"
+#include "app_error.h"
+#include "app_util.h"
+
+#define BLE_STACK_EVT_MSG_BUF_SIZE       (sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT))     /**< Size of BLE event message buffer. This will be provided to the SoftDevice while fetching an event. */
+#define BLE_STACK_HANDLER_SCHED_EVT_SIZE 0                                                 /**< The size of the scheduler event used by SoftDevice handler when passing BLE events using the @ref app_scheduler. */
+
+/**@brief Application stack event handler type. */
+typedef void (*ble_evt_handler_t) (ble_evt_t * p_ble_evt);
+
+/**@brief     Function for registering for BLE events.
+ *
+ * @details   The application should use this function to register for receiving BLE events from
+ *            the SoftDevice. If the application does not call this function, then any BLE event
+ *            that may be generated by the SoftDevice will NOT be fetched. Once the application has
+ *            registered for the events, it is not possible to cancel the registration.
+ *            However, it is possible to register a different function for handling the events at
+ *            any point of time.
+ *
+ * @param[in] ble_evt_handler Function to be called for each received BLE event.
+ *
+ * @retval    NRF_SUCCESS     Successful registration.
+ * @retval    NRF_ERROR_NULL  Null pointer provided as input.
+ */
+uint32_t softdevice_ble_evt_handler_set(ble_evt_handler_t ble_evt_handler);
+
+#else
+
+#define BLE_STACK_EVT_MSG_BUF_SIZE        0                                                /**< Since the BLE stack support is not required, this is equated to 0, so that the @ref softdevice_handler.h can compute the internal event buffer size without having to care for BLE events.*/
+#define BLE_STACK_HANDLER_SCHED_EVT_SIZE  0
+
+#endif // BLE_STACK_SUPPORT_REQD
+
+#endif // BLE_STACK_HANDLER_TYPES_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "softdevice_handler.h"
+#include <stdlib.h>
+#include "nordic_common.h"
+#include "app_error.h"
+#include "app_util.h"
+#include "nrf_assert.h"
+#include "nrf_soc.h"
+#include "nrf.h"
+
+#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD)
+    #include "ant_interface.h"
+#elif defined(ANT_STACK_SUPPORT_REQD) 
+    #include "ant_interface.h"
+#elif defined(BLE_STACK_SUPPORT_REQD)
+    #include "nrf_ble.h"
+#endif
+
+#ifdef NRF51
+#define SOFTDEVICE_EVT_IRQ        SD_EVT_IRQn       /**< SoftDevice Event IRQ number. Used for both protocol events and SoC events. */
+#define SOFTDEVICE_EVT_IRQHandler SD_EVT_IRQHandler
+#elif defined (NRF52)
+#define SOFTDEVICE_EVT_IRQ        SWI2_EGU2_IRQn
+#define SOFTDEVICE_EVT_IRQHandler SWI2_EGU2_IRQHandler
+#endif /* NRF51 */
+
+static softdevice_evt_schedule_func_t m_evt_schedule_func;              /**< Pointer to function for propagating SoftDevice events to the scheduler. */
+
+static volatile bool                  m_softdevice_enabled = false;     /**< Variable to indicate whether the SoftDevice is enabled. */
+
+#ifdef BLE_STACK_SUPPORT_REQD
+// The following three definitions is needed only if BLE events are needed to be pulled from the stack.
+static uint8_t                      * mp_ble_evt_buffer;                /**< Buffer for receiving BLE events from the SoftDevice. */
+static uint16_t                       m_ble_evt_buffer_size;            /**< Size of BLE event buffer. */
+static ble_evt_handler_t              m_ble_evt_handler;                /**< Application event handler for handling BLE events. */
+#endif
+
+#ifdef ANT_STACK_SUPPORT_REQD
+// The following two definition is needed only if ANT events are needed to be pulled from the stack.
+static ant_evt_t                      m_ant_evt_buffer;                 /**< Buffer for receiving ANT events from the SoftDevice. */
+static ant_evt_handler_t              m_ant_evt_handler;                /**< Application event handler for handling ANT events.  */
+#endif
+
+static sys_evt_handler_t              m_sys_evt_handler;                /**< Application event handler for handling System (SOC) events.  */
+
+
+/**@brief       Callback function for asserts in the SoftDevice.
+ *
+ * @details     A pointer to this function will be passed to the SoftDevice. This function will be
+ *              called if an ASSERT statement in the SoftDevice fails.
+ *
+ * @param[in]   pc         The value of the program counter when the ASSERT call failed.
+ * @param[in]   line_num   Line number of the failing ASSERT call.
+ * @param[in]   file_name  File name of the failing ASSERT call.
+ */
+void softdevice_assertion_handler(uint32_t pc, uint16_t line_num, const uint8_t * file_name)
+{
+    UNUSED_PARAMETER(pc);
+    assert_nrf_callback(line_num, file_name);
+}
+
+
+void intern_softdevice_events_execute(void)
+{
+    if (!m_softdevice_enabled)
+    {
+        // SoftDevice not enabled. This can be possible if the SoftDevice was enabled by the
+        // application without using this module's API (i.e softdevice_handler_init)
+
+        return;
+    }
+
+    bool no_more_soc_evts = (m_sys_evt_handler == NULL);
+#ifdef BLE_STACK_SUPPORT_REQD
+    bool no_more_ble_evts = (m_ble_evt_handler == NULL);
+#endif
+#ifdef ANT_STACK_SUPPORT_REQD
+    bool no_more_ant_evts = (m_ant_evt_handler == NULL);
+#endif
+
+    for (;;)
+    {
+        uint32_t err_code;
+
+        if (!no_more_soc_evts)
+        {
+            uint32_t evt_id;
+
+            // Pull event from SOC.
+            err_code = sd_evt_get(&evt_id);
+            
+            if (err_code == NRF_ERROR_NOT_FOUND)
+            {
+                no_more_soc_evts = true;
+            }
+            else if (err_code != NRF_SUCCESS)
+            {
+                APP_ERROR_HANDLER(err_code);
+            }
+            else
+            {
+                // Call application's SOC event handler.
+                m_sys_evt_handler(evt_id);
+            }
+        }
+
+#ifdef BLE_STACK_SUPPORT_REQD
+        // Fetch BLE Events.
+        if (!no_more_ble_evts)
+        {
+            // Pull event from stack
+            uint16_t evt_len = m_ble_evt_buffer_size;
+
+            err_code = sd_ble_evt_get(mp_ble_evt_buffer, &evt_len);
+            if (err_code == NRF_ERROR_NOT_FOUND)
+            {
+                no_more_ble_evts = true;
+            }
+            else if (err_code != NRF_SUCCESS)
+            {
+                APP_ERROR_HANDLER(err_code);
+            }
+            else
+            {
+                // Call application's BLE stack event handler.
+                m_ble_evt_handler((ble_evt_t *)mp_ble_evt_buffer);
+            }
+        }
+#endif
+
+#ifdef ANT_STACK_SUPPORT_REQD
+        // Fetch ANT Events.
+        if (!no_more_ant_evts)
+        {
+            // Pull event from stack
+            err_code = sd_ant_event_get(&m_ant_evt_buffer.channel,
+                                        &m_ant_evt_buffer.event,
+                                        m_ant_evt_buffer.evt_buffer);
+            if (err_code == NRF_ERROR_NOT_FOUND)
+            {
+                no_more_ant_evts = true;
+            }
+            else if (err_code != NRF_SUCCESS)
+            {
+                APP_ERROR_HANDLER(err_code);
+            }
+            else
+            {
+                // Call application's ANT stack event handler.
+                m_ant_evt_handler(&m_ant_evt_buffer);
+            }
+        }
+#endif
+
+        if (no_more_soc_evts)
+        {
+            // There are no remaining System (SOC) events to be fetched from the SoftDevice.
+#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD)
+            // Check if there are any remaining BLE and ANT events.
+            if (no_more_ble_evts && no_more_ant_evts)
+            {
+                break;
+            }
+#elif defined(BLE_STACK_SUPPORT_REQD)
+            // Check if there are any remaining BLE events.
+            if (no_more_ble_evts)
+            {
+                break;
+            }
+#elif defined(ANT_STACK_SUPPORT_REQD)
+            // Check if there are any remaining ANT events.
+            if (no_more_ant_evts)
+            {
+                break;
+            }
+#else
+            // No need to check for BLE or ANT events since there is no support for BLE and ANT
+            // required.
+            break;
+#endif
+        }
+    }
+}
+
+bool softdevice_handler_isEnabled(void)
+{
+    return m_softdevice_enabled;
+}
+
+uint32_t softdevice_handler_init(nrf_clock_lfclksrc_t           clock_source,
+                                 void *                         p_ble_evt_buffer,
+                                 uint16_t                       ble_evt_buffer_size,
+                                 softdevice_evt_schedule_func_t evt_schedule_func)
+{
+    uint32_t err_code;
+
+    // Save configuration.
+#if defined (BLE_STACK_SUPPORT_REQD)
+    // Check that buffer is not NULL.
+    if (p_ble_evt_buffer == NULL)
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+    
+    // Check that buffer is correctly aligned.
+    if (!is_word_aligned(p_ble_evt_buffer))
+    {
+        return NRF_ERROR_INVALID_PARAM;
+    }
+
+    mp_ble_evt_buffer     = (uint8_t *)p_ble_evt_buffer;
+    m_ble_evt_buffer_size = ble_evt_buffer_size;
+#else
+    // The variables p_ble_evt_buffer and ble_evt_buffer_size is not needed if BLE Stack support
+    // is not required.
+    UNUSED_PARAMETER(p_ble_evt_buffer);
+    UNUSED_PARAMETER(ble_evt_buffer_size);
+#endif
+
+    m_evt_schedule_func = evt_schedule_func;
+
+//Enabling FPU for SoftDevice
+#ifdef S132
+    SCB->CPACR |= (3UL << 20) | (3UL << 22);
+    __DSB();
+    __ISB();
+#endif
+    // Initialize SoftDevice.
+    err_code = sd_softdevice_enable(clock_source, softdevice_assertion_handler);
+    if (err_code != NRF_SUCCESS)
+    {
+        return err_code;
+    }
+#ifdef S132
+    SCB->CPACR = 0;
+    __DSB();
+    __ISB();
+#endif
+
+    m_softdevice_enabled = true;
+
+    // Enable BLE event interrupt (interrupt priority has already been set by the stack).
+    return sd_nvic_EnableIRQ(SOFTDEVICE_EVT_IRQ);
+}
+
+
+uint32_t softdevice_handler_sd_disable(void)
+{
+    uint32_t err_code = sd_softdevice_disable();
+ 
+    m_softdevice_enabled = !(err_code == NRF_SUCCESS);
+
+    return err_code;
+}
+
+
+#ifdef BLE_STACK_SUPPORT_REQD
+uint32_t softdevice_ble_evt_handler_set(ble_evt_handler_t ble_evt_handler)
+{
+    if (ble_evt_handler == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    m_ble_evt_handler = ble_evt_handler;
+
+    return NRF_SUCCESS;
+}
+#endif
+
+
+#ifdef ANT_STACK_SUPPORT_REQD
+uint32_t softdevice_ant_evt_handler_set(ant_evt_handler_t ant_evt_handler)
+{
+    if (ant_evt_handler == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    m_ant_evt_handler = ant_evt_handler;
+
+    return NRF_SUCCESS;
+}
+#endif
+
+
+uint32_t softdevice_sys_evt_handler_set(sys_evt_handler_t sys_evt_handler)
+{
+    if (sys_evt_handler == NULL)
+    {
+        return NRF_ERROR_NULL;
+    }
+
+    m_sys_evt_handler = sys_evt_handler;
+
+    return NRF_SUCCESS;
+}
+
+
+/**@brief   Function for handling the Application's BLE Stack events interrupt.
+ *
+ * @details This function is called whenever an event is ready to be pulled.
+ */
+void SOFTDEVICE_EVT_IRQHandler(void)
+{
+    if (m_evt_schedule_func != NULL)
+    {
+        uint32_t err_code = m_evt_schedule_func();
+        APP_ERROR_CHECK(err_code);
+    }
+    else
+    {
+        intern_softdevice_events_execute();
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @file
+ *
+ * @defgroup softdevice_handler SoftDevice Event Handler
+ * @{
+ * @ingroup  app_common
+ * @brief    API for initializing and disabling the SoftDevice
+ *
+ * @details  This API contains the functions and defines exposed by the @ref lib_softdevice_handler.
+ *           For more information on the library and how the application should use it, please refer
+ *           @ref lib_softdevice_handler.
+ *
+ * @note     Use the USE_SCHEDULER parameter of the SOFTDEVICE_HANDLER_INIT() macro to select if
+ *           the @ref app_scheduler is to be used or not.
+ *
+ * @note     Even if the scheduler is not used, softdevice_handler.h will include app_scheduler.h.
+ *           So when compiling, app_scheduler.h must be available in one of the compiler include
+ *           paths.
+ */
+
+#ifndef SOFTDEVICE_HANDLER_H__
+#define SOFTDEVICE_HANDLER_H__
+
+#include <stdlib.h>
+#include "nordic_common.h"
+#include "nrf_sdm.h"
+#include "app_error.h"
+#include "app_util.h"
+#include "ble_stack_handler_types.h"
+#include "ant_stack_handler_types.h"
+
+#define SOFTDEVICE_SCHED_EVT_SIZE       0                                                 /**< Size of button events being passed through the scheduler (is to be used for computing the maximum size of scheduler events). For SoftDevice events, this size is 0, since the events are being pulled in the event handler. */
+#define SYS_EVT_MSG_BUF_SIZE            sizeof(uint32_t)                                  /**< Size of System (SOC) event message buffer. */
+
+/**@brief Type of function for passing events from the stack handler module to the scheduler. */
+typedef uint32_t (*softdevice_evt_schedule_func_t) (void);
+
+/**@brief Application System (SOC) event handler type. */
+typedef void (*sys_evt_handler_t) (uint32_t evt_id);
+
+
+/**@brief     Macro for initializing the stack event handler.
+ *
+ * @details   It will handle dimensioning and allocation of the memory buffer required for reading
+ *            events from the stack, making sure the buffer is correctly aligned. It will also
+ *            connect the stack event handler to the scheduler/RTOS (if specified).
+ *
+ * @param[in] CLOCK_SOURCE     Low frequency clock source and accuracy (type nrf_clock_lfclksrc_t,
+ *                             see sd_softdevice_enable() for details).
+ * @param[in] EVT_HANDLER      scheduler/RTOS event handler function.
+ *
+ * @note      Since this macro allocates a buffer, it must only be called once (it is OK to call it
+ *            several times as long as it is from the same location, that is to do a
+ *            reinitialization).
+ */
+/*lint -emacro(506, SOFTDEVICE_HANDLER_INIT) */ /* Suppress "Constant value Boolean */
+#define SOFTDEVICE_HANDLER_INIT(CLOCK_SOURCE,                                                      \
+                                EVT_HANDLER)                                                     \
+    do                                                                                             \
+    {                                                                                              \
+        static uint32_t BLE_EVT_BUFFER[CEIL_DIV(BLE_STACK_EVT_MSG_BUF_SIZE, sizeof(uint32_t))];    \
+        uint32_t ERR_CODE;                                                                         \
+        ERR_CODE = softdevice_handler_init((CLOCK_SOURCE),                                         \
+                                           BLE_EVT_BUFFER,                                         \
+                                           sizeof(BLE_EVT_BUFFER),                                 \
+                                           EVT_HANDLER);      \
+        APP_ERROR_CHECK(ERR_CODE);                                                                 \
+    } while (0)
+
+/**
+ * @brief Function for retrieving the information about SD state
+ *
+ * The information about current state of softdevice.
+ * @retval false SD is not initialized and SD commands should not be called.
+ * @retval true  SD is already initialized
+ */
+bool softdevice_handler_isEnabled(void);
+
+/**@brief      Function for initializing the stack handler module.
+ *
+ * @details    Enables the SoftDevice and the stack event interrupt handler.
+ *
+ * @note       This function must be called before calling any function in the SoftDevice API.
+ *
+ * @note       Normally initialization should be done using the SOFTDEVICE_HANDLER_INIT() macro,
+ *             as that will both allocate the event buffer, and also align the buffer correctly.
+ *
+ * @param[in]  clock_source        Low frequency clock source to be used by the SoftDevice.
+ * @param[in]  p_ble_evt_buffer    Buffer for holding one BLE stack event. Since heap is not being
+ *                                 used, this buffer must be provided by the application. The
+ *                                 buffer must be large enough to hold the biggest stack event the
+ *                                 application is supposed to handle. The buffer must be aligned to
+ *                                 a 4 byte boundary. This parameter is unused if BLE stack support 
+ *                                 is not required.
+ * @param[in]  ble_evt_buffer_size Size of SoftDevice BLE event buffer. This parameter is unused if
+ *                                 BLE stack support is not required.
+ * @param[in]  evt_schedule_func   Function for passing events to the scheduler. Point to
+ *                                 ble_ant_stack_evt_schedule() to connect to the scheduler.
+ *                                 Set to NULL to make the stack handler module call the event
+ *                                 handler directly from the stack event interrupt handler.
+ *
+ * @retval     NRF_SUCCESS               Successful initialization.
+ * @retval     NRF_ERROR_INVALID_PARAM   Invalid parameter (buffer not aligned to a 4 byte
+ *                                       boundary) or NULL.
+ */
+uint32_t softdevice_handler_init(nrf_clock_lfclksrc_t              clock_source,
+                                 void *                            p_ble_evt_buffer,
+                                 uint16_t                          ble_evt_buffer_size,
+                                 softdevice_evt_schedule_func_t    evt_schedule_func);
+
+
+/**@brief     Function for disabling the SoftDevice.
+ *
+ * @details   This function will disable the SoftDevice. It will also update the internal state
+ *            of this module.
+ */
+uint32_t softdevice_handler_sd_disable(void);
+
+
+/**@brief     Function for registering for System (SOC) events.
+ *
+ * @details   The application should use this function to register for receiving System (SOC)
+ *            events from the SoftDevice. If the application does not call this function, then any
+ *            System (SOC) events that may be generated by the SoftDevice will NOT be fetched. Once
+ *            the application has registered for the events, it is not possible to  possible to
+ *            cancel the registration. However, it is possible to register a different function for
+ *            handling the events at any point of time.
+ *
+ * @param[in] sys_evt_handler Function to be called for each received System (SOC) event.
+ *
+ * @retval    NRF_SUCCESS     Successful registration.
+ * @retval    NRF_ERROR_NULL  Null pointer provided as input.
+ */
+uint32_t softdevice_sys_evt_handler_set(sys_evt_handler_t sys_evt_handler);
+
+
+// Functions for connecting the Stack Event Handler to the scheduler:
+/**@cond NO_DOXYGEN */
+void intern_softdevice_events_execute(void);
+
+
+/**@endcond */
+
+#endif // SOFTDEVICE_HANDLER_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.c	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "softdevice_handler_appsh.h"
+#include "app_scheduler.h"
+#include <string.h>
+
+void softdevice_evt_get(void * p_event_data, uint16_t event_size)
+{
+    APP_ERROR_CHECK_BOOL(event_size == 0);
+    intern_softdevice_events_execute();
+}
+
+uint32_t softdevice_evt_schedule(void)
+{
+    return app_sched_event_put(NULL, 0, softdevice_evt_get);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/common/softdevice_handler/softdevice_handler_appsh.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SOFTDEVICE_HANDLER_APPSH_H
+#define SOFTDEVICE_HANDLER_APPSH_H
+
+#include "softdevice_handler.h"
+#include <stdint.h>
+
+#define SOFTDEVICE_HANDLER_APPSH_INIT(CLOCK_SOURCE,USE_SCHEDULER) \
+    SOFTDEVICE_HANDLER_INIT(CLOCK_SOURCE,(USE_SCHEDULER) ? softdevice_evt_schedule : NULL)
+
+uint32_t softdevice_evt_schedule(void);
+
+#endif //SOFTDEVICE_HANDLER_APPSH_H
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_err.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_err.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_COMMON
+  @{
+  @addtogroup  nrf_error
+  @{
+    @ingroup BLE_COMMON
+  @}
+
+  @defgroup ble_err General error codes
+  @{
+
+  @brief General error code definitions for the BLE API.
+
+  @ingroup BLE_COMMON
+*/
+#ifndef NRF_BLE_ERR_H__
+#define NRF_BLE_ERR_H__
+
+#include "nrf_error.h"
+
+/* @defgroup BLE_ERRORS Error Codes
+ * @{ */
+#define BLE_ERROR_NOT_ENABLED            (NRF_ERROR_STK_BASE_NUM+0x001) /**< @ref sd_ble_enable has not been called. */
+#define BLE_ERROR_INVALID_CONN_HANDLE    (NRF_ERROR_STK_BASE_NUM+0x002) /**< Invalid connection handle. */
+#define BLE_ERROR_INVALID_ATTR_HANDLE    (NRF_ERROR_STK_BASE_NUM+0x003) /**< Invalid attribute handle. */
+#define BLE_ERROR_NO_TX_BUFFERS          (NRF_ERROR_STK_BASE_NUM+0x004) /**< Buffer capacity exceeded. */
+#define BLE_ERROR_INVALID_ROLE           (NRF_ERROR_STK_BASE_NUM+0x005) /**< Invalid role. */
+/** @} */
+
+
+/** @defgroup BLE_ERROR_SUBRANGES Module specific error code subranges
+ *  @brief Assignment of subranges for module specific error codes.
+ *  @note For specific error codes, see ble_<module>.h or ble_error_<module>.h.
+ * @{ */
+#define NRF_L2CAP_ERR_BASE             (NRF_ERROR_STK_BASE_NUM+0x100) /**< L2CAP specific errors. */
+#define NRF_GAP_ERR_BASE               (NRF_ERROR_STK_BASE_NUM+0x200) /**< GAP specific errors. */
+#define NRF_GATTC_ERR_BASE             (NRF_ERROR_STK_BASE_NUM+0x300) /**< GATT client specific errors. */
+#define NRF_GATTS_ERR_BASE             (NRF_ERROR_STK_BASE_NUM+0x400) /**< GATT server specific errors. */
+/** @} */
+
+#endif
+
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,1362 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_GAP Generic Access Profile (GAP)
+  @{
+  @brief Definitions and prototypes for the GAP interface.
+ */
+
+#ifndef BLE_GAP_H__
+#define BLE_GAP_H__
+
+#include "ble_types.h"
+#include "ble_ranges.h"
+#include "nrf_svc.h"
+
+/**@addtogroup BLE_GAP_ENUMERATIONS Enumerations
+ * @{ */
+
+/**@brief GAP API SVC numbers.
+ */
+enum BLE_GAP_SVCS
+{
+  SD_BLE_GAP_ADDRESS_SET  = BLE_GAP_SVC_BASE,  /**< Set own Bluetooth Address. */
+  SD_BLE_GAP_ADDRESS_GET,                      /**< Get own Bluetooth Address. */
+  SD_BLE_GAP_ADV_DATA_SET,                     /**< Set Advertising Data. */
+  SD_BLE_GAP_ADV_START,                        /**< Start Advertising. */
+  SD_BLE_GAP_ADV_STOP,                         /**< Stop Advertising. */
+  SD_BLE_GAP_CONN_PARAM_UPDATE,                /**< Connection Parameter Update. */
+  SD_BLE_GAP_DISCONNECT,                       /**< Disconnect. */
+  SD_BLE_GAP_TX_POWER_SET,                     /**< Set TX Power. */
+  SD_BLE_GAP_APPEARANCE_SET,                   /**< Set Appearance. */
+  SD_BLE_GAP_APPEARANCE_GET,                   /**< Get Appearance. */
+  SD_BLE_GAP_PPCP_SET,                         /**< Set PPCP. */
+  SD_BLE_GAP_PPCP_GET,                         /**< Get PPCP. */
+  SD_BLE_GAP_DEVICE_NAME_SET,                  /**< Set Device Name. */
+  SD_BLE_GAP_DEVICE_NAME_GET,                  /**< Get Device Name. */
+  SD_BLE_GAP_AUTHENTICATE,                     /**< Initiate Pairing/Bonding. */
+  SD_BLE_GAP_SEC_PARAMS_REPLY,                 /**< Reply with Security Parameters. */
+  SD_BLE_GAP_AUTH_KEY_REPLY,                   /**< Reply with an authentication key. */
+  SD_BLE_GAP_ENCRYPT,                          /**< Initiate encryption procedure. */
+  SD_BLE_GAP_SEC_INFO_REPLY,                   /**< Reply with Security Information. */
+  SD_BLE_GAP_CONN_SEC_GET,                     /**< Obtain connection security level. */
+  SD_BLE_GAP_RSSI_START,                       /**< Start reporting of changes in RSSI. */ 
+  SD_BLE_GAP_RSSI_STOP,                        /**< Stop reporting of changes in RSSI. */ 
+  SD_BLE_GAP_SCAN_START,                       /**< Start Scanning. */
+  SD_BLE_GAP_SCAN_STOP,                        /**< Stop Scanning. */
+  SD_BLE_GAP_CONNECT,                          /**< Connect. */
+  SD_BLE_GAP_CONNECT_CANCEL,                   /**< Cancel ongoing connection procedure. */
+  SD_BLE_GAP_RSSI_GET,                         /**< Get the last RSSI sample. */
+};
+
+/**@brief GAP Event IDs.
+ * IDs that uniquely identify an event coming from the stack to the application.
+ */
+enum BLE_GAP_EVTS
+{
+  BLE_GAP_EVT_CONNECTED  = BLE_GAP_EVT_BASE,    /**< Connection established. @ref ble_gap_evt_connected_t */
+  BLE_GAP_EVT_DISCONNECTED,                     /**< Disconnected from peer. @ref ble_gap_evt_disconnected_t */
+  BLE_GAP_EVT_CONN_PARAM_UPDATE,                /**< Connection Parameters updated. ble_gap_evt_conn_param_update_t */
+  BLE_GAP_EVT_SEC_PARAMS_REQUEST,               /**< Request to provide security parameters. @ref ble_gap_evt_sec_params_request_t */
+  BLE_GAP_EVT_SEC_INFO_REQUEST,                 /**< Request to provide security information. @ref ble_gap_evt_sec_info_request_t */
+  BLE_GAP_EVT_PASSKEY_DISPLAY,                  /**< Request to display a passkey to the user. @ref ble_gap_evt_passkey_display_t */
+  BLE_GAP_EVT_AUTH_KEY_REQUEST,                 /**< Request to provide an authentication key. @ref ble_gap_evt_auth_key_request_t */
+  BLE_GAP_EVT_AUTH_STATUS,                      /**< Authentication procedure completed with status. @ref ble_gap_evt_auth_status_t */
+  BLE_GAP_EVT_CONN_SEC_UPDATE,                  /**< Connection security updated. @ref ble_gap_evt_conn_sec_update_t */
+  BLE_GAP_EVT_TIMEOUT,                          /**< Timeout expired. @ref ble_gap_evt_timeout_t */
+  BLE_GAP_EVT_RSSI_CHANGED,                     /**< RSSI report. @ref ble_gap_evt_rssi_changed_t */
+  BLE_GAP_EVT_ADV_REPORT,                       /**< Advertising report. @ref ble_gap_evt_adv_report_t */
+  BLE_GAP_EVT_SEC_REQUEST,                      /**< Security Request. @ref ble_gap_evt_sec_request_t */
+  BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST,        /**< Connection Parameter Update Request. @ref ble_gap_evt_conn_param_update_request_t */
+  BLE_GAP_EVT_SCAN_REQ_REPORT,                  /**< Scan request report. @ref ble_gap_evt_scan_req_report_t */
+};
+
+/**@brief GAP Option IDs.
+ * IDs that uniquely identify a GAP option.
+ */
+enum BLE_GAP_OPTS
+{
+  BLE_GAP_OPT_CH_MAP  = BLE_GAP_OPT_BASE,       /**< Channel Map. @ref ble_gap_opt_ch_map_t  */
+  BLE_GAP_OPT_LOCAL_CONN_LATENCY,               /**< Local connection latency. @ref ble_gap_opt_local_conn_latency_t */
+  BLE_GAP_OPT_PASSKEY,                          /**< Set passkey. @ref ble_gap_opt_passkey_t */
+  BLE_GAP_OPT_PRIVACY,                          /**< Custom privacy. @ref ble_gap_opt_privacy_t */
+  BLE_GAP_OPT_SCAN_REQ_REPORT,                  /**< Scan request report. @ref ble_gap_opt_scan_req_report_t */
+  BLE_GAP_OPT_COMPAT_MODE                       /**< Compatibility mode. @ref ble_gap_opt_compat_mode_t */
+};
+/** @} */
+
+/**@addtogroup BLE_GAP_DEFINES Defines
+ * @{ */
+
+/**@defgroup BLE_ERRORS_GAP SVC return values specific to GAP
+ * @{ */
+#define BLE_ERROR_GAP_UUID_LIST_MISMATCH            (NRF_GAP_ERR_BASE + 0x000)  /**< UUID list does not contain an integral number of UUIDs. */
+#define BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST   (NRF_GAP_ERR_BASE + 0x001)  /**< Use of Whitelist not permitted with discoverable advertising. */
+#define BLE_ERROR_GAP_INVALID_BLE_ADDR              (NRF_GAP_ERR_BASE + 0x002)  /**< The upper two bits of the address do not correspond to the specified address type. */
+#define BLE_ERROR_GAP_WHITELIST_IN_USE              (NRF_GAP_ERR_BASE + 0x003)  /**< Attempt to overwrite the whitelist while already in use by another operation. */ 
+/**@} */
+
+
+/**@defgroup BLE_GAP_ROLES GAP Roles
+ * @note Not explicitly used in peripheral API, but will be relevant for central API.
+ * @{ */
+#define BLE_GAP_ROLE_INVALID     0x0            /**< Invalid Role. */
+#define BLE_GAP_ROLE_PERIPH      0x1            /**< Peripheral Role. */
+#define BLE_GAP_ROLE_CENTRAL     0x2            /**< Central Role. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_TIMEOUT_SOURCES GAP Timeout sources
+ * @{ */
+#define BLE_GAP_TIMEOUT_SRC_ADVERTISING                0x00 /**< Advertising timeout. */
+#define BLE_GAP_TIMEOUT_SRC_SECURITY_REQUEST           0x01 /**< Security request timeout. */
+#define BLE_GAP_TIMEOUT_SRC_SCAN                       0x02 /**< Scanning timeout. */
+#define BLE_GAP_TIMEOUT_SRC_CONN                       0x03 /**< Connection timeout. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_ADDR_TYPES GAP Address types
+ * @{ */
+#define BLE_GAP_ADDR_TYPE_PUBLIC                        0x00 /**< Public address. */
+#define BLE_GAP_ADDR_TYPE_RANDOM_STATIC                 0x01 /**< Random Static address. */
+#define BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE     0x02 /**< Private Resolvable address. */
+#define BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE 0x03 /**< Private Non-Resolvable address. */
+/**@} */
+
+/**@defgroup BLE_GAP_ADDR_CYCLE_MODES GAP Address cycle modes
+ * @{ */
+#define BLE_GAP_ADDR_CYCLE_MODE_NONE      0x00 /**< Set addresses directly, no automatic address cycling. */
+#define BLE_GAP_ADDR_CYCLE_MODE_AUTO      0x01 /**< Automatically generate and update private addresses. */
+/** @} */
+
+/**@brief The default interval in seconds at which a private address is refreshed when address cycle mode is @ref BLE_GAP_ADDR_CYCLE_MODE_AUTO.  */
+#define BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S (60 * 15)
+
+/** @brief BLE address length. */
+#define BLE_GAP_ADDR_LEN            6
+
+
+/**@defgroup BLE_GAP_AD_TYPE_DEFINITIONS GAP Advertising and Scan Response Data format
+ * @note Found at https://www.bluetooth.org/Technical/AssignedNumbers/generic_access_profile.htm
+ * @{ */
+#define BLE_GAP_AD_TYPE_FLAGS                               0x01 /**< Flags for discoverability. */
+#define BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE   0x02 /**< Partial list of 16 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE         0x03 /**< Complete list of 16 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE   0x04 /**< Partial list of 32 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_COMPLETE         0x05 /**< Complete list of 32 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE  0x06 /**< Partial list of 128 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE        0x07 /**< Complete list of 128 bit service UUIDs. */
+#define BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME                    0x08 /**< Short local device name. */
+#define BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME                 0x09 /**< Complete local device name. */
+#define BLE_GAP_AD_TYPE_TX_POWER_LEVEL                      0x0A /**< Transmit power level. */
+#define BLE_GAP_AD_TYPE_CLASS_OF_DEVICE                     0x0D /**< Class of device. */
+#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_HASH_C               0x0E /**< Simple Pairing Hash C. */
+#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_RANDOMIZER_R         0x0F /**< Simple Pairing Randomizer R. */
+#define BLE_GAP_AD_TYPE_SECURITY_MANAGER_TK_VALUE           0x10 /**< Security Manager TK Value. */
+#define BLE_GAP_AD_TYPE_SECURITY_MANAGER_OOB_FLAGS          0x11 /**< Security Manager Out Of Band Flags. */
+#define BLE_GAP_AD_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE     0x12 /**< Slave Connection Interval Range. */
+#define BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_16BIT       0x14 /**< List of 16-bit Service Solicitation UUIDs. */
+#define BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_128BIT      0x15 /**< List of 128-bit Service Solicitation UUIDs. */
+#define BLE_GAP_AD_TYPE_SERVICE_DATA                        0x16 /**< Service Data - 16-bit UUID. */
+#define BLE_GAP_AD_TYPE_PUBLIC_TARGET_ADDRESS               0x17 /**< Public Target Address. */
+#define BLE_GAP_AD_TYPE_RANDOM_TARGET_ADDRESS               0x18 /**< Random Target Address. */
+#define BLE_GAP_AD_TYPE_APPEARANCE                          0x19 /**< Appearance. */
+#define BLE_GAP_AD_TYPE_ADVERTISING_INTERVAL                0x1A /**< Advertising Interval. */ 
+#define BLE_GAP_AD_TYPE_LE_BLUETOOTH_DEVICE_ADDRESS         0x1B /**< LE Bluetooth Device Address. */
+#define BLE_GAP_AD_TYPE_LE_ROLE                             0x1C /**< LE Role. */
+#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_HASH_C256            0x1D /**< Simple Pairing Hash C-256. */
+#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_RANDOMIZER_R256      0x1E /**< Simple Pairing Randomizer R-256. */
+#define BLE_GAP_AD_TYPE_SERVICE_DATA_32BIT_UUID             0x20 /**< Service Data - 32-bit UUID. */
+#define BLE_GAP_AD_TYPE_SERVICE_DATA_128BIT_UUID            0x21 /**< Service Data - 128-bit UUID. */
+#define BLE_GAP_AD_TYPE_3D_INFORMATION_DATA                 0x3D /**< 3D Information Data. */
+#define BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA          0xFF /**< Manufacturer Specific Data. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_ADV_FLAGS GAP Advertisement Flags
+ * @{ */
+#define BLE_GAP_ADV_FLAG_LE_LIMITED_DISC_MODE         (0x01)   /**< LE Limited Discoverable Mode. */
+#define BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE         (0x02)   /**< LE General Discoverable Mode. */
+#define BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED         (0x04)   /**< BR/EDR not supported. */
+#define BLE_GAP_ADV_FLAG_LE_BR_EDR_CONTROLLER         (0x08)   /**< Simultaneous LE and BR/EDR, Controller. */
+#define BLE_GAP_ADV_FLAG_LE_BR_EDR_HOST               (0x10)   /**< Simultaneous LE and BR/EDR, Host. */
+#define BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE   (BLE_GAP_ADV_FLAG_LE_LIMITED_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED)   /**< LE Limited Discoverable Mode, BR/EDR not supported. */
+#define BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE   (BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED)   /**< LE General Discoverable Mode, BR/EDR not supported. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_ADV_INTERVALS GAP Advertising interval max and min
+ * @{ */
+#define BLE_GAP_ADV_INTERVAL_MIN        0x0020 /**< Minimum Advertising interval in 625 us units, i.e. 20 ms. */
+#define BLE_GAP_ADV_NONCON_INTERVAL_MIN 0x00A0 /**< Minimum Advertising interval in 625 us units for non connectable mode, i.e. 100 ms. */
+#define BLE_GAP_ADV_INTERVAL_MAX        0x4000 /**< Maximum Advertising interval in 625 us units, i.e. 10.24 s. */
+ /**@}  */
+
+
+/**@defgroup BLE_GAP_SCAN_INTERVALS GAP Scan interval max and min
+ * @{ */
+#define BLE_GAP_SCAN_INTERVAL_MIN       0x0004 /**< Minimum Scan interval in 625 us units, i.e. 2.5 ms. */
+#define BLE_GAP_SCAN_INTERVAL_MAX       0x4000 /**< Maximum Scan interval in 625 us units, i.e. 10.24 s. */
+ /** @}  */
+
+
+/**@defgroup BLE_GAP_SCAN_WINDOW GAP Scan window max and min
+ * @{ */
+#define BLE_GAP_SCAN_WINDOW_MIN         0x0004 /**< Minimum Scan window in 625 us units, i.e. 2.5 ms. */
+#define BLE_GAP_SCAN_WINDOW_MAX         0x4000 /**< Maximum Scan window in 625 us units, i.e. 10.24 s. */
+ /** @}  */
+
+
+/**@defgroup BLE_GAP_SCAN_TIMEOUT GAP Scan timeout max and min
+ * @{ */
+#define BLE_GAP_SCAN_TIMEOUT_MIN        0x0001 /**< Minimum Scan timeout in seconds. */
+#define BLE_GAP_SCAN_TIMEOUT_MAX        0xFFFF /**< Maximum Scan timeout in seconds. */
+ /** @}  */
+
+
+/**@brief Maximum size of advertising data in octets. */
+#define  BLE_GAP_ADV_MAX_SIZE           31
+
+
+/**@defgroup BLE_GAP_ADV_TYPES GAP Advertising types
+ * @{ */
+#define BLE_GAP_ADV_TYPE_ADV_IND          0x00   /**< Connectable undirected. */
+#define BLE_GAP_ADV_TYPE_ADV_DIRECT_IND   0x01   /**< Connectable directed. */
+#define BLE_GAP_ADV_TYPE_ADV_SCAN_IND     0x02   /**< Scannable undirected. */
+#define BLE_GAP_ADV_TYPE_ADV_NONCONN_IND  0x03   /**< Non connectable undirected. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_ADV_FILTER_POLICIES GAP Advertising filter policies
+ * @{ */
+#define BLE_GAP_ADV_FP_ANY                0x00   /**< Allow scan requests and connect requests from any device. */
+#define BLE_GAP_ADV_FP_FILTER_SCANREQ     0x01   /**< Filter scan requests with whitelist. */
+#define BLE_GAP_ADV_FP_FILTER_CONNREQ     0x02   /**< Filter connect requests with whitelist. */
+#define BLE_GAP_ADV_FP_FILTER_BOTH        0x03   /**< Filter both scan and connect requests with whitelist. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_ADV_TIMEOUT_VALUES GAP Advertising timeout values
+ * @{ */
+#define BLE_GAP_ADV_TIMEOUT_LIMITED_MAX      180 /**< Maximum advertising time in limited discoverable mode (TGAP(lim_adv_timeout) = 180s). */
+#define BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED  0 /**< Unlimited advertising in general discoverable mode. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_DISC_MODES GAP Discovery modes
+ * @{ */
+#define BLE_GAP_DISC_MODE_NOT_DISCOVERABLE  0x00   /**< Not discoverable discovery Mode. */
+#define BLE_GAP_DISC_MODE_LIMITED           0x01   /**< Limited Discovery Mode. */
+#define BLE_GAP_DISC_MODE_GENERAL           0x02   /**< General Discovery Mode. */
+/**@} */
+
+/**@defgroup BLE_GAP_IO_CAPS GAP IO Capabilities
+ * @{ */
+#define BLE_GAP_IO_CAPS_DISPLAY_ONLY      0x00   /**< Display Only. */
+#define BLE_GAP_IO_CAPS_DISPLAY_YESNO     0x01   /**< Display and Yes/No entry. */
+#define BLE_GAP_IO_CAPS_KEYBOARD_ONLY     0x02   /**< Keyboard Only. */
+#define BLE_GAP_IO_CAPS_NONE              0x03   /**< No I/O capabilities. */
+#define BLE_GAP_IO_CAPS_KEYBOARD_DISPLAY  0x04   /**< Keyboard and Display. */
+/**@} */
+
+
+/**@defgroup BLE_GAP_AUTH_KEY_TYPES GAP Authentication Key Types
+ * @{ */
+#define BLE_GAP_AUTH_KEY_TYPE_NONE        0x00   /**< No key (may be used to reject). */
+#define BLE_GAP_AUTH_KEY_TYPE_PASSKEY     0x01   /**< 6-digit Passkey. */
+#define BLE_GAP_AUTH_KEY_TYPE_OOB         0x02   /**< Out Of Band data. */
+/**@} */
+
+/**@defgroup BLE_GAP_SEC_STATUS GAP Security status
+ * @{ */
+#define BLE_GAP_SEC_STATUS_SUCCESS                0x00  /**< Procedure completed with success. */
+#define BLE_GAP_SEC_STATUS_TIMEOUT                0x01  /**< Procedure timed out. */
+#define BLE_GAP_SEC_STATUS_PDU_INVALID            0x02  /**< Invalid PDU received. */
+#define BLE_GAP_SEC_STATUS_RFU_RANGE1_BEGIN       0x03  /**< Reserved for Future Use range #1 begin. */
+#define BLE_GAP_SEC_STATUS_RFU_RANGE1_END         0x80  /**< Reserved for Future Use range #1 end. */
+#define BLE_GAP_SEC_STATUS_PASSKEY_ENTRY_FAILED   0x81  /**< Passkey entry failed (user cancelled or other). */
+#define BLE_GAP_SEC_STATUS_OOB_NOT_AVAILABLE      0x82  /**< Out of Band Key not available. */
+#define BLE_GAP_SEC_STATUS_AUTH_REQ               0x83  /**< Authentication requirements not met. */
+#define BLE_GAP_SEC_STATUS_CONFIRM_VALUE          0x84  /**< Confirm value failed. */
+#define BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP       0x85  /**< Pairing not supported.  */
+#define BLE_GAP_SEC_STATUS_ENC_KEY_SIZE           0x86  /**< Encryption key size. */
+#define BLE_GAP_SEC_STATUS_SMP_CMD_UNSUPPORTED    0x87  /**< Unsupported SMP command. */
+#define BLE_GAP_SEC_STATUS_UNSPECIFIED            0x88  /**< Unspecified reason. */
+#define BLE_GAP_SEC_STATUS_REPEATED_ATTEMPTS      0x89  /**< Too little time elapsed since last attempt. */
+#define BLE_GAP_SEC_STATUS_INVALID_PARAMS         0x8A  /**< Invalid parameters. */
+#define BLE_GAP_SEC_STATUS_RFU_RANGE2_BEGIN       0x8B  /**< Reserved for Future Use range #2 begin. */
+#define BLE_GAP_SEC_STATUS_RFU_RANGE2_END         0xFF  /**< Reserved for Future Use range #2 end. */
+/**@} */
+
+/**@defgroup BLE_GAP_SEC_STATUS_SOURCES GAP Security status sources
+ * @{ */
+#define BLE_GAP_SEC_STATUS_SOURCE_LOCAL           0x00  /**< Local failure. */
+#define BLE_GAP_SEC_STATUS_SOURCE_REMOTE          0x01  /**< Remote failure. */
+/**@} */
+
+/**@defgroup BLE_GAP_CP_LIMITS GAP Connection Parameters Limits
+ * @{ */
+#define BLE_GAP_CP_MIN_CONN_INTVL_NONE           0xFFFF  /**< No new minimum connction interval specified in connect parameters. */
+#define BLE_GAP_CP_MIN_CONN_INTVL_MIN            0x0006  /**< Lowest mimimum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */
+#define BLE_GAP_CP_MIN_CONN_INTVL_MAX            0x0C80  /**< Highest minimum connection interval permitted, in units of 1.25 ms, i.e. 4 s. */
+#define BLE_GAP_CP_MAX_CONN_INTVL_NONE           0xFFFF  /**< No new maximum connction interval specified in connect parameters. */
+#define BLE_GAP_CP_MAX_CONN_INTVL_MIN            0x0006  /**< Lowest maximum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */
+#define BLE_GAP_CP_MAX_CONN_INTVL_MAX            0x0C80  /**< Highest maximum connection interval permitted, in units of 1.25 ms, i.e. 4 s. */
+#define BLE_GAP_CP_SLAVE_LATENCY_MAX             0x01F3  /**< Highest slave latency permitted, in connection events. */
+#define BLE_GAP_CP_CONN_SUP_TIMEOUT_NONE         0xFFFF  /**< No new supervision timeout specified in connect parameters. */
+#define BLE_GAP_CP_CONN_SUP_TIMEOUT_MIN          0x000A  /**< Lowest supervision timeout permitted, in units of 10 ms, i.e. 100 ms. */
+#define BLE_GAP_CP_CONN_SUP_TIMEOUT_MAX          0x0C80  /**< Highest supervision timeout permitted, in units of 10 ms, i.e. 32 s. */
+/**@} */
+
+
+/**@brief GAP device name maximum length. */
+#define BLE_GAP_DEVNAME_MAX_LEN           31
+
+/**@brief Disable RSSI events for connections */
+#define BLE_GAP_RSSI_THRESHOLD_INVALID    0xFF
+
+/**@defgroup BLE_GAP_CONN_SEC_MODE_SET_MACROS GAP attribute security requirement setters
+ *
+ * See @ref ble_gap_conn_sec_mode_t.
+ * @{ */
+/**@brief Set sec_mode pointed to by ptr to have no access rights.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr)         do {(ptr)->sm = 0; (ptr)->lv = 0;} while(0)
+/**@brief Set sec_mode pointed to by ptr to require no protection, open link.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr)              do {(ptr)->sm = 1; (ptr)->lv = 1;} while(0)
+/**@brief Set sec_mode pointed to by ptr to require encryption, but no MITM protection.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr)       do {(ptr)->sm = 1; (ptr)->lv = 2;} while(0)
+/**@brief Set sec_mode pointed to by ptr to require encryption and MITM protection.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr)     do {(ptr)->sm = 1; (ptr)->lv = 3;} while(0)
+/**@brief Set sec_mode pointed to by ptr to require signing or encryption, no MITM protection needed.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr)    do {(ptr)->sm = 2; (ptr)->lv = 1;} while(0)
+/**@brief Set sec_mode pointed to by ptr to require signing or encryption with MITM protection.*/
+#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr)  do {(ptr)->sm = 2; (ptr)->lv = 2;} while(0)
+/**@} */
+
+
+/**@brief GAP Security Random Number Length. */
+#define BLE_GAP_SEC_RAND_LEN 8
+
+/**@brief GAP Security Key Length. */
+#define BLE_GAP_SEC_KEY_LEN 16
+
+/**@brief GAP Passkey Length. */
+#define BLE_GAP_PASSKEY_LEN 6
+
+/**@brief Maximum amount of addresses in a whitelist. */
+#define BLE_GAP_WHITELIST_ADDR_MAX_COUNT (8)
+
+/**@brief Maximum amount of IRKs in a whitelist.
+ * @note  The number of IRKs is limited to 8, even if the hardware supports more.
+ */
+#define BLE_GAP_WHITELIST_IRK_MAX_COUNT (8)
+
+/**@defgroup GAP_SEC_MODES GAP Security Modes
+ * @{ */
+#define BLE_GAP_SEC_MODE 0x00 /**< No key (may be used to reject). */
+/**@} */
+
+/**@} */
+
+/**@addtogroup BLE_GAP_STRUCTURES Structures
+ * @{ */
+
+/**@brief Bluetooth Low Energy address. */
+typedef struct
+{
+  uint8_t addr_type;                    /**< See @ref BLE_GAP_ADDR_TYPES. */
+  uint8_t addr[BLE_GAP_ADDR_LEN];       /**< 48-bit address, LSB format. */
+} ble_gap_addr_t;
+
+
+/**@brief GAP connection parameters.
+ *
+ * @note  When ble_conn_params_t is received in an event, both min_conn_interval and
+ *        max_conn_interval will be equal to the connection interval set by the central.
+ *
+ * @note If both conn_sup_timeout and max_conn_interval are specified, then the following constraint applies:
+ *       conn_sup_timeout * 4 > (1 + slave_latency) * max_conn_interval
+ *       that corresponds to the following Bluetooth Spec requirement:
+ *       The Supervision_Timeout in milliseconds shall be larger than
+ *       (1 + Conn_Latency) * Conn_Interval_Max * 2, where Conn_Interval_Max is given in milliseconds.
+ */
+typedef struct
+{
+  uint16_t min_conn_interval;         /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
+  uint16_t max_conn_interval;         /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
+  uint16_t slave_latency;             /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/
+  uint16_t conn_sup_timeout;          /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/
+} ble_gap_conn_params_t;
+
+
+/**@brief GAP connection security modes.
+ *
+ * Security Mode 0 Level 0: No access permissions at all (this level is not defined by the Bluetooth Core specification).\n
+ * Security Mode 1 Level 1: No security is needed (aka open link).\n
+ * Security Mode 1 Level 2: Encrypted link required, MITM protection not necessary.\n
+ * Security Mode 1 Level 3: MITM protected encrypted link required.\n
+ * Security Mode 2 Level 1: Signing or encryption required, MITM protection not necessary.\n
+ * Security Mode 2 Level 2: MITM protected signing required, unless link is MITM protected encrypted.\n
+ */
+typedef struct
+{
+  uint8_t sm : 4;                     /**< Security Mode (1 or 2), 0 for no permissions at all. */
+  uint8_t lv : 4;                     /**< Level (1, 2 or 3), 0 for no permissions at all. */
+
+} ble_gap_conn_sec_mode_t;
+
+
+/**@brief GAP connection security status.*/
+typedef struct
+{
+  ble_gap_conn_sec_mode_t sec_mode;           /**< Currently active security mode for this connection.*/
+  uint8_t                 encr_key_size;      /**< Length of currently active encryption key, 7 to 16 octets (only applicable for bonding procedures). */
+} ble_gap_conn_sec_t;
+
+
+/**@brief Identity Resolving Key. */
+typedef struct
+{
+  uint8_t irk[BLE_GAP_SEC_KEY_LEN];   /**< Array containing IRK. */
+} ble_gap_irk_t;
+
+
+/**@brief Whitelist structure. */
+typedef struct
+{
+  ble_gap_addr_t    **pp_addrs;        /**< Pointer to an array of device address pointers, pointing to addresses to be used in whitelist. NULL if none are given. */
+  uint8_t             addr_count;      /**< Count of device addresses in array, up to @ref BLE_GAP_WHITELIST_ADDR_MAX_COUNT. */
+  ble_gap_irk_t     **pp_irks;         /**< Pointer to an array of Identity Resolving Key (IRK) pointers, each pointing to an IRK in the whitelist. NULL if none are given. */
+  uint8_t             irk_count;       /**< Count of IRKs in array, up to @ref BLE_GAP_WHITELIST_IRK_MAX_COUNT. */
+} ble_gap_whitelist_t;
+
+/**@brief Channel mask for RF channels used in advertising and scanning. */ 
+typedef struct
+{
+  uint8_t ch_37_off : 1;  /**< Setting this bit to 1 will turn off advertising on channel 37 */
+  uint8_t ch_38_off : 1;  /**< Setting this bit to 1 will turn off advertising on channel 38 */
+  uint8_t ch_39_off : 1;  /**< Setting this bit to 1 will turn off advertising on channel 39 */
+} ble_gap_adv_ch_mask_t;
+
+/**@brief GAP advertising parameters.*/
+typedef struct
+{
+  uint8_t               type;                 /**< See @ref BLE_GAP_ADV_TYPES. */
+  ble_gap_addr_t       *p_peer_addr;          /**< For @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND mode only, known peer address. */
+  uint8_t               fp;                   /**< Filter Policy, see @ref BLE_GAP_ADV_FILTER_POLICIES. */
+  ble_gap_whitelist_t  *p_whitelist;          /**< Pointer to whitelist, NULL if no whitelist or the current active whitelist is to be used. */
+  uint16_t              interval;             /**< Advertising interval between 0x0020 and 0x4000 in 0.625 ms units (20ms to 10.24s), see @ref BLE_GAP_ADV_INTERVALS.
+                                                   - If type equals @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND, this parameter must be set to 0 for high duty cycle directed advertising.
+                                                   - If type equals @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND, set @ref BLE_GAP_ADV_INTERVAL_MIN <= interval <= @ref BLE_GAP_ADV_INTERVAL_MAX for low duty cycle advertising.*/
+  uint16_t              timeout;              /**< Advertising timeout between 0x0001 and 0x3FFF in seconds, 0x0000 disables timeout. See also @ref BLE_GAP_ADV_TIMEOUT_VALUES. If type equals @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND, this parameter must be set to 0 for High duty cycle directed advertising. */
+  ble_gap_adv_ch_mask_t channel_mask;         /**< Advertising channel mask. @see ble_gap_channel_mask_t for documentation. */
+} ble_gap_adv_params_t;
+
+
+/**@brief GAP scanning parameters. */
+typedef struct
+{
+  uint8_t                 active    : 1;        /**< If 1, perform active scanning (scan requests). */
+  uint8_t                 selective : 1;        /**< If 1, ignore unknown devices (non whitelisted). */
+  ble_gap_whitelist_t *   p_whitelist;          /**< Pointer to whitelist, NULL if no whitelist or the current active whitelist is to be used. */
+  uint16_t                interval;             /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+  uint16_t                window;               /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+  uint16_t                timeout;              /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+} ble_gap_scan_params_t;
+
+
+/** @brief Keys that can be exchanged during a bonding procedure. */
+typedef struct
+{
+  uint8_t enc     : 1;                        /**< Long Term Key and Master Identification. */
+  uint8_t id      : 1;                        /**< Identity Resolving Key and Identity Address Information. */
+  uint8_t sign    : 1;                        /**< Connection Signature Resolving Key. */
+} ble_gap_sec_kdist_t;
+
+
+/**@brief GAP security parameters. */
+typedef struct
+{
+  uint8_t               bond    : 1;               /**< Perform bonding. */
+  uint8_t               mitm    : 1;               /**< Man In The Middle protection required. */
+  uint8_t               io_caps : 3;               /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */
+  uint8_t               oob     : 1;               /**< Out Of Band data available. */
+  uint8_t               min_key_size;              /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */
+  uint8_t               max_key_size;              /**< Maximum encryption key size in octets between min_key_size and 16. */
+  ble_gap_sec_kdist_t   kdist_periph;              /**< Key distribution bitmap: keys that the peripheral device will distribute. */
+  ble_gap_sec_kdist_t   kdist_central;             /**< Key distribution bitmap: keys that the central device will distribute. */
+} ble_gap_sec_params_t;
+
+
+/**@brief GAP Encryption Information. */
+typedef struct
+{
+  uint8_t   ltk[BLE_GAP_SEC_KEY_LEN];   /**< Long Term Key. */
+  uint8_t   auth : 1;                   /**< Authenticated Key. */
+  uint8_t   ltk_len : 7;                /**< LTK length in octets. */
+} ble_gap_enc_info_t;
+
+
+/**@brief GAP Master Identification. */
+typedef struct
+{
+  uint16_t  ediv;                       /**< Encrypted Diversifier. */
+  uint8_t   rand[BLE_GAP_SEC_RAND_LEN]; /**< Random Number. */
+} ble_gap_master_id_t;
+
+
+/**@brief GAP Signing Information. */
+typedef struct
+{
+  uint8_t   csrk[BLE_GAP_SEC_KEY_LEN];        /**< Connection Signature Resolving Key. */
+} ble_gap_sign_info_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_CONNECTED. */
+typedef struct
+{
+  ble_gap_addr_t        peer_addr;              /**< Bluetooth address of the peer device. */
+  ble_gap_addr_t        own_addr;               /**< Bluetooth address of the local device used during connection setup. */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+  uint8_t               role;                   /**< BLE role for this connection, see @ref BLE_GAP_ROLES */
+#endif
+  uint8_t               irk_match :1;           /**< If 1, peer device's address resolved using an IRK. */
+  uint8_t               irk_match_idx  :7;      /**< Index in IRK list where the address was matched. */
+  ble_gap_conn_params_t conn_params;            /**< GAP Connection Parameters. */
+} ble_gap_evt_connected_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_DISCONNECTED. */
+typedef struct
+{
+  uint8_t reason;                               /**< HCI error code, see @ref BLE_HCI_STATUS_CODES. */
+} ble_gap_evt_disconnected_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE. */
+typedef struct
+{
+  ble_gap_conn_params_t conn_params;            /**<  GAP Connection Parameters. */
+} ble_gap_evt_conn_param_update_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST. */
+typedef struct
+{
+  ble_gap_sec_params_t peer_params;             /**< Initiator Security Parameters. */
+} ble_gap_evt_sec_params_request_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_SEC_INFO_REQUEST. */
+typedef struct
+{
+  ble_gap_addr_t      peer_addr;                     /**< Bluetooth address of the peer device. */
+  ble_gap_master_id_t master_id;                     /**< Master Identification for LTK lookup. */
+  uint8_t             enc_info  : 1;                 /**< If 1, Encryption Information required. */
+  uint8_t             id_info   : 1;                 /**< If 1, Identity Information required. */
+  uint8_t             sign_info : 1;                 /**< If 1, Signing Information required. */
+} ble_gap_evt_sec_info_request_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_PASSKEY_DISPLAY. */
+typedef struct
+{
+  uint8_t passkey[BLE_GAP_PASSKEY_LEN];         /**< 6-digit passkey in ASCII ('0'-'9' digits only). */
+} ble_gap_evt_passkey_display_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_AUTH_KEY_REQUEST. */
+typedef struct
+{
+  uint8_t key_type;                             /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */
+} ble_gap_evt_auth_key_request_t;
+
+
+/**@brief Security levels supported.
+ * @note See Bluetooth Specification Version 4.1 Volume 3, Part C, Chapter 10.
+*/
+typedef struct
+{
+  uint8_t lv1 : 1;                              /**< If 1: Level 1 is supported. */
+  uint8_t lv2 : 1;                              /**< If 1: Level 2 is supported. */
+  uint8_t lv3 : 1;                              /**< If 1: Level 3 is supported. */
+} ble_gap_sec_levels_t;
+
+
+/**@brief Encryption Key. */
+typedef struct
+{
+  ble_gap_enc_info_t    enc_info;             /**< Encryption Information. */
+  ble_gap_master_id_t   master_id;            /**< Master Identification. */
+} ble_gap_enc_key_t;
+
+
+/**@brief Identity Key. */
+typedef struct
+{
+  ble_gap_irk_t         id_info;              /**< Identity Information. */
+  ble_gap_addr_t        id_addr_info;         /**< Identity Address Information. */
+} ble_gap_id_key_t;
+
+
+/**@brief Security Keys. */
+typedef struct
+{
+  ble_gap_enc_key_t     *p_enc_key;           /**< Encryption Key, or NULL. */
+  ble_gap_id_key_t      *p_id_key;            /**< Identity Key, or NULL. */
+  ble_gap_sign_info_t   *p_sign_key;          /**< Signing Key, or NULL. */
+} ble_gap_sec_keys_t;
+
+
+/**@brief Security key set (both Peripheral and Central keys).
+ *         Note that when distributing Bluetooth addresses pertaining to the local device those
+ *         will have to be filled in by the user. */
+typedef struct
+{
+  ble_gap_sec_keys_t keys_periph;     /**< Keys distributed by the device in the Peripheral role. */
+  ble_gap_sec_keys_t keys_central;    /**< Keys distributed by the device in the Central role. */
+} ble_gap_sec_keyset_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_AUTH_STATUS. */
+typedef struct
+{
+  uint8_t               auth_status;            /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */
+  uint8_t               error_src : 2;          /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */
+  uint8_t               bonded : 1;             /**< Procedure resulted in a bond. */
+  ble_gap_sec_levels_t  sm1_levels;             /**< Levels supported in Security Mode 1. */
+  ble_gap_sec_levels_t  sm2_levels;             /**< Levels supported in Security Mode 2. */
+  ble_gap_sec_kdist_t   kdist_periph;           /**< Bitmap stating which keys were exchanged (distributed) by the peripheral. */
+  ble_gap_sec_kdist_t   kdist_central;          /**< Bitmap stating which keys were exchanged (distributed) by the central. */
+} ble_gap_evt_auth_status_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_CONN_SEC_UPDATE. */
+typedef struct
+{
+  ble_gap_conn_sec_t conn_sec;                  /**< Connection security level. */
+} ble_gap_evt_conn_sec_update_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_TIMEOUT. */
+typedef struct
+{
+  uint8_t src;                                  /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */
+} ble_gap_evt_timeout_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_RSSI_CHANGED. */
+typedef struct
+{
+  int8_t  rssi;                               /**< Received Signal Strength Indication in dBm. */
+} ble_gap_evt_rssi_changed_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_ADV_REPORT. */
+typedef struct
+{
+  ble_gap_addr_t peer_addr;                     /**< Bluetooth address of the peer device. */
+  int8_t         rssi;                          /**< Received Signal Strength Indication in dBm. */
+  uint8_t        scan_rsp : 1;                  /**< If 1, the report corresponds to a scan response and the type field may be ignored. */
+  uint8_t        type     : 2;                  /**< See @ref BLE_GAP_ADV_TYPES. Only valid if the scan_rsp field is 0. */
+  uint8_t        dlen     : 5;                  /**< Advertising or scan response data length. */
+  uint8_t        data[BLE_GAP_ADV_MAX_SIZE];    /**< Advertising or scan response data. */
+} ble_gap_evt_adv_report_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_SEC_REQUEST. */
+typedef struct
+{
+  uint8_t    bond    : 1;                       /**< Perform bonding. */
+  uint8_t    mitm    : 1;                       /**< Man In The Middle protection required. */
+} ble_gap_evt_sec_request_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST. */
+typedef struct
+{
+  ble_gap_conn_params_t conn_params;            /**<  GAP Connection Parameters. */
+} ble_gap_evt_conn_param_update_request_t;
+
+
+/**@brief Event structure for @ref BLE_GAP_EVT_SCAN_REQ_REPORT. */
+typedef struct
+{
+  int8_t                  rssi;              /**< Received Signal Strength Indication in dBm. */
+  ble_gap_addr_t          peer_addr;         /**< Bluetooth address of the peer device. */
+} ble_gap_evt_scan_req_report_t;
+
+
+
+/**@brief GAP event structure. */
+typedef struct
+{
+  uint16_t conn_handle;                                     /**< Connection Handle on which event occured. */
+  union                                                     /**< union alternative identified by evt_id in enclosing struct. */
+  {
+    ble_gap_evt_connected_t                   connected;                    /**< Connected Event Parameters. */
+    ble_gap_evt_disconnected_t                disconnected;                 /**< Disconnected Event Parameters. */
+    ble_gap_evt_conn_param_update_t           conn_param_update;            /**< Connection Parameter Update Parameters. */
+    ble_gap_evt_sec_params_request_t          sec_params_request;           /**< Security Parameters Request Event Parameters. */
+    ble_gap_evt_sec_info_request_t            sec_info_request;             /**< Security Information Request Event Parameters. */
+    ble_gap_evt_passkey_display_t             passkey_display;              /**< Passkey Display Event Parameters. */
+    ble_gap_evt_auth_key_request_t            auth_key_request;             /**< Authentication Key Request Event Parameters. */
+    ble_gap_evt_auth_status_t                 auth_status;                  /**< Authentication Status Event Parameters. */
+    ble_gap_evt_conn_sec_update_t             conn_sec_update;              /**< Connection Security Update Event Parameters. */
+    ble_gap_evt_timeout_t                     timeout;                      /**< Timeout Event Parameters. */
+    ble_gap_evt_rssi_changed_t                rssi_changed;                 /**< RSSI Event parameters. */
+    ble_gap_evt_adv_report_t                  adv_report;                   /**< Advertising Report Event Parameters. */
+    ble_gap_evt_sec_request_t                 sec_request;                  /**< Security Request Event Parameters. */
+    ble_gap_evt_conn_param_update_request_t   conn_param_update_request;    /**< Connection Parameter Update Parameters. */
+    ble_gap_evt_scan_req_report_t             scan_req_report;              /**< Scan Request Report parameters. */
+  } params;                                                                 /**< Event Parameters. */
+
+} ble_gap_evt_t;
+
+
+/**@brief Channel Map option.
+ *        Used with @ref sd_ble_opt_get to get the current channel map
+ *        or @ref sd_ble_opt_set to set a new channel map. When setting the
+ *        channel map, it applies to all current and future connections. When getting the
+ *        current channel map, it applies to a single connection and the connection handle
+ *        must be supplied.
+ *
+ * @note  Setting the channel map may take some time, depending on connection parameters.
+ *        The time taken may be different for each connection and the get operation will
+ *        return the previous channel map until the new one has taken effect.
+ *
+ * @note  After setting the channel map, by spec it can not be set again until at least 1 s has passed.
+ *        See Bluetooth Specification Version 4.1 Volume 2, Part E, Section 7.3.46.
+ *
+ * @retval ::NRF_SUCCESS Get or set successful.
+ * @retval ::NRF_ERROR_BUSY Channel map was set again before enough time had passed.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied for get.
+ * @retval ::NRF_ERROR_NOT_SUPPORTED Returned by sd_ble_opt_set in peripheral-only SoftDevices.
+ *
+ */
+typedef struct
+{
+  uint16_t conn_handle;                   /**< Connection Handle (only applicable for get) */
+  uint8_t ch_map[5];                      /**< Channel Map (37-bit). */
+} ble_gap_opt_ch_map_t;
+
+
+/**@brief Local connection latency option.
+ *
+ *        Local connection latency is a feature which enables the slave to improve
+ *        current consumption by ignoring the slave latency set by the peer. The
+ *        local connection latency can only be set to a multiple of the slave latency,
+ *        and cannot be longer than half of the supervision timeout.
+ *
+ *        Used with @ref sd_ble_opt_set to set the local connection latency. The
+ *        @ref sd_ble_opt_get is not supported for this option, but the actual
+ *        local connection latency (unless set to NULL) is set as a return parameter
+ *        when setting the option.
+ *
+ * @note  The latency set will be truncated down to the closest slave latency event
+ *        multiple, or the nearest multiple before half of the supervision timeout.
+ *
+ * @note  The local connection latency is disabled by default, and needs to be enabled for new
+ *        connections and whenever the connection is updated.
+ *
+ * @retval ::NRF_SUCCESS Set successfully.
+ * @retval ::NRF_ERROR_NOT_SUPPORTED Get is not supported.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle parameter.
+ */
+typedef struct
+{
+  uint16_t   conn_handle;                       /**< Connection Handle */
+  uint16_t   requested_latency;                 /**< Requested local connection latency. */
+  uint16_t * p_actual_latency;                  /**< Pointer to storage for the actual local connection latency (can be set to NULL to skip return value). */
+} ble_gap_opt_local_conn_latency_t;
+
+
+/**@brief Passkey Option.
+ *
+ *        Structure containing the passkey to be used during pairing. This can be used with @ref
+ *        sd_ble_opt_set to make the SoftDevice use a pre-programmed passkey for authentication
+ *        instead of generating a random one.
+ *
+ * @note  @ref sd_ble_opt_get is not supported for this option.
+ *
+ */
+typedef struct
+{
+  uint8_t * p_passkey;                          /**< Pointer to 6-digit ASCII string (digit 0..9 only, no NULL termination) passkey to be used during pairing. If this is NULL, the SoftDevice will generate a random passkey if required.*/
+} ble_gap_opt_passkey_t;
+
+
+/**@brief Custom Privacy Option.
+ *
+ *        This structure is used with both @ref sd_ble_opt_set (as input) and with
+ *        @ref sd_ble_opt_get (as output).
+ *
+ *        Structure containing:
+ *        - A pointer to an IRK to set (if input), or a place to store a read IRK (if output).
+ *        - A private address refresh cycle.
+ *
+ * @note  The specified address cycle interval is used when the address cycle mode is
+ *        @ref BLE_GAP_ADDR_CYCLE_MODE_AUTO. If 0 is given, the address will not be automatically 
+ *        refreshed at all. The default interval is @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S.
+ *
+ * @note  If the current address cycle mode is @ref BLE_GAP_ADDR_CYCLE_MODE_AUTO, the address will immediately be
+ *        refreshed when a custom privacy option is set. A new address can be generated manually by calling
+ *        @ref sd_ble_gap_address_set with the same type again. 
+ *
+ * @note  If the IRK is updated, the new IRK becomes the one to be distributed in all
+ *        bonding procedures performed after @ref sd_ble_opt_set returns.
+ *
+ * @retval ::NRF_SUCCESS Set or read successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR The pointer to IRK storage is invalid.
+ */
+typedef struct
+{
+  ble_gap_irk_t * p_irk;        /**< When input: Pointer to custom IRK, or NULL to use/reset to the device's default IRK. When output: Pointer to where the current IRK is to be stored, or NULL to not read out the IRK. */
+  uint16_t        interval_s;   /**< When input: Custom private address cycle interval in seconds. When output: The current private address cycle interval. */
+} ble_gap_opt_privacy_t;
+
+
+/**@brief Scan request report option.
+ *
+ *        This can be used with @ref sd_ble_opt_set to make the SoftDevice send
+ *        @ref BLE_GAP_EVT_SCAN_REQ_REPORT events.
+ *
+ *  @note   Due to the limited space reserved for scan request report events,
+ *          not all received scan requests will be reported.
+ *
+ *  @note   If whitelisting is used, only whitelisted requests are reported.
+ *
+ *  @retval ::NRF_SUCCESS Set successfully.
+ *  @retval ::NRF_ERROR_INVALID_STATE When advertising is ongoing while the option is set.
+ */
+typedef struct
+{
+   uint8_t enable : 1;                           /**< Enable scan request reports. */
+} ble_gap_opt_scan_req_report_t;
+
+/**@brief Compatibility mode option.
+ *
+ *        This can be used with @ref sd_ble_opt_set to enable and disable
+ *        compatibility modes. Compatibility modes are disabled by default.
+ *
+ *  @note  Compatibility mode 1 enables interoperability with devices that do not support 
+ *         a value of 0 for the WinOffset parameter in the Link Layer CONNECT_REQ packet.
+ *
+ *  @retval ::NRF_SUCCESS Set successfully.
+ *  @retval ::NRF_ERROR_INVALID_STATE When connection creation is ongoing while mode 1 is set.
+ */
+typedef struct
+{
+   uint8_t mode_1_enable : 1;                           /**< Enable compatibility mode 1.*/
+} ble_gap_opt_compat_mode_t;
+
+
+/**@brief Option structure for GAP options. */
+typedef union
+{
+  ble_gap_opt_ch_map_t                  ch_map;                    /**< Parameters for the Channel Map option. */
+  ble_gap_opt_local_conn_latency_t      local_conn_latency;        /**< Parameters for the Local connection latency option */
+  ble_gap_opt_passkey_t                 passkey;                   /**< Parameters for the Passkey option.*/
+  ble_gap_opt_privacy_t                 privacy;                   /**< Parameters for the Custom privacy option. */
+  ble_gap_opt_scan_req_report_t         scan_req_report;           /**< Parameters for the scan request report option.*/
+  ble_gap_opt_compat_mode_t             compat_mode;               /**< Parameters for the compatibility mode option.*/
+} ble_gap_opt_t;
+/**@} */
+
+
+/**@addtogroup BLE_GAP_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Set local Bluetooth address.
+ *
+ * @note If the address cycle mode is @ref BLE_GAP_ADDR_CYCLE_MODE_AUTO, the address type is required to
+ * be @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE or
+ * @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. The given address is ignored and the
+ * SoftDevice will generate a new private address automatically every 
+ * @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S seconds. If this API
+ * call is used again with the same parameters, the SoftDevice will immediately
+ * generate a new private address to replace the current address.
+ *
+ * @note If the application wishes to use a @ref BLE_GAP_ADDR_TYPE_PUBLIC or
+ * @ref BLE_GAP_ADDR_TYPE_RANDOM_STATIC address, the cycle mode must be
+ * @ref BLE_GAP_ADDR_CYCLE_MODE_NONE.
+ *
+ * @note If this API function is called while advertising or scanning, the softdevice will immediately update the
+ * advertising or scanning address without the need to stop the procedure in the following cases:
+ *   - If the previously set address is of type @ref BLE_GAP_ADDR_TYPE_PUBLIC and the new address
+ *   is also of type @ref BLE_GAP_ADDR_TYPE_PUBLIC
+ *   - If the previously set address is not @ref BLE_GAP_ADDR_TYPE_PUBLIC and the new address is
+ *   also not @ref BLE_GAP_ADDR_TYPE_PUBLIC.
+ * If the address is changed from a @ref BLE_GAP_ADDR_TYPE_PUBLIC address to another type or from
+ * another type to a @ref BLE_GAP_ADDR_TYPE_PUBLIC address, the change will take effect the next
+ * time an advertising or scanning procedure is started.
+ *
+ * @note If the address cycle mode is @ref BLE_GAP_ADDR_CYCLE_MODE_NONE and the application is
+ *       using privacy, the application must take care to generate and set new private addresses
+ *       periodically to comply with the Privacy specification in Bluetooth Core Spec.
+ *
+ * @param[in] addr_cycle_mode Address cycle mode, see @ref BLE_GAP_ADDR_CYCLE_MODES.
+ * @param[in] p_addr          Pointer to address structure.
+ *
+ * @retval ::NRF_SUCCESS Address successfully set.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameters.
+ * @retval ::BLE_ERROR_GAP_INVALID_BLE_ADDR Invalid address.
+ * @retval ::NRF_ERROR_BUSY The stack is busy, process pending events and retry.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ */
+SVCALL(SD_BLE_GAP_ADDRESS_SET, uint32_t, sd_ble_gap_address_set(uint8_t addr_cycle_mode, const ble_gap_addr_t *p_addr));
+
+
+/**@brief Get local Bluetooth address.
+ *
+ * @param[out] p_addr Pointer to address structure to be filled in.
+ *
+ * @retval ::NRF_SUCCESS Address successfully retrieved.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ */
+SVCALL(SD_BLE_GAP_ADDRESS_GET, uint32_t, sd_ble_gap_address_get(ble_gap_addr_t *p_addr));
+
+
+/**@brief Set, clear or update advertising and scan response data.
+ *
+ * @note The format of the advertising data will be checked by this call to ensure interoperability.
+ *       Limitations imposed by this API call to the data provided include having a flags data type in the scan response data and
+ *       duplicating the local name in the advertising data and scan response data. 
+ *
+ * @note To clear the advertising data and set it to a 0-length packet, simply provide a valid pointer (p_data/p_sr_data) with its corresponding 
+ *        length (dlen/srdlen) set to 0.
+ *
+ * @note The call will fail if p_data and p_sr_data are both NULL since this would have no effect.
+ *
+ * @param[in] p_data    Raw data to be placed in advertising packet. If NULL, no changes are made to the current advertising packet data.
+ * @param[in] dlen      Data length for p_data. Max size: @ref BLE_GAP_ADV_MAX_SIZE octets. Should be 0 if p_data is NULL, can be 0 if p_data is not NULL.
+ * @param[in] p_sr_data Raw data to be placed in scan response packet. If NULL, no changes are made to the current scan response packet data.
+ * @param[in] srdlen    Data length for p_sr_data. Max size: @ref BLE_GAP_ADV_MAX_SIZE octets. Should be 0 if p_sr_data is NULL, can be 0 if p_data is not NULL.
+ *
+ * @retval ::NRF_SUCCESS Advertising data successfully updated or cleared.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_FLAGS Invalid combination of advertising flags supplied.
+ * @retval ::NRF_ERROR_INVALID_DATA Invalid data type(s) supplied, check the advertising data format specification.
+ * @retval ::NRF_ERROR_INVALID_LENGTH Invalid data length(s) supplied.
+ * @retval ::NRF_ERROR_NOT_SUPPORTED Unsupported data type.
+ * @retval ::BLE_ERROR_GAP_UUID_LIST_MISMATCH Invalid UUID list supplied.
+ */
+SVCALL(SD_BLE_GAP_ADV_DATA_SET, uint32_t, sd_ble_gap_adv_data_set(uint8_t const *p_data, uint8_t dlen, uint8_t const *p_sr_data, uint8_t srdlen));
+
+
+/**@brief Start advertising (GAP Discoverable, Connectable modes, Broadcast Procedure).
+ *
+ * @note An application can start an advertising procedure for broadcasting purposes while a connection
+ *       is active. After a @ref BLE_GAP_EVT_CONNECTED event is received, this function may therefore
+ *       be called to start a broadcast advertising procedure. The advertising procedure
+ *       cannot however be connectable (it must be of type @ref BLE_GAP_ADV_TYPE_ADV_SCAN_IND or
+ *       @ref BLE_GAP_ADV_TYPE_ADV_NONCONN_IND). @note Only one advertiser may be active at any time.
+ *
+ * @note To use the currently active whitelist set p_adv_params->p_whitelist to NULL.
+ *
+ * @param[in] p_adv_params Pointer to advertising parameters structure.
+ *
+ * @retval ::NRF_SUCCESS The BLE stack has started advertising.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check the accepted ranges and limits.
+ * @retval ::BLE_ERROR_GAP_INVALID_BLE_ADDR Invalid Bluetooth address supplied.
+ * @retval ::BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST Discoverable mode and whitelist incompatible.
+ * @retval ::NRF_ERROR_BUSY The stack is busy, process pending events and retry.
+ * @retval ::BLE_ERROR_GAP_WHITELIST_IN_USE Unable to replace the whitelist while another operation is using it.
+ */
+SVCALL(SD_BLE_GAP_ADV_START, uint32_t, sd_ble_gap_adv_start(ble_gap_adv_params_t const *p_adv_params));
+
+
+/**@brief Stop advertising (GAP Discoverable, Connectable modes, Broadcast Procedure).
+ *
+ * @retval ::NRF_SUCCESS The BLE stack has stopped advertising.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation (most probably not in advertising state).
+ */
+SVCALL(SD_BLE_GAP_ADV_STOP, uint32_t, sd_ble_gap_adv_stop(void));
+
+
+/**@brief Update connection parameters.
+ *
+ * @details In the central role this will initiate a Link Layer connection parameter update procedure,
+ *          otherwise in the peripheral role, this will send the corresponding L2CAP request and wait for
+ *          the central to perform the procedure. In both cases, and regardless of success or failure, the application
+ *          will be informed of the result with a @ref BLE_GAP_EVT_CONN_PARAM_UPDATE event.
+ *
+ * @details This function can be used as a central both to reply to a @ref BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST or to start the procedure unrequested.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] p_conn_params  Pointer to desired connection parameters. If NULL is provided on a peripheral role,
+ *                           the parameters in the PPCP characteristic of the GAP service will be used instead.
+ *                           If NULL is provided on a central role and in response to a @ref BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST, the peripheral request will be rejected
+ *
+ * @retval ::NRF_SUCCESS The Connection Update procedure has been started successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check parameter limits and constraints.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::NRF_ERROR_BUSY Procedure already in progress or not allowed at this time, process pending events and wait for pending procedures to complete and retry.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ */
+SVCALL(SD_BLE_GAP_CONN_PARAM_UPDATE, uint32_t, sd_ble_gap_conn_param_update(uint16_t conn_handle, ble_gap_conn_params_t const *p_conn_params));
+
+
+/**@brief Disconnect (GAP Link Termination).
+ *
+ * @details This call initiates the disconnection procedure, and its completion will be communicated to the application
+ *          with a @ref BLE_GAP_EVT_DISCONNECTED event.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] hci_status_code HCI status code, see @ref BLE_HCI_STATUS_CODES (accepted values are @ref BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION and @ref BLE_HCI_CONN_INTERVAL_UNACCEPTABLE).
+ *
+ * @retval ::NRF_SUCCESS The disconnection procedure has been started successfully.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation (disconnection is already in progress).
+ */
+SVCALL(SD_BLE_GAP_DISCONNECT, uint32_t, sd_ble_gap_disconnect(uint16_t conn_handle, uint8_t hci_status_code));
+
+
+/**@brief Set the radio's transmit power.
+ *
+ * @param[in] tx_power Radio transmit power in dBm (accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm).
+ *
+ * @note -40 dBm will not actually give -40 dBm, but will instead be remapped to -30 dBm.
+ *
+ * @retval ::NRF_SUCCESS Successfully changed the transmit power.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ */
+SVCALL(SD_BLE_GAP_TX_POWER_SET, uint32_t, sd_ble_gap_tx_power_set(int8_t tx_power));
+
+
+/**@brief Set GAP Appearance value.
+ *
+ * @param[in] appearance Appearance (16-bit), see @ref BLE_APPEARANCES.
+ *
+ * @retval ::NRF_SUCCESS  Appearance value set successfully.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ */
+SVCALL(SD_BLE_GAP_APPEARANCE_SET, uint32_t, sd_ble_gap_appearance_set(uint16_t appearance));
+
+
+/**@brief Get GAP Appearance value.
+ *
+ * @param[out] p_appearance Pointer to appearance (16-bit) to be filled in, see @ref BLE_APPEARANCES.
+ *
+ * @retval ::NRF_SUCCESS Appearance value retrieved successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ */
+SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t *p_appearance));
+
+
+/**@brief Set GAP Peripheral Preferred Connection Parameters.
+ *
+ * @param[in] p_conn_params Pointer to a @ref ble_gap_conn_params_t structure with the desired parameters.
+ *
+ * @retval ::NRF_SUCCESS Peripheral Preferred Connection Parameters set successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ */
+SVCALL(SD_BLE_GAP_PPCP_SET, uint32_t, sd_ble_gap_ppcp_set(ble_gap_conn_params_t const *p_conn_params));
+
+
+/**@brief Get GAP Peripheral Preferred Connection Parameters.
+ *
+ * @param[out] p_conn_params Pointer to a @ref ble_gap_conn_params_t structure where the parameters will be stored.
+ *
+ * @retval ::NRF_SUCCESS Peripheral Preferred Connection Parameters retrieved successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ */
+SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t *p_conn_params));
+
+
+/**@brief Set GAP device name.
+ *
+ * @param[in] p_write_perm Write permissions for the Device Name characteristic, see @ref ble_gap_conn_sec_mode_t.
+ * @param[in] p_dev_name Pointer to a UTF-8 encoded, <b>non NULL-terminated</b> string.
+ * @param[in] len Length of the UTF-8, <b>non NULL-terminated</b> string pointed to by p_dev_name in octets (must be smaller or equal than @ref BLE_GAP_DEVNAME_MAX_LEN).
+ *
+ * @retval ::NRF_SUCCESS GAP device name and permissions set successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied.
+ */
+SVCALL(SD_BLE_GAP_DEVICE_NAME_SET, uint32_t, sd_ble_gap_device_name_set(ble_gap_conn_sec_mode_t const *p_write_perm, uint8_t const *p_dev_name, uint16_t len));
+
+
+/**@brief Get GAP device name.
+ *
+ * @param[out]    p_dev_name Pointer to an empty buffer where the UTF-8 <b>non NULL-terminated</b> string will be placed. Set to NULL to obtain the complete device name length.
+ * @param[in,out] p_len      Length of the buffer pointed by p_dev_name, complete device name length on output.
+ *
+ * @note          If the device name is longer than the size of the supplied buffer,
+ *                p_len will return the complete device name length,
+ *                and not the number of bytes actually returned in p_dev_name.
+ *                The application may use this information to allocate a suitable buffer size.
+ *
+ * @retval ::NRF_SUCCESS GAP device name retrieved successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied.
+ */
+SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t *p_dev_name, uint16_t *p_len));
+
+
+/**@brief Initiate the GAP Authentication procedure.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] p_sec_params Pointer to the @ref ble_gap_sec_params_t structure with the security parameters to be used during the pairing or bonding procedure.
+ *                         In the peripheral role, only the timeout, bond and mitm fields of this structure are used.
+ *                         In the central role, this pointer may be NULL to reject a Security Request.
+ *
+ * @details In the central role, this function will send an SMP Pairing Request (or an SMP Pairing Failed if rejected), 
+ *          otherwise in the peripheral role, an SMP Security Request will be sent.
+ *
+ * @note    Calling this function may result in the following events depending on the outcome and parameters: @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST,
+ *          @ref BLE_GAP_EVT_SEC_INFO_REQUEST, @ref BLE_GAP_EVT_AUTH_KEY_REQUEST, @ref BLE_GAP_EVT_CONN_SEC_UPDATE, @ref BLE_GAP_EVT_AUTH_STATUS.
+ *
+ *
+ * @retval ::NRF_SUCCESS Successfully initiated authentication procedure.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::NRF_ERROR_BUSY The stack is busy, process pending events and retry.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::NRF_ERROR_TIMEOUT A SMP timout has occured, and further SMP operations on this link is prohibited.
+ */
+SVCALL(SD_BLE_GAP_AUTHENTICATE, uint32_t, sd_ble_gap_authenticate(uint16_t conn_handle, ble_gap_sec_params_t const *p_sec_params));
+
+
+/**@brief Reply with GAP security parameters.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] sec_status Security status, see @ref BLE_GAP_SEC_STATUS.
+ * @param[in] p_sec_params Pointer to a @ref ble_gap_sec_params_t security parameters structure. In the central role this must be set to NULL, as the parameters have
+ *                         already been provided during a previous call to @ref sd_ble_gap_authenticate.
+ * @param[in,out] p_sec_keyset Pointer to a @ref ble_gap_sec_keyset_t security keyset structure. Any keys distributed as a result of the ongoing security procedure 
+ *                         will be stored into the memory referenced by the pointers inside this structure. The keys will be stored and available to the application 
+ *                         upon reception of a @ref BLE_GAP_EVT_AUTH_STATUS event.
+ *                         The pointer to the ID key data distributed by the <b>local device</b> constitutes however an exception. It can either point to ID key data 
+ *                         filled in by the user before calling this function, in which case a user-supplied Bluetooth address and IRK will be distributed, 
+ *                         or the pointer to the ID key data structure can be NULL, in which case the device's configured (or default, if none is configured) 
+ *                         Bluetooth address and IRK will be distributed. 
+ *
+ * @details This function is only used to reply to a @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST, calling it at other times will result in an @ref NRF_ERROR_INVALID_STATE.
+ * @note    If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters.
+ *
+ * @retval ::NRF_SUCCESS Successfully accepted security parameter from the application.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_SEC_PARAMS_REPLY, uint32_t, sd_ble_gap_sec_params_reply(uint16_t conn_handle, uint8_t sec_status, ble_gap_sec_params_t const *p_sec_params, ble_gap_sec_keyset_t const *p_sec_keyset));
+
+
+/**@brief Reply with an authentication key.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] key_type See @ref BLE_GAP_AUTH_KEY_TYPES.
+ * @param[in] p_key If key type is @ref BLE_GAP_AUTH_KEY_TYPE_NONE, then NULL.
+ *                If key type is @ref BLE_GAP_AUTH_KEY_TYPE_PASSKEY, then a 6-byte ASCII string (digit 0..9 only, no NULL termination).
+ *                If key type is @ref BLE_GAP_AUTH_KEY_TYPE_OOB, then a 16-byte OOB key value in Little Endian format.
+ *
+ * @details This function is only used to reply to a @ref BLE_GAP_EVT_AUTH_KEY_REQUEST, calling it at other times will result in an @ref NRF_ERROR_INVALID_STATE.
+ * @note    If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters.
+ *
+ * @retval ::NRF_SUCCESS Authentication key successfully set.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_AUTH_KEY_REPLY, uint32_t, sd_ble_gap_auth_key_reply(uint16_t conn_handle, uint8_t key_type, uint8_t const *p_key));
+
+
+/**@brief Initiate GAP Encryption procedure.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] p_master_id Pointer to a @ref ble_gap_master_id_t master identification structure.
+ * @param[in] p_enc_info  Pointer to a @ref ble_gap_enc_info_t encryption information structure.
+ *
+ * @details In the central role, this function will initiate the encryption procedure using the encryption information provided.
+ *
+ * @note    Calling this function may result in the following event depending on the outcome and parameters: @ref BLE_GAP_EVT_CONN_SEC_UPDATE.
+ *
+ * @retval ::NRF_SUCCESS Successfully initiated authentication procedure.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::BLE_ERROR_INVALID_ROLE Operation is not supported in the Peripheral role.
+ * @retval ::NRF_ERROR_BUSY Procedure already in progress or not allowed at this time, wait for pending procedures to complete and retry.
+ */
+SVCALL(SD_BLE_GAP_ENCRYPT, uint32_t, sd_ble_gap_encrypt(uint16_t conn_handle, ble_gap_master_id_t const *p_master_id, ble_gap_enc_info_t const *p_enc_info));
+
+
+/**@brief Reply with GAP security information.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in] p_enc_info Pointer to a @ref ble_gap_enc_info_t encryption information structure. May be NULL to signal none is available.
+ * @param[in] p_id_info Pointer to a @ref ble_gap_irk_t identity information structure. May be NULL to signal none is available.
+ * @param[in] p_sign_info Pointer to a @ref ble_gap_sign_info_t signing information structure. May be NULL to signal none is available.
+ *
+ * @details This function is only used to reply to a @ref BLE_GAP_EVT_SEC_INFO_REQUEST, calling it at other times will result in @ref NRF_ERROR_INVALID_STATE.
+ * @note    If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters.
+ * @note    Data signing is not yet supported, and p_sign_info must therefore be NULL.
+ *
+ * @retval ::NRF_SUCCESS Successfully accepted security information.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_SEC_INFO_REPLY, uint32_t, sd_ble_gap_sec_info_reply(uint16_t conn_handle, ble_gap_enc_info_t const *p_enc_info, ble_gap_irk_t const *p_id_info, ble_gap_sign_info_t const *p_sign_info));
+
+
+/**@brief Get the current connection security.
+ *
+ * @param[in]  conn_handle Connection handle.
+ * @param[out] p_conn_sec  Pointer to a @ref ble_gap_conn_sec_t structure to be filled in.
+ *
+ * @retval ::NRF_SUCCESS Current connection security successfully retrieved.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t *p_conn_sec));
+
+
+/**@brief Start reporting the received signal strength to the application. 
+ *
+ * A new event is reported whenever the RSSI value changes, until @ref sd_ble_gap_rssi_stop is called.
+ *
+ * @param[in] conn_handle        Connection handle.
+ * @param[in] threshold_dbm      Minimum change in dBm before triggering the @ref BLE_GAP_EVT_RSSI_CHANGED event. Events are disabled if threshold_dbm equals @ref BLE_GAP_RSSI_THRESHOLD_INVALID.
+ * @param[in] skip_count         Number of RSSI samples with a change of threshold_dbm or more before sending a new @ref BLE_GAP_EVT_RSSI_CHANGED event.
+ *
+ * @retval ::NRF_SUCCESS                   Successfully activated RSSI reporting.
+ * @retval ::NRF_ERROR_INVALID_STATE       Disconnection in progress. Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_RSSI_START, uint32_t, sd_ble_gap_rssi_start(uint16_t conn_handle, uint8_t threshold_dbm, uint8_t skip_count));
+
+
+/**@brief Stop reporting the received signal strength.
+ *
+ * @note An RSSI change detected before the call but not yet received by the application 
+ * may be reported after @ref sd_ble_gap_rssi_stop has been called.
+ *
+ * @param[in] conn_handle Connection handle.
+ *
+ * @retval ::NRF_SUCCESS                   Successfully deactivated RSSI reporting.
+ * @retval ::NRF_ERROR_INVALID_STATE       Invalid state to perform operation.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ */
+SVCALL(SD_BLE_GAP_RSSI_STOP, uint32_t, sd_ble_gap_rssi_stop(uint16_t conn_handle));
+
+
+/**@brief Get the received signal strength for the last connection event.
+ *
+ * @param[in]  conn_handle Connection handle.
+ * @param[out] p_rssi      Pointer to the location where the RSSI measurement shall be stored.
+ *
+ * @ref sd_ble_gap_rssi_start must be called to start reporting RSSI before using this function. @ref NRF_ERROR_NOT_FOUND
+ * will be returned until RSSI was sampled for the first time after calling @ref sd_ble_gap_rssi_start.
+ *
+ * @retval ::NRF_SUCCESS                   Successfully read the RSSI.
+ * @retval ::NRF_ERROR_NOT_FOUND           No sample is available.
+ * @retval ::NRF_ERROR_INVALID_ADDR        Invalid pointer supplied.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE       RSSI reporting is not ongoing, or disconnection in progress.
+ */
+SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t *p_rssi));
+
+
+/**@brief Start scanning (GAP Discovery procedure, Observer Procedure).
+ *
+ * @note To use the currently active whitelist set p_scan_params->p_whitelist to NULL.
+ *
+ * @param[in] p_scan_params Pointer to scan parameters structure.
+ *
+ * @retval ::NRF_SUCCESS Successfully initiated scanning procedure.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_BUSY The stack is busy, process pending events and retry.
+ * @retval ::BLE_ERROR_GAP_WHITELIST_IN_USE Unable to replace the whitelist while another operation is using it.
+ */
+SVCALL(SD_BLE_GAP_SCAN_START, uint32_t, sd_ble_gap_scan_start(ble_gap_scan_params_t const *p_scan_params));
+
+
+/**@brief Stop scanning (GAP Discovery procedure, Observer Procedure).
+ *
+ * @retval ::NRF_SUCCESS Successfully stopped scanning procedure.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation (most probably not in scanning state).
+ */
+SVCALL(SD_BLE_GAP_SCAN_STOP, uint32_t, sd_ble_gap_scan_stop(void));
+
+
+/**@brief Create a connection (GAP Link Establishment).
+ *
+ * @note To use the currently active whitelist set p_scan_params->p_whitelist to NULL.    
+ *
+ * @param[in] p_peer_addr   Pointer to peer address. If the selective bit is set in @ref ble_gap_scan_params_t, then this must be NULL.
+ * @param[in] p_scan_params Pointer to scan parameters structure.
+ * @param[in] p_conn_params Pointer to desired connection parameters.
+ *
+ * @retval ::NRF_SUCCESS Successfully initiated connection procedure.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid parameter(s) pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::BLE_ERROR_GAP_INVALID_BLE_ADDR Invalid Peer address.
+ * @retval ::NRF_ERROR_NO_MEM limit of available connections reached.
+ * @retval ::NRF_ERROR_BUSY The stack is busy, process pending events and retry. If another connection is being established wait for the corresponding
+ *                          @ref BLE_GAP_EVT_CONNECTED event before calling again.
+ * @retval ::BLE_ERROR_GAP_WHITELIST_IN_USE Unable to replace the whitelist while another operation is using it.
+ */
+SVCALL(SD_BLE_GAP_CONNECT, uint32_t, sd_ble_gap_connect(ble_gap_addr_t const *p_peer_addr, ble_gap_scan_params_t const *p_scan_params, ble_gap_conn_params_t const *p_conn_params));
+
+
+/**@brief Cancel a connection establishment.
+ *
+ * @retval ::NRF_SUCCESS Successfully cancelled an ongoing connection procedure.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ */
+SVCALL(SD_BLE_GAP_CONNECT_CANCEL, uint32_t, sd_ble_gap_connect_cancel(void));
+
+/** @} */
+
+#endif // BLE_GAP_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatt.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatt.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_GATT Generic Attribute Profile (GATT) Common
+  @{
+  @brief  Common definitions and prototypes for the GATT interfaces.
+ */
+
+#ifndef BLE_GATT_H__
+#define BLE_GATT_H__
+
+#include "ble_types.h"
+#include "ble_ranges.h"
+
+
+/** @addtogroup BLE_GATT_DEFINES Defines
+ * @{ */
+
+/** @brief Default MTU size. */
+#define GATT_MTU_SIZE_DEFAULT 23
+
+/** @brief Only the default MTU size of 23 is currently supported. */
+#define GATT_RX_MTU 23
+
+
+/**@brief Invalid Attribute Handle. */
+#define BLE_GATT_HANDLE_INVALID            0x0000
+
+/** @defgroup BLE_GATT_TIMEOUT_SOURCES GATT Timeout sources
+ * @{ */
+#define BLE_GATT_TIMEOUT_SRC_PROTOCOL                  0x00 /**< ATT Protocol timeout. */
+/** @} */
+
+/** @defgroup BLE_GATT_WRITE_OPS GATT Write operations
+ * @{ */
+#define BLE_GATT_OP_INVALID                0x00  /**< Invalid Operation. */
+#define BLE_GATT_OP_WRITE_REQ              0x01  /**< Write Request. */
+#define BLE_GATT_OP_WRITE_CMD              0x02  /**< Write Command. */
+#define BLE_GATT_OP_SIGN_WRITE_CMD         0x03  /**< Signed Write Command. */
+#define BLE_GATT_OP_PREP_WRITE_REQ         0x04  /**< Prepare Write Request. */
+#define BLE_GATT_OP_EXEC_WRITE_REQ         0x05  /**< Execute Write Request. */
+/** @} */
+
+/** @defgroup BLE_GATT_EXEC_WRITE_FLAGS GATT Execute Write flags
+ * @{ */
+#define BLE_GATT_EXEC_WRITE_FLAG_PREPARED_CANCEL 0x00
+#define BLE_GATT_EXEC_WRITE_FLAG_PREPARED_WRITE  0x01
+/** @} */
+
+/** @defgroup BLE_GATT_HVX_TYPES GATT Handle Value operations
+ * @{ */
+#define BLE_GATT_HVX_INVALID               0x00  /**< Invalid Operation. */
+#define BLE_GATT_HVX_NOTIFICATION          0x01  /**< Handle Value Notification. */
+#define BLE_GATT_HVX_INDICATION            0x02  /**< Handle Value Indication. */
+/** @} */
+
+/** @defgroup BLE_GATT_STATUS_CODES GATT Status Codes
+ * @{ */
+#define BLE_GATT_STATUS_SUCCESS                           0x0000  /**< Success. */
+#define BLE_GATT_STATUS_UNKNOWN                           0x0001  /**< Unknown or not applicable status. */
+#define BLE_GATT_STATUS_ATTERR_INVALID                    0x0100  /**< ATT Error: Invalid Error Code. */
+#define BLE_GATT_STATUS_ATTERR_INVALID_HANDLE             0x0101  /**< ATT Error: Invalid Attribute Handle. */
+#define BLE_GATT_STATUS_ATTERR_READ_NOT_PERMITTED         0x0102  /**< ATT Error: Read not permitted. */
+#define BLE_GATT_STATUS_ATTERR_WRITE_NOT_PERMITTED        0x0103  /**< ATT Error: Write not permitted. */
+#define BLE_GATT_STATUS_ATTERR_INVALID_PDU                0x0104  /**< ATT Error: Used in ATT as Invalid PDU. */
+#define BLE_GATT_STATUS_ATTERR_INSUF_AUTHENTICATION       0x0105  /**< ATT Error: Authenticated link required. */
+#define BLE_GATT_STATUS_ATTERR_REQUEST_NOT_SUPPORTED      0x0106  /**< ATT Error: Used in ATT as Request Not Supported. */
+#define BLE_GATT_STATUS_ATTERR_INVALID_OFFSET             0x0107  /**< ATT Error: Offset specified was past the end of the attribute. */
+#define BLE_GATT_STATUS_ATTERR_INSUF_AUTHORIZATION        0x0108  /**< ATT Error: Used in ATT as Insufficient Authorisation. */
+#define BLE_GATT_STATUS_ATTERR_PREPARE_QUEUE_FULL         0x0109  /**< ATT Error: Used in ATT as Prepare Queue Full. */
+#define BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND        0x010A  /**< ATT Error: Used in ATT as Attribute not found. */
+#define BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_LONG         0x010B  /**< ATT Error: Attribute cannot be read or written using read/write blob requests. */
+#define BLE_GATT_STATUS_ATTERR_INSUF_ENC_KEY_SIZE         0x010C  /**< ATT Error: Encryption key size used is insufficient. */
+#define BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH     0x010D  /**< ATT Error: Invalid value size. */
+#define BLE_GATT_STATUS_ATTERR_UNLIKELY_ERROR             0x010E  /**< ATT Error: Very unlikely error. */
+#define BLE_GATT_STATUS_ATTERR_INSUF_ENCRYPTION           0x010F  /**< ATT Error: Encrypted link required. */
+#define BLE_GATT_STATUS_ATTERR_UNSUPPORTED_GROUP_TYPE     0x0110  /**< ATT Error: Attribute type is not a supported grouping attribute. */
+#define BLE_GATT_STATUS_ATTERR_INSUF_RESOURCES            0x0111  /**< ATT Error: Encrypted link required. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE1_BEGIN           0x0112  /**< ATT Error: Reserved for Future Use range #1 begin. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE1_END             0x017F  /**< ATT Error: Reserved for Future Use range #1 end. */
+#define BLE_GATT_STATUS_ATTERR_APP_BEGIN                  0x0180  /**< ATT Error: Application range begin. */
+#define BLE_GATT_STATUS_ATTERR_APP_END                    0x019F  /**< ATT Error: Application range end. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE2_BEGIN           0x01A0  /**< ATT Error: Reserved for Future Use range #2 begin. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE2_END             0x01DF  /**< ATT Error: Reserved for Future Use range #2 end. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE3_BEGIN           0x01E0  /**< ATT Error: Reserved for Future Use range #3 begin. */
+#define BLE_GATT_STATUS_ATTERR_RFU_RANGE3_END             0x01FC  /**< ATT Error: Reserved for Future Use range #3 end. */
+#define BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR      0x01FD  /**< ATT Common Profile and Service Error: Client Characteristic Configuration Descriptor improperly configured. */
+#define BLE_GATT_STATUS_ATTERR_CPS_PROC_ALR_IN_PROG       0x01FE  /**< ATT Common Profile and Service Error: Procedure Already in Progress. */
+#define BLE_GATT_STATUS_ATTERR_CPS_OUT_OF_RANGE           0x01FF  /**< ATT Common Profile and Service Error: Out Of Range. */
+/** @} */
+
+
+/** @defgroup BLE_GATT_CPF_FORMATS Characteristic Presentation Formats
+ *  @note Found at http://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml
+ * @{ */
+#define BLE_GATT_CPF_FORMAT_RFU                 0x00 /**< Reserved For Future Use. */
+#define BLE_GATT_CPF_FORMAT_BOOLEAN             0x01 /**< Boolean. */
+#define BLE_GATT_CPF_FORMAT_2BIT                0x02 /**< Unsigned 2-bit integer. */
+#define BLE_GATT_CPF_FORMAT_NIBBLE              0x03 /**< Unsigned 4-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT8               0x04 /**< Unsigned 8-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT12              0x05 /**< Unsigned 12-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT16              0x06 /**< Unsigned 16-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT24              0x07 /**< Unsigned 24-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT32              0x08 /**< Unsigned 32-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT48              0x09 /**< Unsigned 48-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT64              0x0A /**< Unsigned 64-bit integer. */
+#define BLE_GATT_CPF_FORMAT_UINT128             0x0B /**< Unsigned 128-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT8               0x0C /**< Signed 2-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT12              0x0D /**< Signed 12-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT16              0x0E /**< Signed 16-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT24              0x0F /**< Signed 24-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT32              0x10 /**< Signed 32-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT48              0x11 /**< Signed 48-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT64              0x12 /**< Signed 64-bit integer. */
+#define BLE_GATT_CPF_FORMAT_SINT128             0x13 /**< Signed 128-bit integer. */
+#define BLE_GATT_CPF_FORMAT_FLOAT32             0x14 /**< IEEE-754 32-bit floating point. */
+#define BLE_GATT_CPF_FORMAT_FLOAT64             0x15 /**< IEEE-754 64-bit floating point. */
+#define BLE_GATT_CPF_FORMAT_SFLOAT              0x16 /**< IEEE-11073 16-bit SFLOAT. */
+#define BLE_GATT_CPF_FORMAT_FLOAT               0x17 /**< IEEE-11073 32-bit FLOAT. */
+#define BLE_GATT_CPF_FORMAT_DUINT16             0x18 /**< IEEE-20601 format. */
+#define BLE_GATT_CPF_FORMAT_UTF8S               0x19 /**< UTF-8 string. */
+#define BLE_GATT_CPF_FORMAT_UTF16S              0x1A /**< UTF-16 string. */
+#define BLE_GATT_CPF_FORMAT_STRUCT              0x1B /**< Opaque Structure. */
+/** @} */
+
+/** @defgroup BLE_GATT_CPF_NAMESPACES GATT Bluetooth Namespaces
+ * @{
+ */
+#define BLE_GATT_CPF_NAMESPACE_BTSIG            0x01 /**< Bluetooth SIG defined Namespace. */
+#define BLE_GATT_CPF_NAMESPACE_DESCRIPTION_UNKNOWN 0x0000 /**< Namespace Description Unknown. */
+/** @} */
+
+/** @} */
+
+/** @addtogroup BLE_GATT_STRUCTURES Structures
+ * @{ */
+
+/**@brief GATT Characteristic Properties. */
+typedef struct
+{
+  /* Standard properties */
+  uint8_t broadcast       :1; /**< Broadcasting of the value permitted. */
+  uint8_t read            :1; /**< Reading the value permitted. */
+  uint8_t write_wo_resp   :1; /**< Writing the value with Write Command permitted. */
+  uint8_t write           :1; /**< Writing the value with Write Request permitted. */
+  uint8_t notify          :1; /**< Notications of the value permitted. */
+  uint8_t indicate        :1; /**< Indications of the value permitted. */
+  uint8_t auth_signed_wr  :1; /**< Writing the value with Signed Write Command permitted. */
+} ble_gatt_char_props_t;
+
+/**@brief GATT Characteristic Extended Properties. */
+typedef struct
+{
+  /* Extended properties */
+  uint8_t reliable_wr     :1; /**< Writing the value with Queued Write operations permitted. */
+  uint8_t wr_aux          :1; /**< Writing the Characteristic User Description descriptor permitted. */
+} ble_gatt_char_ext_props_t;
+
+#endif // BLE_GATT_H__
+
+/** @} */
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gattc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gattc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,437 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_GATTC Generic Attribute Profile (GATT) Client
+  @{
+  @brief  Definitions and prototypes for the GATT Client interface.
+ */
+
+#ifndef BLE_GATTC_H__
+#define BLE_GATTC_H__
+
+#include "ble_gatt.h"
+#include "ble_types.h"
+#include "ble_ranges.h"
+#include "nrf_svc.h"
+
+/** @addtogroup BLE_GATTC_ENUMERATIONS Enumerations
+ * @{ */
+
+/**@brief GATTC API SVC numbers. */
+enum BLE_GATTC_SVCS
+{
+  SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */
+  SD_BLE_GATTC_RELATIONSHIPS_DISCOVER,                         /**< Relationship Discovery. */
+  SD_BLE_GATTC_CHARACTERISTICS_DISCOVER,                       /**< Characteristic Discovery. */
+  SD_BLE_GATTC_DESCRIPTORS_DISCOVER,                           /**< Characteristic Descriptor Discovery. */
+  SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ,                        /**< Read Characteristic Value by UUID. */
+  SD_BLE_GATTC_READ,                                           /**< Generic read. */
+  SD_BLE_GATTC_CHAR_VALUES_READ,                               /**< Read multiple Characteristic Values. */
+  SD_BLE_GATTC_WRITE,                                          /**< Generic write. */
+  SD_BLE_GATTC_HV_CONFIRM                                      /**< Handle Value Confirmation. */
+};
+
+/**
+ * @brief GATT Client Event IDs.
+ */
+enum BLE_GATTC_EVTS
+{
+  BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE,  /**< Primary Service Discovery Response event. @ref ble_gattc_evt_prim_srvc_disc_rsp_t */
+  BLE_GATTC_EVT_REL_DISC_RSP,                             /**< Relationship Discovery Response event. @ref ble_gattc_evt_rel_disc_rsp_t */
+  BLE_GATTC_EVT_CHAR_DISC_RSP,                            /**< Characteristic Discovery Response event. @ref ble_gattc_evt_char_disc_rsp_t */
+  BLE_GATTC_EVT_DESC_DISC_RSP,                            /**< Descriptor Discovery Response event. @ref ble_gattc_evt_desc_disc_rsp_t */
+  BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP,                /**< Read By UUID Response event. @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t */
+  BLE_GATTC_EVT_READ_RSP,                                 /**< Read Response event. @ref ble_gattc_evt_read_rsp_t */
+  BLE_GATTC_EVT_CHAR_VALS_READ_RSP,                       /**< Read multiple Response event. @ref ble_gattc_evt_char_vals_read_rsp_t */
+  BLE_GATTC_EVT_WRITE_RSP,                                /**< Write Response event. @ref ble_gattc_evt_write_rsp_t */
+  BLE_GATTC_EVT_HVX,                                      /**< Handle Value Notification or Indication event. @ref ble_gattc_evt_hvx_t */
+  BLE_GATTC_EVT_TIMEOUT                                   /**< Timeout event. @ref ble_gattc_evt_timeout_t */
+};
+
+/** @} */
+
+/** @addtogroup BLE_GATTC_DEFINES Defines
+ * @{ */
+
+/** @defgroup BLE_ERRORS_GATTC SVC return values specific to GATTC
+ * @{ */
+#define BLE_ERROR_GATTC_PROC_NOT_PERMITTED    (NRF_GATTC_ERR_BASE + 0x000) /**< Procedure not Permitted. */
+/** @} */
+
+/**@brief Last Attribute Handle. */
+#define BLE_GATTC_HANDLE_END                0xFFFF
+
+/** @} */
+
+/** @addtogroup BLE_GATTC_STRUCTURES Structures
+ * @{ */
+
+/**@brief Operation Handle Range. */
+typedef struct
+{
+  uint16_t          start_handle; /**< Start Handle. */
+  uint16_t          end_handle;   /**< End Handle. */
+} ble_gattc_handle_range_t;
+
+
+/**@brief GATT service. */
+typedef struct
+{
+  ble_uuid_t               uuid;          /**< Service UUID. */
+  ble_gattc_handle_range_t handle_range;  /**< Service Handle Range. */
+} ble_gattc_service_t;
+
+
+/**@brief  GATT include. */
+typedef struct
+{
+  uint16_t            handle;           /**< Include Handle. */
+  ble_gattc_service_t included_srvc;    /**< Handle of the included service. */
+} ble_gattc_include_t;
+
+
+/**@brief GATT characteristic. */
+typedef struct
+{
+  ble_uuid_t              uuid;                 /**< Characteristic UUID. */
+  ble_gatt_char_props_t   char_props;           /**< Characteristic Properties. */
+  uint8_t                 char_ext_props : 1;   /**< Extended properties present. */
+  uint16_t                handle_decl;          /**< Handle of the Characteristic Declaration. */
+  uint16_t                handle_value;         /**< Handle of the Characteristic Value. */
+} ble_gattc_char_t;
+
+
+/**@brief GATT descriptor. */
+typedef struct
+{
+  uint16_t          handle;         /**< Descriptor Handle. */
+  ble_uuid_t        uuid;           /**< Descriptor UUID. */
+} ble_gattc_desc_t;
+
+
+/**@brief Write Parameters. */
+typedef struct
+{
+  uint8_t    write_op;                 /**< Write Operation to be performed, see @ref BLE_GATT_WRITE_OPS. */
+  uint8_t    flags;                    /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */
+  uint16_t   handle;                   /**< Handle to the attribute to be written. */
+  uint16_t   offset;                   /**< Offset in bytes. @note For WRITE_CMD and WRITE_REQ, offset must be 0. */
+  uint16_t   len;                      /**< Length of data in bytes. */
+  uint8_t   *p_value;                  /**< Pointer to the value data. */
+} ble_gattc_write_params_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP. */
+typedef struct
+{
+  uint16_t             count;           /**< Service count. */
+  ble_gattc_service_t services[1];      /**< Service data, variable length. */
+} ble_gattc_evt_prim_srvc_disc_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_REL_DISC_RSP. */
+typedef struct
+{
+  uint16_t             count;           /**< Include count. */
+  ble_gattc_include_t includes[1];      /**< Include data, variable length. */
+} ble_gattc_evt_rel_disc_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_DISC_RSP. */
+typedef struct
+{
+  uint16_t            count;          /**< Characteristic count. */
+  ble_gattc_char_t    chars[1];       /**< Characteristic data, variable length. */
+} ble_gattc_evt_char_disc_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_DESC_DISC_RSP. */
+typedef struct
+{
+  uint16_t            count;          /**< Descriptor count. */
+  ble_gattc_desc_t    descs[1];       /**< Descriptor data, variable length. */
+} ble_gattc_evt_desc_disc_rsp_t;
+
+/**@brief GATT read by UUID handle value pair. */
+typedef struct 
+{
+  uint16_t            handle;          /**< Attribute Handle. */
+  uint8_t             *p_value;        /**< Pointer to value, variable length (length available as value_len in @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t). 
+                                            Please note that this pointer is absolute to the memory provided by the user when retrieving the event,
+                                            so it will effectively point to a location inside the handle_value array. */
+} ble_gattc_handle_value_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP. */
+typedef struct
+{
+  uint16_t                  count;            /**< Handle-Value Pair Count. */
+  uint16_t                  value_len;        /**< Length of the value in Handle-Value(s) list. */
+  ble_gattc_handle_value_t  handle_value[1];  /**< Handle-Value(s) list, variable length. */
+} ble_gattc_evt_char_val_by_uuid_read_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_READ_RSP. */
+typedef struct
+{
+  uint16_t            handle;         /**< Attribute Handle. */
+  uint16_t            offset;         /**< Offset of the attribute data. */
+  uint16_t            len;            /**< Attribute data length. */
+  uint8_t             data[1];        /**< Attribute data, variable length. */
+} ble_gattc_evt_read_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VALS_READ_RSP. */
+typedef struct
+{
+  uint16_t            len;            /**< Concatenated Attribute values length. */
+  uint8_t             values[1];      /**< Attribute values, variable length. */
+} ble_gattc_evt_char_vals_read_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_WRITE_RSP. */
+typedef struct
+{
+  uint16_t            handle;           /**< Attribute Handle. */
+  uint8_t             write_op;         /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */
+  uint16_t            offset;           /**< Data offset. */
+  uint16_t            len;              /**< Data length. */
+  uint8_t             data[1];          /**< Data, variable length. */
+} ble_gattc_evt_write_rsp_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_HVX. */
+typedef struct
+{
+  uint16_t            handle;         /**< Handle to which the HVx operation applies. */
+  uint8_t             type;           /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */
+  uint16_t            len;            /**< Attribute data length. */
+  uint8_t             data[1];        /**< Attribute data, variable length. */
+} ble_gattc_evt_hvx_t;
+
+/**@brief Event structure for @ref BLE_GATTC_EVT_TIMEOUT. */
+typedef struct
+{
+  uint8_t          src;                       /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */
+} ble_gattc_evt_timeout_t;
+
+/**@brief GATTC event structure. */
+typedef struct
+{
+  uint16_t            conn_handle;                /**< Connection Handle on which event occured. */
+  uint16_t            gatt_status;                /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */
+  uint16_t            error_handle;               /**< In case of error: The handle causing the error. In all other cases @ref BLE_GATT_HANDLE_INVALID. */
+  union
+  {
+    ble_gattc_evt_prim_srvc_disc_rsp_t          prim_srvc_disc_rsp;         /**< Primary Service Discovery Response Event Parameters. */
+    ble_gattc_evt_rel_disc_rsp_t                rel_disc_rsp;               /**< Relationship Discovery Response Event Parameters. */
+    ble_gattc_evt_char_disc_rsp_t               char_disc_rsp;              /**< Characteristic Discovery Response Event Parameters. */
+    ble_gattc_evt_desc_disc_rsp_t               desc_disc_rsp;              /**< Descriptor Discovery Response Event Parameters. */
+    ble_gattc_evt_char_val_by_uuid_read_rsp_t   char_val_by_uuid_read_rsp;  /**< Characteristic Value Read by UUID Response Event Parameters. */
+    ble_gattc_evt_read_rsp_t                    read_rsp;                   /**< Read Response Event Parameters. */
+    ble_gattc_evt_char_vals_read_rsp_t          char_vals_read_rsp;         /**< Characteristic Values Read Response Event Parameters. */
+    ble_gattc_evt_write_rsp_t                   write_rsp;                  /**< Write Response Event Parameters. */
+    ble_gattc_evt_hvx_t                         hvx;                        /**< Handle Value Notification/Indication Event Parameters. */
+    ble_gattc_evt_timeout_t                     timeout;                    /**< Timeout Event Parameters. */
+  } params;                                                                 /**< Event Parameters. @note Only valid if @ref gatt_status == @ref BLE_GATT_STATUS_SUCCESS. */
+} ble_gattc_evt_t;
+/** @} */
+
+/** @addtogroup BLE_GATTC_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Initiate or continue a GATT Primary Service Discovery procedure.
+ *
+ * @details This function initiates or resumes a Primary Service discovery procedure, starting from the supplied handle. 
+ *          If the last service has not been reached, this function must be called again with an updated start handle value to continue the search.
+ *
+ * @note If any of the discovered services have 128-bit UUIDs which are not present in the table provided to ble_vs_uuids_assign, a UUID structure with
+ *       type @ref BLE_UUID_TYPE_UNKNOWN will be received in the corresponding event.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] start_handle Handle to start searching from.
+ * @param[in] p_srvc_uuid Pointer to the service UUID to be found. If it is NULL, all primary services will be returned.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Primary Service Discovery procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER, uint32_t, sd_ble_gattc_primary_services_discover(uint16_t conn_handle, uint16_t start_handle, ble_uuid_t const *p_srvc_uuid));
+
+
+/**@brief Initiate or continue a GATT Relationship Discovery procedure.
+ *
+ * @details This function initiates or resumes the Find Included Services sub-procedure. If the last included service has not been reached,
+ *          this must be called again with an updated handle range to continue the search.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_handle_range A pointer to the range of handles of the Service to perform this procedure on.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Relationship Discovery procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, uint32_t, sd_ble_gattc_relationships_discover(uint16_t conn_handle, ble_gattc_handle_range_t const *p_handle_range));
+
+
+/**@brief Initiate or continue a GATT Characteristic Discovery procedure.
+ *
+ * @details This function initiates or resumes a Characteristic discovery procedure. If the last Characteristic has not been reached,
+ *          this must be called again with an updated handle range to continue the discovery.
+ *
+ * @note If any of the discovered characteristics have 128-bit UUIDs which are not present in the table provided to ble_vs_uuids_assign, a UUID structure with
+ *       type @ref BLE_UUID_TYPE_UNKNOWN will be received in the corresponding event.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_handle_range A pointer to the range of handles of the Service to perform this procedure on.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Characteristic Discovery procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, uint32_t, sd_ble_gattc_characteristics_discover(uint16_t conn_handle, ble_gattc_handle_range_t const *p_handle_range));
+
+
+/**@brief Initiate or continue a GATT Characteristic Descriptor Discovery procedure.
+ *
+ * @details This function initiates or resumes a Characteristic Descriptor discovery procedure. If the last Descriptor has not been reached,
+ *          this must be called again with an updated handle range to continue the discovery.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_handle_range A pointer to the range of handles of the Characteristic to perform this procedure on.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Descriptor Discovery procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_DESCRIPTORS_DISCOVER, uint32_t, sd_ble_gattc_descriptors_discover(uint16_t conn_handle, ble_gattc_handle_range_t const *p_handle_range));
+
+
+/**@brief Initiate or continue a GATT Read using Characteristic UUID procedure.
+ *
+ * @details This function initiates or resumes a Read using Characteristic UUID procedure. If the last Characteristic has not been reached,
+ *          this must be called again with an updated handle range to continue the discovery.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_uuid Pointer to a Characteristic value UUID to read.
+ * @param[in] p_handle_range A pointer to the range of handles to perform this procedure on.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Read using Characteristic UUID procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, uint32_t, sd_ble_gattc_char_value_by_uuid_read(uint16_t conn_handle, ble_uuid_t const *p_uuid, ble_gattc_handle_range_t const *p_handle_range));
+
+
+/**@brief Initiate or continue a GATT Read (Long) Characteristic or Descriptor procedure.
+ *
+ * @details This function initiates or resumes a GATT Read (Long) Characteristic or Descriptor procedure. If the Characteristic or Descriptor
+ *          to be read is longer than ATT_MTU - 1, this function must be called multiple times with appropriate offset to read the 
+ *          complete value.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] handle The handle of the attribute to be read.
+ * @param[in] offset Offset into the attribute value to be read.
+ *
+ * @retval ::NRF_SUCCESS Successfully started or resumed the Read (Long) procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_READ, uint32_t, sd_ble_gattc_read(uint16_t conn_handle, uint16_t handle, uint16_t offset));
+
+
+/**@brief Initiate a GATT Read Multiple Characteristic Values procedure.
+ *
+ * @details This function initiates a GATT Read Multiple Characteristic Values procedure. 
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_handles A pointer to the handle(s) of the attribute(s) to be read.
+ * @param[in] handle_count The number of handles in p_handles.
+ *
+ * @retval ::NRF_SUCCESS Successfully started the Read Multiple Characteristic Values procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY Client procedure already in progress.
+ */
+SVCALL(SD_BLE_GATTC_CHAR_VALUES_READ, uint32_t, sd_ble_gattc_char_values_read(uint16_t conn_handle, uint16_t const *p_handles, uint16_t handle_count));
+
+
+/**@brief Perform a Write (Characteristic Value or Descriptor, with or without response, signed or not, long or reliable) procedure.
+ *
+ * @details This function can perform all write procedures described in GATT. 
+ *
+ * @note    It is important to note that a write without response will <b>consume an application buffer</b>, and will therefore 
+ *          generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. A write (with response) on the other hand will use the 
+ *          standard client internal buffer and thus will only generate a @ref BLE_GATTC_EVT_WRITE_RSP event as soon as the write response 
+ *          has been received from the peer. Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] p_write_params A pointer to a write parameters structure.
+ *
+ * @retval ::NRF_SUCCESS Successfully started the Write procedure.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied.
+ * @retval ::NRF_ERROR_BUSY Procedure already in progress.
+ * @retval ::BLE_ERROR_NO_TX_BUFFERS There are no available buffers left.
+ */
+SVCALL(SD_BLE_GATTC_WRITE, uint32_t, sd_ble_gattc_write(uint16_t conn_handle, ble_gattc_write_params_t const *p_write_params));
+
+
+/**@brief Send a Handle Value Confirmation to the GATT Server.
+ *
+ * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on.
+ * @param[in] handle The handle of the attribute in the indication.
+ *
+ * @retval ::NRF_SUCCESS Successfully queued the Handle Value Confirmation for transmission.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State or no Indication pending to be confirmed.
+ * @retval ::BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle.
+ */
+SVCALL(SD_BLE_GATTC_HV_CONFIRM, uint32_t, sd_ble_gattc_hv_confirm(uint16_t conn_handle, uint16_t handle));
+
+/** @} */
+
+#endif /* BLE_GATTC_H__ */
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatts.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_gatts.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,635 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_GATTS Generic Attribute Profile (GATT) Server
+  @{
+  @brief  Definitions and prototypes for the GATTS interface.
+ */
+
+#ifndef BLE_GATTS_H__
+#define BLE_GATTS_H__
+
+#include "ble_types.h"
+#include "ble_ranges.h"
+#include "ble_l2cap.h"
+#include "ble_gap.h"
+#include "ble_gatt.h"
+#include "nrf_svc.h"
+
+/** @addtogroup BLE_GATTS_ENUMERATIONS Enumerations
+ * @{ */
+
+/**
+ * @brief GATTS API SVC numbers.
+ */
+enum BLE_GATTS_SVCS
+{
+  SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */
+  SD_BLE_GATTS_INCLUDE_ADD,                      /**< Add an included service. */
+  SD_BLE_GATTS_CHARACTERISTIC_ADD,               /**< Add a characteristic. */
+  SD_BLE_GATTS_DESCRIPTOR_ADD,                   /**< Add a generic attribute. */
+  SD_BLE_GATTS_VALUE_SET,                        /**< Set an attribute value. */
+  SD_BLE_GATTS_VALUE_GET,                        /**< Get an attribute value. */
+  SD_BLE_GATTS_HVX,                              /**< Handle Value Notification or Indication. */
+  SD_BLE_GATTS_SERVICE_CHANGED,                  /**< Perform a Service Changed Indication to one or more peers. */
+  SD_BLE_GATTS_RW_AUTHORIZE_REPLY,               /**< Reply to an authorization request for a read or write operation on one or more attributes. */ 
+  SD_BLE_GATTS_SYS_ATTR_SET,                     /**< Set the persistent system attributes for a connection. */  
+  SD_BLE_GATTS_SYS_ATTR_GET,                     /**< Retrieve the persistent system attributes. */
+};
+
+/**
+ * @brief GATT Server Event IDs.
+ */
+enum BLE_GATTS_EVTS
+{
+  BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE,       /**< Write operation performed. @ref ble_gatts_evt_write_t */
+  BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST,             /**< Read/Write Authorization request.@ref ble_gatts_evt_rw_authorize_request_t */
+  BLE_GATTS_EVT_SYS_ATTR_MISSING,                 /**< A persistent system attribute access is pending, awaiting a sd_ble_gatts_sys_attr_set(). @ref ble_gatts_evt_sys_attr_missing_t */
+  BLE_GATTS_EVT_HVC,                              /**< Handle Value Confirmation. @ref ble_gatts_evt_hvc_t */
+  BLE_GATTS_EVT_SC_CONFIRM,                       /**< Service Changed Confirmation. No additional event structure applies. */
+  BLE_GATTS_EVT_TIMEOUT                           /**< Timeout. @ref ble_gatts_evt_timeout_t */
+};
+/** @} */
+
+/** @addtogroup BLE_GATTS_DEFINES Defines
+ * @{ */
+
+/** @defgroup BLE_ERRORS_GATTS SVC return values specific to GATTS
+ * @{ */
+#define BLE_ERROR_GATTS_INVALID_ATTR_TYPE   (NRF_GATTS_ERR_BASE + 0x000) /**< Invalid attribute type. */
+#define BLE_ERROR_GATTS_SYS_ATTR_MISSING    (NRF_GATTS_ERR_BASE + 0x001) /**< System Attributes missing. */
+/** @} */
+
+/** @defgroup BLE_GATTS_ATTR_LENS_MAX Maximum attribute lengths
+ * @{ */
+#define BLE_GATTS_FIX_ATTR_LEN_MAX (510)  /**< Maximum length for fixed length Attribute Values. */
+#define BLE_GATTS_VAR_ATTR_LEN_MAX (512)  /**< Maximum length for variable length Attribute Values. */ 
+/** @} */
+
+/** @defgroup BLE_GATTS_SRVC_TYPES GATT Server Service Types
+ * @{ */
+#define BLE_GATTS_SRVC_TYPE_INVALID          0x00  /**< Invalid Service Type. */
+#define BLE_GATTS_SRVC_TYPE_PRIMARY          0x01  /**< Primary Service. */
+#define BLE_GATTS_SRVC_TYPE_SECONDARY        0x02  /**< Secondary Type. */
+/** @} */
+
+
+/** @defgroup BLE_GATTS_ATTR_TYPES GATT Server Attribute Types
+ * @{ */
+#define BLE_GATTS_ATTR_TYPE_INVALID         0x00  /**< Invalid Attribute Type. */
+#define BLE_GATTS_ATTR_TYPE_PRIM_SRVC_DECL  0x01  /**< Primary Service Declaration. */
+#define BLE_GATTS_ATTR_TYPE_SEC_SRVC_DECL   0x02  /**< Secondary Service Declaration. */
+#define BLE_GATTS_ATTR_TYPE_INC_DECL        0x03  /**< Include Declaration. */
+#define BLE_GATTS_ATTR_TYPE_CHAR_DECL       0x04  /**< Characteristic Declaration. */
+#define BLE_GATTS_ATTR_TYPE_CHAR_VAL        0x05  /**< Characteristic Value. */
+#define BLE_GATTS_ATTR_TYPE_DESC            0x06  /**< Descriptor. */
+#define BLE_GATTS_ATTR_TYPE_OTHER           0x07  /**< Other, non-GATT specific type. */
+/** @} */
+
+
+/** @defgroup BLE_GATTS_OPS GATT Server Operations
+ * @{ */
+#define BLE_GATTS_OP_INVALID                0x00  /**< Invalid Operation. */
+#define BLE_GATTS_OP_WRITE_REQ              0x01  /**< Write Request. */
+#define BLE_GATTS_OP_WRITE_CMD              0x02  /**< Write Command. */
+#define BLE_GATTS_OP_SIGN_WRITE_CMD         0x03  /**< Signed Write Command. */
+#define BLE_GATTS_OP_PREP_WRITE_REQ         0x04  /**< Prepare Write Request. */
+#define BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL  0x05  /**< Execute Write Request: Cancel all prepared writes. */
+#define BLE_GATTS_OP_EXEC_WRITE_REQ_NOW     0x06  /**< Execute Write Request: Immediately execute all prepared writes. */
+/** @} */
+
+/** @defgroup BLE_GATTS_VLOCS GATT Value Locations
+ * @{ */
+#define BLE_GATTS_VLOC_INVALID       0x00  /**< Invalid Location. */
+#define BLE_GATTS_VLOC_STACK         0x01  /**< Attribute Value is located in stack memory, no user memory is required. */
+#define BLE_GATTS_VLOC_USER          0x02  /**< Attribute Value is located in user memory. This requires the user to maintain a valid buffer through the lifetime of the attribute, since the stack
+                                                will read and write directly to the memory using the pointer provided in the APIs. There are no alignment requirements for the buffer. */
+/** @} */
+
+/** @defgroup BLE_GATTS_AUTHORIZE_TYPES GATT Server Authorization Types
+ * @{ */
+#define BLE_GATTS_AUTHORIZE_TYPE_INVALID    0x00  /**< Invalid Type. */
+#define BLE_GATTS_AUTHORIZE_TYPE_READ       0x01  /**< Authorize a Read Operation. */
+#define BLE_GATTS_AUTHORIZE_TYPE_WRITE      0x02  /**< Authorize a Write Request Operation. */
+/** @} */
+
+/** @defgroup BLE_GATTS_SYS_ATTR_FLAGS System Attribute Flags
+ * @{ */
+#define BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS (1 << 0)  /**< Restrict system attributes to system services only. */
+#define BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS (1 << 1)  /**< Restrict system attributes to user services only. */
+/** @} */
+
+/** @defgroup BLE_GATTS_ATTR_TAB_SIZE Attribute Table size
+ * @{
+ */
+#define BLE_GATTS_ATTR_TAB_SIZE_MIN         216    /**< Minimum Attribute Table size */
+#define BLE_GATTS_ATTR_TAB_SIZE_DEFAULT     0x0000 /**< Default Attribute Table size (0x600 bytes for this version of the SoftDevice). */
+/** @} */
+
+/** @} */
+
+/** @addtogroup BLE_GATTS_STRUCTURES Structures
+ * @{ */
+
+/**
+ * @brief BLE GATTS init options
+ */
+typedef struct
+{
+  uint8_t   service_changed:1;             /**< Include the Service Changed characteristic in the Attribute Table. */
+  uint32_t  attr_tab_size;                 /**< Attribute Table size in bytes. The size must be a multiple of 4. @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT is used to set the default size. */
+} ble_gatts_enable_params_t;
+
+/**@brief Attribute metadata. */
+typedef struct
+{
+  ble_gap_conn_sec_mode_t read_perm;       /**< Read permissions. */
+  ble_gap_conn_sec_mode_t write_perm;      /**< Write permissions. */
+  uint8_t                 vlen       :1;   /**< Variable length attribute. */
+  uint8_t                 vloc       :2;   /**< Value location, see @ref BLE_GATTS_VLOCS.*/
+  uint8_t                 rd_auth    :1;   /**< Read authorization and value will be requested from the application on every read operation. */ 
+  uint8_t                 wr_auth    :1;   /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */
+} ble_gatts_attr_md_t;
+
+
+/**@brief GATT Attribute. */
+typedef struct
+{
+  ble_uuid_t          *p_uuid;          /**< Pointer to the attribute UUID. */
+  ble_gatts_attr_md_t *p_attr_md;       /**< Pointer to the attribute metadata structure. */
+  uint16_t             init_len;        /**< Initial attribute value length in bytes. */
+  uint16_t             init_offs;       /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */
+  uint16_t             max_len;         /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */
+  uint8_t*             p_value;         /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer
+                                             that remains valid through the lifetime of the attribute. This excludes usage of automatic variables that may go out of scope or any other temporary location. 
+                                             The stack may access that memory directly without the application's knowledge. For writable characteristics, this value must not be a location in flash memory.*/
+} ble_gatts_attr_t;
+
+/**@brief GATT Attribute Value. */
+typedef struct
+{
+  uint16_t  len;        /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/
+  uint16_t  offset;     /**< Attribute value offset. */
+  uint8_t   *p_value;   /**< Pointer to where value is stored or will be stored. 
+                             If value is stored in user memory, only the attribute length is updated when p_value == NULL.
+                             Set to NULL when reading to obtain the complete length of the attribute value */
+} ble_gatts_value_t;
+
+
+/**@brief GATT Attribute Context. */
+typedef struct
+{
+  ble_uuid_t           srvc_uuid;       /**< Service UUID. */
+  ble_uuid_t           char_uuid;       /**< Characteristic UUID if applicable (BLE_UUID_TYPE_UNKNOWN otherwise). */
+  ble_uuid_t           desc_uuid;       /**< Descriptor UUID if applicable (BLE_UUID_TYPE_UNKNOWN otherwise). */
+  uint16_t             srvc_handle;     /**< Service Handle. */
+  uint16_t             value_handle;    /**< Characteristic Value Handle if applicable (BLE_GATT_HANDLE_INVALID otherwise). */
+  uint8_t              type;            /**< Attribute Type, see @ref BLE_GATTS_ATTR_TYPES. */
+} ble_gatts_attr_context_t;
+
+
+/**@brief GATT Characteristic Presentation Format. */
+typedef struct
+{
+  uint8_t          format;      /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */
+  int8_t           exponent;    /**< Exponent for integer data types. */
+  uint16_t         unit;        /**< Unit from Bluetooth Assigned Numbers. */
+  uint8_t          name_space;  /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */
+  uint16_t         desc;        /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */
+} ble_gatts_char_pf_t;
+
+
+/**@brief GATT Characteristic metadata. */
+typedef struct
+{
+  ble_gatt_char_props_t       char_props;               /**< Characteristic Properties. */
+  ble_gatt_char_ext_props_t   char_ext_props;           /**< Characteristic Extended Properties. */
+  uint8_t                    *p_char_user_desc;         /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */
+  uint16_t                    char_user_desc_max_size;  /**< The maximum size in bytes of the user description descriptor. */
+  uint16_t                    char_user_desc_size;      /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ 
+  ble_gatts_char_pf_t*        p_char_pf;                /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */
+  ble_gatts_attr_md_t*        p_user_desc_md;           /**< Attribute metadata for the User Description descriptor, or NULL for default values. */
+  ble_gatts_attr_md_t*        p_cccd_md;                /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */
+  ble_gatts_attr_md_t*        p_sccd_md;                /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */
+} ble_gatts_char_md_t;
+
+
+/**@brief GATT Characteristic Definition Handles. */
+typedef struct
+{
+  uint16_t          value_handle;       /**< Handle to the characteristic value. */
+  uint16_t          user_desc_handle;   /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
+  uint16_t          cccd_handle;        /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
+  uint16_t          sccd_handle;        /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
+} ble_gatts_char_handles_t;
+
+
+/**@brief GATT HVx parameters. */
+typedef struct
+{
+  uint16_t          handle;             /**< Characteristic Value Handle. */
+  uint8_t           type;               /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */
+  uint16_t          offset;             /**< Offset within the attribute value. */
+  uint16_t         *p_len;              /**< Length in bytes to be written, length in bytes written after successful return. */
+  uint8_t          *p_data;             /**< Actual data content, use NULL to use the current attribute value. */
+} ble_gatts_hvx_params_t;
+
+/**@brief GATT Read Authorization parameters. */
+typedef struct
+{
+  uint16_t          gatt_status;        /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */
+  uint8_t           update : 1;         /**< If set, data supplied in p_data will be used in the ATT response. */
+  uint16_t          offset;             /**< Offset of the attribute value being updated. */
+  uint16_t          len;                /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */
+  uint8_t          *p_data;             /**< Pointer to new value used to update the attribute value. */
+} ble_gatts_read_authorize_params_t;
+
+/**@brief GATT Write Authorization parameters. */
+typedef struct
+{
+  uint16_t          gatt_status;        /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */
+} ble_gatts_write_authorize_params_t;
+
+/**@brief GATT Read or Write Authorize Reply parameters. */
+typedef struct
+{
+  uint8_t                               type;   /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */
+  union {
+    ble_gatts_read_authorize_params_t   read;   /**< Read authorization parameters. */
+    ble_gatts_write_authorize_params_t  write;  /**< Write authorization parameters. */
+  } params;                                     /**< Reply Parameters. */
+} ble_gatts_rw_authorize_reply_params_t;
+
+
+
+/**@brief Event structure for @ref BLE_GATTS_EVT_WRITE. */
+typedef struct
+{
+  uint16_t                    handle;             /**< Attribute Handle. */
+  uint8_t                     op;                 /**< Type of write operation, see @ref BLE_GATTS_OPS. */
+  ble_gatts_attr_context_t    context;            /**< Attribute Context. */
+  uint16_t                    offset;             /**< Offset for the write operation. */
+  uint16_t                    len;                /**< Length of the received data. */
+  uint8_t                     data[1];            /**< Received data, variable length. */
+} ble_gatts_evt_write_t;
+
+/**@brief Event substructure for authorized read requests, see @ref ble_gatts_evt_rw_authorize_request_t. */
+typedef struct
+{
+  uint16_t                    handle;             /**< Attribute Handle. */
+  ble_gatts_attr_context_t    context;            /**< Attribute Context. */
+  uint16_t                    offset;             /**< Offset for the read operation. */
+} ble_gatts_evt_read_t;
+
+/**@brief Event structure for @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST. */
+typedef struct
+{
+  uint8_t                     type;             /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */
+  union {
+    ble_gatts_evt_read_t      read;             /**< Attribute Read Parameters. */
+    ble_gatts_evt_write_t     write;            /**< Attribute Write Parameters. */
+  } request;                                    /**< Request Parameters. */
+} ble_gatts_evt_rw_authorize_request_t;
+
+/**@brief Event structure for @ref BLE_GATTS_EVT_SYS_ATTR_MISSING. */
+typedef struct
+{
+  uint8_t hint;                                 /**< Hint (currently unused). */
+} ble_gatts_evt_sys_attr_missing_t;
+
+
+/**@brief Event structure for @ref BLE_GATTS_EVT_HVC. */
+typedef struct
+{
+  uint16_t          handle;                       /**< Attribute Handle. */
+} ble_gatts_evt_hvc_t;
+
+/**@brief Event structure for @ref BLE_GATTS_EVT_TIMEOUT. */
+typedef struct
+{
+  uint8_t          src;                       /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */
+} ble_gatts_evt_timeout_t;
+
+
+/**@brief GATT Server event callback event structure. */
+typedef struct
+{
+  uint16_t conn_handle;                                       /**< Connection Handle on which the event occurred. */
+  union
+  {
+    ble_gatts_evt_write_t                 write;              /**< Write Event Parameters. */
+    ble_gatts_evt_rw_authorize_request_t  authorize_request;  /**< Read or Write Authorize Request Parameters. */
+    ble_gatts_evt_sys_attr_missing_t      sys_attr_missing;   /**< System attributes missing. */
+    ble_gatts_evt_hvc_t                   hvc;                /**< Handle Value Confirmation Event Parameters. */
+    ble_gatts_evt_timeout_t               timeout;            /**< Timeout Event. */
+  } params;                                                   /**< Event Parameters. */
+} ble_gatts_evt_t;
+
+/** @} */
+
+/** @addtogroup BLE_GATTS_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Add a service declaration to the Attribute Table.
+ *
+ * @param[in] type      Toggles between primary and secondary services, see @ref BLE_GATTS_SRVC_TYPES.
+ * @param[in] p_uuid    Pointer to service UUID.
+ * @param[out] p_handle Pointer to a 16-bit word where the assigned handle will be stored.
+ *
+ * @note Secondary Services are only relevant in the context of the entity that references them, it is therefore forbidden to
+ *       add a secondary service declaration that is not referenced by another service later in the Attribute Table.
+ *
+ * @retval ::NRF_SUCCESS Successfully added a service declaration.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, Vendor Specific UUIDs need to be present in the table.
+ * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ */
+SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t *p_handle));
+
+
+/**@brief Add an include declaration to the Attribute Table.
+ *
+ * @note It is currently only possible to add an include declaration to the last added service (i.e. only sequential population is supported at this time). 
+ *
+ * @note The included service must already be present in the Attribute Table prior to this call.
+ *
+ * @param[in] service_handle    Handle of the service where the included service is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
+ * @param[in] inc_srvc_handle   Handle of the included service.
+ * @param[out] p_include_handle Pointer to a 16-bit word where the assigned handle will be stored.
+ *
+ * @retval ::NRF_SUCCESS Successfully added an include declaration.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, handle values need to match previously added services.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
+ * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, self inclusions are not allowed.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
+ */
+SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t *p_include_handle));
+
+
+/**@brief Add a characteristic declaration, a characteristic value declaration and optional characteristic descriptor declarations to the Attribute Table.
+ *
+ * @note It is currently only possible to add a characteristic to the last added service (i.e. only sequential population is supported at this time). 
+ *
+ * @note Several restrictions apply to the parameters, such as matching permissions between the user description descriptor and the writeable auxiliaries bits,
+ *       readable (no security) and writeable (selectable) CCCDs and SCCDs and valid presentation format values.
+ *
+ * @note If no metadata is provided for the optional descriptors, their permissions will be derived from the characteristic permissions.
+ *
+ * @param[in] service_handle    Handle of the service where the characteristic is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
+ * @param[in] p_char_md         Characteristic metadata.
+ * @param[in] p_attr_char_value Pointer to the attribute structure corresponding to the characteristic value.
+ * @param[out] p_handles        Pointer to the structure where the assigned handles will be stored.
+ *
+ * @retval ::NRF_SUCCESS Successfully added a characteristic.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, service handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, a service context is required.
+ * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
+ */
+SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t *p_handles));
+
+
+/**@brief Add a descriptor to the Attribute Table.
+ *
+ * @note It is currently only possible to add a descriptor to the last added characteristic (i.e. only sequential population is supported at this time). 
+ *
+ * @param[in] char_handle   Handle of the characteristic where the descriptor is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
+ * @param[in] p_attr        Pointer to the attribute structure.
+ * @param[out] p_handle     Pointer to a 16-bit word where the assigned handle will be stored.
+ *
+ * @retval ::NRF_SUCCESS Successfully added a descriptor.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, characteristic handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, a characteristic context is required.
+ * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
+ */
+SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t *p_handle));
+
+/**@brief Set the value of a given attribute.
+ *
+ * @param[in] conn_handle  Connection handle. If the value does not belong to a system attribute then @ref BLE_CONN_HANDLE_INVALID can be used.
+ * @param[in] handle       Attribute handle.
+ * @param[in,out] p_value  Attribute value information.
+ *
+ * @note Values other than system attributes can be set at any time, regardless of wheter any active connections exist.
+ *
+ * @retval ::NRF_SUCCESS Successfully set the value of the attribute.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
+ * @retval ::NRF_ERROR_FORBIDDEN Forbidden handle supplied, certain attributes are not modifiable by the application.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE @ref BLE_CONN_HANDLE_INVALID supplied on a system attribute.
+ */
+SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value));
+
+/**@brief Get the value of a given attribute.
+ *
+ * @param[in] conn_handle  Connection handle. If the value does not belong to a system attribute then @ref BLE_CONN_HANDLE_INVALID can be used.
+ * @param[in] handle       Attribute handle.
+ * @param[in,out] p_value  Attribute value information.
+ *
+ * @note                 If the attribute value is longer than the size of the supplied buffer,
+ *                       p_len will return the total attribute value length (excluding offset),
+ *                       and not the number of bytes actually returned in p_data.
+ *                       The application may use this information to allocate a suitable buffer size.
+ * 
+ * @note                 When retrieving system attribute values with this function, the connection handle
+ *                       may refer to an already disconnected connection. Refer to the documentation of
+ *                       @ref sd_ble_gatts_sys_attr_get for further information.
+ *
+ * @retval ::NRF_SUCCESS Successfully retrieved the value of the attribute.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
+ * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE @ref BLE_CONN_HANDLE_INVALID supplied on a system attribute.
+ */
+SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value));
+
+/**@brief Notify or Indicate an attribute value.
+ *
+ * @details This function checks for the relevant Client Characteristic Configuration descriptor value to verify that the relevant operation
+ *          (notification or indication) has been enabled by the client. It is also able to update the attribute value before issuing the PDU, so that
+ *          the application can atomically perform a value update and a server initiated transaction with a single API call.
+ *          If the application chooses to indicate an attribute value, a @ref BLE_GATTS_EVT_HVC event will be issued as soon as the confirmation arrives from
+ *          the peer.
+ *
+ * @note    The local attribute value may be updated even if an outgoing packet is not sent to the peer due to an error during execution. 
+ *          When receiveing the error codes @ref NRF_ERROR_INVALID_STATE, @ref NRF_ERROR_BUSY, @ref BLE_ERROR_GATTS_SYS_ATTR_MISSING and 
+ *          @ref BLE_ERROR_NO_TX_BUFFERS the Attribute Table has been updated.
+ *          The caller can check whether the value has been updated by looking at the contents of *(p_hvx_params->p_len).
+ *
+ * @note    It is important to note that a notification will <b>consume an application buffer</b>, and will therefore 
+ *          generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. An indication on the other hand will use the 
+ *          standard server internal buffer and thus will only generate a @ref BLE_GATTS_EVT_HVC event as soon as the confirmation 
+ *          has been received from the peer. Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details.
+ *
+ * @param[in] conn_handle  Connection handle.
+ * @param[in] p_hvx_params Pointer to an HVx parameters structure. If the p_data member contains a non-NULL pointer the attribute value will be updated with
+ *                         the contents pointed by it before sending the notification or indication.
+ *
+ * @retval ::NRF_SUCCESS Successfully queued a notification or indication for transmission, and optionally updated the attribute value.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State or notifications and/or indications not enabled in the CCCD.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied. Only attributes added directly by the application are available to notify and indicate.
+ * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE Invalid attribute type(s) supplied, only characteristic values may be notified and indicated.
+ * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied.
+ * @retval ::NRF_ERROR_BUSY Procedure already in progress.
+ * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value.
+ * @retval ::BLE_ERROR_NO_TX_BUFFERS There are no available buffers to send the data, applies only to notifications.
+ */
+SVCALL(SD_BLE_GATTS_HVX, uint32_t, sd_ble_gatts_hvx(uint16_t conn_handle, ble_gatts_hvx_params_t const *p_hvx_params));
+
+/**@brief Indicate the Service Changed attribute value.
+ *
+ * @details This call will send a Handle Value Indication to one or more peers connected to inform them that the Attribute
+ *          Table layout has changed. As soon as the peer has confirmed the indication, a @ref BLE_GATTS_EVT_SC_CONFIRM event will
+ *          be issued.
+ *
+ * @note    Some of the restrictions and limitations that apply to @ref sd_ble_gatts_hvx also apply here.
+ *
+ * @param[in] conn_handle  Connection handle.
+ * @param[in] start_handle Start of affected attribute handle range.
+ * @param[in] end_handle   End of affected attribute handle range.
+ *
+ * @retval ::NRF_SUCCESS Successfully queued the Service Changed indication for transmission.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State or notifications and/or indications not enabled in the CCCD.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied, handles must be in the range populated by the application.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, notifications or indications must be enabled in the CCCD.
+ * @retval ::NRF_ERROR_BUSY Procedure already in progress.
+ * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value.
+ */
+SVCALL(SD_BLE_GATTS_SERVICE_CHANGED, uint32_t, sd_ble_gatts_service_changed(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle));
+
+/**@brief Respond to a Read/Write authorization request.
+ *
+ * @note This call should only be used as a response to a @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST event issued to the application.
+ *
+ * @param[in] conn_handle                 Connection handle.
+ * @param[in] p_rw_authorize_reply_params Pointer to a structure with the attribute provided by the application.
+ *
+ * @retval ::NRF_SUCCESS               Successfully queued a response to the peer, and in the case of a write operation, Attribute Table updated.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE   Invalid Connection State or no authorization request pending.
+ * @retval ::NRF_ERROR_INVALID_PARAM   Authorization op invalid,
+ *                                         or for Read Authorization reply: requested handles not replied with,
+ *                                         or for Write Authorization reply: handle supplied does not match requested handle.
+ * @retval ::NRF_ERROR_BUSY The stack is busy. Retry at later time.
+ */
+SVCALL(SD_BLE_GATTS_RW_AUTHORIZE_REPLY, uint32_t, sd_ble_gatts_rw_authorize_reply(uint16_t conn_handle, ble_gatts_rw_authorize_reply_params_t const *p_rw_authorize_reply_params));
+
+
+/**@brief Update persistent system attribute information.
+ *
+ * @details Supply information about persistent system attributes to the stack, 
+ *          previously obtained using @ref sd_ble_gatts_sys_attr_get.
+ *          This call is only allowed for active connections, and is usually 
+ *          made immediately after a connection is established with an known bonded device,
+ *          often as a response to a @ref BLE_GATTS_EVT_SYS_ATTR_MISSING.
+ *
+ *          p_sysattrs may point directly to the application's stored copy of the system attributes 
+ *          obtained using @ref sd_ble_gatts_sys_attr_get.
+ *          If the pointer is NULL, the system attribute info is initialized, assuming that
+ *          the application does not have any previously saved system attribute data for this device.
+ *
+ * @note The state of persistent system attributes is reset upon connection establishment and then remembered for its duration. 
+ *
+ * @note If this call returns with an error code different from @ref NRF_SUCCESS, the storage of persistent system attributes may have been completed only partially.
+ *       This means that the state of the attribute table is undefined, and the application should either provide a new set of attributes using this same call or
+ *       reset the SoftDevice to return to a known state.
+ *
+ * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS is used with this function, only the system attributes included in system services will be modified.
+ * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS is used with this function, only the system attributes included in user services will be modified.
+ *
+ * @param[in]  conn_handle        Connection handle.
+ * @param[in]  p_sys_attr_data    Pointer to a saved copy of system attributes supplied to the stack, or NULL.
+ * @param[in]  len                Size of data pointed by p_sys_attr_data, in octets. 
+ * @param[in]  flags              Optional additional flags, see @ref BLE_GATTS_SYS_ATTR_FLAGS
+ *
+ * @retval ::NRF_SUCCESS Successfully set the system attribute information.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE   Invalid Connection State.
+ * @retval ::NRF_ERROR_INVALID_DATA Invalid data supplied, the data should be exactly the same as retrieved with @ref sd_ble_gatts_sys_attr_get.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ * @retval ::NRF_ERROR_BUSY The stack is busy. Retry at later time.
+ */ 
+SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t conn_handle, uint8_t const *p_sys_attr_data, uint16_t len, uint32_t flags)); 
+
+ 
+/**@brief Retrieve persistent system attribute information from the stack.
+ *
+ * @details This call is used to retrieve information about values to be stored perisistently by the application
+ *          during the lifetime of a connection or after it has been terminated. When a new connection is established with the same bonded device, 
+ *          the system attribute information retrieved with this function should be restored using using @ref sd_ble_gatts_sys_attr_set.
+ *          If retrieved after disconnection, the data should be read before a new connection established. The connection handle for
+ *          the previous, now disconnected, connection will remain valid until a new one is created to allow this API call to refer to it.
+ *          Connection handles belonging to active connections can be used as well, but care should be taken since the system attributes
+ *          may be written to at any time by the peer during a connection's lifetime.
+ *
+ * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS is used with this function, only the system attributes included in system services will be returned.
+ * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS is used with this function, only the system attributes included in user services will be returned.
+ *
+ * @param[in]     conn_handle       Connection handle of the recently terminated connection.
+ * @param[out]    p_sys_attr_data   Pointer to a buffer where updated information about system attributes will be filled in. NULL can be provided to 
+ *                                  obtain the length of the data
+ * @param[in,out] p_len             Size of application buffer if p_sys_attr_data is not NULL. Unconditially updated to actual length of system attribute data.
+ * @param[in]     flags             Optional additional flags, see @ref BLE_GATTS_SYS_ATTR_FLAGS
+ *
+ * @retval ::NRF_SUCCESS Successfully retrieved the system attribute information.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_DATA_SIZE The system attribute information did not fit into the provided buffer.
+ * @retval ::NRF_ERROR_NOT_FOUND No system attributes found.
+ */ 
+SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t *p_sys_attr_data, uint16_t *p_len, uint32_t flags)); 
+
+/** @} */
+
+#endif // BLE_GATTS_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_hci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_hci.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_COMMON 
+  @{
+*/
+
+
+#ifndef BLE_HCI_H__
+#define BLE_HCI_H__ 
+
+/** @defgroup BLE_HCI_STATUS_CODES Bluetooth status codes
+ * @{ */
+
+#define BLE_HCI_STATUS_CODE_SUCCESS                        0x00   /**< Success. */
+#define BLE_HCI_STATUS_CODE_UNKNOWN_BTLE_COMMAND           0x01   /**< Unknown BLE Command. */
+#define BLE_HCI_STATUS_CODE_UNKNOWN_CONNECTION_IDENTIFIER  0x02   /**< Unknown Connection Identifier. */
+/*0x03 Hardware Failure
+0x04 Page Timeout
+*/
+#define BLE_HCI_AUTHENTICATION_FAILURE                     0x05   /**< Authentication Failure. */
+#define BLE_HCI_STATUS_CODE_PIN_OR_KEY_MISSING             0x06   /**< Pin or Key missing. */
+#define BLE_HCI_MEMORY_CAPACITY_EXCEEDED                   0x07   /**< Memory Capacity Exceeded. */
+#define BLE_HCI_CONNECTION_TIMEOUT                         0x08   /**< Connection Timeout. */
+/*0x09 Connection Limit Exceeded
+0x0A Synchronous Connection Limit To A Device Exceeded
+0x0B ACL Connection Already Exists*/
+#define BLE_HCI_STATUS_CODE_COMMAND_DISALLOWED             0x0C   /**< Command Disallowed. */
+/*0x0D Connection Rejected due to Limited Resources
+0x0E Connection Rejected Due To Security Reasons
+0x0F Connection Rejected due to Unacceptable BD_ADDR
+0x10 Connection Accept Timeout Exceeded
+0x11 Unsupported Feature or Parameter Value*/
+#define BLE_HCI_STATUS_CODE_INVALID_BTLE_COMMAND_PARAMETERS 0x12  /**< Invalid BLE Command Parameters. */
+#define BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION           0x13  /**< Remote User Terminated Connection. */
+#define BLE_HCI_REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES 0x14  /**< Remote Device Terminated Connection due to low resources.*/
+#define BLE_HCI_REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF     0x15  /**< Remote Device Terminated Connection due to power off. */
+#define BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION            0x16  /**< Local Host Terminated Connection. */
+/*
+0x17 Repeated Attempts
+0x18 Pairing Not Allowed
+0x19 Unknown LMP PDU
+*/
+#define BLE_HCI_UNSUPPORTED_REMOTE_FEATURE 0x1A                   /**< Unsupported Remote Feature. */
+/*
+0x1B SCO Offset Rejected
+0x1C SCO Interval Rejected
+0x1D SCO Air Mode Rejected*/
+#define BLE_HCI_STATUS_CODE_INVALID_LMP_PARAMETERS     0x1E       /**< Invalid LMP Parameters. */
+#define BLE_HCI_STATUS_CODE_UNSPECIFIED_ERROR          0x1F       /**< Unspecified Error. */
+/*0x20 Unsupported LMP Parameter Value
+0x21 Role Change Not Allowed
+*/
+#define BLE_HCI_STATUS_CODE_LMP_RESPONSE_TIMEOUT       0x22       /**< LMP Response Timeout. */
+/*0x23 LMP Error Transaction Collision*/
+#define BLE_HCI_STATUS_CODE_LMP_PDU_NOT_ALLOWED        0x24       /**< LMP PDU Not Allowed. */
+/*0x25 Encryption Mode Not Acceptable
+0x26 Link Key Can Not be Changed
+0x27 Requested QoS Not Supported
+*/
+#define BLE_HCI_INSTANT_PASSED                         0x28       /**< Instant Passed. */
+#define BLE_HCI_PAIRING_WITH_UNIT_KEY_UNSUPPORTED      0x29       /**< Pairing with Unit Key Unsupported. */
+#define BLE_HCI_DIFFERENT_TRANSACTION_COLLISION        0x2A       /**< Different Transaction Collision. */
+/*
+0x2B Reserved
+0x2C QoS Unacceptable Parameter
+0x2D QoS Rejected
+0x2E Channel Classification Not Supported
+0x2F Insufficient Security
+0x30 Parameter Out Of Mandatory Range
+0x31 Reserved
+0x32 Role Switch Pending
+0x33 Reserved
+0x34 Reserved Slot Violation
+0x35 Role Switch Failed
+0x36 Extended Inquiry Response Too Large
+0x37 Secure Simple Pairing Not Supported By Host.
+0x38 Host Busy - Pairing
+0x39 Connection Rejected due to No Suitable Channel Found*/
+#define BLE_HCI_CONTROLLER_BUSY                        0x3A       /**< Controller Busy. */
+#define BLE_HCI_CONN_INTERVAL_UNACCEPTABLE             0x3B       /**< Connection Interval Unacceptable. */
+#define BLE_HCI_DIRECTED_ADVERTISER_TIMEOUT            0x3C       /**< Directed Adverisement Timeout. */
+#define BLE_HCI_CONN_TERMINATED_DUE_TO_MIC_FAILURE     0x3D       /**< Connection Terminated due to MIC Failure. */
+#define BLE_HCI_CONN_FAILED_TO_BE_ESTABLISHED          0x3E       /**< Connection Failed to be Established. */
+
+/** @} */
+
+
+#endif // BLE_HCI_H__
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_l2cap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_l2cap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_L2CAP Logical Link Control and Adaptation Protocol (L2CAP)
+  @{
+  @brief Definitions and prototypes for the L2CAP interface.
+ */
+
+#ifndef BLE_L2CAP_H__
+#define BLE_L2CAP_H__ 
+
+#include "ble_types.h"
+#include "ble_ranges.h"
+#include "ble_err.h"
+#include "nrf_svc.h"
+
+/**@addtogroup BLE_L2CAP_ENUMERATIONS Enumerations
+ * @{ */
+
+/**@brief L2CAP API SVC numbers. */
+enum BLE_L2CAP_SVCS 
+{
+  SD_BLE_L2CAP_CID_REGISTER = BLE_L2CAP_SVC_BASE,  /**< Register a CID. */
+  SD_BLE_L2CAP_CID_UNREGISTER,                     /**< Unregister a CID. */
+  SD_BLE_L2CAP_TX                                  /**< Transmit a packet. */
+};
+
+/**@brief L2CAP Event IDs. */
+enum BLE_L2CAP_EVTS 
+{
+  BLE_L2CAP_EVT_RX  = BLE_L2CAP_EVT_BASE          /**< L2CAP packet received. */
+};
+
+/** @} */
+
+/**@addtogroup BLE_L2CAP_DEFINES Defines
+ * @{ */
+
+/**@defgroup BLE_ERRORS_L2CAP SVC return values specific to L2CAP
+ * @{ */
+#define BLE_ERROR_L2CAP_CID_IN_USE            (NRF_L2CAP_ERR_BASE + 0x000)  /**< CID already in use. */
+/** @} */
+
+/**@brief Default L2CAP MTU. */
+#define BLE_L2CAP_MTU_DEF           (23)    
+
+/**@brief Invalid Channel Identifier. */
+#define BLE_L2CAP_CID_INVALID       (0x0000) 
+
+/**@brief Dynamic Channel Identifier base. */
+#define BLE_L2CAP_CID_DYN_BASE      (0x0040) 
+
+/**@brief Maximum amount of dynamic CIDs. */
+#define BLE_L2CAP_CID_DYN_MAX       (8) 
+
+/** @} */
+
+/**@addtogroup BLE_L2CAP_STRUCTURES Structures
+ * @{ */
+
+/**@brief Packet header format for L2CAP transmission. */
+typedef struct
+{
+  uint16_t   len;                                 /**< Length of valid info in data member. */
+  uint16_t   cid;                                 /**< Channel ID on which packet is transmitted. */
+} ble_l2cap_header_t;
+
+
+/**@brief L2CAP Received packet event report. */
+typedef struct
+{
+  ble_l2cap_header_t header;                      /**< L2CAP packet header. */
+  uint8_t    data[1];                             /**< Packet data, variable length. */
+} ble_l2cap_evt_rx_t;
+
+
+/**@brief L2CAP event callback event structure. */
+typedef struct
+{
+  uint16_t conn_handle;                           /**< Connection Handle on which event occured. */
+  union
+  {
+    ble_l2cap_evt_rx_t rx;                        /**< RX Event parameters. */
+  } params;                                       /**< Event Parameters. */
+} ble_l2cap_evt_t;
+
+/** @} */
+
+/**@addtogroup BLE_L2CAP_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Register a CID with L2CAP.
+ *
+ * @details This registers a higher protocol layer with the L2CAP multiplexer, and is requried prior to all operations on the CID.
+ *          
+ * @param[in] cid L2CAP CID.
+ *
+ * @retval ::NRF_SUCCESS Successfully registered a CID with the L2CAP layer.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, CID must be above @ref BLE_L2CAP_CID_DYN_BASE.
+ * @retval ::BLE_ERROR_L2CAP_CID_IN_USE L2CAP CID already in use.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ */
+SVCALL(SD_BLE_L2CAP_CID_REGISTER, uint32_t, sd_ble_l2cap_cid_register(uint16_t cid));
+
+/**@brief Unregister a CID with L2CAP.
+ *
+ * @details This unregisters a previously registerd higher protocol layer with the L2CAP multiplexer.
+ *          
+ * @param[in] cid L2CAP CID.
+ *
+ * @retval ::NRF_SUCCESS Successfully unregistered the CID.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
+ * @retval ::NRF_ERROR_NOT_FOUND CID not previously registered.
+ */
+SVCALL(SD_BLE_L2CAP_CID_UNREGISTER, uint32_t, sd_ble_l2cap_cid_unregister(uint16_t cid));
+
+/**@brief Transmit an L2CAP packet.
+ *
+ * @note    It is important to note that a call to this function will <b>consume an application buffer</b>, and will therefore 
+ *          generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. 
+ *          Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details.
+ *
+ * @param[in] conn_handle Connection Handle.
+ * @param[in] p_header    Pointer to a packet header containing length and CID.
+ * @param[in] p_data      Pointer to the data to be transmitted.
+ *
+ * @retval ::NRF_SUCCESS Successfully queued an L2CAP packet for transmission.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, CIDs must be registered beforehand with @ref sd_ble_l2cap_cid_register.
+ * @retval ::NRF_ERROR_NOT_FOUND CID not found.
+ * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
+ * @retval ::BLE_ERROR_NO_TX_BUFFERS Not enough application buffers available.
+ * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, see @ref BLE_L2CAP_MTU_DEF.
+ */
+SVCALL(SD_BLE_L2CAP_TX, uint32_t, sd_ble_l2cap_tx(uint16_t conn_handle, ble_l2cap_header_t const *p_header, uint8_t const *p_data));
+
+/** @} */
+
+#endif // BLE_L2CAP_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_ranges.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_ranges.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_COMMON
+  @{
+  @defgroup ble_ranges Module specific SVC, event and option number subranges
+  @{
+
+  @brief Definition of SVC, event and option number subranges for each API module.
+
+  @note
+  SVCs, event and option numbers are split into subranges for each API module.
+  Each module receives its entire allocated range of SVC calls, whether implemented or not,
+  but return BLE_ERROR_NOT_SUPPORTED for unimplemented or undefined calls in its range.
+
+  Note that the symbols BLE_<module>_SVC_LAST is the end of the allocated SVC range,
+  rather than the last SVC function call actually defined and implemented.
+
+  Specific SVC, event and option values are defined in each module's ble_<module>.h file,
+  which defines names of each individual SVC code based on the range start value.
+*/
+
+#ifndef BLE_RANGES_H__
+#define BLE_RANGES_H__
+
+#define BLE_SVC_BASE           0x60       /**< Common BLE SVC base. */
+#define BLE_SVC_LAST           0x6B       /**< Total: 12. */
+
+#define BLE_RESERVED_SVC_BASE  0x6C       /**< Reserved BLE SVC base. */
+#define BLE_RESERVED_SVC_LAST  0x6F       /**< Total: 4. */
+
+#define BLE_GAP_SVC_BASE       0x70       /**< GAP BLE SVC base. */
+#define BLE_GAP_SVC_LAST       0x8F       /**< Total: 32. */
+
+#define BLE_GATTC_SVC_BASE     0x90       /**< GATTC BLE SVC base. */
+#define BLE_GATTC_SVC_LAST     0x9F       /**< Total: 32. */
+
+#define BLE_GATTS_SVC_BASE     0xA0       /**< GATTS BLE SVC base. */
+#define BLE_GATTS_SVC_LAST     0xAF       /**< Total: 16. */
+
+#define BLE_L2CAP_SVC_BASE     0xB0       /**< L2CAP BLE SVC base. */
+#define BLE_L2CAP_SVC_LAST     0xBF       /**< Total: 16. */
+
+
+#define BLE_EVT_INVALID        0x00       /**< Invalid BLE Event. */
+
+#define BLE_EVT_BASE           0x01       /**< Common BLE Event base. */
+#define BLE_EVT_LAST           0x0F       /**< Total: 15. */
+
+#define BLE_GAP_EVT_BASE       0x10       /**< GAP BLE Event base. */
+#define BLE_GAP_EVT_LAST       0x2F       /**< Total: 32. */
+
+#define BLE_GATTC_EVT_BASE     0x30       /**< GATTC BLE Event base. */
+#define BLE_GATTC_EVT_LAST     0x4F       /**< Total: 32. */
+
+#define BLE_GATTS_EVT_BASE     0x50       /**< GATTS BLE Event base. */
+#define BLE_GATTS_EVT_LAST     0x6F       /**< Total: 32. */
+
+#define BLE_L2CAP_EVT_BASE     0x70       /**< L2CAP BLE Event base. */
+#define BLE_L2CAP_EVT_LAST     0x8F       /**< Total: 32.  */
+
+
+#define BLE_OPT_INVALID        0x00       /**< Invalid BLE Option. */
+
+#define BLE_OPT_BASE           0x01       /**< Common BLE Option base. */
+#define BLE_OPT_LAST           0x1F       /**< Total: 31. */
+
+#define BLE_GAP_OPT_BASE       0x20       /**< GAP BLE Option base. */
+#define BLE_GAP_OPT_LAST       0x3F       /**< Total: 32. */
+
+#define BLE_GATTC_OPT_BASE     0x40       /**< GATTC BLE Option base. */
+#define BLE_GATTC_OPT_LAST     0x5F       /**< Total: 32. */
+
+#define BLE_GATTS_OPT_BASE     0x60       /**< GATTS BLE Option base. */
+#define BLE_GATTS_OPT_LAST     0x7F       /**< Total: 32. */
+
+#define BLE_L2CAP_OPT_BASE     0x80       /**< L2CAP BLE Option base. */
+#define BLE_L2CAP_OPT_LAST     0x9F       /**< Total: 32.  */
+
+#endif /* BLE_RANGES_H__ */
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/ble_types.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_COMMON
+  @{
+  @defgroup ble_types Common types and macro definitions
+  @{
+
+  @brief Common types and macro definitions for the BLE SoftDevice.
+ */
+
+#ifndef BLE_TYPES_H__
+#define BLE_TYPES_H__
+
+#include <stdint.h>
+
+/** @addtogroup BLE_TYPES_DEFINES Defines
+ * @{ */
+
+/** @defgroup BLE_CONN_HANDLES BLE Connection Handles
+ * @{ */
+#define BLE_CONN_HANDLE_INVALID 0xFFFF  /**< Invalid Connection Handle. */
+#define BLE_CONN_HANDLE_ALL     0xFFFE  /**< Applies to all Connection Handles. */
+/** @} */
+
+
+#if 0 /* The following have been duplicated in blecommon.h */
+/** @defgroup BLE_UUID_VALUES Assigned Values for BLE UUIDs
+ * @{ */
+/* Generic UUIDs, applicable to all services */
+#define BLE_UUID_UNKNOWN                              0x0000 /**< Reserved UUID. */
+#define BLE_UUID_SERVICE_PRIMARY                      0x2800 /**< Primary Service. */
+#define BLE_UUID_SERVICE_SECONDARY                    0x2801 /**< Secondary Service. */
+#define BLE_UUID_SERVICE_INCLUDE                      0x2802 /**< Include. */
+#define BLE_UUID_CHARACTERISTIC                       0x2803 /**< Characteristic. */
+#define BLE_UUID_DESCRIPTOR_CHAR_EXT_PROP             0x2900 /**< Characteristic Extended Properties Descriptor. */
+#define BLE_UUID_DESCRIPTOR_CHAR_USER_DESC            0x2901 /**< Characteristic User Description Descriptor. */
+#define BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG        0x2902 /**< Client Characteristic Configuration Descriptor. */
+#define BLE_UUID_DESCRIPTOR_SERVER_CHAR_CONFIG        0x2903 /**< Server Characteristic Configuration Descriptor. */
+#define BLE_UUID_DESCRIPTOR_CHAR_PRESENTATION_FORMAT  0x2904 /**< Characteristic Presentation Format Descriptor. */
+#define BLE_UUID_DESCRIPTOR_CHAR_AGGREGATE_FORMAT     0x2905 /**< Characteristic Aggregate Format Descriptor. */
+/* GATT specific UUIDs */
+#define BLE_UUID_GATT                                 0x1801 /**< Generic Attribute Profile. */
+#define BLE_UUID_GATT_CHARACTERISTIC_SERVICE_CHANGED  0x2A05 /**< Service Changed Characteristic. */
+/* GAP specific UUIDs */
+#define BLE_UUID_GAP                                  0x1800 /**< Generic Access Profile. */
+#define BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME       0x2A00 /**< Device Name Characteristic. */
+#define BLE_UUID_GAP_CHARACTERISTIC_APPEARANCE        0x2A01 /**< Appearance Characteristic. */
+#define BLE_UUID_GAP_CHARACTERISTIC_PPF               0x2A02 /**< Peripheral Privacy Flag Characteristic. */
+#define BLE_UUID_GAP_CHARACTERISTIC_RECONN_ADDR       0x2A03 /**< Reconnection Address Characteristic. */
+#define BLE_UUID_GAP_CHARACTERISTIC_PPCP              0x2A04 /**< Peripheral Preferred Connection Parameters Characteristic. */
+/** @} */
+#endif /* The following have been duplicated in blecommon.h */
+
+
+/** @defgroup BLE_UUID_TYPES Types of UUID
+ * @{ */
+#define BLE_UUID_TYPE_UNKNOWN       0x00 /**< Invalid UUID type. */
+#define BLE_UUID_TYPE_BLE           0x01 /**< Bluetooth SIG UUID (16-bit). */
+#define BLE_UUID_TYPE_VENDOR_BEGIN  0x02 /**< Vendor UUID types start at this index (128-bit). */
+/** @} */
+
+
+#if 0 /* The following have been duplicated in blecommon.h */
+/** @defgroup BLE_APPEARANCES Bluetooth Appearance values
+ *  @note Retrieved from http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml
+ * @{ */
+#define BLE_APPEARANCE_UNKNOWN                                0 /**< Unknown. */
+#define BLE_APPEARANCE_GENERIC_PHONE                         64 /**< Generic Phone. */
+#define BLE_APPEARANCE_GENERIC_COMPUTER                     128 /**< Generic Computer. */
+#define BLE_APPEARANCE_GENERIC_WATCH                        192 /**< Generic Watch. */
+#define BLE_APPEARANCE_WATCH_SPORTS_WATCH                   193 /**< Watch: Sports Watch. */
+#define BLE_APPEARANCE_GENERIC_CLOCK                        256 /**< Generic Clock. */
+#define BLE_APPEARANCE_GENERIC_DISPLAY                      320 /**< Generic Display. */
+#define BLE_APPEARANCE_GENERIC_REMOTE_CONTROL               384 /**< Generic Remote Control. */
+#define BLE_APPEARANCE_GENERIC_EYE_GLASSES                  448 /**< Generic Eye-glasses. */
+#define BLE_APPEARANCE_GENERIC_TAG                          512 /**< Generic Tag. */
+#define BLE_APPEARANCE_GENERIC_KEYRING                      576 /**< Generic Keyring. */
+#define BLE_APPEARANCE_GENERIC_MEDIA_PLAYER                 640 /**< Generic Media Player. */
+#define BLE_APPEARANCE_GENERIC_BARCODE_SCANNER              704 /**< Generic Barcode Scanner. */
+#define BLE_APPEARANCE_GENERIC_THERMOMETER                  768 /**< Generic Thermometer. */
+#define BLE_APPEARANCE_THERMOMETER_EAR                      769 /**< Thermometer: Ear. */
+#define BLE_APPEARANCE_GENERIC_HEART_RATE_SENSOR            832 /**< Generic Heart rate Sensor. */
+#define BLE_APPEARANCE_HEART_RATE_SENSOR_HEART_RATE_BELT    833 /**< Heart Rate Sensor: Heart Rate Belt. */
+#define BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE               896 /**< Generic Blood Pressure. */
+#define BLE_APPEARANCE_BLOOD_PRESSURE_ARM                   897 /**< Blood Pressure: Arm. */
+#define BLE_APPEARANCE_BLOOD_PRESSURE_WRIST                 898 /**< Blood Pressure: Wrist. */
+#define BLE_APPEARANCE_GENERIC_HID                          960 /**< Human Interface Device (HID). */
+#define BLE_APPEARANCE_HID_KEYBOARD                         961 /**< Keyboard (HID Subtype). */
+#define BLE_APPEARANCE_HID_MOUSE                            962 /**< Mouse (HID Subtype). */
+#define BLE_APPEARANCE_HID_JOYSTICK                         963 /**< Joystiq (HID Subtype). */
+#define BLE_APPEARANCE_HID_GAMEPAD                          964 /**< Gamepad (HID Subtype). */
+#define BLE_APPEARANCE_HID_DIGITIZERSUBTYPE                 965 /**< Digitizer Tablet (HID Subtype). */
+#define BLE_APPEARANCE_HID_CARD_READER                      966 /**< Card Reader (HID Subtype). */
+#define BLE_APPEARANCE_HID_DIGITAL_PEN                      967 /**< Digital Pen (HID Subtype). */
+#define BLE_APPEARANCE_HID_BARCODE                          968 /**< Barcode Scanner (HID Subtype). */
+#define BLE_APPEARANCE_GENERIC_GLUCOSE_METER               1024 /**< Generic Glucose Meter. */
+#define BLE_APPEARANCE_GENERIC_RUNNING_WALKING_SENSOR      1088 /**< Generic Running Walking Sensor. */
+#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_IN_SHOE      1089 /**< Running Walking Sensor: In-Shoe. */
+#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_ON_SHOE      1090 /**< Running Walking Sensor: On-Shoe. */
+#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_ON_HIP       1091 /**< Running Walking Sensor: On-Hip. */
+#define BLE_APPEARANCE_GENERIC_CYCLING                     1152 /**< Generic Cycling. */
+#define BLE_APPEARANCE_CYCLING_CYCLING_COMPUTER            1153 /**< Cycling: Cycling Computer. */
+#define BLE_APPEARANCE_CYCLING_SPEED_SENSOR                1154 /**< Cycling: Speed Sensor. */
+#define BLE_APPEARANCE_CYCLING_CADENCE_SENSOR              1155 /**< Cycling: Cadence Sensor. */
+#define BLE_APPEARANCE_CYCLING_POWER_SENSOR                1156 /**< Cycling: Power Sensor. */
+#define BLE_APPEARANCE_CYCLING_SPEED_CADENCE_SENSOR        1157 /**< Cycling: Speed and Cadence Sensor. */
+#define BLE_APPEARANCE_GENERIC_PULSE_OXIMETER              3136 /**< Generic Pulse Oximeter. */
+#define BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP            3137 /**< Fingertip (Pulse Oximeter subtype). */
+#define BLE_APPEARANCE_PULSE_OXIMETER_WRIST_WORN           3138 /**< Wrist Worn(Pulse Oximeter subtype). */
+#define BLE_APPEARANCE_GENERIC_WEIGHT_SCALE                3200 /**< Generic Weight Scale. */
+#define BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS_ACT          5184 /**< Generic Outdoor Sports Activity. */
+#define BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_DISP         5185 /**< Location Display Device (Outdoor Sports Activity subtype). */
+#define BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_AND_NAV_DISP 5186 /**< Location and Navigation Display Device (Outdoor Sports Activity subtype). */
+#define BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_POD          5187 /**< Location Pod (Outdoor Sports Activity subtype). */
+#define BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_AND_NAV_POD  5188 /**< Location and Navigation Pod (Outdoor Sports Activity subtype). */
+/** @} */
+#endif /* The following have been duplicated in blecommon.h */
+
+/** @brief Set .type and .uuid fields of ble_uuid_struct to specified uuid value. */
+#define BLE_UUID_BLE_ASSIGN(instance, value) do {\
+            instance.type = BLE_UUID_TYPE_BLE; \
+            instance.uuid = value;} while(0)
+
+/** @brief Copy type and uuid members from src to dst ble_uuid_t pointer. Both pointers must be valid/non-null. */
+#define BLE_UUID_COPY_PTR(dst, src) do {\
+            (dst)->type = (src)->type; \
+            (dst)->uuid = (src)->uuid;} while(0)
+
+/** @brief Copy type and uuid members from src to dst ble_uuid_t struct. */
+#define BLE_UUID_COPY_INST(dst, src) do {\
+            (dst).type = (src).type; \
+            (dst).uuid = (src).uuid;} while(0)
+
+/** @brief Compare for equality both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */
+#define BLE_UUID_EQ(p_uuid1, p_uuid2) \
+            (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid))
+
+/** @brief Compare for difference both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */
+#define BLE_UUID_NEQ(p_uuid1, p_uuid2) \
+            (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid))
+
+/** @} */
+
+/** @addtogroup BLE_TYPES_STRUCTURES Structures
+ * @{ */
+
+/** @brief 128 bit UUID values. */
+typedef struct
+{ 
+    unsigned char uuid128[16]; /**< Little-Endian UUID bytes. */
+} ble_uuid128_t;
+
+/** @brief  Bluetooth Low Energy UUID type, encapsulates both 16-bit and 128-bit UUIDs. */
+typedef struct
+{
+    uint16_t    uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */
+    uint8_t     type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is @ref BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */
+} ble_uuid_t;
+
+/** @} */
+
+#endif /* BLE_TYPES_H__ */
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_ble.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_ble.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,451 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+  @addtogroup BLE_COMMON BLE SoftDevice Common
+  @{
+  @defgroup ble_api Events, type definitions and API calls
+  @{
+
+  @brief Module independent events, type definitions and API calls for the BLE SoftDevice.
+
+ */
+
+#ifndef BLE_H__
+#define BLE_H__
+
+#include "ble_ranges.h"
+#include "ble_types.h"
+#include "ble_gap.h"
+#include "ble_l2cap.h"
+#include "ble_gatt.h"
+#include "ble_gattc.h"
+#include "ble_gatts.h"
+
+/** @addtogroup BLE_COMMON_ENUMERATIONS Enumerations
+ * @{ */
+
+/**
+ * @brief Common API SVC numbers.
+ */
+enum BLE_COMMON_SVCS
+{
+  SD_BLE_ENABLE = BLE_SVC_BASE,         /**< Enable and initialize the BLE stack */
+  SD_BLE_EVT_GET,                       /**< Get an event from the pending events queue. */
+  SD_BLE_TX_BUFFER_COUNT_GET,           /**< Get the total number of available application transmission buffers from the BLE stack. */
+  SD_BLE_UUID_VS_ADD,                   /**< Add a Vendor Specific UUID. */
+  SD_BLE_UUID_DECODE,                   /**< Decode UUID bytes. */
+  SD_BLE_UUID_ENCODE,                   /**< Encode UUID bytes. */
+  SD_BLE_VERSION_GET,                   /**< Get the local version information (company id, Link Layer Version, Link Layer Subversion). */
+  SD_BLE_USER_MEM_REPLY,                /**< User Memory Reply. */
+  SD_BLE_OPT_SET,                       /**< Set a BLE option. */
+  SD_BLE_OPT_GET,                       /**< Get a BLE option. */
+};
+
+/**
+ * @brief BLE Module Independent Event IDs.
+ */
+enum BLE_COMMON_EVTS
+{
+  BLE_EVT_TX_COMPLETE  = BLE_EVT_BASE,  /**< Transmission Complete. @ref ble_evt_tx_complete_t */
+  BLE_EVT_USER_MEM_REQUEST,             /**< User Memory request. @ref ble_evt_user_mem_request_t */
+  BLE_EVT_USER_MEM_RELEASE              /**< User Memory release. @ref ble_evt_user_mem_release_t */
+};
+
+/**@brief Common Option IDs.
+ * IDs that uniquely identify a common option.
+ */
+enum BLE_COMMON_OPTS
+{
+  BLE_COMMON_OPT_RADIO_CPU_MUTEX = BLE_OPT_BASE    /**< Radio CPU mutex option. @ref ble_common_opt_radio_cpu_mutex_t */
+};
+/** @} */
+
+/** @addtogroup BLE_COMMON_DEFINES Defines
+ * @{ */
+
+/** @brief  Required pointer alignment for BLE Events.
+*/
+#define BLE_EVTS_PTR_ALIGNMENT    4
+
+/** @defgroup BLE_USER_MEM_TYPES User Memory Types
+ * @{ */
+#define BLE_USER_MEM_TYPE_INVALID               0x00  /**< Invalid User Memory Types. */
+#define BLE_USER_MEM_TYPE_GATTS_QUEUED_WRITES   0x01  /**< User Memory for GATTS queued writes. */
+/** @} */
+
+/** @brief  Maximum number of Vendor Specific UUIDs.
+*/
+#define BLE_UUID_VS_MAX_COUNT     10
+
+/** @} */
+
+/** @addtogroup BLE_COMMON_STRUCTURES Structures
+ * @{ */
+
+/**@brief User Memory Block. */
+typedef struct
+{
+  uint8_t          *p_mem;      /**< Pointer to the start of the user memory block. */
+  uint16_t          len;        /**< Length in bytes of the user memory block. */
+} ble_user_mem_block_t;
+
+/**
+ * @brief Event structure for @ref BLE_EVT_TX_COMPLETE.
+ */
+typedef struct
+{
+  uint8_t count;                        /**< Number of packets transmitted. */
+} ble_evt_tx_complete_t;
+
+/**@brief Event structure for @ref BLE_EVT_USER_MEM_REQUEST. */
+typedef struct
+{
+  uint8_t                     type;     /**< User memory type, see @ref BLE_USER_MEM_TYPES. */
+} ble_evt_user_mem_request_t;
+
+/**@brief Event structure for @ref BLE_EVT_USER_MEM_RELEASE. */
+typedef struct
+{
+  uint8_t                     type;       /**< User memory type, see @ref BLE_USER_MEM_TYPES. */
+  ble_user_mem_block_t        mem_block;  /**< User memory block */
+} ble_evt_user_mem_release_t;
+
+
+/**@brief Event structure for events not associated with a specific function module. */
+typedef struct
+{
+  uint16_t conn_handle;                 /**< Connection Handle on which this event occurred. */
+  union
+  {
+    ble_evt_tx_complete_t           tx_complete;        /**< Transmission Complete. */
+    ble_evt_user_mem_request_t      user_mem_request;   /**< User Memory Request Event Parameters. */
+    ble_evt_user_mem_release_t      user_mem_release;   /**< User Memory Release Event Parameters. */
+  } params;
+} ble_common_evt_t;
+
+/**@brief BLE Event header. */
+typedef struct
+{
+  uint16_t evt_id;                      /**< Value from a BLE_<module>_EVT series. */
+  uint16_t evt_len;                     /**< Length in octets excluding this header. */
+} ble_evt_hdr_t;
+
+/**@brief Common BLE Event type, wrapping the module specific event reports. */
+typedef struct
+{
+  ble_evt_hdr_t header;                 /**< Event header. */
+  union
+  {
+    ble_common_evt_t  common_evt;         /**< Common Event, evt_id in BLE_EVT_* series. */
+    ble_gap_evt_t     gap_evt;            /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */
+    ble_l2cap_evt_t   l2cap_evt;          /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */
+    ble_gattc_evt_t   gattc_evt;          /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */
+    ble_gatts_evt_t   gatts_evt;          /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */
+  } evt;
+} ble_evt_t;
+
+
+/**
+ * @brief Version Information.
+ */
+typedef struct
+{
+  uint8_t   version_number;             /**< Link Layer Version number for BT 4.1 spec is 7 (https://www.bluetooth.org/en-us/specification/assigned-numbers/link-layer). */
+  uint16_t  company_id;                 /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */
+  uint16_t  subversion_number;          /**< Link Layer Sub Version number, corresponds to the SoftDevice Config ID or Firmware ID (FWID). */
+} ble_version_t;
+
+/**@brief Mutual exclusion of radio activity and CPU execution.
+ *
+ *        This option configures the application's access to the CPU when the radio is active. The
+ *        application can configure itself to be blocked from using the CPU while the radio is
+ *        active. By default, the application will be able to share CPU time with the SoftDevice
+ *        during radio activity. This parameter structure is used together with @ref sd_ble_opt_set
+ *        to configure the @ref BLE_COMMON_OPT_RADIO_CPU_MUTEX option.
+ *
+ * @note  Note that the application should use this option to configure the SoftDevice to block the
+ *        CPU during radio activity (i.e enable mutual exclusion) when running the SoftDevice on
+ *        hardware affected by PAN #44 "CCM may exceed real time requirements"and PAN #45 "AAR may
+ *        exceed real time requirements".
+ *
+ * @note  Note that when acting as a scanner, the mutex is only enabled for radio TX activity.
+ *
+ * @note  @ref sd_ble_opt_get is not supported for this option.
+ *
+ */
+typedef struct
+{
+  uint8_t enable : 1;                          /**< Enable mutual exclusion of radio activity and the CPU execution. */
+} ble_common_opt_radio_cpu_mutex_t;
+
+/**@brief Option structure for common options. */
+typedef union
+{
+  ble_common_opt_radio_cpu_mutex_t  radio_cpu_mutex;        /**< Parameters for the option for the mutual exclusion of radio activity and CPU execution. */
+} ble_common_opt_t;
+
+/**@brief Common BLE Option type, wrapping the module specific options. */
+typedef union
+{
+  ble_common_opt_t  common_opt;         /**< Common option, opt_id in BLE_COMMON_OPT_* series. */
+  ble_gap_opt_t     gap_opt;            /**< GAP option, opt_id in BLE_GAP_OPT_* series. */
+} ble_opt_t;
+
+/**
+ * @brief BLE GATTS init options
+ */
+typedef struct
+{
+  ble_gatts_enable_params_t  gatts_enable_params; /**< GATTS init options @ref ble_gatts_enable_params_t. */
+} ble_enable_params_t;
+
+/** @} */
+
+/** @addtogroup BLE_COMMON_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Enable the BLE stack
+ *
+ * @param[in] p_ble_enable_params Pointer to ble_enable_params_t
+ *
+ * @details This call initializes the BLE stack, no other BLE related function can be called before this one.
+ *
+ * @return @ref NRF_SUCCESS BLE the BLE stack has been initialized successfully
+ * @retval @ref NRF_ERROR_INVALID_STATE the BLE stack had already been initialized and cannot be reinitialized.
+ * @return @ref NRF_ERROR_INVALID_ADDR Invalid or not sufficiently aligned pointer supplied.
+ * @return @ref NRF_ERROR_INVALID_LENGTH The specified Attribute Table size is either too small or not a multiple of 4.
+ *                                       The minimum acceptable size is defined by @ref BLE_GATTS_ATTR_TAB_SIZE_MIN.
+ * @return @ref NRF_ERROR_NO_MEM         The Attribute Table size is too large. Decrease size in @ref ble_gatts_enable_params_t.
+ */
+SVCALL(SD_BLE_ENABLE, uint32_t, sd_ble_enable(ble_enable_params_t * p_ble_enable_params));
+
+/**@brief Get an event from the pending events queue.
+ *
+ * @param[out] p_dest Pointer to buffer to be filled in with an event, or NULL to retrieve the event length. This buffer <b>must be 4-byte aligned in memory</b>.
+ * @param[in, out] p_len Pointer the length of the buffer, on return it is filled with the event length.
+ *
+ * @details This call allows the application to pull a BLE event from the BLE stack. The application is signalled that an event is 
+ * available from the BLE stack by the triggering of the SD_EVT_IRQn interrupt.
+ * The application is free to choose whether to call this function from thread mode (main context) or directly from the Interrupt Service Routine
+ * that maps to SD_EVT_IRQn. In any case however, and because the BLE stack runs at a higher priority than the application, this function should be called
+ * in a loop (until @ref NRF_ERROR_NOT_FOUND is returned) every time SD_EVT_IRQn is raised to ensure that all available events are pulled from the BLE stack. 
+ * Failure to do so could potentially leave events in the internal queue without the application being aware of this fact.
+ * Sizing the p_dest buffer is equally important, since the application needs to provide all the memory necessary for the event to be copied into
+ * application memory. If the buffer provided is not large enough to fit the entire contents of the event, @ref NRF_ERROR_DATA_SIZE will be returned
+ * and the application can then call again with a larger buffer size.
+ * Please note that because of the variable length nature of some events, sizeof(ble_evt_t) will not always be large enough to fit certain events, 
+ * and so it is the application's responsibility to provide an amount of memory large enough so that the relevant event is copied in full.
+ * The application may "peek" the event length by providing p_dest as a NULL pointer and inspecting the value of *p_len upon return.
+ *
+ * @note The pointer supplied must be aligned to the extend defined by @ref BLE_EVTS_PTR_ALIGNMENT
+ *
+ * @retval ::NRF_SUCCESS Event pulled and stored into the supplied buffer.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid or not sufficiently aligned pointer supplied.
+ * @retval ::NRF_ERROR_NOT_FOUND No events ready to be pulled.
+ * @retval ::NRF_ERROR_DATA_SIZE Event ready but could not fit into the supplied buffer.
+ */
+SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t *p_dest, uint16_t *p_len));
+
+
+/**@brief Get the total number of available application transmission buffers per link in the BLE stack.
+ *
+ * @details This call allows the application to obtain the total number of
+ *          transmission buffers available per link for application data. Please note that
+ *          this does not give the number of free buffers, but rather the total amount of them.
+ *          The application has two options to handle its own application transmission buffers:
+ *          - Use a simple arithmetic calculation: at boot time the application should use this function
+ *          to find out the total amount of buffers available to it and store it in a variable.
+ *          Every time a packet that consumes an application buffer is sent using any of the 
+ *          exposed functions in this BLE API, the application should decrement that variable.
+ *          Conversely, whenever a @ref BLE_EVT_TX_COMPLETE event is received by the application
+ *          it should retrieve the count field in such event and add that number to the same
+ *          variable storing the number of available packets.
+ *          This mechanism allows the application to be aware at any time of the number of
+ *          application packets available in the BLE stack's internal buffers, and therefore
+ *          it can know with certainty whether it is possible to send more data or it has to
+ *          wait for a @ref BLE_EVT_TX_COMPLETE event before it proceeds.
+ *          - Choose to simply not keep track of available buffers at all, and instead handle the 
+ *          @ref BLE_ERROR_NO_TX_BUFFERS error by queueing the packet to be transmitted and 
+ *          try again as soon as a @ref BLE_EVT_TX_COMPLETE event arrives.
+ *
+ *          The API functions that <b>may</b> consume an application buffer depending on 
+ *          the parameters supplied to them can be found below:
+ *
+ *          - @ref sd_ble_gattc_write (write without response only)
+ *          - @ref sd_ble_gatts_hvx (notifications only)
+ *          - @ref sd_ble_l2cap_tx (all packets)
+ *
+ * @param[out] p_count Pointer to a uint8_t which will contain the number of application transmission buffers upon
+ *                     successful return.
+ *
+ * @retval ::NRF_SUCCESS Number of application transmission buffers retrieved successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ */
+SVCALL(SD_BLE_TX_BUFFER_COUNT_GET, uint32_t, sd_ble_tx_buffer_count_get(uint8_t *p_count));
+
+
+/**@brief Add a Vendor Specific UUID.
+ *
+ * @details This call enables the application to add a vendor specific UUID to the BLE stack's table,
+ *          for later use all other modules and APIs. This then allows the application to use the shorter,
+ *          24-bit @ref ble_uuid_t format when dealing with both 16-bit and 128-bit UUIDs without having to
+ *          check for lengths and having split code paths. The way that this is accomplished is by extending the 
+ *          grouping mechanism that the Bluetooth SIG standard base UUID uses for all other 128-bit UUIDs. The 
+ *          type field in the @ref ble_uuid_t structure is an index (relative to @ref BLE_UUID_TYPE_VENDOR_BEGIN) 
+ *          to the table populated by multiple calls to this function, and the uuid field in the same structure 
+ *          contains the 2 bytes at indices 12 and 13. The number of possible 128-bit UUIDs available to the 
+ *          application is therefore the number of Vendor Specific UUIDs added with the help of this function times 65536, 
+ *          although restricted to modifying bytes 12 and 13 for each of the entries in the supplied array.
+ *
+ * @note Bytes 12 and 13 of the provided UUID will not be used internally, since those are always replaced by 
+ * the 16-bit uuid field in @ref ble_uuid_t.
+ *
+ *
+ * @param[in]  p_vs_uuid    Pointer to a 16-octet (128-bit) little endian Vendor Specific UUID disregarding
+ *                          bytes 12 and 13.
+ * @param[out] p_uuid_type  Pointer to a uint8_t where the type field in @ref ble_uuid_t corresponding to this UUID will be stored.
+ *
+ * @retval ::NRF_SUCCESS Successfully added the Vendor Specific UUID.
+ * @retval ::NRF_ERROR_INVALID_ADDR If p_vs_uuid or p_uuid_type is NULL or invalid.
+ * @retval ::NRF_ERROR_NO_MEM If there are no more free slots for VS UUIDs.
+ * @retval ::NRF_ERROR_FORBIDDEN If p_vs_uuid has already been added to the VS UUID table.
+ */
+SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_vs_uuid, uint8_t *p_uuid_type));
+
+
+/** @brief Decode little endian raw UUID bytes (16-bit or 128-bit) into a 24 bit @ref ble_uuid_t structure.
+ * 
+ * @details The raw UUID bytes excluding bytes 12 and 13 (i.e. bytes 0-11 and 14-15) of p_uuid_le are compared 
+ * to the corresponding ones in each entry of the table of vendor specific UUIDs populated with @ref sd_ble_uuid_vs_add 
+ * to look for a match. If there is such a match, bytes 12 and 13 are returned as p_uuid->uuid and the index 
+ * relative to @ref BLE_UUID_TYPE_VENDOR_BEGIN as p_uuid->type. 
+ *
+ * @note If the UUID length supplied is 2, then the type set by this call will always be @ref BLE_UUID_TYPE_BLE.
+ *
+ * @param[in]      uuid_le_len Length in bytes of the buffer pointed to by p_uuid_le (must be 2 or 16 bytes).
+ * @param[in]      p_uuid_le   Pointer pointing to little endian raw UUID bytes.
+ * @param[out]  p_uuid      Pointer to a @ref ble_uuid_t structure to be filled in.
+ *
+ * @retval ::NRF_SUCCESS Successfully decoded into the @ref ble_uuid_t structure.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_LENGTH Invalid UUID length.
+ * @retval ::NRF_ERROR_NOT_FOUND For a 128-bit UUID, no match in the populated table of UUIDs.
+ */                                                 
+SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const *p_uuid_le, ble_uuid_t *p_uuid));
+
+
+/** @brief Encode a @ref ble_uuid_t structure into little endian raw UUID bytes (16-bit or 128-bit).
+ *
+ * @note The pointer to the destination buffer p_uuid_le may be NULL, in which case only the validity and size of p_uuid is computed.
+ *
+ * @param[in]      p_uuid        Pointer to a @ref ble_uuid_t structure that will be encoded into bytes.
+ * @param[out]     p_uuid_le_len Pointer to a uint8_t that will be filled with the encoded length (2 or 16 bytes).
+ * @param[out]     p_uuid_le     Pointer to a buffer where the little endian raw UUID bytes (2 or 16) will be stored.
+ *
+ * @retval ::NRF_SUCCESS Successfully encoded into the buffer.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid UUID type.
+ */
+SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid, uint8_t *p_uuid_le_len, uint8_t *p_uuid_le));
+
+
+/**@brief Get Version Information.
+ *
+ * @details This call allows the application to get the BLE stack version information.
+ *
+ * @param[out] p_version Pointer to a ble_version_t structure to be filled in.
+ *
+ * @retval ::NRF_SUCCESS  Version information stored successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::NRF_ERROR_BUSY The BLE stack is busy (typically doing a locally-initiated disconnection procedure).
+ */
+SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t *p_version));
+
+
+/**@brief Provide a user memory block.
+ *
+ * @note This call can only be used as a response to a @ref BLE_EVT_USER_MEM_REQUEST event issued to the application.
+ *
+ * @param[in] conn_handle Connection handle.
+ * @param[in,out] p_block Pointer to a user memory block structure.
+ *
+ * @retval ::NRF_SUCCESS Successfully queued a response to the peer.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection state or no execute write request pending.
+ * @retval ::NRF_ERROR_BUSY The BLE stack is busy. Retry at later time.
+ */
+SVCALL(SD_BLE_USER_MEM_REPLY, uint32_t, sd_ble_user_mem_reply(uint16_t conn_handle, ble_user_mem_block_t const *p_block));
+
+/**@brief Set a BLE option.
+ *
+ * @details This call allows the application to set the value of an option.
+ *
+ * @param[in] opt_id Option ID.
+ * @param[in] p_opt Pointer to a ble_opt_t structure containing the option value.
+ *
+ * @retval ::NRF_SUCCESS  Option set successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check parameter limits and constraints.
+ * @retval ::NRF_ERROR_INVALID_STATE Unable to set the parameter at this time.
+ * @retval ::NRF_ERROR_BUSY The BLE stack is busy or the previous procedure has not completed.
+ */
+SVCALL(SD_BLE_OPT_SET, uint32_t, sd_ble_opt_set(uint32_t opt_id, ble_opt_t const *p_opt));
+
+
+/**@brief Get a BLE option.
+ *
+ * @details This call allows the application to retrieve the value of an option.
+ *
+ * @param[in] opt_id Option ID.
+ * @param[out] p_opt Pointer to a ble_opt_t structure to be filled in.
+ *
+ * @retval ::NRF_SUCCESS  Option retrieved successfully.
+ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
+ * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
+ * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check parameter limits and constraints.
+ * @retval ::NRF_ERROR_INVALID_STATE Unable to retrieve the parameter at this time.
+ * @retval ::NRF_ERROR_BUSY The BLE stack is busy or the previous procedure has not completed.
+ * @retval ::NRF_ERROR_NOT_SUPPORTED This option is not supported.
+ *
+ */
+SVCALL(SD_BLE_OPT_GET, uint32_t, sd_ble_opt_get(uint32_t opt_id, ble_opt_t *p_opt));
+
+/** @} */
+
+#endif /* BLE_H__ */
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */ 
+ /**
+  @defgroup nrf_error SoftDevice Global Error Codes
+  @{
+   
+  @brief Global Error definitions
+*/
+
+/* Header guard */
+#ifndef NRF_ERROR_H__
+#define NRF_ERROR_H__
+
+/** @defgroup NRF_ERRORS_BASE Error Codes Base number definitions
+ * @{ */
+#define NRF_ERROR_BASE_NUM      (0x0)       ///< Global error base
+#define NRF_ERROR_SDM_BASE_NUM  (0x1000)    ///< SDM error base
+#define NRF_ERROR_SOC_BASE_NUM  (0x2000)    ///< SoC error base
+#define NRF_ERROR_STK_BASE_NUM  (0x3000)    ///< STK error base
+/** @} */
+
+#define NRF_SUCCESS                           (NRF_ERROR_BASE_NUM + 0)  ///< Successful command
+#define NRF_ERROR_SVC_HANDLER_MISSING         (NRF_ERROR_BASE_NUM + 1)  ///< SVC handler is missing
+#define NRF_ERROR_SOFTDEVICE_NOT_ENABLED      (NRF_ERROR_BASE_NUM + 2)  ///< SoftDevice has not been enabled
+#define NRF_ERROR_INTERNAL                    (NRF_ERROR_BASE_NUM + 3)  ///< Internal Error
+#define NRF_ERROR_NO_MEM                      (NRF_ERROR_BASE_NUM + 4)  ///< No Memory for operation
+#define NRF_ERROR_NOT_FOUND                   (NRF_ERROR_BASE_NUM + 5)  ///< Not found
+#define NRF_ERROR_NOT_SUPPORTED               (NRF_ERROR_BASE_NUM + 6)  ///< Not supported
+#define NRF_ERROR_INVALID_PARAM               (NRF_ERROR_BASE_NUM + 7)  ///< Invalid Parameter
+#define NRF_ERROR_INVALID_STATE               (NRF_ERROR_BASE_NUM + 8)  ///< Invalid state, operation disallowed in this state
+#define NRF_ERROR_INVALID_LENGTH              (NRF_ERROR_BASE_NUM + 9)  ///< Invalid Length
+#define NRF_ERROR_INVALID_FLAGS               (NRF_ERROR_BASE_NUM + 10) ///< Invalid Flags
+#define NRF_ERROR_INVALID_DATA                (NRF_ERROR_BASE_NUM + 11) ///< Invalid Data
+#define NRF_ERROR_DATA_SIZE                   (NRF_ERROR_BASE_NUM + 12) ///< Data size exceeds limit
+#define NRF_ERROR_TIMEOUT                     (NRF_ERROR_BASE_NUM + 13) ///< Operation timed out
+#define NRF_ERROR_NULL                        (NRF_ERROR_BASE_NUM + 14) ///< Null Pointer
+#define NRF_ERROR_FORBIDDEN                   (NRF_ERROR_BASE_NUM + 15) ///< Forbidden Operation
+#define NRF_ERROR_INVALID_ADDR                (NRF_ERROR_BASE_NUM + 16) ///< Bad Memory Address
+#define NRF_ERROR_BUSY                        (NRF_ERROR_BASE_NUM + 17) ///< Busy
+
+#endif // NRF_ERROR_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_sdm.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_sdm.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ /**
+  @addtogroup nrf_sdm_api
+  @{
+  @defgroup nrf_sdm_error SoftDevice Manager Error Codes
+  @{
+     
+  @brief Error definitions for the SDM API
+*/
+
+/* Header guard */
+#ifndef NRF_ERROR_SDM_H__
+#define NRF_ERROR_SDM_H__
+
+#include "nrf_error.h"
+
+#define NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN              (NRF_ERROR_SDM_BASE_NUM + 0)  ///< Unknown lfclk source.
+#define NRF_ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION (NRF_ERROR_SDM_BASE_NUM + 1)  ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts).
+#define NRF_ERROR_SDM_INCORRECT_CLENR0                  (NRF_ERROR_SDM_BASE_NUM + 2)  ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing).
+
+#endif // NRF_ERROR_SDM_H__
+
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_soc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_error_soc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+/**
+  @addtogroup nrf_soc_api
+  @{
+  @defgroup nrf_soc_error SoC Library Error Codes
+  @{
+     
+  @brief Error definitions for the SoC library
+
+*/
+
+/* Header guard */
+#ifndef NRF_ERROR_SOC_H__
+#define NRF_ERROR_SOC_H__
+
+#include "nrf_error.h"
+
+/* Mutex Errors */
+#define NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN                 (NRF_ERROR_SOC_BASE_NUM + 0)  ///< Mutex already taken
+
+/* NVIC errors */
+#define NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE        (NRF_ERROR_SOC_BASE_NUM + 1)  ///< NVIC interrupt not available
+#define NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED (NRF_ERROR_SOC_BASE_NUM + 2)  ///< NVIC interrupt priority not allowed
+#define NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN              (NRF_ERROR_SOC_BASE_NUM + 3)  ///< NVIC should not return
+
+/* Power errors */
+#define NRF_ERROR_SOC_POWER_MODE_UNKNOWN                  (NRF_ERROR_SOC_BASE_NUM + 4)  ///< Power mode unknown
+#define NRF_ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN         (NRF_ERROR_SOC_BASE_NUM + 5)  ///< Power POF threshold unknown
+#define NRF_ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN         (NRF_ERROR_SOC_BASE_NUM + 6)  ///< Power off should not return
+
+/* Rand errors */
+#define NRF_ERROR_SOC_RAND_NOT_ENOUGH_VALUES              (NRF_ERROR_SOC_BASE_NUM + 7)  ///< RAND not enough values
+
+/* PPI errors */
+#define NRF_ERROR_SOC_PPI_INVALID_CHANNEL                 (NRF_ERROR_SOC_BASE_NUM + 8)  ///< Invalid PPI Channel
+#define NRF_ERROR_SOC_PPI_INVALID_GROUP                   (NRF_ERROR_SOC_BASE_NUM + 9)  ///< Invalid PPI Group
+
+#endif // NRF_ERROR_SOC_H__
+/**
+  @}
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_mbr.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_mbr.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+/**
+  @defgroup nrf_mbr_api Master Boot Record API
+  @{
+
+  @brief APIs for updating SoftDevice and BootLoader
+
+*/
+
+/* Header guard */
+#ifndef NRF_MBR_H__
+#define NRF_MBR_H__
+
+#include "nrf_svc.h"
+#include <stdint.h>
+
+
+/** @addtogroup NRF_MBR_DEFINES Defines
+ * @{ */
+
+/**@brief MBR SVC Base number. */
+#define MBR_SVC_BASE        (0x18)
+
+/**@brief Page size in words. */
+#define PAGE_SIZE_IN_WORDS 256
+/** @} */
+
+/** @addtogroup NRF_MBR_ENUMS Enumerations
+ * @{ */
+
+/**@brief nRF Master Boot Record API SVC numbers. */
+enum NRF_MBR_SVCS
+{
+  SD_MBR_COMMAND = MBR_SVC_BASE, /**< ::sd_mbr_command */
+};
+
+/**@brief Possible values for ::sd_mbr_command_t.command */
+enum NRF_MBR_COMMANDS
+{
+  SD_MBR_COMMAND_COPY_BL,               /**< Copy a new BootLoader. @see sd_mbr_command_copy_bl_t */
+  SD_MBR_COMMAND_COPY_SD,               /**< Copy a new SoftDevice. @see ::sd_mbr_command_copy_sd_t*/
+  SD_MBR_COMMAND_INIT_SD,               /**< Init forwarding interrupts to SD, and run reset function in SD*/
+  SD_MBR_COMMAND_COMPARE,               /**< This command works like memcmp. @see ::sd_mbr_command_compare_t*/
+  SD_MBR_COMMAND_VECTOR_TABLE_BASE_SET, /**< Start forwarding all exception to this address @see ::sd_mbr_command_vector_table_base_set_t*/
+};
+
+/** @} */
+
+/** @addtogroup NRF_MBR_TYPES Types
+ * @{ */
+
+/**@brief This command copies part of a new SoftDevice
+ * The destination area is erased before copying.
+ * If dst is in the middle of a flash page, that whole flash page will be erased.
+ * If (dst+len) is in the middle of a flash page, that whole flash page will be erased.
+ *
+ * The user of this function is responsible for setting the PROTENSET registers.
+ *
+ * @retval ::NRF_SUCCESS indicates that the contents of the memory blocks where copied correctly.
+ * @retval ::NRF_ERROR_INTERNAL indicates that the contents of the memory blocks where not verified correctly after copying.
+ */
+typedef struct
+{
+  uint32_t *src;  /**< Pointer to the source of data to be copied.*/
+  uint32_t *dst;  /**< Pointer to the destination where the content is to be copied.*/
+  uint32_t len;   /**< Number of 32 bit words to copy. Must be a multiple of @ref PAGE_SIZE_IN_WORDS words.*/
+} sd_mbr_command_copy_sd_t;
+
+
+/**@brief This command works like memcmp, but takes the length in words.
+ *
+ * @retval ::NRF_SUCCESS indicates that the contents of both memory blocks are equal.
+ * @retval ::NRF_ERROR_NULL indicates that the contents of the memory blocks are not equal.
+ */
+typedef struct
+{
+  uint32_t *ptr1; /**< Pointer to block of memory. */
+  uint32_t *ptr2; /**< Pointer to block of memory. */
+  uint32_t len;   /**< Number of 32 bit words to compare.*/
+} sd_mbr_command_compare_t;
+
+
+/**@brief This command copies a new BootLoader.
+ *  With this command, destination of BootLoader is always the address written in NRF_UICR->BOOTADDR.
+ *
+ *  Destination is erased by this function.
+ *  If (destination+bl_len) is in the middle of a flash page, that whole flash page will be erased.
+ *
+ *  This function will use PROTENSET to protect the flash that is not intended to be written.
+ *
+ *  On Success, this function will not return. It will start the new BootLoader from reset-vector as normal.
+ *
+ * @retval ::NRF_ERROR_INTERNAL indicates an internal error that should not happen.
+ * @retval ::NRF_ERROR_FORBIDDEN if NRF_UICR->BOOTADDR is not set.
+ * @retval ::NRF_ERROR_INVALID_LENGTH if parameters attempts to read or write outside flash area.
+ */
+typedef struct
+{
+  uint32_t *bl_src;  /**< Pointer to the source of the Bootloader to be be copied.*/
+  uint32_t bl_len;   /**< Number of 32 bit words to copy for BootLoader. */
+} sd_mbr_command_copy_bl_t;
+
+/**@brief Sets the base address of the interrupt vector table for interrupts forwarded from the MBR
+ *
+ * Once this function has been called, this address is where the MBR will start to forward interrupts to after a reset.
+ *
+ * To restore default forwarding this function should be called with @param address set to 0.
+ * The MBR will then start forwarding to interrupts to the address in NFR_UICR->BOOTADDR or to the SoftDevice if the BOOTADDR is not set.
+ *
+ * @retval ::NRF_ERROR_INTERNAL indicates an internal error that should not happen.
+ * @retval ::NRF_ERROR_INVALID_ADDR if parameter address is outside of the flash size.
+ */
+typedef struct
+{
+  uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/
+} sd_mbr_command_vector_table_base_set_t;
+
+typedef struct
+{
+  uint32_t command;  /**< type of command to be issued see @ref NRF_MBR_COMMANDS. */
+  union
+  {
+    sd_mbr_command_copy_sd_t copy_sd;  /**< Parameters for copy SoftDevice.*/
+    sd_mbr_command_copy_bl_t copy_bl;  /**< Parameters for copy BootLoader.*/
+    sd_mbr_command_compare_t compare;  /**< Parameters for verify.*/
+    sd_mbr_command_vector_table_base_set_t base_set; /**< Parameters for vector table base set.*/
+  } params;
+} sd_mbr_command_t;
+
+/** @} */
+
+/** @addtogroup NRF_MBR_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Issue Master Boot Record commands
+ *
+ * Commands used when updating a SoftDevice and bootloader.
+ *
+ * @param[in]  param Pointer to a struct describing the command.
+ *
+ *@note for retvals see ::sd_mbr_command_copy_sd_t ::sd_mbr_command_copy_bl_t ::sd_mbr_command_compare_t
+
+*/
+SVCALL(SD_MBR_COMMAND, uint32_t, sd_mbr_command(sd_mbr_command_t* param));
+
+/** @} */
+#endif // NRF_MBR_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_sdm.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_sdm.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+/**
+  @defgroup nrf_sdm_api SoftDevice Manager API
+  @{
+     
+  @brief APIs for SoftDevice management.
+ 
+*/
+
+/* Header guard */
+#ifndef NRF_SDM_H__
+#define NRF_SDM_H__
+
+#include "nrf_svc.h"
+#include "nrf.h"
+#include "nrf_soc.h"
+#include "nrf_error_sdm.h"
+
+/** @addtogroup NRF_SDM_DEFINES Defines
+ * @{ */
+
+/** @brief SoftDevice Manager SVC Base number. */
+#define SDM_SVC_BASE 0x10   
+
+/** @} */
+
+/** @brief Defines the SoftDevice Information Structure location (address) as an offset from 
+the start of the softdevice (without MBR)*/
+#define SOFTDEVICE_INFO_STRUCT_OFFSET (0x2000)
+
+/** @brief Defines the usual size reserverd for the MBR when a softdevice is written to flash. 
+This is the offset where the first byte of the softdevice hex file is written.*/
+#define MBR_SIZE (0x1000)
+
+/** @brief Defines the absolute Softdevice information structure location (address)*/
+#define SOFTDEVICE_INFO_STRUCT_ADDRESS (SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE)
+
+/** @brief Defines the offset for Softdevice size value relative to Softdevice base address*/
+#define SD_SIZE_OFFSET (SOFTDEVICE_INFO_STRUCT_OFFSET + 0x08)
+
+/** @brief Defines the offset for FWID value relative to Softdevice base address*/
+#define SD_FWID_OFFSET (SOFTDEVICE_INFO_STRUCT_OFFSET + 0x0C)
+
+/** @brief Defines a macro for retreiving the actual Softdevice size value from a given base address
+           use @ref MBR_SIZE when Softdevice is installed just above the MBR (the usual case)*/
+#define SD_SIZE_GET(baseaddr) (*((uint32_t *) ((baseaddr) + SD_SIZE_OFFSET)))
+
+/** @brief Defines a macro for retreiving the actual FWID value from a given base address
+           use @ref MBR_SIZE when Softdevice is installed just above the MBR (the usual case)*/
+#define SD_FWID_GET(baseaddr) ((*((uint32_t *) ((baseaddr) + SD_FWID_OFFSET))) & 0xFFFF)
+
+
+/** @addtogroup NRF_SDM_ENUMS Enumerations
+ * @{ */
+
+/**@brief nRF SoftDevice Manager API SVC numbers. */
+enum NRF_SD_SVCS
+{
+  SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */
+  SD_SOFTDEVICE_DISABLE,               /**< ::sd_softdevice_disable */
+  SD_SOFTDEVICE_IS_ENABLED,            /**< ::sd_softdevice_is_enabled */
+  SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, /**< ::sd_softdevice_vector_table_base_set */
+  SVC_SDM_LAST                         /**< Placeholder for last SDM SVC */
+};
+
+/**@brief Possible lfclk oscillator sources. */
+enum NRF_CLOCK_LFCLKSRCS
+{
+  NRF_CLOCK_LFCLKSRC_SYNTH_250_PPM,                       /**< LFCLK Synthesized from HFCLK.                    */
+  NRF_CLOCK_LFCLKSRC_XTAL_500_PPM,                        /**< LFCLK crystal oscillator 500 PPM accuracy.       */
+  NRF_CLOCK_LFCLKSRC_XTAL_250_PPM,                        /**< LFCLK crystal oscillator 250 PPM accuracy.       */
+  NRF_CLOCK_LFCLKSRC_XTAL_150_PPM,                        /**< LFCLK crystal oscillator 150 PPM accuracy.       */
+  NRF_CLOCK_LFCLKSRC_XTAL_100_PPM,                        /**< LFCLK crystal oscillator 100 PPM accuracy.       */
+  NRF_CLOCK_LFCLKSRC_XTAL_75_PPM,                         /**< LFCLK crystal oscillator 75 PPM accuracy.        */
+  NRF_CLOCK_LFCLKSRC_XTAL_50_PPM,                         /**< LFCLK crystal oscillator 50 PPM accuracy.        */
+  NRF_CLOCK_LFCLKSRC_XTAL_30_PPM,                         /**< LFCLK crystal oscillator 30 PPM accuracy.        */
+  NRF_CLOCK_LFCLKSRC_XTAL_20_PPM,                         /**< LFCLK crystal oscillator 20 PPM accuracy.        */
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_250MS_CALIBRATION,        /**< LFCLK RC oscillator, 250ms  calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_500MS_CALIBRATION,        /**< LFCLK RC oscillator, 500ms  calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_1000MS_CALIBRATION,       /**< LFCLK RC oscillator, 1000ms calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_2000MS_CALIBRATION,       /**< LFCLK RC oscillator, 2000ms calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_4000MS_CALIBRATION,       /**< LFCLK RC oscillator, 4000ms calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_8000MS_CALIBRATION,       /**< LFCLK RC oscillator, 8000ms calibration interval.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_TEMP_1000MS_CALIBRATION,  /**< LFCLK RC oscillator. Temperature checked every 1000ms, if changed above a threshold, a calibration is done.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_TEMP_2000MS_CALIBRATION,  /**< LFCLK RC oscillator. Temperature checked every 2000ms, if changed above a threshold, a calibration is done.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_TEMP_4000MS_CALIBRATION,  /**< LFCLK RC oscillator. Temperature checked every 4000ms, if changed above a threshold, a calibration is done.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_TEMP_8000MS_CALIBRATION,  /**< LFCLK RC oscillator. Temperature checked every 8000ms, if changed above a threshold, a calibration is done.*/
+  NRF_CLOCK_LFCLKSRC_RC_250_PPM_TEMP_16000MS_CALIBRATION, /**< LFCLK RC oscillator. Temperature checked every 16000ms, if changed above a threshold, a calibration is done.*/
+};
+
+/** @} */
+
+/** @addtogroup NRF_SDM_TYPES Types
+ * @{ */
+
+/**@brief Type representing lfclk oscillator source. */
+typedef uint32_t nrf_clock_lfclksrc_t;
+
+
+/**@brief SoftDevice Assertion Handler type.
+ *
+ * When an unexpected error occurs within the SoftDevice it will call the SoftDevice assertion handler callback.
+ * The protocol stack will be in an undefined state when this happens and the only way to recover will be to
+ * perform a reset, using e.g. CMSIS NVIC_SystemReset().
+ *
+ * @note This callback is executed in HardFault context, thus SVC functions cannot be called from the SoftDevice assert callback.
+ *       
+ * @param[in] pc The program counter of the failed assert.
+ * @param[in] line_number Line number where the assert failed.
+ * @param[in] file_name File name where the assert failed.
+ */
+typedef void (*softdevice_assertion_handler_t)(uint32_t pc, uint16_t line_number, const uint8_t * p_file_name);
+
+/** @} */
+
+/** @addtogroup NRF_SDM_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Enables the SoftDevice and by extension the protocol stack.
+ *
+ * Idempotent function to enable the SoftDevice.
+ *
+ * @note Some care must be taken if a low frequency clock source is already running when calling this function:
+ *       If the LF clock has a different source then the one currently running, it will be stopped. Then, the new
+ *       clock source will be started.
+ *
+ * @note This function has no effect when returning with an error.
+ *
+ * @post If return code is ::NRF_SUCCESS 
+ *       - SoC library and protocol stack APIs are made available.
+ *       - A portion of RAM will be unavailable (see relevant SDS documentation).
+ *       - Some peripherals will be unavailable or available only through the SoC API (see relevant SDS documentation).
+ *       - Interrupts will not arrive from protected peripherals or interrupts.
+ *       - nrf_nvic_ functions must be used instead of CMSIS NVIC_ functions for reliable usage of the softdevice.
+ *       - Interrupt latency may be affected by the SoftDevice  (see relevant SDS documentation).
+ *       - Chosen low frequency clock source will be running.
+ *
+ * @param clock_source Low frequency clock source and accuracy. (Note: In the case of XTAL source, the PPM accuracy of the chosen clock source must be greater than or equal to the actual characteristics of your XTAL clock).
+ * @param assertion_handler Callback for SoftDevice assertions.
+ *
+ * @retval ::NRF_SUCCESS
+ * @retval ::NRF_ERROR_INVALID_STATE SoftDevice is already enabled, and the clock source and assertion handler cannot be updated.
+ * @retval ::NRF_ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION SoftDeviceinterrupt is already enabled, or an enabled interrupt has an illegal priority level.
+ * @retval ::NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN Unknown low frequency clock source selected.
+ */
+SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lfclksrc_t clock_source, softdevice_assertion_handler_t assertion_handler));
+
+/**@brief Disables the SoftDevice and by extension the protocol stack.
+ * 
+ * Idempotent function to disable the SoftDevice.
+ *
+ * @post SoC library and protocol stack APIs are made unavailable.
+ * @post All interrupts that was protected by the SoftDevice will be disabled and initialized to priority 0 (highest).
+ * @post All peripherals used by the SoftDevice will be reset to default values.
+ * @post All of RAM become available.
+ * @post All interrupts are forwarded to the application.
+ * @post LFCLK source chosen in ::sd_softdevice_enable will be left running.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_SOFTDEVICE_DISABLE, uint32_t, sd_softdevice_disable(void));
+
+/**@brief Check if the SoftDevice is enabled.
+ *
+ * @param[out]  p_softdevice_enabled If the SoftDevice is enabled: 1 else 0.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_SOFTDEVICE_IS_ENABLED, uint32_t, sd_softdevice_is_enabled(uint8_t * p_softdevice_enabled));
+
+/**@brief Sets the base address of the interrupt vector table for interrupts forwarded from the SoftDevice
+ * 
+ * This function is only intended to be called when a bootloader is enabled.
+ *
+ * @param[in] address The base address of the interrupt vector table for forwarded interrupts.
+ 
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, uint32_t, sd_softdevice_vector_table_base_set(uint32_t address)); 
+
+/** @} */
+
+#endif // NRF_SDM_H__
+
+/**
+  @}
+*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_soc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_soc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,988 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */ 
+/**
+ * @defgroup nrf_soc_api SoC Library API
+ * @{
+ * 
+ * @brief APIs for the SoC library.
+ * 
+ */
+
+#ifndef NRF_SOC_H__
+#define NRF_SOC_H__
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "nrf_svc.h"
+#include "nrf.h"
+#include "nrf_error_soc.h"
+
+/**@addtogroup NRF_SOC_DEFINES Defines
+ * @{ */
+
+/**@brief The number of the lowest SVC number reserved for the SoC library. */
+#define SOC_SVC_BASE               (0x20)
+#define SOC_SVC_BASE_NOT_AVAILABLE (0x2B)
+
+/**@brief Guranteed time for application to process radio inactive notification. */
+#define NRF_RADIO_NOTIFICATION_INACTIVE_GUARANTEED_TIME_US  (62)
+
+/**@brief The minimum allowed timeslot extension time. */
+#define NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US (200)
+
+#define SOC_ECB_KEY_LENGTH                (16)                       /**< ECB key length. */
+#define SOC_ECB_CLEARTEXT_LENGTH          (16)                       /**< ECB cleartext length. */
+#define SOC_ECB_CIPHERTEXT_LENGTH         (SOC_ECB_CLEARTEXT_LENGTH) /**< ECB ciphertext length. */
+
+#define SD_EVT_IRQn                       (SWI2_IRQn)        /**< SoftDevice Event IRQ number. Used for both protocol events and SoC events. */
+#define SD_EVT_IRQHandler                 (SWI2_IRQHandler)  /**< SoftDevice Event IRQ handler. Used for both protocol events and SoC events. */
+#define RADIO_NOTIFICATION_IRQn           (SWI1_IRQn)        /**< The radio notification IRQ number. */
+#define RADIO_NOTIFICATION_IRQHandler     (SWI1_IRQHandler)  /**< The radio notification IRQ handler. */
+
+#define NRF_RADIO_LENGTH_MIN_US           (100)               /**< The shortest allowed radio timeslot, in microseconds. */
+#define NRF_RADIO_LENGTH_MAX_US           (100000)            /**< The longest allowed radio timeslot, in microseconds. */
+
+#define NRF_RADIO_DISTANCE_MAX_US         (128000000UL - 1UL) /**< The longest timeslot distance, in microseconds, allowed for the distance parameter (see @ref nrf_radio_request_normal_t) in the request. */
+
+#define NRF_RADIO_EARLIEST_TIMEOUT_MAX_US (128000000UL - 1UL) /**< The longest timeout, in microseconds, allowed when requesting the earliest possible timeslot. */
+
+#define NRF_RADIO_START_JITTER_US         (2)                 /**< The maximum jitter in @ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_START relative to the requested start time. */
+
+/**@} */
+
+/**@addtogroup NRF_SOC_TYPES Types
+ * @{ */
+
+/**@brief The SVC numbers used by the SVC functions in the SoC library. */
+enum NRF_SOC_SVCS
+{
+  SD_PPI_CHANNEL_ENABLE_GET = SOC_SVC_BASE,
+  SD_PPI_CHANNEL_ENABLE_SET,
+  SD_PPI_CHANNEL_ENABLE_CLR,
+  SD_PPI_CHANNEL_ASSIGN,
+  SD_PPI_GROUP_TASK_ENABLE,
+  SD_PPI_GROUP_TASK_DISABLE,
+  SD_PPI_GROUP_ASSIGN,
+  SD_PPI_GROUP_GET,
+  SD_FLASH_PAGE_ERASE,
+  SD_FLASH_WRITE,
+  SD_FLASH_PROTECT,
+  SD_MUTEX_NEW = SOC_SVC_BASE_NOT_AVAILABLE,
+  SD_MUTEX_ACQUIRE,
+  SD_MUTEX_RELEASE,
+  SD_NVIC_ENABLEIRQ,
+  SD_NVIC_DISABLEIRQ,
+  SD_NVIC_GETPENDINGIRQ,
+  SD_NVIC_SETPENDINGIRQ,
+  SD_NVIC_CLEARPENDINGIRQ,
+  SD_NVIC_SETPRIORITY,
+  SD_NVIC_GETPRIORITY,
+  SD_NVIC_SYSTEMRESET,
+  SD_NVIC_CRITICAL_REGION_ENTER,
+  SD_NVIC_CRITICAL_REGION_EXIT,
+  SD_RAND_APPLICATION_POOL_CAPACITY,
+  SD_RAND_APPLICATION_BYTES_AVAILABLE,
+  SD_RAND_APPLICATION_GET_VECTOR,
+  SD_POWER_MODE_SET,
+  SD_POWER_SYSTEM_OFF,
+  SD_POWER_RESET_REASON_GET,
+  SD_POWER_RESET_REASON_CLR,
+  SD_POWER_POF_ENABLE,
+  SD_POWER_POF_THRESHOLD_SET,
+  SD_POWER_RAMON_SET,
+  SD_POWER_RAMON_CLR,
+  SD_POWER_RAMON_GET,
+  SD_POWER_GPREGRET_SET,
+  SD_POWER_GPREGRET_CLR,
+  SD_POWER_GPREGRET_GET,
+  SD_POWER_DCDC_MODE_SET,
+  SD_APP_EVT_WAIT,
+  SD_CLOCK_HFCLK_REQUEST,
+  SD_CLOCK_HFCLK_RELEASE,
+  SD_CLOCK_HFCLK_IS_RUNNING,
+  SD_RADIO_NOTIFICATION_CFG_SET,
+  SD_ECB_BLOCK_ENCRYPT,
+  SD_RADIO_SESSION_OPEN,
+  SD_RADIO_SESSION_CLOSE,
+  SD_RADIO_REQUEST,
+  SD_EVT_GET,
+  SD_TEMP_GET,
+  SVC_SOC_LAST
+};
+
+/**@brief Possible values of a ::nrf_mutex_t. */
+enum NRF_MUTEX_VALUES
+{
+  NRF_MUTEX_FREE,
+  NRF_MUTEX_TAKEN
+};
+
+/**@brief Possible values of ::nrf_app_irq_priority_t. */
+enum NRF_APP_PRIORITIES
+{
+  NRF_APP_PRIORITY_HIGH = 1,
+  NRF_APP_PRIORITY_LOW = 3
+};
+
+/**@brief Possible values of ::nrf_power_mode_t. */
+enum NRF_POWER_MODES
+{
+  NRF_POWER_MODE_CONSTLAT,  /**< Constant latency mode. See power management in the reference manual. */
+  NRF_POWER_MODE_LOWPWR     /**< Low power mode. See power management in the reference manual. */
+};
+
+
+/**@brief Possible values of ::nrf_power_failure_threshold_t */
+enum NRF_POWER_THRESHOLDS
+{
+  NRF_POWER_THRESHOLD_V21,  /**< 2.1 Volts power failure threshold. */
+  NRF_POWER_THRESHOLD_V23,  /**< 2.3 Volts power failure threshold. */
+  NRF_POWER_THRESHOLD_V25,  /**< 2.5 Volts power failure threshold. */ 
+  NRF_POWER_THRESHOLD_V27   /**< 2.7 Volts power failure threshold. */
+};
+
+
+/**@brief Possible values of ::nrf_power_dcdc_mode_t. */
+enum NRF_POWER_DCDC_MODES
+{
+  NRF_POWER_DCDC_DISABLE,          /**< The DCDC is disabled. */
+  NRF_POWER_DCDC_ENABLE            /**< The DCDC is enabled.  */
+};
+
+/**@brief Possible values of ::nrf_radio_notification_distance_t. */
+enum NRF_RADIO_NOTIFICATION_DISTANCES
+{
+  NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_800US,    /**< The distance from the active notification to start of radio activity. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_1740US,   /**< The distance from the active notification to start of radio activity. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_2680US,   /**< The distance from the active notification to start of radio activity. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_3620US,   /**< The distance from the active notification to start of radio activity. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_4560US,   /**< The distance from the active notification to start of radio activity. */
+  NRF_RADIO_NOTIFICATION_DISTANCE_5500US    /**< The distance from the active notification to start of radio activity. */
+};
+
+
+/**@brief Possible values of ::nrf_radio_notification_type_t. */
+enum NRF_RADIO_NOTIFICATION_TYPES
+{
+  NRF_RADIO_NOTIFICATION_TYPE_NONE = 0,        /**< The event does not have a radio notification signal. */
+  NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE,   /**< Using interrupt for notification when the radio will be enabled. */
+  NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */
+  NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH,     /**< Using interrupt for notification both when the radio will be enabled and disabled. */
+};
+
+/**@brief SoC Events. */
+enum NRF_SOC_EVTS
+{
+  NRF_EVT_HFCLKSTARTED,                         /**< Event indicating that the HFCLK has started. */
+  NRF_EVT_POWER_FAILURE_WARNING,                /**< Event indicating that a power failure warning has occurred. */
+  NRF_EVT_FLASH_OPERATION_SUCCESS,              /**< Event indicating that the ongoing flash operation has completed successfully. */
+  NRF_EVT_FLASH_OPERATION_ERROR,                /**< Event indicating that the ongoing flash operation has timed out with an error. */
+  NRF_EVT_RADIO_BLOCKED,                        /**< Event indicating that a radio timeslot was blocked. */
+  NRF_EVT_RADIO_CANCELED,                       /**< Event indicating that a radio timeslot was canceled by SoftDevice. */
+  NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN, /**< Event indicating that a radio signal callback handler return was invalid. */
+  NRF_EVT_RADIO_SESSION_IDLE,                   /**< Event indicating that a radio session is idle. */
+  NRF_EVT_RADIO_SESSION_CLOSED,                 /**< Event indicating that a radio session is closed. */
+  NRF_EVT_NUMBER_OF_EVTS
+};
+
+/**@} */
+
+/**@addtogroup NRF_SOC_TYPES Types
+ * @{ */
+
+/**@brief Represents a mutex for use with the nrf_mutex functions.
+ * @note Accessing the value directly is not safe, use the mutex functions!
+ */
+typedef volatile uint8_t nrf_mutex_t;
+
+/**@brief The interrupt priorities available to the application while the softdevice is active. */
+typedef uint8_t nrf_app_irq_priority_t;
+
+/**@brief Represents a power mode, used in power mode functions */
+typedef uint8_t nrf_power_mode_t;
+
+/**@brief Represents a power failure threshold value. */
+typedef uint8_t nrf_power_failure_threshold_t;
+
+/**@brief Represents a DCDC mode value. */
+typedef uint32_t nrf_power_dcdc_mode_t;
+
+/**@brief Radio notification distances. */
+typedef uint8_t nrf_radio_notification_distance_t;
+
+/**@brief Radio notification types. */
+typedef uint8_t nrf_radio_notification_type_t;
+
+/**@brief The Radio signal callback types. */
+enum NRF_RADIO_CALLBACK_SIGNAL_TYPE
+{
+  NRF_RADIO_CALLBACK_SIGNAL_TYPE_START,             /**< This signal indicates the start of the radio timeslot. */
+  NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0,            /**< This signal indicates the NRF_TIMER0 interrupt. */
+  NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO,             /**< This signal indicates the NRF_RADIO interrupt. */
+  NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_FAILED,     /**< This signal indicates extend action failed. */
+  NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_SUCCEEDED   /**< This signal indicates extend action succeeded. */
+};
+
+/**@brief The actions requested by the signal callback.
+ *
+ *  This code gives the SOC instructions about what action to take when the signal callback has
+ *  returned.
+ */
+enum NRF_RADIO_SIGNAL_CALLBACK_ACTION
+{
+  NRF_RADIO_SIGNAL_CALLBACK_ACTION_NONE,            /**< Return without action. */
+  NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND,          /**< Request an extension of the current timeslot (maximum execution time for this action is when the extension succeeded). */
+  NRF_RADIO_SIGNAL_CALLBACK_ACTION_END,             /**< End the current radio timeslot. */
+  NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END  /**< Request a new radio timeslot and end the current timeslot. */
+};
+
+/**@brief Radio timeslot high frequency clock source configuration. */
+enum NRF_RADIO_HFCLK_CFG
+{
+  NRF_RADIO_HFCLK_CFG_DEFAULT,                      /**< Use the currently selected oscillator as HF clock source during the timeslot (i.e. the source is not specified). */
+  NRF_RADIO_HFCLK_CFG_FORCE_XTAL,                   /**< Force external crystal to be used as HF clock source during whole the timeslot. */
+};
+
+/**@brief Radio timeslot priorities. */
+enum NRF_RADIO_PRIORITY
+{
+  NRF_RADIO_PRIORITY_HIGH,                          /**< High (equal priority as the normal connection priority of the SoftDevice stack(s)). */
+  NRF_RADIO_PRIORITY_NORMAL,                        /**< Normal (equal priority as the priority of secondary activites of the SoftDevice stack(s)). */
+};
+
+/**@brief Radio timeslot request type. */
+enum NRF_RADIO_REQUEST_TYPE
+{
+  NRF_RADIO_REQ_TYPE_EARLIEST,                      /**< Request timeslot as early as possible. This should always be used for the first request in a session. */
+  NRF_RADIO_REQ_TYPE_NORMAL                         /**< Normal timeslot request. */
+};
+
+/**@brief Parameters for a request for a timeslot as early as possible. */
+typedef struct
+{
+  uint8_t       hfclk;                              /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */
+  uint8_t       priority;                           /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */
+  uint32_t      length_us;                          /**< The radio timeslot length (in the range 100 to 100,000] microseconds). */
+  uint32_t      timeout_us;                         /**< Longest acceptable delay until the start of the requested timeslot (up to @ref NRF_RADIO_EARLIEST_TIMEOUT_MAX_US microseconds). */
+} nrf_radio_request_earliest_t;
+
+/**@brief Parameters for a normal radio request. */
+typedef struct
+{
+  uint8_t       hfclk;                              /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */
+  uint8_t       priority;                           /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */
+  uint32_t      distance_us;                        /**< Distance from the start of the previous radio timeslot (up to @ref NRF_RADIO_DISTANCE_MAX_US microseconds). */
+  uint32_t      length_us;                          /**< The radio timeslot length (in the range [100..100,000] microseconds). */
+} nrf_radio_request_normal_t;
+
+/**@brief Radio request parameters. */
+typedef struct
+{
+  uint8_t                         request_type;     /**< Type of request, see @ref NRF_RADIO_REQUEST_TYPE. */
+  union
+  {
+    nrf_radio_request_earliest_t  earliest;         /**< Parameters for a request for a timeslot as early as possible. */
+    nrf_radio_request_normal_t    normal;           /**< Parameters for a normal radio request. */
+  } params;
+} nrf_radio_request_t;
+
+/**@brief Return parameters of the radio timeslot signal callback. */
+typedef struct
+{
+  uint8_t               callback_action;            /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */
+  union
+  {
+    struct
+    {
+      nrf_radio_request_t * p_next;                 /**< The request parameters for the next radio timeslot. */
+    } request;                                      /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END. */
+    struct
+    {
+      uint32_t              length_us;              /**< Requested extension of the timeslot duration (microseconds) (for minimum time see @ref NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US). */
+    } extend;                                       /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND. */
+  } params;
+} nrf_radio_signal_callback_return_param_t;
+
+/**@brief The radio signal callback type.
+ *
+ * @note In case of invalid return parameters, the radio timeslot will automatically end
+ *       immediately after returning from the signal callback and the
+ *       @ref NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN event will be sent.
+ * @note The returned struct pointer must remain valid after the signal callback
+ *       function returns. For instance, this means that it must not point to a stack variable.
+ *
+ * @param[in] signal_type Type of signal, see @ref NRF_RADIO_CALLBACK_SIGNAL_TYPE.
+ *
+ * @return Pointer to structure containing action requested by the application.
+ */
+typedef nrf_radio_signal_callback_return_param_t * (*nrf_radio_signal_callback_t) (uint8_t signal_type);
+
+/**@brief AES ECB data structure */
+typedef struct
+{
+  uint8_t key[SOC_ECB_KEY_LENGTH];                  /**< Encryption key. */
+  uint8_t cleartext[SOC_ECB_CLEARTEXT_LENGTH];      /**< Clear Text data. */
+  uint8_t ciphertext[SOC_ECB_CIPHERTEXT_LENGTH];    /**< Cipher Text data. */
+} nrf_ecb_hal_data_t;
+
+/**@} */
+
+/**@addtogroup NRF_SOC_FUNCTIONS Functions
+ * @{ */
+
+/**@brief Initialize a mutex.
+ *
+ * @param[in] p_mutex Pointer to the mutex to initialize.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_MUTEX_NEW, uint32_t, sd_mutex_new(nrf_mutex_t * p_mutex));
+
+/**@brief Attempt to acquire a mutex.
+ *
+ * @param[in] p_mutex Pointer to the mutex to acquire.
+ *
+ * @retval ::NRF_SUCCESS The mutex was successfully acquired.
+ * @retval ::NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN The mutex could not be acquired.
+ */
+SVCALL(SD_MUTEX_ACQUIRE, uint32_t, sd_mutex_acquire(nrf_mutex_t * p_mutex));
+
+/**@brief Release a mutex.
+ *
+ * @param[in] p_mutex Pointer to the mutex to release.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_MUTEX_RELEASE, uint32_t, sd_mutex_release(nrf_mutex_t * p_mutex));
+
+/**@brief Enable External Interrupt.
+ * @note Corresponds to NVIC_EnableIRQ in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in] IRQn See the NVIC_EnableIRQ documentation in CMSIS.
+ *
+ * @retval ::NRF_SUCCESS The interrupt was enabled.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE The interrupt is not available for the application.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED The interrupt has a priority not available for the application.
+ */
+SVCALL(SD_NVIC_ENABLEIRQ, uint32_t, sd_nvic_EnableIRQ(IRQn_Type IRQn));
+
+/**@brief  Disable External Interrupt.
+ * @note Corresponds to NVIC_DisableIRQ in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in] IRQn See the NVIC_DisableIRQ documentation in CMSIS.
+ *
+ * @retval ::NRF_SUCCESS The interrupt was disabled.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE The interrupt is not available for the application.
+ */
+SVCALL(SD_NVIC_DISABLEIRQ, uint32_t, sd_nvic_DisableIRQ(IRQn_Type IRQn));
+
+/**@brief  Get Pending Interrupt.
+ * @note Corresponds to NVIC_GetPendingIRQ in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in]   IRQn          See the NVIC_GetPendingIRQ documentation in CMSIS.
+ * @param[out]  p_pending_irq Return value from NVIC_GetPendingIRQ.
+ *
+ * @retval ::NRF_SUCCESS The interrupt is available for the application.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application.
+ */
+SVCALL(SD_NVIC_GETPENDINGIRQ, uint32_t, sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq));
+
+/**@brief  Set Pending Interrupt.
+ * @note Corresponds to NVIC_SetPendingIRQ in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in] IRQn See the NVIC_SetPendingIRQ documentation in CMSIS.
+ *
+ * @retval ::NRF_SUCCESS The interrupt is set pending.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application.
+ */
+SVCALL(SD_NVIC_SETPENDINGIRQ, uint32_t, sd_nvic_SetPendingIRQ(IRQn_Type IRQn));
+
+/**@brief  Clear Pending Interrupt.
+ * @note Corresponds to NVIC_ClearPendingIRQ in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in] IRQn See the NVIC_ClearPendingIRQ documentation in CMSIS.
+ *
+ * @retval ::NRF_SUCCESS The interrupt pending flag is cleared.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application.
+ */
+SVCALL(SD_NVIC_CLEARPENDINGIRQ, uint32_t, sd_nvic_ClearPendingIRQ(IRQn_Type IRQn));
+
+/**@brief Set Interrupt Priority.
+ * @note Corresponds to NVIC_SetPriority in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ * @pre Priority is valid and not reserved by the stack.
+ *
+ * @param[in] IRQn      See the NVIC_SetPriority documentation in CMSIS.
+ * @param[in] priority  A valid IRQ priority for use by the application.
+ *
+ * @retval ::NRF_SUCCESS The interrupt and priority level is available for the application.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED The interrupt priority is not available for the application.
+ */
+SVCALL(SD_NVIC_SETPRIORITY, uint32_t, sd_nvic_SetPriority(IRQn_Type IRQn, nrf_app_irq_priority_t priority));
+
+/**@brief Get Interrupt Priority.
+ * @note Corresponds to NVIC_GetPriority in CMSIS.
+ *
+ * @pre IRQn is valid and not reserved by the stack.
+ *
+ * @param[in]  IRQn         See the NVIC_GetPriority documentation in CMSIS.
+ * @param[out] p_priority   Return value from NVIC_GetPriority.
+ *
+ * @retval ::NRF_SUCCESS The interrupt priority is returned in p_priority.
+ * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE - IRQn is not available for the application.
+ */
+SVCALL(SD_NVIC_GETPRIORITY, uint32_t, sd_nvic_GetPriority(IRQn_Type IRQn, nrf_app_irq_priority_t * p_priority));
+
+/**@brief System Reset.
+ * @note Corresponds to NVIC_SystemReset in CMSIS.
+ *
+ * @retval ::NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN
+ */
+SVCALL(SD_NVIC_SYSTEMRESET, uint32_t, sd_nvic_SystemReset(void));
+
+/**@brief Enters critical region.
+ *
+ * @post Application interrupts will be disabled.
+ * @sa sd_nvic_critical_region_exit
+ *
+ * @param[out]  p_is_nested_critical_region  1: If in a nested critical region.
+ *                                           0: Otherwise.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_NVIC_CRITICAL_REGION_ENTER, uint32_t, sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region));
+
+/**@brief Exit critical region.
+ *
+ * @pre Application has entered a critical region using ::sd_nvic_critical_region_enter.
+ * @post If not in a nested critical region, the application interrupts will restored to the state before ::sd_nvic_critical_region_enter was called. 
+ *
+ * @param[in] is_nested_critical_region If this is set to 1, the critical region won't be exited. @sa sd_nvic_critical_region_enter.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_NVIC_CRITICAL_REGION_EXIT, uint32_t, sd_nvic_critical_region_exit(uint8_t is_nested_critical_region));
+
+/**@brief Query the capacity of the application random pool.
+ *
+ * @param[out] p_pool_capacity The capacity of the pool.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_RAND_APPLICATION_POOL_CAPACITY, uint32_t, sd_rand_application_pool_capacity_get(uint8_t * p_pool_capacity));
+
+/**@brief Get number of random bytes available to the application.
+ *
+ * @param[out] p_bytes_available The number of bytes currently available in the pool.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_RAND_APPLICATION_BYTES_AVAILABLE, uint32_t, sd_rand_application_bytes_available_get(uint8_t * p_bytes_available));
+
+/**@brief Get random bytes from the application pool.
+ *
+ * @param[out]  p_buff  Pointer to unit8_t buffer for storing the bytes.
+ * @param[in]   length  Number of bytes to take from pool and place in p_buff.
+ *
+ * @retval ::NRF_SUCCESS The requested bytes were written to p_buff.
+ * @retval ::NRF_ERROR_SOC_RAND_NOT_ENOUGH_VALUES No bytes were written to the buffer, because there were not enough bytes available.
+*/
+SVCALL(SD_RAND_APPLICATION_GET_VECTOR, uint32_t, sd_rand_application_vector_get(uint8_t * p_buff, uint8_t length));
+
+/**@brief Gets the reset reason register. 
+ *
+ * @param[out]  p_reset_reason  Contents of the NRF_POWER->RESETREAS register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_RESET_REASON_GET, uint32_t, sd_power_reset_reason_get(uint32_t * p_reset_reason));
+
+/**@brief Clears the bits of the reset reason register. 
+ *
+ * @param[in] reset_reason_clr_msk Contains the bits to clear from the reset reason register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_RESET_REASON_CLR, uint32_t, sd_power_reset_reason_clr(uint32_t reset_reason_clr_msk));
+
+/**@brief Sets the power mode when in CPU sleep.
+ *
+ * @param[in] power_mode The power mode to use when in CPU sleep. @sa sd_app_evt_wait
+ *
+ * @retval ::NRF_SUCCESS The power mode was set.
+ * @retval ::NRF_ERROR_SOC_POWER_MODE_UNKNOWN The power mode was unknown.
+ */
+SVCALL(SD_POWER_MODE_SET, uint32_t, sd_power_mode_set(nrf_power_mode_t power_mode));
+
+/**@brief Puts the chip in System OFF mode. 
+ *
+ * @retval ::NRF_ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN
+ */
+SVCALL(SD_POWER_SYSTEM_OFF, uint32_t, sd_power_system_off(void));
+
+/**@brief Enables or disables the power-fail comparator.
+ *
+ * Enabling this will give a softdevice event (NRF_EVT_POWER_FAILURE_WARNING) when the power failure warning occurs.
+ * The event can be retrieved with sd_evt_get();
+ *
+ * @param[in] pof_enable    True if the power-fail comparator should be enabled, false if it should be disabled.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_POF_ENABLE, uint32_t, sd_power_pof_enable(uint8_t pof_enable));
+
+/**@brief Sets the power-fail threshold value.
+ *
+ * @param[in] threshold The power-fail threshold value to use.
+ *
+ * @retval ::NRF_SUCCESS The power failure threshold was set.
+ * @retval ::NRF_ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN The power failure threshold is unknown.
+ */
+SVCALL(SD_POWER_POF_THRESHOLD_SET, uint32_t, sd_power_pof_threshold_set(nrf_power_failure_threshold_t threshold));
+
+/**@brief Sets bits in the NRF_POWER->RAMON register.
+ *
+ * @param[in] ramon Contains the bits needed to be set in the NRF_POWER->RAMON register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_RAMON_SET, uint32_t, sd_power_ramon_set(uint32_t ramon));
+
+/**@brief Clears bits in the NRF_POWER->RAMON register.
+ *
+ * @param ramon Contains the bits needed to be cleared in the NRF_POWER->RAMON register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_RAMON_CLR, uint32_t, sd_power_ramon_clr(uint32_t ramon));
+
+/**@brief Get contents of NRF_POWER->RAMON register, indicates power status of ram blocks.
+ *
+ * @param[out] p_ramon Content of NRF_POWER->RAMON register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_RAMON_GET, uint32_t, sd_power_ramon_get(uint32_t * p_ramon));
+
+/**@brief Set bits in the NRF_POWER->GPREGRET register.
+ *
+ * @param[in] gpregret_msk Bits to be set in the GPREGRET register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_GPREGRET_SET, uint32_t, sd_power_gpregret_set(uint32_t gpregret_msk));
+
+/**@brief Clear bits in the NRF_POWER->GPREGRET register.
+ *
+ * @param[in] gpregret_msk Bits to be clear in the GPREGRET register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_GPREGRET_CLR, uint32_t, sd_power_gpregret_clr(uint32_t gpregret_msk));
+
+/**@brief Get contents of the NRF_POWER->GPREGRET register.
+ *
+ * @param[out] p_gpregret Contents of the GPREGRET register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t *p_gpregret));
+
+/**@brief Sets the DCDC mode.
+ *
+ * This function is to enable or disable the DCDC periperhal.
+ *
+ * @param[in] dcdc_mode The mode of the DCDC.
+ *
+ * @retval ::NRF_SUCCESS
+ * @retval ::NRF_ERROR_INVALID_PARAM The DCDC mode is invalid.
+ */
+SVCALL(SD_POWER_DCDC_MODE_SET, uint32_t, sd_power_dcdc_mode_set(nrf_power_dcdc_mode_t dcdc_mode));
+
+/**@brief Request the high frequency crystal oscillator.
+ *
+ * Will start the high frequency crystal oscillator, the startup time of the crystal varies
+ * and the ::sd_clock_hfclk_is_running function can be polled to check if it has started.
+ *
+ * @see sd_clock_hfclk_is_running
+ * @see sd_clock_hfclk_release
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_CLOCK_HFCLK_REQUEST, uint32_t, sd_clock_hfclk_request(void));
+
+/**@brief Releases the high frequency crystal oscillator.
+ *
+ * Will stop the high frequency crystal oscillator, this happens immediately.
+ *
+ * @see sd_clock_hfclk_is_running
+ * @see sd_clock_hfclk_request
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_CLOCK_HFCLK_RELEASE, uint32_t, sd_clock_hfclk_release(void));
+
+/**@brief Checks if the high frequency crystal oscillator is running.
+ *
+ * @see sd_clock_hfclk_request
+ * @see sd_clock_hfclk_release
+ *
+ * @param[out] p_is_running 1 if the external crystal oscillator is running, 0 if not.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_CLOCK_HFCLK_IS_RUNNING, uint32_t, sd_clock_hfclk_is_running(uint32_t * p_is_running));
+
+/**@brief Waits for an application event.
+ * 
+ * An application event is either an application interrupt or a pended interrupt when the
+ * interrupt is disabled. When the interrupt is enabled it will be taken immediately since
+ * this function will wait in thread mode, then the execution will return in the application's
+ * main thread. When an interrupt is disabled and gets pended it will return to the application's 
+ * thread main. The application must ensure that the pended flag is cleared using 
+ * ::sd_nvic_ClearPendingIRQ in order to sleep using this function. This is only necessary for
+ * disabled interrupts, as the interrupt handler will clear the pending flag automatically for
+ * enabled interrupts.
+ *
+ * In order to wake up from disabled interrupts, the SEVONPEND flag has to be set in the Cortex-M0
+ * System Control Register (SCR). @sa CMSIS_SCB
+ *
+ * @note If an application interrupt has happened since the last time sd_app_evt_wait was
+ *       called this function will return immediately and not go to sleep. This is to avoid race
+ *       conditions that can occur when a flag is updated in the interrupt handler and processed
+ *       in the main loop.
+ *
+ * @post An application interrupt has happened or a interrupt pending flag is set.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_APP_EVT_WAIT, uint32_t, sd_app_evt_wait(void));
+
+/**@brief Get PPI channel enable register contents.
+ *
+ * @param[out] p_channel_enable The contents of the PPI CHEN register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_CHANNEL_ENABLE_GET, uint32_t, sd_ppi_channel_enable_get(uint32_t * p_channel_enable));
+
+/**@brief Set PPI channel enable register.
+ *
+ * @param[in] channel_enable_set_msk Mask containing the bits to set in the PPI CHEN register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_CHANNEL_ENABLE_SET, uint32_t, sd_ppi_channel_enable_set(uint32_t channel_enable_set_msk));
+
+/**@brief Clear PPI channel enable register.
+ *
+ * @param[in] channel_enable_clr_msk Mask containing the bits to clear in the PPI CHEN register.
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_CHANNEL_ENABLE_CLR, uint32_t, sd_ppi_channel_enable_clr(uint32_t channel_enable_clr_msk));
+
+/**@brief Assign endpoints to a PPI channel.
+ *
+ * @param[in] channel_num Number of the PPI channel to assign.
+ * @param[in] evt_endpoint Event endpoint of the PPI channel.
+ * @param[in] task_endpoint Task endpoint of the PPI channel.
+ *
+ * @retval ::NRF_ERROR_SOC_PPI_INVALID_CHANNEL The channel number is invalid.
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void * evt_endpoint, const volatile void * task_endpoint));
+
+/**@brief Task to enable a channel group.
+ *
+ * @param[in] group_num Number of the channel group.
+ *
+ * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_GROUP_TASK_ENABLE, uint32_t, sd_ppi_group_task_enable(uint8_t group_num));
+
+/**@brief Task to disable a channel group.
+ *
+ * @param[in] group_num Number of the PPI group.
+ *
+ * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid.
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_GROUP_TASK_DISABLE, uint32_t, sd_ppi_group_task_disable(uint8_t group_num));
+
+/**@brief Assign PPI channels to a channel group.
+ *
+ * @param[in] group_num Number of the channel group.
+ * @param[in] channel_msk Mask of the channels to assign to the group.
+ *
+ * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid.
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_GROUP_ASSIGN, uint32_t, sd_ppi_group_assign(uint8_t group_num, uint32_t channel_msk));
+
+/**@brief Gets the PPI channels of a channel group.
+ *
+ * @param[in]   group_num Number of the channel group.
+ * @param[out]  p_channel_msk Mask of the channels assigned to the group.
+ *
+ * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid.
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_PPI_GROUP_GET, uint32_t, sd_ppi_group_get(uint8_t group_num, uint32_t * p_channel_msk));
+
+/**@brief Configures the Radio Notification signal.
+ *
+ * @note
+ *      - The notification signal latency depends on the interrupt priority settings of SWI used
+ *        for notification signal.
+ *      - To ensure that the radio notification signal behaves in a consistent way, always 
+ *        configure radio notifications when there is no protocol stack or other SoftDevice 
+ *        activity in progress. It is recommended that the radio notification signal is 
+ *        configured directly after the SoftDevice has been enabled.
+ *      - In the period between the ACTIVE signal and the start of the Radio Event, the SoftDevice
+ *        will interrupt the application to do Radio Event preparation.
+ *      - Using the Radio Notification feature may limit the bandwidth, as the SoftDevice may have
+ *        to shorten the connection events to have time for the Radio Notification signals.
+ *
+ * @param[in]  type      Type of notification signal.
+ *                       @ref NRF_RADIO_NOTIFICATION_TYPE_NONE shall be used to turn off radio
+ *                       notification. Using @ref NRF_RADIO_NOTIFICATION_DISTANCE_NONE is
+ *                       recommended (but not required) to be used with
+ *                       @ref NRF_RADIO_NOTIFICATION_TYPE_NONE.
+ *
+ * @param[in]  distance  Distance between the notification signal and start of radio activity.
+ *                       This parameter is ignored when @ref NRF_RADIO_NOTIFICATION_TYPE_NONE or 
+ *                       @ref NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE is used.
+ *
+ * @retval ::NRF_ERROR_INVALID_PARAM The group number is invalid.
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_RADIO_NOTIFICATION_CFG_SET, uint32_t, sd_radio_notification_cfg_set(nrf_radio_notification_type_t type, nrf_radio_notification_distance_t distance));
+
+/**@brief Encrypts a block according to the specified parameters.
+ *
+ * 128-bit AES encryption.
+ *
+ * @param[in, out] p_ecb_data Pointer to the ECB parameters' struct (two input
+ *                            parameters and one output parameter).
+ *
+ * @retval ::NRF_SUCCESS
+ */
+SVCALL(SD_ECB_BLOCK_ENCRYPT, uint32_t, sd_ecb_block_encrypt(nrf_ecb_hal_data_t * p_ecb_data));
+
+/**@brief Gets any pending events generated by the SoC API.
+ *
+ * The application should keep calling this function to get events, until ::NRF_ERROR_NOT_FOUND is returned.
+ *
+ * @param[out] p_evt_id Set to one of the values in @ref NRF_SOC_EVTS, if any events are pending.
+ *
+ * @retval ::NRF_SUCCESS An event was pending. The event id is written in the p_evt_id parameter.
+ * @retval ::NRF_ERROR_NOT_FOUND No pending events. 
+ */
+SVCALL(SD_EVT_GET, uint32_t, sd_evt_get(uint32_t * p_evt_id));
+
+/**@brief Get the temperature measured on the chip
+ * 
+ * This function will block until the temperature measurement is done.
+ * It takes around 50us from call to return.
+ *
+ * @note Pan #28 in PAN-028 v 1.6 "Negative measured values are not represented correctly" is corrected by this function.
+ *
+ * @param[out] p_temp Result of temperature measurement. Die temperature in 0.25 degrees celsius.
+ *
+ * @retval ::NRF_SUCCESS A temperature measurement was done, and the temperature was written to temp
+ */
+SVCALL(SD_TEMP_GET, uint32_t, sd_temp_get(int32_t * p_temp));
+
+/**@brief Flash Write
+*
+* Commands to write a buffer to flash
+*
+* If the SoftDevice is enabled:
+*  This call initiates the flash access command, and its completion will be communicated to the
+*  application with exactly one of the following events:
+*      - @ref NRF_EVT_FLASH_OPERATION_SUCCESS - The command was successfully completed.
+*      - @ref NRF_EVT_FLASH_OPERATION_ERROR   - The command could not be started.
+*
+* If the SoftDevice is not enabled no event will be generated, and this call will return @ref NRF_SUCCESS when the 
+ * write has been completed
+*
+* @note
+*      - This call takes control over the radio and the CPU during flash erase and write to make sure that
+*        they will not interfere with the flash access. This means that all interrupts will be blocked
+*        for a predictable time (depending on the NVMC specification in nRF51 Series Reference Manual
+*        and the command parameters).
+*
+*
+* @param[in]  p_dst Pointer to start of flash location to be written.
+* @param[in]  p_src Pointer to buffer with data to be written.
+* @param[in]  size  Number of 32-bit words to write. Maximum size is 256 32bit words.
+*
+* @retval ::NRF_ERROR_INVALID_ADDR   Tried to write to a non existing flash address, or p_dst or p_src was unaligned.
+* @retval ::NRF_ERROR_BUSY           The previous command has not yet completed.
+* @retval ::NRF_ERROR_INVALID_LENGTH Size was 0, or more than 256 words.
+* @retval ::NRF_ERROR_FORBIDDEN      Tried to write to or read from protected location.
+* @retval ::NRF_SUCCESS              The command was accepted.
+*/
+SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * const p_dst, uint32_t const * const p_src, uint32_t size));
+
+
+/**@brief Flash Erase page
+*
+* Commands to erase a flash page
+* If the SoftDevice is enabled:
+*  This call initiates the flash access command, and its completion will be communicated to the
+*  application with exactly one of the following events:
+*      - @ref NRF_EVT_FLASH_OPERATION_SUCCESS - The command was successfully completed.
+*      - @ref NRF_EVT_FLASH_OPERATION_ERROR   - The command could not be started.
+*
+* If the SoftDevice is not enabled no event will be generated, and this call will return @ref NRF_SUCCESS when the 
+* erase has been completed
+*
+* @note
+*      - This call takes control over the radio and the CPU during flash erase and write to make sure that
+*        they will not interfere with the flash access. This means that all interrupts will be blocked
+*        for a predictable time (depending on the NVMC specification in nRF51 Series Reference Manual
+*        and the command parameters).
+*
+*
+* @param[in]  page_number Pagenumber of the page to erase
+* @retval ::NRF_ERROR_INTERNAL      If a new session could not be opened due to an internal error.
+* @retval ::NRF_ERROR_INVALID_ADDR  Tried to erase to a non existing flash page.
+* @retval ::NRF_ERROR_BUSY          The previous command has not yet completed.
+* @retval ::NRF_ERROR_FORBIDDEN     Tried to erase a protected page.
+* @retval ::NRF_SUCCESS             The command was accepted.
+*/
+SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number));
+
+
+/**@brief Flash Protection set
+ *
+ * Commands to set the flash protection registers PROTENSETx
+ *
+ * @note To read the values in PROTENSETx you can read them directly. They are only write-protected.
+ *
+ * @param[in]  protenset0 Value to be written to PROTENSET0.
+ * @param[in]  protenset1 Value to be written to PROTENSET1.
+ *
+ * @retval ::NRF_ERROR_FORBIDDEN Tried to protect the SoftDevice.
+ * @retval ::NRF_SUCCESS Values successfully written to PROTENSETx.
+ */
+SVCALL(SD_FLASH_PROTECT, uint32_t, sd_flash_protect(uint32_t protenset0, uint32_t protenset1));
+
+/**@brief Opens a session for radio requests.
+ *
+ * @note Only one session can be open at a time.
+ * @note p_radio_signal_callback(@ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_START) will be called when the radio timeslot
+ *       starts. From this point the NRF_RADIO and NRF_TIMER0 peripherals can be freely accessed
+ *       by the application.
+ * @note p_radio_signal_callback(@ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0) is called whenever the NRF_TIMER0
+ *       interrupt occurs.
+ * @note p_radio_signal_callback(@ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO) is called whenever the NRF_RADIO
+ *       interrupt occurs.
+ * @note p_radio_signal_callback() will be called at ARM interrupt priority level 0. This
+ *       implies that none of the sd_* API calls can be used from p_radio_signal_callback().
+ *
+ * @param[in] p_radio_signal_callback The signal callback.
+ *
+ * @retval ::NRF_ERROR_INVALID_ADDR p_radio_signal_callback is an invalid function pointer.
+ * @retval ::NRF_ERROR_BUSY If session cannot be opened.
+ * @retval ::NRF_ERROR_INTERNAL If a new session could not be opened due to an internal error.
+ * @retval ::NRF_SUCCESS Otherwise.
+ */
+ SVCALL(SD_RADIO_SESSION_OPEN, uint32_t, sd_radio_session_open(nrf_radio_signal_callback_t p_radio_signal_callback));
+
+/**@brief Closes a session for radio requests.
+ *
+ * @note Any current radio timeslot will be finished before the session is closed.
+ * @note If a radio timeslot is scheduled when the session is closed, it will be canceled.
+ * @note The application cannot consider the session closed until the @ref NRF_EVT_RADIO_SESSION_CLOSED
+ *       event is received.
+ *
+ * @retval ::NRF_ERROR_FORBIDDEN If session not opened.
+ * @retval ::NRF_ERROR_BUSY If session is currently being closed.
+ * @retval ::NRF_SUCCESS Otherwise.
+ */
+ SVCALL(SD_RADIO_SESSION_CLOSE, uint32_t, sd_radio_session_close(void));
+
+/**@brief Requests a radio timeslot.
+ *
+ * @note The request type is determined by p_request->request_type, and can be one of @ref NRF_RADIO_REQ_TYPE_EARLIEST
+ *       and @ref NRF_RADIO_REQ_TYPE_NORMAL. The first request in a session must always be of type
+ *       @ref NRF_RADIO_REQ_TYPE_EARLIEST.
+ * @note For a normal request (@ref NRF_RADIO_REQ_TYPE_NORMAL), the start time of a radio timeslot is specified by
+ *       p_request->distance_us and is given relative to the start of the previous timeslot. 
+ * @note A too small p_request->distance_us will lead to a @ref NRF_EVT_RADIO_BLOCKED event.
+ * @note Timeslots scheduled too close will lead to a @ref NRF_EVT_RADIO_BLOCKED event.
+ * @note See the SoftDevice Specification for more on radio timeslot scheduling, distances and lengths.
+ * @note If an opportunity for the first radio timeslot is not found before 100ms after the call to this
+ *       function, it is not scheduled, and instead a @ref NRF_EVT_RADIO_BLOCKED event is sent.
+ *       The application may then try to schedule the first radio timeslot again.
+ * @note Successful requests will result in nrf_radio_signal_callback_t(@ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_START).
+ *       Unsuccessful requests will result in a @ref NRF_EVT_RADIO_BLOCKED event, see @ref NRF_SOC_EVTS.
+ * @note The jitter in the start time of the radio timeslots is +/- @ref NRF_RADIO_START_JITTER_US us.
+ * @note The nrf_radio_signal_callback_t(@ref NRF_RADIO_CALLBACK_SIGNAL_TYPE_START) call has a latency relative to the
+ *       specified radio timeslot start, but this does not affect the actual start time of the timeslot.
+ * @note NRF_TIMER0 is reset at the start of the radio timeslot, and is clocked at 1MHz from the high frequency
+ *       (16 MHz) clock source. If p_request->hfclk_force_xtal is true, the high frequency clock is 
+ *       guaranteed to be clocked from the external crystal.
+ * @note The SoftDevice will neither access the NRF_RADIO peripheral nor the NRF_TIMER0 peripheral
+ *       during the radio timeslot.
+ *
+ * @param[in] p_request Pointer to the request parameters.
+ *
+ * @retval ::NRF_ERROR_FORBIDDEN If session not opened or the session is not IDLE.
+ * @retval ::NRF_ERROR_INVALID_ADDR If the p_request pointer is invalid.
+ * @retval ::NRF_ERROR_INVALID_PARAM If the parameters of p_request are not valid.
+ * @retval ::NRF_SUCCESS Otherwise.
+ */
+ SVCALL(SD_RADIO_REQUEST, uint32_t, sd_radio_request(nrf_radio_request_t * p_request ));
+
+/**@} */
+
+#endif // NRF_SOC_H__
+
+/**@} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_svc.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/nrf_svc.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+ 
+#ifndef NRF_SVC__
+#define NRF_SVC__
+
+#ifdef SVCALL_AS_NORMAL_FUNCTION
+#define SVCALL(number, return_type, signature) return_type signature
+#else
+
+#ifndef SVCALL
+#if defined (__CC_ARM)
+#define SVCALL(number, return_type, signature) return_type __svc(number) signature
+#elif defined (__GNUC__)
+#define SVCALL(number, return_type, signature) \
+  _Pragma("GCC diagnostic ignored \"-Wunused-function\"") \
+  _Pragma("GCC diagnostic ignored \"-Wunused-parameter\"") \
+  _Pragma("GCC diagnostic push") \
+  _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \
+  __attribute__((naked)) static return_type signature \
+  { \
+    __asm( \
+        "svc %0\n" \
+        "bx r14" : : "I" ((uint32_t) number) : "r0" \
+    ); \
+  }    \
+  _Pragma("GCC diagnostic pop")
+#elif defined (__ICCARM__)
+#define PRAGMA(x) _Pragma(#x)
+#define SVCALL(number, return_type, signature) \
+PRAGMA(swi_number = number) \
+ __swi return_type signature;
+#else
+#define SVCALL(number, return_type, signature) return_type signature  
+#endif
+#endif  // SVCALL
+
+#endif  // SVCALL_AS_NORMAL_FUNCTION
+#endif  // NRF_SVC__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/softdevice_assert.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/softdevice/s130/headers/softdevice_assert.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/** @brief Utilities for verifying program logic
+ */
+
+#ifndef SOFTDEVICE_ASSERT_H_
+#define SOFTDEVICE_ASSERT_H_
+
+#include <stdint.h>
+
+/** @brief This function handles assertions.
+ *
+ *
+ * @note
+ * This function is called when an assertion has triggered.
+ * 
+ *
+ * @param line_num The line number where the assertion is called
+ * @param file_name Pointer to the file name
+ */
+void assert_softdevice_callback(uint16_t line_num, const uint8_t *file_name);
+
+
+/*lint -emacro(506, ASSERT) */ /* Suppress "Constant value Boolean */ 
+/*lint -emacro(774, ASSERT) */ /* Suppress "Boolean within 'if' always evaluates to True" */ \
+/** @brief Check intended for production code
+ *
+ * Check passes if "expr" evaluates to true. */
+#define ASSERT(expr) \
+if (expr)                                                                     \
+{                                                                             \
+}                                                                             \
+else                                                                          \
+{                                                                             \
+  assert_softdevice_callback((uint16_t)__LINE__, (uint8_t *)__FILE__);        \
+  /*lint -unreachable */                                                      \
+}
+
+#endif /* SOFTDEVICE_ASSERT_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/supress-warnings.cmake
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/supress-warnings.cmake	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,21 @@
+# Copyright 2015 ARM Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+message("suppressing warnings from nrf51-sdk")
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+    set_target_properties(nrf51-sdk
+        PROPERTIES COMPILE_FLAGS "-Wno-sign-compare -Wno-unused-variable -Wno-unused-parameter -Wno-unused-function -Wno-missing-field-initializers"
+    )
+endif()
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/sdk/source/toolchain/system_nrf51.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/sdk/source/toolchain/system_nrf51.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Nordic Semiconductor ASA
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ *   1. Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form must reproduce the above copyright notice, this
+ *   list of conditions and the following disclaimer in the documentation and/or
+ *   other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
+ *   contributors to this software may be used to endorse or promote products
+ *   derived from this software without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SYSTEM_NRF51_H
+#define SYSTEM_NRF51_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+
+extern uint32_t SystemCoreClock;    /*!< System Clock Frequency (Core Clock)  */
+
+/**
+ * Initialize the system
+ *
+ * @param  none
+ * @return none
+ *
+ * @brief  Setup the microcontroller system.
+ *         Initialize the System and update the SystemCoreClock variable.
+ */
+extern void SystemInit (void);
+
+/**
+ * Update SystemCoreClock variable
+ *
+ * @param  none
+ * @return none
+ *
+ * @brief  Updates the SystemCoreClock with current core Clock 
+ *         retrieved from cpu registers.
+ */
+extern void SystemCoreClockUpdate (void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SYSTEM_NRF51_H */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/softdevice_nrf51822_licence_agreement.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/softdevice_nrf51822_licence_agreement.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,30 @@
+/*
+ * S110/S120/S130 License Agreement
+ *
+ * Copyright (c) 2015, Nordic Semiconductor ASA, All rights reserved.
+ *
+ * Redistribution. Redistribution and use in binary form, without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * • Redistributions must reproduce the above copyright notice and the following
+ *   disclaimer in the documentation and/or other materials provided with the
+ *   distribution.
+ * • Neither the name of the copyright holder nor the names of its contributors
+ *   may be used to endorse or promote products derived from this software
+ *   without specific prior written permission.
+ * • No reverse engineering, decompilation, or disassembly of this software is
+ *   permitted.
+ *
+ * DISCLAIMER.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * /
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,248 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "common/common.h"
+#include "nordic_common.h"
+
+#include "btle.h"
+
+#include "ble_flash.h"
+#include "ble_conn_params.h"
+
+#include "btle_gap.h"
+#include "btle_advertising.h"
+#include "custom/custom_helper.h"
+
+#include "ble/GapEvents.h"
+#include "nRF5xn.h"
+
+extern "C" {
+#include "pstorage.h"
+#include "device_manager.h"
+#include "softdevice_handler.h"
+#include "ble_stack_handler_types.h"
+}
+
+#include "ble_hci.h"
+#include "btle_discovery.h"
+
+#include "nRF5xGattClient.h"
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+
+bool isEventsSignaled = false;
+
+extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name);
+void            app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name);
+
+static void btle_handler(ble_evt_t *p_ble_evt);
+
+static void sys_evt_dispatch(uint32_t sys_evt)
+{
+    pstorage_sys_event_handler(sys_evt);
+}
+
+/**
+ * This function is called in interrupt context to handle BLE events; i.e. pull
+ * system and user events out of the pending events-queue of the BLE stack. The
+ * BLE stack signals the availability of events by the triggering the SWI2
+ * interrupt, which forwards the handling to this function.
+ *
+ * The event processing loop is implemented in intern_softdevice_events_execute().
+ *
+ * This function will signal to the user code by calling signalEventsToProcess
+ * that their is events to process and BLE::processEvents should be called.
+ */
+static uint32_t signalEvent()
+{
+    if(isEventsSignaled == false) {
+        isEventsSignaled = true;
+        nRF5xn::Instance(BLE::DEFAULT_INSTANCE).signalEventsToProcess(BLE::DEFAULT_INSTANCE);
+    }
+    return NRF_SUCCESS;
+}
+
+error_t btle_init(void)
+{
+    nrf_clock_lfclksrc_t clockSource;
+    if (NRF_CLOCK->LFCLKSRC & (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos)) {
+        clockSource = NRF_CLOCK_LFCLKSRC_XTAL_20_PPM;
+    } else {
+        clockSource = NRF_CLOCK_LFCLKSRC_RC_250_PPM_4000MS_CALIBRATION;
+    }
+    SOFTDEVICE_HANDLER_INIT(clockSource, signalEvent);
+
+    // Enable BLE stack
+    /**
+     * Using this call, the application can select whether to include the
+     * Service Changed characteristic in the GATT Server. The default in all
+     * previous releases has been to include the Service Changed characteristic,
+     * but this affects how GATT clients behave. Specifically, it requires
+     * clients to subscribe to this attribute and not to cache attribute handles
+     * between connections unless the devices are bonded. If the application
+     * does not need to change the structure of the GATT server attributes at
+     * runtime this adds unnecessary complexity to the interaction with peer
+     * clients. If the SoftDevice is enabled with the Service Changed
+     * Characteristics turned off, then clients are allowed to cache attribute
+     * handles making applications simpler on both sides.
+     */
+    static const bool IS_SRVC_CHANGED_CHARACT_PRESENT = true;
+    ble_enable_params_t enableParams = {
+        .gatts_enable_params = {
+            .service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT
+        }
+    };
+    if (sd_ble_enable(&enableParams) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+
+    ble_gap_addr_t addr;
+    if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+    if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+
+    ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler));
+    ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch));
+
+    return btle_gap_init();
+}
+
+static void btle_handler(ble_evt_t *p_ble_evt)
+{
+    /* Library service handlers */
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+    ble_conn_params_on_ble_evt(p_ble_evt);
+#endif
+
+    dm_ble_evt_handler(p_ble_evt);
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    bleGattcEventHandler(p_ble_evt);
+#endif
+
+    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xGap             &gap             = (nRF5xGap &) ble.getGap();
+    nRF5xGattServer      &gattServer      = (nRF5xGattServer &) ble.getGattServer();
+    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
+
+    /* Custom event handler */
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GAP_EVT_CONNECTED: {
+            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
+#if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110)
+            /* Only peripheral role is supported by S110 */
+            Gap::Role_t role = Gap::PERIPHERAL;
+#else
+            Gap::Role_t role = static_cast<Gap::Role_t>(p_ble_evt->evt.gap_evt.params.connected.role);
+#endif
+            gap.setConnectionHandle(handle);
+            const Gap::ConnectionParams_t *params = reinterpret_cast<Gap::ConnectionParams_t *>(&(p_ble_evt->evt.gap_evt.params.connected.conn_params));
+            const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr;
+            const ble_gap_addr_t *own  = &p_ble_evt->evt.gap_evt.params.connected.own_addr;
+            gap.processConnectionEvent(handle,
+                                                           role,
+                                                           static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr,
+                                                           static_cast<BLEProtocol::AddressType_t>(own->addr_type),  own->addr,
+                                                           params);
+            break;
+        }
+
+        case BLE_GAP_EVT_DISCONNECTED: {
+            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
+            // Since we are not in a connection and have not started advertising,
+            // store bonds
+            gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID);
+
+            Gap::DisconnectionReason_t reason;
+            switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) {
+                case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION:
+                    reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION;
+                    break;
+                case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION:
+                    reason = Gap::REMOTE_USER_TERMINATED_CONNECTION;
+                    break;
+                case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE:
+                    reason = Gap::CONN_INTERVAL_UNACCEPTABLE;
+                    break;
+                default:
+                    /* Please refer to the underlying transport library for an
+                     * interpretion of this reason's value. */
+                    reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason);
+                    break;
+            }
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+            // Close all pending discoveries for this connection
+            nRF5xGattClient& gattClient = ble.getGattClient();
+            gattClient.characteristicDescriptorDiscoverer().terminate(handle, BLE_ERROR_INVALID_STATE);
+            gattClient.discovery().terminate(handle);
+#endif
+
+            gap.processDisconnectionEvent(handle, reason);
+            break;
+        }
+
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            securityManager.processPasskeyDisplayEvent(p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->evt.gap_evt.params.passkey_display.passkey);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src));
+            break;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+        case BLE_GATTS_EVT_TIMEOUT:
+            // Disconnect on GATT Server and Client timeout events.
+            // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle,
+            // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION));
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT: {
+            const ble_gap_evt_adv_report_t *advReport = &p_ble_evt->evt.gap_evt.params.adv_report;
+            gap.processAdvertisementReport(advReport->peer_addr.addr,
+                                           advReport->rssi,
+                                           advReport->scan_rsp,
+                                           static_cast<GapAdvertisingParams::AdvertisingType_t>(advReport->type),
+                                           advReport->dlen,
+                                           advReport->data);
+            break;
+        }
+
+        default:
+            break;
+    }
+
+    gattServer.hwCallback(p_ble_evt);
+}
+
+/*! @brief      Callback when an error occurs inside the SoftDevice */
+void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name)
+{
+    ASSERT(false, (void) 0);
+}
+
+/*!
+    @brief      Handler for general errors above the SoftDevice layer.
+                Typically we can' recover from this so we do a reset.
+*/
+void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name)
+{
+    ASSERT_STATUS_RET_VOID( error_code );
+    NVIC_SystemReset();
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,41 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_H_
+#define _BTLE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "common/common.h"
+
+#include "ble_srv_common.h"
+#include "nrf_ble.h"
+
+error_t     btle_init(void);
+
+// flag indicating if events have been signaled or not
+// It is used by processEvents and signalEventsToProcess
+// signalEventsToProcess raise the flag and processEvents
+// clears it.
+extern bool isEventsSignaled;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ifndef _BTLE_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_advertising.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_advertising.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,46 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "common/common.h"
+
+#include "ble_advdata.h"
+#include "btle.h"
+
+/**************************************************************************/
+/*!
+    @brief      Starts the advertising process
+
+    @returns
+*/
+/**************************************************************************/
+error_t btle_advertising_start(void)
+{
+    ble_gap_adv_params_t adv_para = {0};
+
+    /* Set the default advertising parameters */
+    adv_para.type        = BLE_GAP_ADV_TYPE_ADV_IND;
+    adv_para.p_peer_addr = NULL; /* Undirected advertising */
+    adv_para.fp          = BLE_GAP_ADV_FP_ANY;
+    adv_para.p_whitelist = NULL;
+    adv_para.interval    = (CFG_GAP_ADV_INTERVAL_MS * 8) / 5; /* Advertising
+                                                               * interval in
+                                                               * units of 0.625
+                                                               * ms */
+    adv_para.timeout     = CFG_GAP_ADV_TIMEOUT_S;
+
+    ASSERT_STATUS( sd_ble_gap_adv_start(&adv_para));
+
+    return ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_advertising.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_advertising.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,24 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_ADVERTISING_H_
+#define _BTLE_ADVERTISING_H_
+
+#include "common/common.h"
+
+error_t btle_advertising_start(void);
+
+#endif // ifndef _BTLE_ADVERTISING_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_discovery.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_discovery.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,129 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+#include "nRF5xGattClient.h"
+#include "nRF5xn.h"
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+void bleGattcEventHandler(const ble_evt_t *p_ble_evt)
+{
+    nRF5xn                &ble         = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xGap              &gap         = (nRF5xGap &) ble.getGap();
+    nRF5xGattClient       &gattClient  = (nRF5xGattClient &) ble.getGattClient();
+    nRF5xServiceDiscovery &sdSingleton = gattClient.discovery();
+    nRF5xCharacteristicDescriptorDiscoverer &characteristicDescriptorDiscoverer =
+        gattClient.characteristicDescriptorDiscoverer();
+
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
+            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    sdSingleton.setupDiscoveredServices(&p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp);
+                    break;
+
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                default:
+                    sdSingleton.terminate();
+                    break;
+            }
+            break;
+
+        case BLE_GATTC_EVT_CHAR_DISC_RSP:
+            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    sdSingleton.setupDiscoveredCharacteristics(&p_ble_evt->evt.gattc_evt.params.char_disc_rsp);
+                    break;
+
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                default:
+                    sdSingleton.terminateCharacteristicDiscovery(BLE_ERROR_NONE);
+                    break;
+            }
+            break;
+
+        case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP:
+            if (sdSingleton.isActive()) {
+                sdSingleton.processDiscoverUUIDResponse(&p_ble_evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp);
+            }
+            break;
+
+        case BLE_GATTC_EVT_READ_RSP: {
+                GattReadCallbackParams response = {
+                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
+                    .handle     = p_ble_evt->evt.gattc_evt.params.read_rsp.handle,
+                    .offset     = p_ble_evt->evt.gattc_evt.params.read_rsp.offset,
+                    .len        = p_ble_evt->evt.gattc_evt.params.read_rsp.len,
+                    .data       = p_ble_evt->evt.gattc_evt.params.read_rsp.data,
+                };
+                gattClient.processReadResponse(&response);
+            }
+            break;
+
+        case BLE_GATTC_EVT_WRITE_RSP: {
+                GattWriteCallbackParams response = {
+                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
+                    .handle     = p_ble_evt->evt.gattc_evt.params.write_rsp.handle,
+                    .writeOp    = (GattWriteCallbackParams::WriteOp_t)(p_ble_evt->evt.gattc_evt.params.write_rsp.write_op),
+                    .offset     = p_ble_evt->evt.gattc_evt.params.write_rsp.offset,
+                    .len        = p_ble_evt->evt.gattc_evt.params.write_rsp.len,
+                    .data       = p_ble_evt->evt.gattc_evt.params.write_rsp.data,
+                };
+                gattClient.processWriteResponse(&response);
+            }
+            break;
+
+        case BLE_GATTC_EVT_HVX: {
+                GattHVXCallbackParams params;
+                params.connHandle = p_ble_evt->evt.gattc_evt.conn_handle;
+                params.handle     = p_ble_evt->evt.gattc_evt.params.hvx.handle;
+                params.type       = static_cast<HVXType_t>(p_ble_evt->evt.gattc_evt.params.hvx.type);
+                params.len        = p_ble_evt->evt.gattc_evt.params.hvx.len;
+                params.data       = p_ble_evt->evt.gattc_evt.params.hvx.data;
+
+                gattClient.processHVXEvent(&params);
+            }
+            break;
+
+        case BLE_GATTC_EVT_DESC_DISC_RSP: {
+            uint16_t conn_handle = p_ble_evt->evt.gattc_evt.conn_handle;
+            uint16_t status = p_ble_evt->evt.gattc_evt.gatt_status;
+            const ble_gattc_evt_desc_disc_rsp_t& discovered_descriptors = p_ble_evt->evt.gattc_evt.params.desc_disc_rsp;
+
+            switch(status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    characteristicDescriptorDiscoverer.process(
+                        conn_handle,
+                        discovered_descriptors
+                    );
+                    break;
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                    // end of discovery
+                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_NONE);
+                    break;
+                default:
+                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_UNSPECIFIED);
+                    break;
+            }
+        }   break;
+    }
+
+    sdSingleton.progressCharacteristicDiscovery();
+    sdSingleton.progressServiceDiscovery();
+}
+#endif
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_discovery.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_discovery.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,22 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_DISCOVERY_H_
+#define _BTLE_DISCOVERY_H_
+
+void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
+
+#endif /*_BTLE_DISCOVERY_H_*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_gap.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_gap.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,99 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "common/common.h"
+
+#include "ble_gap.h"
+#include "ble_conn_params.h"
+
+static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) ATTR_ALWAYS_INLINE ATTR_CONST;
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+static void   error_callback(uint32_t nrf_error);
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
+
+/**************************************************************************/
+/*!
+    @brief      Initialise GAP in the underlying SoftDevice
+
+    @returns
+*/
+/**************************************************************************/
+error_t btle_gap_init(void)
+{
+    ble_gap_conn_params_t gap_conn_params = {0};
+
+    gap_conn_params.min_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MIN_INTERVAL_MS);  // in 1.25ms units
+    gap_conn_params.max_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MAX_INTERVAL_MS);  // in 1.25ms unit
+    gap_conn_params.slave_latency     = CFG_GAP_CONNECTION_SLAVE_LATENCY;
+    gap_conn_params.conn_sup_timeout  = CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS / 10; // in 10ms unit
+
+    ble_gap_conn_sec_mode_t sec_mode;
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
+
+    ASSERT_STATUS( sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *) CFG_GAP_LOCAL_NAME, strlen(CFG_GAP_LOCAL_NAME)));
+    ASSERT_STATUS( sd_ble_gap_appearance_set(CFG_GAP_APPEARANCE));
+    ASSERT_STATUS( sd_ble_gap_ppcp_set(&gap_conn_params));
+    ASSERT_STATUS( sd_ble_gap_tx_power_set(CFG_BLE_TX_POWER_LEVEL));
+
+    /**
+     * Call to conn_params_init() is not necessary; and so is disabled by default.
+     * This API should be exposed to the user to be invoked when necessary.
+     */
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+    /* Connection Parameters */
+    enum {
+        FIRST_UPDATE_DELAY = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
+        NEXT_UPDATE_DELAY  = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
+        MAX_UPDATE_COUNT   = 3
+    };
+
+    ble_conn_params_init_t cp_init = {0};
+
+    cp_init.p_conn_params                  = NULL;
+    cp_init.first_conn_params_update_delay = FIRST_UPDATE_DELAY;
+    cp_init.next_conn_params_update_delay  = NEXT_UPDATE_DELAY;
+    cp_init.max_conn_params_update_count   = MAX_UPDATE_COUNT;
+    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
+    cp_init.disconnect_on_fail             = true;
+    cp_init.evt_handler                    = NULL;
+    cp_init.error_handler                  = error_callback;
+
+    ASSERT_STATUS ( ble_conn_params_init(&cp_init));
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
+
+    return ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Converts msecs to an integer representing 1.25ms units
+
+    @param[in]  ms
+                The number of milliseconds to conver to 1.25ms units
+
+    @returns    The number of 1.25ms units in the supplied number of ms
+*/
+/**************************************************************************/
+static inline uint32_t msec_to_1_25msec(uint32_t interval_ms)
+{
+    return (interval_ms * 4) / 5;
+}
+
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+static void error_callback(uint32_t nrf_error)
+{
+    ASSERT_STATUS_RET_VOID( nrf_error );
+}
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_gap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_gap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,24 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_GAP_H_
+#define _BTLE_GAP_H_
+
+#include "common/common.h"
+
+error_t btle_gap_init(void);
+
+#endif // ifndef _BTLE_GAP_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_security.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_security.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,316 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "btle.h"
+
+#include "nRF5xn.h"
+
+extern "C" {
+#include "pstorage.h"
+#include "device_manager.h"
+#include "id_manager.h"
+}
+
+#include "btle_security.h"
+
+static dm_application_instance_t applicationInstance;
+static bool                      initialized = false;
+static ret_code_t dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result);
+
+// default security parameters
+static ble_gap_sec_params_t securityParameters = {
+    .bond          = true,         /**< Perform bonding. */
+    .mitm          = true,         /**< Man In The Middle protection required. */
+    .io_caps       = SecurityManager::IO_CAPS_NONE, /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */
+    .oob           = 0,            /**< Out Of Band data available. */
+    .min_key_size  = 16,           /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */
+    .max_key_size  = 16,           /**< Maximum encryption key size in octets between min_key_size and 16. */
+    .kdist_periph  = {
+      .enc  = 1,                   /**< Long Term Key and Master Identification. */
+      .id   = 1,                   /**< Identity Resolving Key and Identity Address Information. */
+      .sign = 1,                   /**< Connection Signature Resolving Key. */
+    },                             /**< Key distribution bitmap: keys that the peripheral device will distribute. */
+};
+
+bool
+btle_hasInitializedSecurity(void)
+{
+    return initialized;
+}
+
+ble_error_t
+btle_initializeSecurity(bool                                      enableBonding,
+                        bool                                      requireMITM,
+                        SecurityManager::SecurityIOCapabilities_t iocaps,
+                        const SecurityManager::Passkey_t          passkey)
+{
+    /* guard against multiple initializations */
+    if (initialized) {
+        return BLE_ERROR_NONE;
+    }
+
+    if (pstorage_init() != NRF_SUCCESS) {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+    ret_code_t rc;
+    if (passkey) {
+        ble_opt_t opts;
+        opts.gap_opt.passkey.p_passkey = const_cast<uint8_t *>(passkey);
+        if ((rc = sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opts)) != NRF_SUCCESS) {
+            switch (rc) {
+                case BLE_ERROR_INVALID_CONN_HANDLE:
+                case NRF_ERROR_INVALID_ADDR:
+                case NRF_ERROR_INVALID_PARAM:
+                default:
+                    return BLE_ERROR_INVALID_PARAM;
+                case NRF_ERROR_INVALID_STATE:
+                    return BLE_ERROR_INVALID_STATE;
+                case NRF_ERROR_BUSY:
+                    return BLE_STACK_BUSY;
+            }
+        }
+    }
+
+    dm_init_param_t dm_init_param = {
+        .clear_persistent_data = false /* Set to true in case the module should clear all persistent data. */
+    };
+    if (dm_init(&dm_init_param) != NRF_SUCCESS) {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+    // update default security parameters with function call parameters
+    securityParameters.bond = enableBonding;
+    securityParameters.mitm = requireMITM;
+    securityParameters.io_caps = iocaps;
+
+    const dm_application_param_t dm_param = {
+        .evt_handler  = dm_handler,
+        .service_type = DM_PROTOCOL_CNTXT_GATT_CLI_ID,
+        .sec_param    = securityParameters
+    };
+
+    if ((rc = dm_register(&applicationInstance, &dm_param)) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_INVALID_STATE:
+                return BLE_ERROR_INVALID_STATE;
+            case NRF_ERROR_NO_MEM:
+                return BLE_ERROR_NO_MEM;
+            default:
+                return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    initialized = true;
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t
+btle_purgeAllBondingState(void)
+{
+    ret_code_t rc;
+    if ((rc = dm_device_delete_all(&applicationInstance)) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+
+    switch (rc) {
+        case NRF_ERROR_INVALID_STATE:
+            return BLE_ERROR_INVALID_STATE;
+        case NRF_ERROR_NO_MEM:
+            return BLE_ERROR_NO_MEM;
+        default:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ble_error_t
+btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP)
+{
+    ret_code_t rc;
+    dm_handle_t dmHandle = {
+        .appl_id = applicationInstance,
+    };
+    if ((rc = dm_handle_get(connectionHandle, &dmHandle)) != NRF_SUCCESS) {
+        if (rc == NRF_ERROR_NOT_FOUND) {
+            return BLE_ERROR_INVALID_PARAM;
+        } else {
+            return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    if ((rc = dm_security_status_req(&dmHandle, reinterpret_cast<dm_security_status_t *>(securityStatusP))) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_INVALID_STATE:
+                return BLE_ERROR_INVALID_STATE;
+            case NRF_ERROR_NO_MEM:
+                return BLE_ERROR_NO_MEM;
+            default:
+                return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t
+btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode)
+{
+    // use default and updated parameters as starting point
+    // and modify structure based on security mode.
+    ble_gap_sec_params_t params = securityParameters;
+
+    switch (securityMode) {
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK:
+            /**< Require no protection, open link. */
+            securityParameters.bond = false;
+            securityParameters.mitm = false;
+            break;
+
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM:
+            /**< Require encryption, but no MITM protection. */
+            securityParameters.bond = true;
+            securityParameters.mitm = false;
+            break;
+
+        // not yet implemented security modes
+        case SecurityManager::SECURITY_MODE_NO_ACCESS:
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM:
+            /**< Require encryption and MITM protection. */
+        case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM:
+            /**< Require signing or encryption, but no MITM protection. */
+        case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM:
+            /**< Require signing or encryption, and MITM protection. */
+        default:
+            return BLE_ERROR_NOT_IMPLEMENTED;
+    }
+
+    // update security settings for given connection
+    uint32_t result = sd_ble_gap_authenticate(connectionHandle, &params);
+
+    if (result == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ret_code_t
+dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result)
+{
+    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
+
+    switch (p_event->event_id) {
+        case DM_EVT_SECURITY_SETUP: /* started */ {
+            const ble_gap_sec_params_t *peerParams = &p_event->event_param.p_gap_param->params.sec_params_request.peer_params;
+            securityManager.processSecuritySetupInitiatedEvent(p_event->event_param.p_gap_param->conn_handle,
+                                                                                   peerParams->bond,
+                                                                                   peerParams->mitm,
+                                                                                   (SecurityManager::SecurityIOCapabilities_t)peerParams->io_caps);
+            break;
+        }
+        case DM_EVT_SECURITY_SETUP_COMPLETE:
+            securityManager.
+                processSecuritySetupCompletedEvent(p_event->event_param.p_gap_param->conn_handle,
+                                                   (SecurityManager::SecurityCompletionStatus_t)(p_event->event_param.p_gap_param->params.auth_status.auth_status));
+            break;
+        case DM_EVT_LINK_SECURED: {
+            unsigned securityMode                    = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.sm;
+            unsigned level                           = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.lv;
+            SecurityManager::SecurityMode_t resolvedSecurityMode = SecurityManager::SECURITY_MODE_NO_ACCESS;
+            switch (securityMode) {
+                case 1:
+                    switch (level) {
+                        case 1:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK;
+                            break;
+                        case 2:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM;
+                            break;
+                        case 3:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM;
+                            break;
+                    }
+                    break;
+                case 2:
+                    switch (level) {
+                        case 1:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_NO_MITM;
+                            break;
+                        case 2:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM;
+                            break;
+                    }
+                    break;
+            }
+
+            securityManager.processLinkSecuredEvent(p_event->event_param.p_gap_param->conn_handle, resolvedSecurityMode);
+            break;
+        }
+        case DM_EVT_DEVICE_CONTEXT_STORED:
+            securityManager.processSecurityContextStoredEvent(p_event->event_param.p_gap_param->conn_handle);
+            break;
+        default:
+            break;
+    }
+
+    return NRF_SUCCESS;
+}
+
+ble_error_t
+btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist)
+{
+    if (!btle_hasInitializedSecurity()) {
+        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
+    }
+    ret_code_t err = dm_whitelist_create(&applicationInstance, p_whitelist);
+    if (err == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else if (err == NRF_ERROR_NULL) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    } else {
+        return BLE_ERROR_INVALID_STATE;
+    }
+}
+
+
+bool
+btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk)
+{
+    /*
+     * Use a helper function from the Nordic SDK to test whether the BLE
+     * address can be generated using the IRK.
+     */
+    return im_address_resolve(p_addr, p_irk);
+}
+
+void
+btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address)
+{
+    /* Set type to resolvable */
+    address.addr_type = BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+
+    /*
+     * Assign a random number to the most significant 3 bytes
+     * of the address.
+     */
+    address.addr[BLE_GAP_ADDR_LEN - 3] = 0x8E;
+    address.addr[BLE_GAP_ADDR_LEN - 2] = 0x4F;
+    address.addr[BLE_GAP_ADDR_LEN - 1] = 0x7C;
+
+    /* Calculate the hash and store it in the top half of the address */
+    ah(irk.irk, &address.addr[BLE_GAP_ADDR_LEN - 3], address.addr);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/btle_security.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/btle_security.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,128 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_SECURITY_H_
+#define _BTLE_SECURITY_H_
+
+#include "ble/Gap.h"
+#include "ble/SecurityManager.h"
+
+/**
+ * Function to test whether the SecurityManager has been initialized.
+ * Possible by a call to @ref btle_initializeSecurity().
+ *
+ * @return True if the SecurityManager was previously initialized, false
+ *         otherwise.
+ */
+bool btle_hasInitializedSecurity(void);
+
+/**
+ * Enable Nordic's Device Manager, which brings in functionality from the
+ * stack's Security Manager. The Security Manager implements the actual
+ * cryptographic algorithms and protocol exchanges that allow two devices to
+ * securely exchange data and privately detect each other.
+ *
+ * @param[in]  enableBonding Allow for bonding.
+ * @param[in]  requireMITM   Require protection for man-in-the-middle attacks.
+ * @param[in]  iocaps        To specify IO capabilities of this peripheral,
+ *                           such as availability of a display or keyboard to
+ *                           support out-of-band exchanges of security data.
+ * @param[in]  passkey       To specify a static passkey.
+ *
+ * @return BLE_ERROR_NONE on success.
+ */
+ble_error_t btle_initializeSecurity(bool                                      enableBonding = true,
+                                    bool                                      requireMITM   = true,
+                                    SecurityManager::SecurityIOCapabilities_t iocaps        = SecurityManager::IO_CAPS_NONE,
+                                    const SecurityManager::Passkey_t          passkey       = NULL);
+
+/**
+ * Get the security status of a link.
+ *
+ * @param[in]  connectionHandle
+ *               Handle to identify the connection.
+ * @param[out] securityStatusP
+ *               security status.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP);
+
+/**
+ * Set the security mode on a connection. Useful for elevating the security mode
+ * once certain conditions are met, e.g., a particular service is found.
+ *
+ * @param[in]  connectionHandle
+ *               Handle to identify the connection.
+ * @param[in]  securityMode
+ *               security mode.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode);
+
+/**
+ * Function for deleting all peer device context and all related bonding
+ * information from the database.
+ *
+ * @retval BLE_ERROR_NONE             On success, else an error code indicating reason for failure.
+ * @retval BLE_ERROR_INVALID_STATE    If the API is called without module initialization and/or
+ *                                    application registration.
+ */
+ble_error_t btle_purgeAllBondingState(void);
+
+/**
+ * Query the SoftDevice bond table to extract a whitelist containing the BLE
+ * addresses and IRKs of bonded devices.
+ *
+ * @param[in/out]  p_whitelist
+ *                  (on input) p_whitelist->addr_count and
+ *                  p_whitelist->irk_count specify the maximum number of
+ *                  addresses and IRKs added to the whitelist structure.
+ *                  (on output) *p_whitelist is a whitelist containing the
+ *                  addresses and IRKs of the bonded devices.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist);
+
+/**
+ * Function to test whether a BLE address is generated using an IRK.
+ *
+ * @param[in]   p_addr
+ *                  Pointer to a BLE address.
+ * @param[in]   p_irk
+ *                  Pointer to an IRK.
+ *
+ * @return True if p_addr can be generated using p_irk, false otherwise.
+ */
+bool btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk);
+
+/**
+ * Function to generate a private resolvable BLE address.
+ *
+ * @param[out]  p_addr
+ *                  The output address.
+ * @param[in]   p_irk
+ *                  A reference to a IRK.
+ *
+ * @note This function does not generate a secure address since the prand number in the
+ *       resolvable address is not truly random. Therefore, the output of this function
+ *       is only meant to be used by the application internally but never exported.
+ */
+void btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address);
+
+#endif /* _BTLE_SECURITY_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/custom/custom_helper.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/custom/custom_helper.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,361 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "custom_helper.h"
+
+/*
+ * The current version of the soft-device doesn't handle duplicate 128-bit UUIDs
+ * very  well. It is therefore necessary to filter away duplicates before
+ * passing long UUIDs to sd_ble_uuid_vs_add(). The following types and data
+ * structures involved in maintaining a local cache of 128-bit UUIDs.
+ */
+typedef struct {
+    UUID::LongUUIDBytes_t uuid;
+    uint8_t         type;
+} converted_uuid_table_entry_t;
+static const unsigned UUID_TABLE_MAX_ENTRIES = 4; /* This is the maximum number of 128-bit UUIDs with distinct bases that
+                                                   * we expect to be in use; increase this limit if needed. */
+static unsigned uuidTableEntries = 0; /* current usage of the table */
+converted_uuid_table_entry_t convertedUUIDTable[UUID_TABLE_MAX_ENTRIES];
+
+/**
+ * lookup the cache of previously converted 128-bit UUIDs to find a type value.
+ * @param  uuid          base 128-bit UUID
+ * @param  recoveredType the type field of the 3-byte nRF's uuid.
+ * @return               true if a match is found.
+ */
+static bool
+lookupConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t *recoveredType)
+{
+    unsigned i;
+    for (i = 0; i < uuidTableEntries; i++) {
+        unsigned byteIndex;
+        for (byteIndex = 0; byteIndex < UUID::LENGTH_OF_LONG_UUID; byteIndex++) {
+            /* Skip bytes 2 and 3, because they contain the shortUUID (16-bit) version of the
+             * long UUID; and we're comparing against the remainder. */
+            if ((byteIndex == 2) || (byteIndex == 3)) {
+                continue;
+            }
+
+            if (convertedUUIDTable[i].uuid[byteIndex] != uuid[byteIndex]) {
+                break;
+            }
+        }
+
+        if (byteIndex == UUID::LENGTH_OF_LONG_UUID) {
+            *recoveredType = convertedUUIDTable[i].type;
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static void
+addToConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t type)
+{
+    if (uuidTableEntries == UUID_TABLE_MAX_ENTRIES) {
+        return; /* recovery needed; or at least the user should be warned about this fact.*/
+    }
+
+    memcpy(convertedUUIDTable[uuidTableEntries].uuid, uuid, UUID::LENGTH_OF_LONG_UUID);
+    convertedUUIDTable[uuidTableEntries].uuid[2] = 0;
+    convertedUUIDTable[uuidTableEntries].uuid[3] = 0;
+    convertedUUIDTable[uuidTableEntries].type    = type;
+    uuidTableEntries++;
+}
+
+/**
+ * The nRF transport has its own 3-byte representation of a UUID. If the user-
+ * specified UUID is 128-bits wide, then the UUID base needs to be added to the
+ * soft-device and converted to a 3-byte handle before being used further. This
+ * function is responsible for this translation of user-specified UUIDs into
+ * nRF's representation.
+ *
+ * @param[in]  uuid
+ *                 user-specified UUID
+ * @return nRF
+ *              3-byte UUID (containing a type and 16-bit UUID) representation
+ *              to be used with SVC calls.
+ */
+ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid)
+{
+    ble_uuid_t nordicUUID;
+    nordicUUID.uuid = uuid.getShortUUID();
+    nordicUUID.type = BLE_UUID_TYPE_UNKNOWN; /* to be set below */
+
+    if (uuid.shortOrLong() == UUID::UUID_TYPE_SHORT) {
+        nordicUUID.type = BLE_UUID_TYPE_BLE;
+    } else {
+        if (!lookupConvertedUUIDTable(uuid.getBaseUUID(), &nordicUUID.type)) {
+            nordicUUID.type = custom_add_uuid_base(uuid.getBaseUUID());
+            addToConvertedUUIDTable(uuid.getBaseUUID(), nordicUUID.type);
+        }
+    }
+
+    return nordicUUID;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Adds the base UUID to the custom service. All UUIDs used
+                by this service are based on this 128-bit UUID.
+
+    @note       This UUID needs to be added to the SoftDevice stack before
+                adding the service's primary service via
+                'sd_ble_gatts_service_add'
+
+    @param[in]  p_uuid_base   A pointer to the 128-bit UUID array (8*16)
+
+    @returns    The UUID type.
+                A return value of 0 should be considered an error.
+
+    @retval     0x00    BLE_UUID_TYPE_UNKNOWN
+    @retval     0x01    BLE_UUID_TYPE_BLE
+    @retval     0x02    BLE_UUID_TYPE_VENDOR_BEGIN
+
+    @section EXAMPLE
+    @code
+
+    // Take note that bytes 2/3 are blank since these are used to identify
+    // the primary service and individual characteristics
+    #define CFG_CUSTOM_UUID_BASE  "\x6E\x40\x00\x00\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E"
+
+    uint8_t uuid_type = custom_add_uuid_base(CFG_CUSTOM_UUID_BASE);
+    ASSERT(uuid_type > 0, ERROR_NOT_FOUND);
+
+    // We can now safely add the primary service and any characteristics
+    // for our custom service ...
+
+    @endcode
+*/
+/**************************************************************************/
+uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base)
+{
+    ble_uuid128_t base_uuid;
+    uint8_t       uuid_type = 0;
+
+    for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
+        base_uuid.uuid128[i] = p_uuid_base[i];
+    }
+
+    ASSERT_INT( ERROR_NONE, sd_ble_uuid_vs_add( &base_uuid, &uuid_type ), 0);
+
+    return uuid_type;
+}
+
+/**************************************************************************/
+/*!
+
+*/
+/**************************************************************************/
+error_t custom_decode_uuid_base(uint8_t const *const p_uuid_base,
+                                ble_uuid_t          *p_uuid)
+{
+    UUID::LongUUIDBytes_t uuid_base_le;
+
+    for (uint8_t i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
+        uuid_base_le[i] = p_uuid_base[i];
+    }
+
+    ASSERT_STATUS( sd_ble_uuid_decode(UUID::LENGTH_OF_LONG_UUID, uuid_base_le, p_uuid));
+
+    return ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Adds a new characteristic to the custom service, assigning
+                properties, a UUID add-on value, etc.
+
+    @param[in]  service_handle
+    @param[in]  p_uuid            The 16-bit value to add to the base UUID
+                                  for this characteristic (normally >1
+                                  since 1 is typically used by the primary
+                                  service).
+    @param[in]  char_props        The characteristic properties, as
+                                  defined by ble_gatt_char_props_t
+    @param[in]  max_length        The maximum length of this characeristic
+    @param[in]  has_variable_len  Whether the characteristic data has
+                                  variable length.
+    @param[out] p_char_handle
+
+    @returns
+    @retval     ERROR_NONE        Everything executed normally
+*/
+/**************************************************************************/
+error_t custom_add_in_characteristic(uint16_t                  service_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                   properties,
+                                     SecurityManager::SecurityMode_t       requiredSecurity,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     const uint8_t            *userDescriptionDescriptorValuePtr,
+                                     uint16_t                  userDescriptionDescriptorValueLen,
+                                     bool                      readAuthorization,
+                                     bool                      writeAuthorization,
+                                     ble_gatts_char_handles_t *p_char_handle)
+{
+    /* Characteristic metadata */
+    ble_gatts_attr_md_t   cccd_md;
+    ble_gatt_char_props_t char_props;
+
+    memcpy(&char_props, &properties, 1);
+
+    if (char_props.notify || char_props.indicate) {
+        /* Notification requires cccd */
+        memclr_( &cccd_md, sizeof(ble_gatts_attr_md_t));
+        cccd_md.vloc = BLE_GATTS_VLOC_STACK;
+        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
+        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
+    }
+
+    ble_gatts_char_md_t char_md = {0};
+
+    char_md.char_props = char_props;
+    char_md.p_cccd_md  =
+        (char_props.notify || char_props.indicate) ? &cccd_md : NULL;
+    if ((userDescriptionDescriptorValueLen > 0) && (userDescriptionDescriptorValuePtr != NULL)) {
+        char_md.p_char_user_desc        = const_cast<uint8_t *>(userDescriptionDescriptorValuePtr);
+        char_md.char_user_desc_max_size = userDescriptionDescriptorValueLen;
+        char_md.char_user_desc_size     = userDescriptionDescriptorValueLen;
+    }
+
+    /* Attribute declaration */
+    ble_gatts_attr_md_t attr_md = {0};
+
+    attr_md.rd_auth = readAuthorization;
+    attr_md.wr_auth = writeAuthorization;
+
+    attr_md.vloc = BLE_GATTS_VLOC_STACK;
+    /* Always set variable size */
+    attr_md.vlen = has_variable_len;
+
+    if (char_props.read || char_props.notify || char_props.indicate) {
+        switch (requiredSecurity) {
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
+                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.read_perm);
+                break;
+            default:
+                break;
+        };
+    }
+
+    if (char_props.write || char_props.write_wo_resp) {
+        switch (requiredSecurity) {
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
+                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.write_perm);
+                break;
+            default:
+                break;
+        };
+    }
+
+    ble_gatts_attr_t attr_char_value = {0};
+
+    attr_char_value.p_uuid    = p_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.init_len  = length;
+    attr_char_value.max_len   = max_length;
+    attr_char_value.p_value   = p_data;
+
+    ASSERT_STATUS ( sd_ble_gatts_characteristic_add(service_handle,
+                                                    &char_md,
+                                                    &attr_char_value,
+                                                    p_char_handle));
+
+    return ERROR_NONE;
+}
+
+
+
+/**************************************************************************/
+/*!
+    @brief      Adds a new descriptor to the custom service, assigning
+                value, a UUID add-on value, etc.
+
+    @param[in]  char_handle
+    @param[in]  p_uuid            The 16-bit value to add to the base UUID
+                                  for this descriptor (normally >1
+                                  since 1 is typically used by the primary
+                                  service).
+    @param[in]  max_length        The maximum length of this descriptor
+    @param[in]  has_variable_len  Whether the characteristic data has
+                                  variable length.
+
+    @returns
+    @retval     ERROR_NONE        Everything executed normally
+*/
+/**************************************************************************/
+error_t custom_add_in_descriptor(uint16_t    char_handle,
+                                 ble_uuid_t *p_uuid,
+                                 uint8_t    *p_data,
+                                 uint16_t    length,
+                                 uint16_t    max_length,
+                                 bool        has_variable_len,
+                                 uint16_t   *p_desc_handle)
+{
+    /* Descriptor metadata */
+    ble_gatts_attr_md_t   desc_md = {0};
+
+    desc_md.vloc = BLE_GATTS_VLOC_STACK;
+    /* Always set variable size */
+    desc_md.vlen = has_variable_len;
+
+    /* Make it readable and writable */
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.read_perm);
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.write_perm);
+
+    ble_gatts_attr_t attr_desc = {0};
+
+    attr_desc.p_uuid    = p_uuid;
+    attr_desc.p_attr_md = &desc_md;
+    attr_desc.init_len  = length;
+    attr_desc.max_len   = max_length;
+    attr_desc.p_value   = p_data;
+
+    ASSERT_STATUS ( sd_ble_gatts_descriptor_add(char_handle,
+                                                &attr_desc,
+                                                p_desc_handle));
+
+    return ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/btle/custom/custom_helper.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/btle/custom/custom_helper.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,60 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _CUSTOM_HELPER_H_
+#define _CUSTOM_HELPER_H_
+
+#include "common/common.h"
+#include "nrf_ble.h"
+#include "ble/UUID.h"
+#include "ble/GattCharacteristic.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base);
+error_t custom_decode_uuid(uint8_t const *const p_uuid_base,
+                           ble_uuid_t          *p_uuid);
+ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid);
+
+error_t custom_add_in_characteristic(uint16_t                  service_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                   properties,
+                                     SecurityManager::SecurityMode_t requiredSecurity,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     const uint8_t            *userDescriptionDescriptorValuePtr,
+                                     uint16_t                  userDescriptionDescriptorValueLen,
+                                     bool                      readAuthorization,
+                                     bool                      writeAuthorization,
+                                     ble_gatts_char_handles_t *p_char_handle);
+
+error_t custom_add_in_descriptor(uint16_t                      char_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     uint16_t                 *p_desc_handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ifndef _CUSTOM_HELPER_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/ansi_escape.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/ansi_escape.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,103 @@
+/**************************************************************************/
+/*!
+    @file     ansi_esc_code.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, hathach (tinyusb.org)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+    This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief TBD
+ *
+ *  \note TBD
+ */
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _ANSI_ESC_CODE_H_
+#define _ANSI_ESC_CODE_H_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CSI_CODE(seq)   "\33[" seq
+#define CSI_SGR(x)      CSI_CODE(#x) "m"
+
+//------------- Cursor movement -------------//
+#define ANSI_CURSOR_UP(n)        CSI_CODE(#n "A")
+#define ANSI_CURSOR_DOWN(n)      CSI_CODE(#n "B")
+#define ANSI_CURSOR_FORWARD(n)   CSI_CODE(#n "C")
+#define ANSI_CURSOR_BACKWARD(n)  CSI_CODE(#n "D")
+#define ANSI_CURSOR_LINE_DOWN(n) CSI_CODE(#n "E")
+#define ANSI_CURSOR_LINE_UP(n)   CSI_CODE(#n "F")
+#define ANSI_CURSOR_POSITION(n, m) CSI_CODE(#n ";" #m "H")
+
+#define ANSI_ERASE_SCREEN(n)     CSI_CODE(#n "J")
+#define ANSI_ERASE_LINE(n)       CSI_CODE(#n "K")
+
+/** text color */
+#define ANSI_TEXT_BLACK          CSI_SGR(30)
+#define ANSI_TEXT_RED            CSI_SGR(31)
+#define ANSI_TEXT_GREEN          CSI_SGR(32)
+#define ANSI_TEXT_YELLOW         CSI_SGR(33)
+#define ANSI_TEXT_BLUE           CSI_SGR(34)
+#define ANSI_TEXT_MAGENTA        CSI_SGR(35)
+#define ANSI_TEXT_CYAN           CSI_SGR(36)
+#define ANSI_TEXT_WHITE          CSI_SGR(37)
+#define ANSI_TEXT_DEFAULT        CSI_SGR(39)
+
+/** background color */
+#define ANSI_BG_BLACK            CSI_SGR(40)
+#define ANSI_BG_RED              CSI_SGR(41)
+#define ANSI_BG_GREEN            CSI_SGR(42)
+#define ANSI_BG_YELLOW           CSI_SGR(43)
+#define ANSI_BG_BLUE             CSI_SGR(44)
+#define ANSI_BG_MAGENTA          CSI_SGR(45)
+#define ANSI_BG_CYAN             CSI_SGR(46)
+#define ANSI_BG_WHITE            CSI_SGR(47)
+#define ANSI_BG_DEFAULT          CSI_SGR(49)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TUSB_ANSI_ESC_CODE_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/assertion.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/assertion.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,198 @@
+/**************************************************************************/
+/*!
+    @file     assertion.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief TBD
+ *
+ *  \note TBD
+ */
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _ASSERTION_H_
+#define _ASSERTION_H_
+
+#include "projectconfig.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+static inline void debugger_breakpoint(void) ATTR_ALWAYS_INLINE;
+static inline void debugger_breakpoint(void)
+{
+#ifndef _TEST_
+  __asm("BKPT #0\n");
+#endif
+}
+
+//--------------------------------------------------------------------+
+// Compile-time Assert
+//--------------------------------------------------------------------+
+#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
+  #define _ASSERT_COUNTER __COUNTER__
+#else
+  #define _ASSERT_COUNTER __LINE__
+#endif
+
+#define ASSERT_STATIC(const_expr, message) enum { XSTRING_CONCAT_(static_assert_, _ASSERT_COUNTER) = 1/(!!(const_expr)) }
+
+//--------------------------------------------------------------------+
+// Assert Helper
+//--------------------------------------------------------------------+
+//#ifndef _TEST_
+//  #define ASSERT_MESSAGE(format, ...) _PRINTF("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
+//#else
+//  #define ASSERT_MESSAGE(format, ...) _PRINTF("%d:note: Assert " format "\n", __LINE__, __VA_ARGS__)
+//#endif
+
+#if CFG_DEBUG == 3
+  #define ASSERT_MESSAGE(format, ...) debugger_breakpoint()
+#elif CFG_DEBUG == 2
+  #define ASSERT_MESSAGE(format, ...) printf("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
+#else
+  #define ASSERT_MESSAGE(format, ...)
+#endif
+
+#define ASSERT_ERROR_HANDLER(x, para)  \
+    return (x)
+
+#define ASSERT_DEFINE_WITH_HANDLER(error_handler, handler_para, setup_statement, condition, error, format, ...) \
+  do{\
+    setup_statement;\
+	  if (!(condition)) {\
+	    ASSERT_MESSAGE(format, __VA_ARGS__);\
+	    error_handler(error, handler_para);\
+	  }\
+	}while(0)
+
+#define ASSERT_DEFINE(...) ASSERT_DEFINE_WITH_HANDLER(ASSERT_ERROR_HANDLER, NULL, __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// error_t Status Assert TODO use ASSERT_DEFINE
+//--------------------------------------------------------------------+
+#define ASSERT_STATUS_MESSAGE(sts, message) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, status, "%s: %s", ErrorStr[status], message)
+
+#define ASSERT_STATUS(sts) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, status, "error = %d", status)
+
+#define ASSERT_STATUS_RET_VOID(sts) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, (void) 0, "error = %d", status)
+
+//--------------------------------------------------------------------+
+// Logical Assert
+//--------------------------------------------------------------------+
+#define ASSERT(...)                      ASSERT_TRUE(__VA_ARGS__)
+#define ASSERT_TRUE(condition  , error)  ASSERT_DEFINE( , (condition), error, "%s", "evaluated to false")
+#define ASSERT_FALSE(condition , error)  ASSERT_DEFINE( ,!(condition), error, "%s", "evaluated to true")
+
+//--------------------------------------------------------------------+
+// Pointer Assert
+//--------------------------------------------------------------------+
+#define ASSERT_PTR(...)                    ASSERT_PTR_NOT_NULL(__VA_ARGS__)
+#define ASSERT_PTR_NOT_NULL(pointer, error) ASSERT_DEFINE( , NULL != (pointer), error, "%s", "pointer is NULL")
+#define ASSERT_PTR_NULL(pointer, error)    ASSERT_DEFINE( , NULL == (pointer), error, "%s", "pointer is not NULL")
+
+//--------------------------------------------------------------------+
+// Integral Assert
+//--------------------------------------------------------------------+
+#define ASSERT_XXX_EQUAL(type_format, expected, actual, error) \
+    ASSERT_DEFINE(\
+                  uint32_t exp = (expected); uint32_t act = (actual),\
+                  exp==act,\
+                  error,\
+                  "expected " type_format ", actual " type_format, exp, act)
+
+#define ASSERT_XXX_WITHIN(type_format, lower, upper, actual, error) \
+    ASSERT_DEFINE(\
+                  uint32_t low = (lower); uint32_t up = (upper); uint32_t act = (actual),\
+                  (low <= act) && (act <= up),\
+                  error,\
+                  "expected within " type_format " - " type_format ", actual " type_format, low, up, act)
+
+//--------------------------------------------------------------------+
+// Integer Assert
+//--------------------------------------------------------------------+
+#define ASSERT_INT(...)        ASSERT_INT_EQUAL(__VA_ARGS__)
+#define ASSERT_INT_EQUAL(...)  ASSERT_XXX_EQUAL("%d", __VA_ARGS__)
+#define ASSERT_INT_WITHIN(...) ASSERT_XXX_WITHIN("%d", __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Hex Assert
+//--------------------------------------------------------------------+
+#define ASSERT_HEX(...)        ASSERT_HEX_EQUAL(__VA_ARGS__)
+#define ASSERT_HEX_EQUAL(...)  ASSERT_XXX_EQUAL("0x%x", __VA_ARGS__)
+#define ASSERT_HEX_WITHIN(...) ASSERT_XXX_WITHIN("0x%x", __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Bin Assert
+//--------------------------------------------------------------------+
+#define BIN8_PRINTF_PATTERN "%d%d%d%d%d%d%d%d"
+#define BIN8_PRINTF_CONVERT(byte)  \
+  ((byte) & 0x80 ? 1 : 0), \
+  ((byte) & 0x40 ? 1 : 0), \
+  ((byte) & 0x20 ? 1 : 0), \
+  ((byte) & 0x10 ? 1 : 0), \
+  ((byte) & 0x08 ? 1 : 0), \
+  ((byte) & 0x04 ? 1 : 0), \
+  ((byte) & 0x02 ? 1 : 0), \
+  ((byte) & 0x01 ? 1 : 0)
+
+#define ASSERT_BIN8(...)        ASSERT_BIN8_EQUAL(__VA_ARGS__)
+#define ASSERT_BIN8_EQUAL(expected, actual, error)\
+    ASSERT_DEFINE(\
+                  uint8_t exp = (expected); uint8_t act = (actual),\
+                  exp==act,\
+                  error,\
+                  "expected " BIN8_PRINTF_PATTERN ", actual " BIN8_PRINTF_PATTERN, BIN8_PRINTF_CONVERT(exp), BIN8_PRINTF_CONVERT(act) )
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ASSERTION_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/binary.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/binary.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,96 @@
+/**************************************************************************/
+/*!
+    @file     binary.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _BINARY_H_
+#define _BINARY_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/// n-th Bit
+#define BIT(n) (1 << (n))
+
+/// set n-th bit of x to 1
+#define BIT_SET(x, n) ( (x) | BIT(n) )
+
+/// clear n-th bit of x
+#define BIT_CLR(x, n) ( (x) & (~BIT(n)) )
+
+/// test n-th bit of x
+#define BIT_TEST(x, n) ( (x) & BIT(n) )
+
+#if defined(__GNUC__) && !defined(__CC_ARM) // keil does not support binary format
+
+#define BIN8(x)               ((uint8_t)  (0b##x))
+#define BIN16(b1, b2)         ((uint16_t) (0b##b1##b2))
+#define BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
+
+#else
+
+//  internal macro of B8, B16, B32
+#define _B8__(x) (((x&0x0000000FUL)?1:0) \
+                +((x&0x000000F0UL)?2:0) \
+                +((x&0x00000F00UL)?4:0) \
+                +((x&0x0000F000UL)?8:0) \
+                +((x&0x000F0000UL)?16:0) \
+                +((x&0x00F00000UL)?32:0) \
+                +((x&0x0F000000UL)?64:0) \
+                +((x&0xF0000000UL)?128:0))
+
+#define BIN8(d) ((uint8_t) _B8__(0x##d##UL))
+#define BIN16(dmsb,dlsb) (((uint16_t)BIN8(dmsb)<<8) + BIN8(dlsb))
+#define BIN32(dmsb,db2,db3,dlsb) \
+            (((uint32_t)BIN8(dmsb)<<24) \
+            + ((uint32_t)BIN8(db2)<<16) \
+            + ((uint32_t)BIN8(db3)<<8) \
+            + BIN8(dlsb))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _BINARY_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/ble_error.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/ble_error.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,151 @@
+/**************************************************************************/
+/*!
+    @file     ble_error.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief Error Header
+ *
+ *  \note TBD
+ */
+
+/** \ingroup Group_Common
+ *  \defgroup Group_Error Error Codes
+ *  @{
+ */
+
+#ifndef _BLE_ERROR_H_
+#define _BLE_ERROR_H_
+
+#include "projectconfig.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+typedef enum 
+{
+  /*=======================================================================
+    NORDIC GLOBAL ERRORS                                   0x0000 .. 0x00FF
+    -----------------------------------------------------------------------
+    Errors mapped from nrf_error.h
+    -----------------------------------------------------------------------*/
+    ERROR_NONE                                    = 0x0000 , ///< Successful command
+    ERROR_SVC_HANDLER_MISSING                     = 0x0001 , ///< SVC handler is missing
+    ERROR_SOFTDEVICE_NOT_ENABLED                  = 0x0002 , ///< SoftDevice has not been enabled
+    ERROR_INTERNAL                                = 0x0003 , ///< Internal Error
+    ERROR_NO_MEM                                  = 0x0004 , ///< No Memory for operation
+    ERROR_NOT_FOUND                               = 0x0005 , ///< Not found
+    ERROR_NOT_SUPPORTED                           = 0x0006 , ///< Not supported
+    ERROR_INVALID_PARAM                           = 0x0007 , ///< Invalid Parameter
+    ERROR_INVALID_STATE                           = 0x0008 , ///< Invalid state, operation disallowed in this state
+    ERROR_INVALID_LENGTH                          = 0x0009 , ///< Invalid Length
+    ERROR_INVALID_FLAGS                           = 0x000A , ///< Invalid Flags
+    ERROR_INVALID_DATA                            = 0x000B , ///< Invalid Data
+    ERROR_DATA_SIZE                               = 0x000C , ///< Data size exceeds limit
+    ERROR_TIMEOUT                                 = 0x000D , ///< Operation timed out
+    ERROR_NULL                                    = 0x000E , ///< Null Pointer
+    ERROR_FORBIDDEN                               = 0x000F , ///< Forbidden Operation
+    ERROR_INVALID_ADDR                            = 0x0010 , ///< Bad Memory Address
+    ERROR_BUSY                                    = 0x0011 , ///< Busy
+  /*=======================================================================*/
+
+  ERROR_INVALIDPARAMETER                        = 0x0100 , /**< An invalid parameter value was provided */
+  ERROR_I2C_XFER_FAILED                         = 0x0101 , /**< an failed attempt to make I2C transfer */
+
+  /*=======================================================================
+    SIMPLE BINARY PROTOCOL ERRORS                          0x0120 .. 0x013F
+    -----------------------------------------------------------------------
+    Errors relating to the simple binary protocol (/src//protocol)
+    -----------------------------------------------------------------------*/
+    ERROR_PROT_INVALIDMSGTYPE                   = 0x121,  /**< Unexpected msg type encountered */
+    ERROR_PROT_INVALIDCOMMANDID                 = 0x122,  /**< Unknown or out of range command ID */
+    ERROR_PROT_INVALIDPAYLOAD                   = 0x123,  /**< Message payload has a problem (invalid len, etc.) */
+  /*=======================================================================*/
+
+  //------------- based on Nordic SDM nrf_error_sdm.h -------------//
+  ERROR_SDM_LFCLK_SOURCE_UNKNOWN                = 0x1000 , ///< Unknown lfclk source
+  ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION   = 0x1001 , ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts)
+  ERROR_SDM_INCORRECT_CLENR0                    = 0x1002 , ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing)
+
+  //------------- based on Nordic SOC nrf_error_soc.h -------------//
+  /* Mutex Errors */
+  ERROR_SOC_MUTEX_ALREADY_TAKEN                 = 0x2000 ,  ///< Mutex already taken
+
+  /* NVIC errors */
+  ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE        = 0x2001 ,  ///< NVIC interrupt not available
+  ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED = 0x2002 ,  ///< NVIC interrupt priority not allowed
+  ERROR_SOC_NVIC_SHOULD_NOT_RETURN              = 0x2003 ,  ///< NVIC should not return
+
+  /* Power errors */
+  ERROR_SOC_POWER_MODE_UNKNOWN                  = 0x2004 ,  ///< Power mode unknown
+  ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN         = 0x2005 ,  ///< Power POF threshold unknown
+  ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN         = 0x2006 ,  ///< Power off should not return
+
+  /* Rand errors */
+  ERROR_SOC_RAND_NOT_ENOUGH_VALUES              = 0x2007 ,  ///< RAND not enough values
+
+  /* PPI errors */
+  ERROR_SOC_PPI_INVALID_CHANNEL                 = 0x2008 ,  ///< Invalid PPI Channel
+  ERROR_SOC_PPI_INVALID_GROUP                   = 0x2009 ,  ///< Invalid PPI Group
+
+  //------------- based on Nordic STK (ble) ble_err.h -------------//
+  ERROR_BLE_INVALID_CONN_HANDLE                 = 0x3001 , /**< Invalid connection handle. */
+  ERROR_BLE_INVALID_ATTR_HANDLE                 = 0x3002 , /**< Invalid attribute handle. */
+  ERROR_BLE_NO_TX_BUFFERS                       = 0x3003 , /**< Buffer capacity exceeded. */
+
+  // L2CAP
+  ERROR_BLE_L2CAP_CID_IN_USE                    = 0x3100 , /**< CID already in use. */
+
+  // GAP
+  ERROR_BLE_GAP_UUID_LIST_MISMATCH              = 0x3200 , /**< UUID list does not contain an integral number of UUIDs. */
+  ERROR_BLE_GAP_DISCOVERABLE_WITH_WHITELIST     = 0x3201 , /**< Use of Whitelist not permitted with discoverable advertising. */
+  ERROR_BLE_GAP_INVALID_BLE_ADDR                = 0x3202 , /**< The upper two bits of the address do not correspond to the specified address type. */
+
+  // GATTC
+  ERROR_BLE_GATTC_PROC_NOT_PERMITTED            = 0x3300 ,
+
+  // GATTS
+  ERROR_BLEGATTS_INVALID_ATTR_TYPE              = 0x3400 , /**< Invalid attribute type. */
+  ERROR_BLEGATTS_SYS_ATTR_MISSING               = 0x3401 , /**< System Attributes missing. */
+
+}error_t;
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _BLE_ERROR_H_ */
+
+ /**  @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,236 @@
+/**************************************************************************/
+/*!
+    @file     common.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \defgroup Group_Common Common Files
+ * @{
+ *
+ *  \defgroup Group_CommonH common.h
+ *
+ *  @{
+ */
+
+#ifndef _COMMON_H_
+#define _COMMON_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDES
+//--------------------------------------------------------------------+
+
+//------------- Standard Header -------------//
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+//------------- General Header -------------//
+#include "projectconfig.h"
+#include "compiler.h"
+#include "assertion.h"
+#include "binary.h"
+#include "ble_error.h"
+
+//------------- MCU header -------------//
+//#include "nrf.h"
+
+//--------------------------------------------------------------------+
+// TYPEDEFS
+//--------------------------------------------------------------------+
+typedef unsigned char byte_t;
+typedef float  float32_t;
+typedef double float64_t;
+
+//--------------------------------------------------------------------+
+// MACROS
+//--------------------------------------------------------------------+
+#define STRING_(x)  #x                             // stringify without expand
+#define XSTRING_(x) STRING_(x)                     // expand then stringify
+#define STRING_CONCAT_(a, b) a##b                  // concat without expand
+#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) // expand then concat
+
+#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
+#define U16_LOW_U8(u16)  ((uint8_t) ((u16)       & 0x00ff))
+#define U16_TO_U8S_BE(u16)  U16_HIGH_U8(u16), U16_LOW_U8(u16)
+#define U16_TO_U8S_LE(u16)  U16_LOW_U8(u16), U16_HIGH_U8(u16)
+
+#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB
+#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff))
+#define U32_B3_U8(u32) ((uint8_t) (((u32) >>  8) & 0x000000ff))
+#define U32_B4_U8(u32) ((uint8_t) ((u32)        & 0x000000ff)) // LSB
+
+#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32)
+#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32)
+
+//--------------------------------------------------------------------+
+// INLINE FUNCTION
+//--------------------------------------------------------------------+
+#define memclr_(buffer, size)  memset(buffer, 0, size)
+
+//------------- Conversion -------------//
+/// form an uint32_t from 4 x uint8_t
+static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4)
+{
+  return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
+}
+
+static inline uint8_t u16_high_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint8_t u16_high_u8(uint16_t u16)
+{
+  return (uint8_t) ((u16 >> 8) & 0x00ff);
+}
+
+static inline uint8_t u16_low_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint8_t u16_low_u8(uint16_t u16)
+{
+  return (uint8_t) (u16 & 0x00ff);
+}
+
+//------------- Min -------------//
+static inline uint8_t min8_of(uint8_t x, uint8_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t min8_of(uint8_t x, uint8_t y)
+{
+  return (x < y) ? x : y;
+}
+
+static inline uint16_t min16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint16_t min16_of(uint16_t x, uint16_t y)
+{
+  return (x < y) ? x : y;
+}
+
+static inline uint32_t min32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t min32_of(uint32_t x, uint32_t y)
+{
+  return (x < y) ? x : y;
+}
+
+//------------- Max -------------//
+static inline uint32_t max32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t max32_of(uint32_t x, uint32_t y)
+{
+  return (x > y) ? x : y;
+}
+
+//------------- Align -------------//
+static inline uint32_t align32 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align32 (uint32_t value)
+{
+	return (value & 0xFFFFFFE0UL);
+}
+
+static inline uint32_t align16 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align16 (uint32_t value)
+{
+	return (value & 0xFFFFFFF0UL);
+}
+
+static inline uint32_t align_n (uint32_t alignment, uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align_n (uint32_t alignment, uint32_t value)
+{
+	return value & (~(alignment-1));
+}
+
+static inline uint32_t align4k (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align4k (uint32_t value)
+{
+	return (value & 0xFFFFF000UL);
+}
+
+static inline uint32_t offset4k(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t offset4k(uint32_t value)
+{
+	return (value & 0xFFFUL);
+}
+
+//------------- Mathematics -------------//
+/// inclusive range checking
+static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper)
+{
+  return (lower <= value) && (value <= upper);
+}
+
+/// exclusive range checking
+static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper)
+{
+  return (lower < value) && (value < upper);
+}
+
+static inline uint8_t log2_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t log2_of(uint32_t value)
+{
+  uint8_t result = 0; // log2 of a value is its MSB's position
+
+  while (value >>= 1)
+  {
+    result++;
+  }
+  return result;
+}
+
+// return the number of set bits in value
+static inline uint8_t cardinality_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t cardinality_of(uint32_t value)
+{
+  // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only
+  // the high bit set, then it will only go once through the loop
+  // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie)
+  // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method
+  // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and
+  // published in 1964 in a book edited by Beckenbach.)"
+  uint8_t count;
+  for (count = 0; value; count++)
+  {
+    value &= value - 1; // clear the least significant bit set
+  }
+
+  return count;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _COMMON_H_ */
+
+/**  @} */
+/**  @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/common/compiler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/common/compiler.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,152 @@
+/**************************************************************************/
+/*!
+    @file     compiler.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief GCC Header
+ */
+
+/** \ingroup Group_Compiler
+ *  \defgroup Group_GCC GNU GCC
+ *  @{
+ */
+
+#ifndef _COMPILER_GCC_H_
+#define _COMPILER_GCC_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#include "projectconfig.h"
+
+//#ifndef __GNUC__
+//  #define ATTR_ALWAYS_INLINE
+//  #define ATTR_CONST
+//#else
+
+#ifdef _TEST_
+  #define ATTR_ALWAYS_INLINE
+  #define STATIC_
+  #define INLINE_
+#else
+  #define STATIC_ static
+  #define INLINE_ inline
+
+  #if CFG_DEBUG == 3
+    #define ATTR_ALWAYS_INLINE  // no inline for debug = 3
+  #endif
+#endif
+
+#define ALIGN_OF(x)                __alignof__(x)
+
+/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section
+#define ATTR_SECTION(section)      __attribute__ ((#section))
+
+/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking
+#define ATTR_ERROR(Message)        __attribute__ ((error(Message)))
+
+/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking
+#define ATTR_WARNING(Message)      __attribute__ ((warning(Message)))
+
+/**
+ *  \defgroup Group_VariableAttr Variable Attributes
+ *  @{
+ */
+
+/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes
+#define ATTR_ALIGNED(Bytes)        __attribute__ ((aligned(Bytes)))
+
+/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute
+#define ATTR_PACKED                __attribute__ ((packed))
+
+#define ATTR_PREPACKED
+
+#define ATTR_PACKED_STRUCT(x)    x __attribute__ ((packed))
+/** @} */
+
+/**
+ *  \defgroup Group_FuncAttr Function Attributes
+ *  @{
+ */
+
+#ifndef ATTR_ALWAYS_INLINE
+/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified
+#define ATTR_ALWAYS_INLINE         __attribute__ ((always_inline))
+#endif
+
+/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null
+#define ATTR_NON_NULL              __attribute__ ((nonull))
+
+/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure
+#define ATTR_PURE                  __attribute__ ((pure))
+
+/// Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
+/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void
+#define ATTR_CONST                 __attribute__ ((const))
+
+/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses
+#define ATTR_DEPRECATED            __attribute__ ((deprecated))
+
+/// Same as the deprecated attribute with optional message in the warning
+#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess)))
+
+/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code
+#define ATTR_WEAK                  __attribute__ ((weak))
+
+/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified
+#define ATTR_ALIAS(func)           __attribute__ ((alias(#func)))
+
+/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static
+#define ATTR_WEAKREF(func)         __attribute__ ((weakref(#func)))
+
+/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug
+#define ATTR_WARN_UNUSED_RESULT    __attribute__ ((warn_unused_result))
+
+/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.
+#define ATTR_USED                  __attribute__ ((used))
+
+/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function.
+#define ATTR_UNUSED                __attribute__ ((unused))
+
+/** @} */
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _COMPILER_GCC_H_ */
+
+/// @}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,235 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2015 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+#include "ble_err.h"
+#include "ble/DiscoveredCharacteristicDescriptor.h"
+
+nRF5xCharacteristicDescriptorDiscoverer::nRF5xCharacteristicDescriptorDiscoverer() :
+    discoveryRunning() {
+    // nothing to do
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::~nRF5xCharacteristicDescriptorDiscoverer() {
+    // nothing to do
+}
+
+ble_error_t nRF5xCharacteristicDescriptorDiscoverer::launch(
+    const DiscoveredCharacteristic& characteristic,
+    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
+) {
+    Gap::Handle_t connHandle = characteristic.getConnectionHandle();
+    // it is ok to deduce that the start handle for descriptors is after
+    // the characteristic declaration and the characteristic value declaration
+    // see BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] (3.3)
+    Gap::Handle_t descriptorStartHandle = characteristic.getDeclHandle() + 2;
+    Gap::Handle_t descriptorEndHandle = characteristic.getLastHandle();
+
+    // check if there is any descriptor to discover
+    if (descriptorEndHandle < descriptorStartHandle) {
+        CharacteristicDescriptorDiscovery::TerminationCallbackParams_t termParams = {
+            characteristic,
+            BLE_ERROR_NONE
+        };
+        terminationCallback.call(&termParams);
+        return BLE_ERROR_NONE;
+    }
+
+    // check if we can run this discovery
+    if (isConnectionInUse(connHandle)) {
+        return BLE_STACK_BUSY;
+    }
+
+    // get a new discovery slot, if none are available, just return
+    Discovery* discovery = getAvailableDiscoverySlot();
+    if(discovery == NULL) {
+        return BLE_STACK_BUSY;
+    }
+
+    // try to launch the discovery
+    ble_error_t err = gattc_descriptors_discover(connHandle, descriptorStartHandle, descriptorEndHandle);
+    if(!err) {
+        // commit the new discovery to its slot
+        *discovery = Discovery(characteristic, discoveryCallback, terminationCallback);
+    }
+
+    return err;
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::isActive(const DiscoveredCharacteristic& characteristic) const {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if(discoveryRunning[i].getCharacteristic() == characteristic) {
+            return true;
+        }
+    }
+    return false;
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::requestTerminate(const DiscoveredCharacteristic& characteristic) {
+    Discovery* discovery = findRunningDiscovery(characteristic);
+    if(discovery) {
+        // call terminate anyway
+        terminate(discovery, BLE_ERROR_NONE);
+    }
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors) {
+    Discovery* discovery = findRunningDiscovery(connectionHandle);
+    // the discovery has been removed
+    if(!discovery) {
+        return;
+    }
+
+    for (uint16_t i = 0; i < descriptors.count; ++i) {
+        discovery->process(
+            descriptors.descs[i].handle, UUID(descriptors.descs[i].uuid.uuid)
+        );
+    }
+
+    // prepare the next discovery request (if needed)
+    uint16_t startHandle = descriptors.descs[descriptors.count - 1].handle + 1;
+    uint16_t endHandle = discovery->getCharacteristic().getLastHandle();
+
+    if(startHandle > endHandle) {
+        terminate(discovery, BLE_ERROR_NONE);
+        return;
+    }
+
+    ble_error_t err = gattc_descriptors_discover(connectionHandle, startHandle, endHandle);
+    if(err) {
+        terminate(discovery, err);
+        return;
+    }
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::terminate(uint16_t handle, ble_error_t err) {
+    Discovery* discovery = findRunningDiscovery(handle);
+    // the discovery has already been terminated
+    if(!discovery) {
+        return;
+    }
+
+    terminate(discovery, err);
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::terminate(Discovery* discovery, ble_error_t err) {
+    // temporary copy, user code can try to launch a new discovery in the onTerminate
+    // callback. So, this discovery should not appear in such case.
+    Discovery tmp = *discovery;
+    *discovery = Discovery();
+    tmp.terminate(err);
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(const DiscoveredCharacteristic& characteristic) {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if((discoveryRunning[i].getCharacteristic() == characteristic) &&
+           (discoveryRunning[i].isEmpty() == false)) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(uint16_t handle) {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if((discoveryRunning[i].getCharacteristic().getConnectionHandle() == handle) &&
+           (discoveryRunning[i].isEmpty() == false)) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::getAvailableDiscoverySlot() {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if(discoveryRunning[i].isEmpty()) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::isConnectionInUse(uint16_t connHandle) {
+     return findRunningDiscovery(connHandle) != NULL;
+}
+
+ble_error_t nRF5xCharacteristicDescriptorDiscoverer::gattc_descriptors_discover(
+    uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle) {
+
+    ble_gattc_handle_range_t discoveryRange = {
+        start_handle,
+        end_handle
+    };
+    uint32_t err = sd_ble_gattc_descriptors_discover(connection_handle, &discoveryRange);
+
+    switch(err) {
+        case NRF_SUCCESS:
+            return BLE_ERROR_NONE;
+        case BLE_ERROR_INVALID_CONN_HANDLE:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_ADDR:
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        case NRF_ERROR_BUSY:
+            return BLE_STACK_BUSY;
+        default:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+// implementation of nRF5xCharacteristicDescriptorDiscoverer::Discovery
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery() :
+    characteristic(), onDiscovery(), onTerminate() {
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery(
+    const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb) :
+    characteristic(c), onDiscovery(dCb), onTerminate(tCb) {
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::Discovery::process(
+    GattAttribute::Handle_t handle, const UUID& uuid) {
+    CharacteristicDescriptorDiscovery::DiscoveryCallbackParams_t params = {
+        characteristic,
+        DiscoveredCharacteristicDescriptor(
+            characteristic.getGattClient(),
+            characteristic.getConnectionHandle(),
+            handle,
+            uuid
+        )
+    };
+    onDiscovery.call(&params);
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::Discovery::terminate(ble_error_t err) {
+    CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = {
+        characteristic,
+        err
+    };
+
+    onTerminate.call(&params);
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::Discovery::isEmpty() const {
+    return *this == Discovery();
+}
+
+const DiscoveredCharacteristic& nRF5xCharacteristicDescriptorDiscoverer::Discovery::getCharacteristic() const {
+    return characteristic;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xCharacteristicDescriptorDiscoverer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,214 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2015 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
+#define __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
+
+#include "ble/Gap.h"
+#include "ble/DiscoveredCharacteristic.h"
+#include "ble/CharacteristicDescriptorDiscovery.h"
+#include "ble/GattClient.h"
+#include "ble_gattc.h"
+
+/**
+ * @brief Manage the discovery of Characteristic descriptors
+ * @details is a bridge between BLE API and Nordic stack regarding Characteristic
+ * Descriptor discovery. The BLE API can launch, monitor and ask for termination
+ * of a discovery. The Nordic stack will provide new descriptors and indicate when
+ * the discovery is done.
+ */
+class nRF5xCharacteristicDescriptorDiscoverer
+{
+    typedef CharacteristicDescriptorDiscovery::DiscoveryCallback_t DiscoveryCallback_t;
+    typedef CharacteristicDescriptorDiscovery::TerminationCallback_t TerminationCallback_t;
+
+public:
+    /**
+     * @brief Construct a new characteristic descriptor discoverer.
+     */
+    nRF5xCharacteristicDescriptorDiscoverer();
+
+    /**
+     * @brief Destroy a characteristic descriptor discoverer.
+     */
+    ~nRF5xCharacteristicDescriptorDiscoverer();
+
+    /**
+     * Launch a new characteristic descriptor discovery for a given DiscoveredCharacteristic.
+     * @param characteristic The characteristic owning the descriptors to discover.
+     * @param discoveryCallback The callback called when a descriptor is discovered.
+     * @param terminationCallback The callback called when the discovery process end.
+     * @return BLE_ERROR_NONE if characteristic descriptor discovery is launched successfully;
+     *         else an appropriate error.
+     * @note: this will be called by BLE API side.
+     */
+    ble_error_t launch(
+        const DiscoveredCharacteristic& characteristic,
+        const DiscoveryCallback_t& discoveryCallback,
+        const TerminationCallback_t& terminationCallback
+    );
+
+    /**
+     * @brief indicate if a characteristic descriptor discovery is active for a
+     * given DiscoveredCharacteristic.
+     * @param characteristic The characteristic for whom the descriptor might be
+     * currently discovered.
+     * @return true if descriptors of characteristic are discovered, false otherwise.
+     * @note: this will be called by BLE API side.
+     */
+    bool isActive(const DiscoveredCharacteristic& characteristic) const;
+
+    /**
+     * @brief request the termination of characteristic descriptor discovery
+     * for a give DiscoveredCharacteristic
+     * @param characteristic The characteristic for whom the descriptor discovery
+     * should be stopped.
+     * @note: this will be called by BLE API side.
+     */
+    void requestTerminate(const DiscoveredCharacteristic& characteristic);
+
+    /**
+     * @brief process descriptors discovered from the Nordic stack.
+     * @param connectionHandle The connection handle upon which descriptors has been
+     * discovered.
+     * @param descriptors Discovered descriptors.
+     * @note This will be called by the Nordic stack.
+     */
+    void process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors);
+
+    /**
+     * @brief Called by the Nordic stack when the discovery is over.
+     * @param The connection handle upon which the discovery process is done.
+     * @param err An error if the termination is due to an error.
+     */
+    void terminate(uint16_t connectionHandle, ble_error_t err);
+
+private:
+    // protection against copy construction and assignment
+    nRF5xCharacteristicDescriptorDiscoverer(const nRF5xCharacteristicDescriptorDiscoverer&);
+    nRF5xCharacteristicDescriptorDiscoverer& operator=(const nRF5xCharacteristicDescriptorDiscoverer&);
+
+    /**
+     * @brief Discovery process, it store the DiscoveredCharacteristic, the
+     * discovery callback and the termination callback.
+     */
+    class Discovery {
+    public:
+        /**
+         * @brief Construct an empty discovery, such can be considerate as a not running discovery.
+         * @note #isEmpty function will return true
+         */
+        Discovery();
+
+        /**
+         * @brief Construct a valid discovery process.
+         *
+         * @param c the characteristic from whom descriptors will be discovered.
+         * @param dCb The discovery callback called each time a descriptor is discovered.
+         * @param tCb The termination callback called when the discovery terminate.
+         *
+         * @note #isEmpty function will return false
+         */
+        Discovery(const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb);
+
+        /**
+         * @brief Process the discovery of a descriptor.
+         *
+         * @param handle The attribute handle of the descriptor found
+         * @param uuid The UUID of the descriptor found.
+         */
+        void process(GattAttribute::Handle_t handle, const UUID& uuid);
+
+        /**
+         * @brief Terminate the discovery process.
+         *
+         * @param err Error associate with the termination
+         * @note after this call #isEmpty function will return true.
+         */
+        void terminate(ble_error_t err);
+
+        /**
+         * @brief check if the discovery process is empty or not. Empty discovery are
+         * not running.
+         *
+         * @detail Discovery are empty after:
+         *     - a default construction
+         *     - a copy construction form a default constructed
+         *     - an assignment from a default constructed Discovery
+         * @return true if the Discovery is empty and false otherwise.
+         */
+        bool isEmpty() const;
+
+        /**
+         * @brief return the characteristic from whom descriptors are discovered.
+         * @return the characteristic from whom descriptors are discovered.
+         */
+        const DiscoveredCharacteristic& getCharacteristic() const;
+
+        /**
+         * @brief equal to operator, test if two discovery process are equal
+         *
+         * @param lhs left hand side of the expression
+         * @param rhs right hand side of the expression
+         * @return true if lhs == rhs
+         */
+        friend bool operator==(const Discovery& lhs, const Discovery& rhs) {
+            return lhs.characteristic == rhs.characteristic &&
+                   lhs.onDiscovery == rhs.onDiscovery &&
+                   lhs.onTerminate == rhs.onTerminate;
+        }
+
+        /**
+         * @brief not equal to operator, test if two discovery process are not equal
+         *
+         * @param lhs left hand side of the expression
+         * @param rhs right hand side of the expression
+         * @return true if lhs != rhs
+         */
+        friend bool operator!=(const Discovery& lhs, const Discovery& rhs) {
+            return !(lhs == rhs);
+        }
+
+    private:
+        DiscoveredCharacteristic characteristic;
+        DiscoveryCallback_t onDiscovery;
+        TerminationCallback_t onTerminate;
+    };
+
+    // find a running discovery process
+    Discovery* findRunningDiscovery(const DiscoveredCharacteristic& characteristic);
+    Discovery* findRunningDiscovery(uint16_t handle);
+
+    // Called to terminate a discovery is over.
+    void terminate(Discovery* discovery, ble_error_t err);
+
+    // get one slot for a discovery process
+    Discovery* getAvailableDiscoverySlot();
+
+    // indicate if a connection is already running a discovery
+    bool isConnectionInUse(uint16_t connHandle);
+
+    // low level start of a discovery
+    static ble_error_t gattc_descriptors_discover(uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle);
+
+    // count of concurrent connections which can run a descriptor discovery process
+    static const size_t MAXIMUM_CONCURRENT_CONNECTIONS_COUNT = 3;
+
+    // array of running discoveries
+    Discovery discoveryRunning[MAXIMUM_CONCURRENT_CONNECTIONS_COUNT];
+};
+
+#endif /*__NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,63 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xDiscoveredCharacteristic.h"
+#include "nRF5xGattClient.h"
+#include "ble_gatt.h"
+
+void
+nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
+                                     Gap::Handle_t            connectionHandleIn,
+                                     ble_gatt_char_props_t    propsIn,
+                                     GattAttribute::Handle_t  declHandleIn,
+                                     GattAttribute::Handle_t  valueHandleIn)
+{
+    gattc       = gattcIn;
+    connHandle  = connectionHandleIn;
+    declHandle  = declHandleIn;
+    valueHandle = valueHandleIn;
+
+    props._broadcast       = propsIn.broadcast;
+    props._read            = propsIn.read;
+    props._writeWoResp     = propsIn.write_wo_resp;
+    props._write           = propsIn.write;
+    props._notify          = propsIn.notify;
+    props._indicate        = propsIn.indicate;
+    props._authSignedWrite = propsIn.auth_signed_wr;
+}
+
+void
+nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
+                                      Gap::Handle_t            connectionHandleIn,
+                                     UUID::ShortUUIDBytes_t   uuidIn,
+                                     ble_gatt_char_props_t    propsIn,
+                                     GattAttribute::Handle_t  declHandleIn,
+                                     GattAttribute::Handle_t  valueHandleIn)
+{
+    gattc       = gattcIn;
+    connHandle  = connectionHandleIn;
+    uuid        = uuidIn;
+    declHandle  = declHandleIn;
+    valueHandle = valueHandleIn;
+
+    props._broadcast       = propsIn.broadcast;
+    props._read            = propsIn.read;
+    props._writeWoResp     = propsIn.write_wo_resp;
+    props._write           = propsIn.write;
+    props._notify          = propsIn.notify;
+    props._indicate        = propsIn.indicate;
+    props._authSignedWrite = propsIn.auth_signed_wr;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xDiscoveredCharacteristic.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,45 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_DISCOVERED_CHARACTERISTIC_H__
+#define __NRF_DISCOVERED_CHARACTERISTIC_H__
+
+#include "ble/DiscoveredCharacteristic.h"
+#include "ble_gatt.h"
+
+class nRF5xGattClient; /* forward declaration */
+
+class nRF5xDiscoveredCharacteristic : public DiscoveredCharacteristic {
+public:
+    void setup(nRF5xGattClient         *gattcIn,
+               Gap::Handle_t            connectionHandleIn,
+               ble_gatt_char_props_t    propsIn,
+               GattAttribute::Handle_t  declHandleIn,
+               GattAttribute::Handle_t  valueHandleIn);
+
+    void setup(nRF5xGattClient         *gattcIn,
+               Gap::Handle_t            connectionHandleIn,
+               UUID::ShortUUIDBytes_t   uuidIn,
+               ble_gatt_char_props_t    propsIn,
+               GattAttribute::Handle_t  declHandleIn,
+               GattAttribute::Handle_t  valueHandleIn);
+
+    void setLastHandle(GattAttribute::Handle_t last) {
+      lastHandle = last;
+    }
+};
+
+#endif /* __NRF_DISCOVERED_CHARACTERISTIC_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGap.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGap.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,933 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xn.h"
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#include "ble/BLE.h"
+
+#include "common/common.h"
+#include "ble_advdata.h"
+#include "ble_hci.h"
+
+void radioNotificationStaticCallback(bool param) {
+    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+    gap.processRadioNotificationEvent(param);
+}
+
+/**************************************************************************/
+/*!
+    @brief  Sets the advertising parameters and payload for the device
+
+    @param[in]  params
+                Basic advertising details, including the advertising
+                delay, timeout and how the device should be advertised
+    @params[in] advData
+                The primary advertising data payload
+    @params[in] scanResponse
+                The optional Scan Response payload if the advertising
+                type is set to \ref GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED
+                in \ref GapAdveritinngParams
+
+    @returns    \ref ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @retval     BLE_ERROR_BUFFER_OVERFLOW
+                The proposed action would cause a buffer overflow.  All
+                advertising payloads must be <= 31 bytes, for example.
+
+    @retval     BLE_ERROR_NOT_IMPLEMENTED
+                A feature was requested that is not yet supported in the
+                nRF51 firmware or hardware.
+
+    @retval     BLE_ERROR_PARAM_OUT_OF_RANGE
+                One of the proposed values is outside the valid range.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse)
+{
+    /* Make sure we don't exceed the advertising payload length */
+    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) {
+        return BLE_ERROR_BUFFER_OVERFLOW;
+    }
+
+    /* Make sure we have a payload! */
+    if (advData.getPayloadLen() == 0) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Check the scan response payload limits */
+    //if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED))
+    //{
+    //    /* Check if we're within the upper limit */
+    //    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD)
+    //    {
+    //        return BLE_ERROR_BUFFER_OVERFLOW;
+    //    }
+    //    /* Make sure we have a payload! */
+    //    if (advData.getPayloadLen() == 0)
+    //    {
+    //        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    //    }
+    //}
+
+    /* Send advertising data! */
+    ASSERT(ERROR_NONE ==
+           sd_ble_gap_adv_data_set(advData.getPayload(),
+                                   advData.getPayloadLen(),
+                                   scanResponse.getPayload(),
+                                   scanResponse.getPayloadLen()),
+           BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    /* Make sure the GAP Service appearance value is aligned with the
+     *appearance from GapAdvertisingData */
+    ASSERT(ERROR_NONE == sd_ble_gap_appearance_set(advData.getAppearance()),
+           BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    /* ToDo: Perform some checks on the payload, for example the Scan Response can't */
+    /* contains a flags AD type, etc. */
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Starts the BLE HW, initialising any services that were
+            added before this function was called.
+
+    @note   All services must be added before calling this function!
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams &params)
+{
+    /* Make sure we support the advertising type */
+    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) {
+        /* ToDo: This requires a propery security implementation, etc. */
+        return BLE_ERROR_NOT_IMPLEMENTED;
+    }
+
+    /* Check interval range */
+    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED) {
+        /* Min delay is slightly longer for unconnectable devices */
+        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) ||
+            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    } else {
+        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN) ||
+            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    }
+
+    /* Check timeout is zero for Connectable Directed */
+    if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) && (params.getTimeout() != 0)) {
+        /* Timeout must be 0 with this type, although we'll never get here */
+        /* since this isn't implemented yet anyway */
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Check timeout for other advertising types */
+    if ((params.getAdvertisingType() != GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) &&
+        (params.getTimeout() > GapAdvertisingParams::GAP_ADV_PARAMS_TIMEOUT_MAX)) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (advertisingPolicyMode != Gap::ADV_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    /* Start Advertising */
+    ble_gap_adv_params_t adv_para = {0};
+
+    adv_para.type        = params.getAdvertisingType();
+    adv_para.p_peer_addr = NULL;                           // Undirected advertisement
+    adv_para.fp          = advertisingPolicyMode;
+    adv_para.p_whitelist = &whitelist;
+    adv_para.interval    = params.getIntervalInADVUnits(); // advertising interval (in units of 0.625 ms)
+    adv_para.timeout     = params.getTimeout();
+
+    ASSERT(ERROR_NONE == sd_ble_gap_adv_start(&adv_para), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+ble_error_t nRF5xGap::startRadioScan(const GapScanningParams &scanningParams)
+{
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    ble_gap_scan_params_t scanParams = {
+        .active      = scanningParams.getActiveScanning(), /**< If 1, perform active scanning (scan requests). */
+        .selective   = scanningPolicyMode,    /**< If 1, ignore unknown devices (non whitelisted). */
+        .p_whitelist = &whitelist, /**< Pointer to whitelist, NULL if none is given. */
+        .interval    = scanningParams.getInterval(),  /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        .window      = scanningParams.getWindow(),    /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        .timeout     = scanningParams.getTimeout(),   /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+    };
+
+    if (sd_ble_gap_scan_start(&scanParams) != NRF_SUCCESS) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::stopScan(void) {
+    if (sd_ble_gap_scan_stop() == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+
+    return BLE_STACK_BUSY;
+}
+#endif
+
+/**************************************************************************/
+/*!
+    @brief  Stops the BLE HW and disconnects from any devices
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::stopAdvertising(void)
+{
+    /* Stop Advertising */
+    ASSERT(ERROR_NONE == sd_ble_gap_adv_stop(), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    state.advertising = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::connect(const Address_t             peerAddr,
+                              BLEProtocol::AddressType_t  peerAddrType,
+                              const ConnectionParams_t   *connectionParams,
+                              const GapScanningParams    *scanParamsIn)
+{
+    ble_gap_addr_t addr;
+    addr.addr_type = peerAddrType;
+    memcpy(addr.addr, peerAddr, Gap::ADDR_LEN);
+
+    ble_gap_conn_params_t connParams;
+    if (connectionParams != NULL) {
+        connParams.min_conn_interval = connectionParams->minConnectionInterval;
+        connParams.max_conn_interval = connectionParams->maxConnectionInterval;
+        connParams.slave_latency     = connectionParams->slaveLatency;
+        connParams.conn_sup_timeout  = connectionParams->connectionSupervisionTimeout;
+    } else {
+        connParams.min_conn_interval = 50;
+        connParams.max_conn_interval = 100;
+        connParams.slave_latency     = 0;
+        connParams.conn_sup_timeout  = 600;
+    }
+
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    ble_gap_scan_params_t scanParams;
+    scanParams.selective   = scanningPolicyMode;    /**< If 1, ignore unknown devices (non whitelisted). */
+    scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */
+    if (scanParamsIn != NULL) {
+        scanParams.active      = scanParamsIn->getActiveScanning();   /**< If 1, perform active scanning (scan requests). */
+        scanParams.interval    = scanParamsIn->getInterval();         /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.window      = scanParamsIn->getWindow();           /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.timeout     = scanParamsIn->getTimeout();          /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+    } else {
+        scanParams.active      = _scanningParams.getActiveScanning(); /**< If 1, perform active scanning (scan requests). */
+        scanParams.interval    = _scanningParams.getInterval();       /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.window      = _scanningParams.getWindow();         /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.timeout     = _scanningParams.getTimeout();        /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+    }
+
+    uint32_t rc = sd_ble_gap_connect(&addr, &scanParams, &connParams);
+    if (rc == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+    switch (rc) {
+        case NRF_ERROR_INVALID_ADDR:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_PARAM:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_STATE:
+            return BLE_ERROR_INVALID_STATE;
+        case BLE_ERROR_GAP_INVALID_BLE_ADDR:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_NO_MEM:
+            return BLE_ERROR_NO_MEM;
+        case NRF_ERROR_BUSY:
+            return BLE_STACK_BUSY;
+        default:
+        case BLE_ERROR_GAP_WHITELIST_IN_USE:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ble_error_t nRF5xGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason)
+{
+    uint8_t code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
+    switch (reason) {
+        case REMOTE_USER_TERMINATED_CONNECTION:
+            code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
+            break;
+        case CONN_INTERVAL_UNACCEPTABLE:
+            code = BLE_HCI_CONN_INTERVAL_UNACCEPTABLE;
+            break;
+        default:
+            break;
+    }
+
+    /* Disconnect if we are connected to a central device */
+    ASSERT_INT(ERROR_NONE, sd_ble_gap_disconnect(connectionHandle, code), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+/*!
+    @brief  Disconnects if we are connected to a central device
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+ble_error_t nRF5xGap::disconnect(DisconnectionReason_t reason)
+{
+    return disconnect(m_connectionHandle, reason);
+}
+
+ble_error_t nRF5xGap::getPreferredConnectionParams(ConnectionParams_t *params)
+{
+    ASSERT_INT(NRF_SUCCESS,
+        sd_ble_gap_ppcp_get(reinterpret_cast<ble_gap_conn_params_t *>(params)),
+        BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::setPreferredConnectionParams(const ConnectionParams_t *params)
+{
+    ASSERT_INT(NRF_SUCCESS,
+        sd_ble_gap_ppcp_set(reinterpret_cast<const ble_gap_conn_params_t *>(params)),
+        BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::updateConnectionParams(Handle_t handle, const ConnectionParams_t *newParams)
+{
+    uint32_t rc;
+
+    rc = sd_ble_gap_conn_param_update(handle, reinterpret_cast<ble_gap_conn_params_t *>(const_cast<ConnectionParams_t*>(newParams)));
+    if (rc == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+/**************************************************************************/
+/*!
+    @brief  Clear nRF5xGap's state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::reset(void)
+{
+    /* Clear all state that is from the parent, including private members */
+    if (Gap::reset() != BLE_ERROR_NONE) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Clear derived class members */
+    m_connectionHandle = BLE_CONN_HANDLE_INVALID;
+
+    /* Set the whitelist policy filter modes to IGNORE_WHITELIST */
+    advertisingPolicyMode = Gap::ADV_POLICY_IGNORE_WHITELIST;
+    scanningPolicyMode    = Gap::SCAN_POLICY_IGNORE_WHITELIST;
+
+    /* Clear the internal whitelist */
+    whitelistAddressesSize = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Sets the 16-bit connection handle
+*/
+/**************************************************************************/
+void nRF5xGap::setConnectionHandle(uint16_t con_handle)
+{
+    m_connectionHandle = con_handle;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Gets the 16-bit connection handle
+*/
+/**************************************************************************/
+uint16_t nRF5xGap::getConnectionHandle(void)
+{
+    return m_connectionHandle;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Sets the BLE device address
+
+    @returns    ble_error_t
+
+    @section EXAMPLE
+
+    @code
+
+    uint8_t device_address[6] = { 0xca, 0xfe, 0xf0, 0xf0, 0xf0, 0xf0 };
+    nrf.getGap().setAddress(Gap::BLEProtocol::AddressType::RANDOM_STATIC, device_address);
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address)
+{
+    uint8_t cycle_mode;
+    ble_gap_addr_t dev_addr;
+
+    /* When using Public or Static addresses, the cycle mode must be None.
+       When using Random Private addresses, the cycle mode must be Auto.
+       In auto mode, the given address is ignored.
+    */
+    if ((type == BLEProtocol::AddressType::PUBLIC) || (type == BLEProtocol::AddressType::RANDOM_STATIC))
+    {
+        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_NONE;
+        memcpy(dev_addr.addr, address, ADDR_LEN);
+    }
+    else if ((type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) || (type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE))
+    {
+        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_AUTO;
+        // address is ignored when in auto mode
+    }
+    else
+    {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    dev_addr.addr_type = type;
+    ASSERT_INT(ERROR_NONE, sd_ble_gap_address_set(cycle_mode, &dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::getAddress(AddressType_t *typeP, Address_t address)
+{
+    ble_gap_addr_t dev_addr;
+    if (sd_ble_gap_address_get(&dev_addr) != NRF_SUCCESS) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    if (typeP != NULL) {
+        *typeP = static_cast<AddressType_t>(dev_addr.addr_type);
+    }
+    if (address != NULL) {
+        memcpy(address, dev_addr.addr, ADDR_LEN);
+    }
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::setDeviceName(const uint8_t *deviceName)
+{
+    ble_gap_conn_sec_mode_t sec_mode;
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
+
+    if (sd_ble_gap_device_name_set(&sec_mode, deviceName, strlen((const char *)deviceName)) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::getDeviceName(uint8_t *deviceName, unsigned *lengthP)
+{
+    if (sd_ble_gap_device_name_get(deviceName, (uint16_t *)lengthP) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::setAppearance(GapAdvertisingData::Appearance appearance)
+{
+    if (sd_ble_gap_appearance_set(appearance) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::getAppearance(GapAdvertisingData::Appearance *appearanceP)
+{
+    if ((sd_ble_gap_appearance_get(reinterpret_cast<uint16_t *>(appearanceP)) == NRF_SUCCESS)) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+/* (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
+ble_error_t nRF5xGap::setTxPower(int8_t txPower)
+{
+    unsigned rc;
+    if ((rc = sd_ble_gap_tx_power_set(txPower)) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case NRF_ERROR_INVALID_PARAM:
+            default:
+                return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+void nRF5xGap::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP)
+{
+    static const int8_t permittedTxValues[] = {
+        -40, -30, -20, -16, -12, -8, -4, 0, 4
+    };
+
+    *valueArrayPP = permittedTxValues;
+    *countP = sizeof(permittedTxValues) / sizeof(int8_t);
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the capacity of the internal whitelist maintained by this
+            implementation.
+
+    @returns    The capacity of the internal whitelist.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+uint8_t nRF5xGap::getMaxWhitelistSize(void) const
+{
+    return YOTTA_CFG_WHITELIST_MAX_SIZE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get a copy of the implementation's internal whitelist.
+
+    @param[out] whitelistOut
+                A \ref Gap::Whitelist_t structure containing a copy of the
+                addresses in the implemenetation's internal whitelist.
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::getWhitelist(Gap::Whitelist_t &whitelistOut) const
+{
+    uint8_t i;
+    for (i = 0; i < whitelistAddressesSize && i < whitelistOut.capacity; ++i) {
+        memcpy(&whitelistOut.addresses[i], &whitelistAddresses[i], sizeof(BLEProtocol::Address_t));
+    }
+    whitelistOut.size = i;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the whitelist that will be used in the next call to
+            startAdvertising().
+
+    @param[in]  whitelistIn
+                A reference to a \ref Gap::Whitelist_t structure
+                representing a whitelist containing all the white listed
+                BLE addresses.
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_INVALID_PARAM
+                The supplied whitelist contains a private non-resolvable
+                address
+
+                BLE_ERROR_PARAM_OUT_OF_RANGE
+                The size of the supplied whitelist exceeds the maximum
+                capacity of the implementation's internal whitelist.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setWhitelist(const Gap::Whitelist_t &whitelistIn)
+{
+    if (whitelistIn.size > getMaxWhitelistSize()) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Test for invalid parameters before we change the internal state */
+    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
+        if (whitelistIn.addresses[i].type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE) {
+            /* This is not allowed because it is completely meaningless */
+            return BLE_ERROR_INVALID_PARAM;
+        }
+    }
+
+    whitelistAddressesSize = 0;
+    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
+        memcpy(&whitelistAddresses[whitelistAddressesSize], &whitelistIn.addresses[i], sizeof(BLEProtocol::Address_t));
+        whitelistAddressesSize++;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the advertising policy filter mode that will be used in
+            the next call to startAdvertising().
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAdvertisingPolicyMode(Gap::AdvertisingPolicyMode_t mode)
+{
+    advertisingPolicyMode = mode;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the scanning policy filter mode that will be used in
+            the next call to startAdvertising().
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setScanningPolicyMode(Gap::ScanningPolicyMode_t mode)
+{
+    scanningPolicyMode = mode;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the initiator policy filter mode that will be used in
+            the next call to startAdvertising()
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setInitiatorPolicyMode(Gap::InitiatorPolicyMode_t mode)
+{
+    return BLE_ERROR_NOT_IMPLEMENTED;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current advertising policy filter mode.
+
+    @returns    The advertising policy filter mode.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::AdvertisingPolicyMode_t nRF5xGap::getAdvertisingPolicyMode(void) const
+{
+    return advertisingPolicyMode;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current scanning policy filter mode.
+
+    @returns    The scanning policy filter mode.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::ScanningPolicyMode_t nRF5xGap::getScanningPolicyMode(void) const
+{
+    return scanningPolicyMode;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current initiator policy filter mode.
+
+    @returns    The initiator policy filter mode.
+
+    @note   Currently initiator filtering using the whitelist is not
+            implemented in this module.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::InitiatorPolicyMode_t nRF5xGap::getInitiatorPolicyMode(void) const
+{
+    return Gap::INIT_POLICY_IGNORE_WHITELIST;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Helper function used to populate the ble_gap_whitelist_t that
+            will be used by the SoftDevice for filtering requests.
+
+    @returns    \ref ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @retval     BLE_ERROR_INVALID_STATE
+                The internal stack was not initialized correctly.
+
+    @note  Both the SecurityManager and Gap must initialize correctly for
+           this function to succeed.
+
+    @note  This function is needed because for the BLE API the whitelist
+           is just a collection of keys, but for the stack it also includes
+           the IRK table.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::generateStackWhitelist(ble_gap_whitelist_t &whitelist)
+{
+    ble_gap_whitelist_t  whitelistFromBondTable;
+    ble_gap_addr_t      *addressPtr[1];
+    ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+
+    nRF5xSecurityManager& securityManager = (nRF5xSecurityManager&) nRF5xn::Instance(0).getSecurityManager();
+
+    if (securityManager.hasInitialized()) {
+        /* We do not care about the addresses, set the count to 0 */
+        whitelistFromBondTable.addr_count = 0;
+        /* The Nordic SDK will return a failure if we set pp_addr to NULL */
+        whitelistFromBondTable.pp_addrs   = addressPtr;
+        /* We want all the IRKs we can get because we do not know which ones match the addresses */
+        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_irks    = irkPtr;
+
+        /* Use the security manager to get the IRKs from the bond table */
+        ble_error_t error = securityManager.createWhitelistFromBondTable(whitelistFromBondTable);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    } else  {
+        /**
+         * If there is no security manager then we cannot access the bond table,
+         * so disable IRK matching
+         */
+        whitelistFromBondTable.addr_count = 0;
+        whitelistFromBondTable.irk_count  = 0;
+    }
+
+    /**
+     * For every private resolvable address in the local whitelist check if
+     * there is an IRK for said address in the bond table and add it to the
+     * local IRK list.
+     */
+    whitelist.irk_count  = 0;
+    whitelist.addr_count = 0;
+    for (uint8_t i = 0; i < whitelistAddressesSize; ++i) {
+        if (whitelistAddresses[i].addr_type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) {
+            /* Test if there is a matching IRK for this private resolvable address */
+            for (uint8_t j = 0; j < whitelistFromBondTable.irk_count; ++j) {
+                if (securityManager.matchAddressAndIrk(&whitelistAddresses[i], whitelistFromBondTable.pp_irks[j])) {
+                    /* Found the corresponding IRK, add it to our local whitelist */
+                    whitelist.pp_irks[whitelist.irk_count] = whitelistFromBondTable.pp_irks[j];
+                    whitelist.irk_count++;
+                    /* Make sure we do not look at this IRK again */
+                    if (j != whitelistFromBondTable.irk_count - 1) {
+                        /**
+                         * This is not the last IRK, so replace the pointer
+                         * with the last pointer in the array
+                         */
+                        whitelistFromBondTable.pp_irks[j] =
+                            whitelistFromBondTable.pp_irks[whitelistFromBondTable.irk_count - 1];
+                    }
+                    /**
+                     * If the IRK is the last pointer in the array simply
+                     * decrement the total IRK count
+                     */
+                    whitelistFromBondTable.irk_count--;
+                    break;
+                }
+            }
+        } else {
+            /* Include the address into the whitelist */
+            whitelist.pp_addrs[whitelist.addr_count] = &whitelistAddresses[i];
+            whitelist.addr_count++;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,246 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF5x_GAP_H__
+#define __NRF5x_GAP_H__
+
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#ifndef YOTTA_CFG_WHITELIST_MAX_SIZE
+    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+#elif YOTTA_CFG_WHITELIST_MAX_SIZE > BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+    #undef YOTTA_CFG_WHITELIST_MAX_SIZE
+    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+#endif
+#ifndef YOTTA_CFG_IRK_TABLE_MAX_SIZE
+    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
+#elif YOTTA_CFG_IRK_TABLE_MAX_SIZE > BLE_GAP_WHITELIST_IRK_MAX_COUNT
+    #undef YOTTA_CFG_IRK_TABLE_MAX_SIZE
+    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
+#endif
+#include "ble/blecommon.h"
+#include "nrf_ble.h"
+#include "ble/GapAdvertisingParams.h"
+#include "ble/GapAdvertisingData.h"
+#include "ble/Gap.h"
+#include "ble/GapScanningParams.h"
+
+#include "nrf_soc.h"
+
+extern "C" {
+#include "ble_radio_notification.h"
+}
+
+#include "btle_security.h"
+
+void radioNotificationStaticCallback(bool param);
+
+/**************************************************************************/
+/*!
+    \brief
+
+*/
+/**************************************************************************/
+class nRF5xGap : public Gap
+{
+public:
+    /* Functions that must be implemented from Gap */
+    virtual ble_error_t setAddress(AddressType_t  type,  const Address_t address);
+    virtual ble_error_t getAddress(AddressType_t *typeP, Address_t address);
+    virtual ble_error_t setAdvertisingData(const GapAdvertisingData &, const GapAdvertisingData &);
+
+    virtual uint16_t    getMinAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MIN);}
+    virtual uint16_t    getMinNonConnectableAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_NONCON_INTERVAL_MIN);}
+    virtual uint16_t    getMaxAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MAX);}
+
+    virtual ble_error_t startAdvertising(const GapAdvertisingParams &);
+    virtual ble_error_t stopAdvertising(void);
+    virtual ble_error_t connect(const Address_t, BLEProtocol::AddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams);
+    virtual ble_error_t disconnect(Handle_t connectionHandle, DisconnectionReason_t reason);
+    virtual ble_error_t disconnect(DisconnectionReason_t reason);
+
+    virtual ble_error_t setDeviceName(const uint8_t *deviceName);
+    virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP);
+    virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance);
+    virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP);
+
+    virtual ble_error_t setTxPower(int8_t txPower);
+    virtual void        getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP);
+
+    void     setConnectionHandle(uint16_t con_handle);
+    uint16_t getConnectionHandle(void);
+
+    virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params);
+    virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params);
+    virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params);
+
+    virtual ble_error_t reset(void);
+
+    /*
+     * The following functions are part of the whitelisting experimental API.
+     * Therefore, this functionality can change in the near future.
+     */
+    virtual uint8_t getMaxWhitelistSize(void) const;
+    virtual ble_error_t getWhitelist(Gap::Whitelist_t &whitelistOut) const;
+    virtual ble_error_t setWhitelist(const Gap::Whitelist_t &whitelistIn);
+
+    virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode);
+    virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode);
+    virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode);
+    virtual Gap::AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const;
+    virtual Gap::ScanningPolicyMode_t getScanningPolicyMode(void) const;
+    virtual Gap::InitiatorPolicyMode_t getInitiatorPolicyMode(void) const;
+
+    virtual ble_error_t initRadioNotification(void) {
+        if (ble_radio_notification_init(NRF_APP_PRIORITY_HIGH, NRF_RADIO_NOTIFICATION_DISTANCE_800US, radioNotificationStaticCallback) == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams);
+    virtual ble_error_t stopScan(void);
+#endif
+
+private:
+    /*
+     * Whitelisting API related structures and helper functions.
+     */
+
+    /* Policy modes set by the user. By default these are set to ignore the whitelist */
+    Gap::AdvertisingPolicyMode_t advertisingPolicyMode;
+    Gap::ScanningPolicyMode_t    scanningPolicyMode;
+
+    /* Internal representation of a whitelist */
+    uint8_t         whitelistAddressesSize;
+    ble_gap_addr_t  whitelistAddresses[YOTTA_CFG_WHITELIST_MAX_SIZE];
+
+    /*
+     * An internal function used to populate the ble_gap_whitelist_t that will be used by
+     * the SoftDevice for filtering requests. This function is needed because for the BLE
+     * API the whitelist is just a collection of keys, but for the stack it also includes
+     * the IRK table.
+     */
+    ble_error_t generateStackWhitelist(ble_gap_whitelist_t &whitelist);
+
+private:
+    bool    radioNotificationCallbackParam; /* parameter to be passed into the Timeout-generated radio notification callback. */
+    Timeout radioNotificationTimeout;
+
+    /*
+     * A helper function to post radio notification callbacks with low interrupt priority.
+     */
+    void postRadioNotificationCallback(void) {
+#ifdef YOTTA_CFG_MBED_OS
+        /*
+         * In mbed OS, all user-facing BLE events (interrupts) are posted to the
+         * MINAR scheduler to be executed as callbacks in thread mode. MINAR guards
+         * its critical sections from interrupts by acquiring CriticalSectionLock,
+         * which results in a call to sd_nvic_critical_region_enter(). Thus, it is
+         * safe to invoke MINAR APIs from interrupt context as long as those
+         * interrupts are blocked by sd_nvic_critical_region_enter().
+         *
+         * Radio notifications are a special case for the above. The Radio
+         * Notification IRQ is handled at a very high priority--higher than the
+         * level blocked by sd_nvic_critical_region_enter(). Thus Radio Notification
+         * events can preempt MINAR's critical sections. Using MINAR APIs (such as
+         * posting an event) directly in processRadioNotification() may result in a
+         * race condition ending in a hard-fault.
+         *
+         * The solution is to *not* call MINAR APIs directly from the Radio
+         * Notification handling; i.e. to do the bulk of RadioNotification
+         * processing at a reduced priority which respects MINAR's critical
+         * sections. Unfortunately, on a cortex-M0, there is no clean way to demote
+         * priority for the currently executing interrupt--we wouldn't want to
+         * demote the radio notification handling anyway because it is sensitive to
+         * timing, and the system expects to finish this handling very quickly. The
+         * workaround is to employ a Timeout to trigger
+         * postRadioNotificationCallback() after a very short delay (~0 us) and post
+         * the MINAR callback that context.
+         *
+         * !!!WARNING!!! Radio notifications are very time critical events. The
+         * current solution is expected to work under the assumption that
+         * postRadioNotificationCalback() will be executed BEFORE the next radio
+         * notification event is generated.
+         */
+        minar::Scheduler::postCallback(
+            mbed::util::FunctionPointer1<void, bool>(&radioNotificationCallback, &FunctionPointerWithContext<bool>::call).bind(radioNotificationCallbackParam)
+        );
+#else
+        /*
+         * In mbed classic, all user-facing BLE events execute callbacks in interrupt
+         * mode. Radio Notifications are a special case because its IRQ is handled at
+         * a very high priority. Thus Radio Notification events can preempt other
+         * operations that require interaction with the SoftDevice such as advertising
+         * payload updates and changing the Gap state. Therefore, executing a Radio
+         * Notification callback directly from processRadioNotification() may result
+         * in a race condition ending in a hard-fault.
+         *
+         * The solution is to *not* execute the Radio Notification callback directly
+         * from the Radio Notification handling; i.e. to do the bulk of the
+         * Radio Notification processing at a reduced priority. Unfortunately, on a
+         * cortex-M0, there is no clean way to demote priority for the currently
+         * executing interrupt--we wouldn't want to demote the radio notification
+         * handling anyway because it is sensitive to timing, and the system expects
+         * to finish this handling very quickly. The workaround is to employ a Timeout
+         * to trigger postRadioNotificationCallback() after a very short delay (~0 us)
+         * and execute the callback in that context.
+         *
+         * !!!WARNING!!! Radio notifications are very time critical events. The
+         * current solution is expected to work under the assumption that
+         * postRadioNotificationCalback() will be executed BEFORE the next radio
+         * notification event is generated.
+         */
+        radioNotificationCallback.call(radioNotificationCallbackParam);
+#endif /* #ifdef YOTTA_CFG_MBED_OS */
+    }
+
+    /**
+     * A helper function to process radio-notification events; to be called internally.
+     * @param param [description]
+     */
+    void processRadioNotificationEvent(bool param) {
+        radioNotificationCallbackParam = param;
+        radioNotificationTimeout.attach_us(this, &nRF5xGap::postRadioNotificationCallback, 0);
+    }
+    friend void radioNotificationStaticCallback(bool param); /* allow invocations of processRadioNotificationEvent() */
+
+private:
+    uint16_t m_connectionHandle;
+
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGap() :
+        advertisingPolicyMode(Gap::ADV_POLICY_IGNORE_WHITELIST),
+        scanningPolicyMode(Gap::SCAN_POLICY_IGNORE_WHITELIST),
+        whitelistAddressesSize(0) {
+        m_connectionHandle = BLE_CONN_HANDLE_INVALID;
+    }
+
+    nRF5xGap(nRF5xGap const &);
+    void operator=(nRF5xGap const &);
+};
+
+#endif // ifndef __NRF5x_GAP_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGattClient.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGattClient.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,50 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xGattClient.h"
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+ble_error_t
+nRF5xGattClient::launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
+                                        ServiceDiscovery::ServiceCallback_t         sc,
+                                        ServiceDiscovery::CharacteristicCallback_t  cc,
+                                        const UUID                                 &matchingServiceUUIDIn,
+                                        const UUID                                 &matchingCharacteristicUUIDIn)
+{
+    return _discovery.launch(connectionHandle, sc, cc, matchingServiceUUIDIn, matchingCharacteristicUUIDIn);
+}
+
+ble_error_t nRF5xGattClient::discoverCharacteristicDescriptors(
+    const DiscoveredCharacteristic& characteristic,
+    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback)
+{
+    return _characteristicDescriptorDiscoverer.launch(
+        characteristic, 
+        discoveryCallback, 
+        terminationCallback
+    );
+}
+
+bool nRF5xGattClient::isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const {
+    return _characteristicDescriptorDiscoverer.isActive(characteristic);   
+}
+
+void nRF5xGattClient::terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic) { 
+    return _characteristicDescriptorDiscoverer.requestTerminate(characteristic);
+}
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGattClient.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGattClient.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,218 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_GATT_CLIENT_H__
+#define __NRF51822_GATT_CLIENT_H__
+
+#include "ble/GattClient.h"
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+
+class nRF5xGattClient : public GattClient
+{
+public:
+    /**
+     * When using S110, all Gatt client features will return
+     * BLE_ERROR_NOT_IMPLEMENTED
+     */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+
+    /**
+     * Launch service discovery. Once launched, service discovery will remain
+     * active with callbacks being issued back into the application for matching
+     * services/characteristics. isActive() can be used to determine status; and
+     * a termination callback (if setup) will be invoked at the end. Service
+     * discovery can be terminated prematurely if needed using terminate().
+     *
+     * @param  connectionHandle
+     *           Handle for the connection with the peer.
+     * @param  sc
+     *           This is the application callback for matching service. Taken as
+     *           NULL by default. Note: service discovery may still be active
+     *           when this callback is issued; calling asynchronous BLE-stack
+     *           APIs from within this application callback might cause the
+     *           stack to abort service discovery. If this becomes an issue, it
+     *           may be better to make local copy of the discoveredService and
+     *           wait for service discovery to terminate before operating on the
+     *           service.
+     * @param  cc
+     *           This is the application callback for matching characteristic.
+     *           Taken as NULL by default. Note: service discovery may still be
+     *           active when this callback is issued; calling asynchronous
+     *           BLE-stack APIs from within this application callback might cause
+     *           the stack to abort service discovery. If this becomes an issue,
+     *           it may be better to make local copy of the discoveredCharacteristic
+     *           and wait for service discovery to terminate before operating on the
+     *           characteristic.
+     * @param  matchingServiceUUID
+     *           UUID based filter for specifying a service in which the application is
+     *           interested. By default it is set as the wildcard UUID_UNKNOWN,
+     *           in which case it matches all services. If characteristic-UUID
+     *           filter (below) is set to the wildcard value, then a service
+     *           callback will be invoked for the matching service (or for every
+     *           service if the service filter is a wildcard).
+     * @param  matchingCharacteristicUUIDIn
+     *           UUID based filter for specifying characteristic in which the application
+     *           is interested. By default it is set as the wildcard UUID_UKNOWN
+     *           to match against any characteristic. If both service-UUID
+     *           filter and characteristic-UUID filter are used with non- wildcard
+     *           values, then only a single characteristic callback is
+     *           invoked for the matching characteristic.
+     *
+     * @Note     Using wildcard values for both service-UUID and characteristic-
+     *           UUID will result in complete service discovery--callbacks being
+     *           called for every service and characteristic.
+     *
+     * @return
+     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
+     */
+    virtual ble_error_t launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
+                                               ServiceDiscovery::ServiceCallback_t         sc = NULL,
+                                               ServiceDiscovery::CharacteristicCallback_t  cc = NULL,
+                                               const UUID                                 &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN),
+                                               const UUID                                 &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN));
+
+    virtual void onServiceDiscoveryTermination(ServiceDiscovery::TerminationCallback_t callback) {
+        _discovery.onTermination(callback);
+    }
+
+    /**
+     * Is service-discovery currently active?
+     */
+    virtual bool isServiceDiscoveryActive(void) const {
+        return _discovery.isActive();
+    }
+
+    /**
+     * Terminate an ongoing service-discovery. This should result in an
+     * invocation of the TerminationCallback if service-discovery is active.
+     */
+    virtual void terminateServiceDiscovery(void) {
+        _discovery.terminate();
+    }
+
+    /**
+     * @brief Implementation of GattClient::discoverCharacteristicDescriptors
+     * @see GattClient::discoverCharacteristicDescriptors
+     */
+    virtual ble_error_t discoverCharacteristicDescriptors(
+        const DiscoveredCharacteristic& characteristic,
+        const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+        const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
+    );
+
+    /**
+     * @brief Implementation of GattClient::isCharacteristicDiscoveryActive
+     * @see GattClient::isCharacteristicDiscoveryActive
+     */
+    virtual bool isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const;
+
+    /**
+     * @brief Implementation of GattClient::terminateCharacteristicDiscovery
+     * @see GattClient::terminateCharacteristicDiscovery
+     */
+    virtual void terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic);
+
+    virtual ble_error_t read(Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset) const {
+        uint32_t rc = sd_ble_gattc_read(connHandle, attributeHandle, offset);
+        if (rc == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case NRF_ERROR_INVALID_STATE:
+            case NRF_ERROR_INVALID_ADDR:
+            default:
+                return BLE_ERROR_INVALID_STATE;
+        }
+    }
+
+    virtual ble_error_t write(GattClient::WriteOp_t cmd, Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value) const {
+        ble_gattc_write_params_t writeParams;
+        writeParams.write_op = cmd;
+        writeParams.flags    = 0; /* this is inconsequential */
+        writeParams.handle   = attributeHandle;
+        writeParams.offset   = 0;
+        writeParams.len      = length;
+        writeParams.p_value  = const_cast<uint8_t *>(value);
+
+        uint32_t rc = sd_ble_gattc_write(connHandle, &writeParams);
+        if (rc == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case BLE_ERROR_NO_TX_BUFFERS:
+                return BLE_ERROR_NO_MEM;
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case NRF_ERROR_INVALID_STATE:
+            case NRF_ERROR_INVALID_ADDR:
+            default:
+                return BLE_ERROR_INVALID_STATE;
+        }
+    }
+
+    /**
+     * @brief  Clear nRF5xGattClient's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void) {
+        /* Clear all state that is from the parent, including private members */
+        if (GattClient::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        /* Clear derived class members */
+        _discovery.reset();
+
+        return BLE_ERROR_NONE;
+    }
+
+public:
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGattClient() : _discovery(this) {
+        /* empty */
+    }
+
+    nRF5xServiceDiscovery& discovery() {
+        return _discovery;
+    }
+
+    nRF5xCharacteristicDescriptorDiscoverer& characteristicDescriptorDiscoverer() {
+        return _characteristicDescriptorDiscoverer;
+    }
+
+private:
+    nRF5xGattClient(const nRF5xGattClient &);
+    const nRF5xGattClient& operator=(const nRF5xGattClient &);
+
+private:
+    nRF5xServiceDiscovery _discovery;
+    nRF5xCharacteristicDescriptorDiscoverer _characteristicDescriptorDiscoverer;
+
+#endif // if !S110
+};
+
+#endif // ifndef __NRF51822_GATT_CLIENT_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGattServer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGattServer.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,532 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xGattServer.h"
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+
+#include "common/common.h"
+#include "btle/custom/custom_helper.h"
+
+#include "nRF5xn.h"
+
+/**************************************************************************/
+/*!
+    @brief  Adds a new service to the GATT table on the peripheral
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::addService(GattService &service)
+{
+    /* ToDo: Make sure this service UUID doesn't already exist (?) */
+    /* ToDo: Basic validation */
+
+    /* Add the service to the nRF51 */
+    ble_uuid_t nordicUUID;
+    nordicUUID = custom_convert_to_nordic_uuid(service.getUUID());
+
+    uint16_t serviceHandle;
+    ASSERT( ERROR_NONE ==
+            sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
+                                     &nordicUUID,
+                                     &serviceHandle),
+            BLE_ERROR_PARAM_OUT_OF_RANGE );
+    service.setHandle(serviceHandle);
+
+    /* Add characteristics to the service */
+    for (uint8_t i = 0; i < service.getCharacteristicCount(); i++) {
+        if (characteristicCount >= BLE_TOTAL_CHARACTERISTICS) {
+            return BLE_ERROR_NO_MEM;
+        }
+        GattCharacteristic *p_char = service.getCharacteristic(i);
+
+        /* Skip any incompletely defined, read-only characteristics. */
+        if ((p_char->getValueAttribute().getValuePtr() == NULL) &&
+            (p_char->getValueAttribute().getLength() == 0) &&
+            (p_char->getProperties() == GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ)) {
+            continue;
+        }
+
+        nordicUUID = custom_convert_to_nordic_uuid(p_char->getValueAttribute().getUUID());
+
+        /* The user-description descriptor is a special case which needs to be
+         * handled at the time of adding the characteristic. The following block
+         * is meant to discover its presence. */
+        const uint8_t *userDescriptionDescriptorValuePtr = NULL;
+        uint16_t userDescriptionDescriptorValueLen = 0;
+        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
+            GattAttribute *p_desc = p_char->getDescriptor(j);
+            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
+                userDescriptionDescriptorValuePtr = p_desc->getValuePtr();
+                userDescriptionDescriptorValueLen = p_desc->getLength();
+            }
+        }
+
+        ASSERT ( ERROR_NONE ==
+                 custom_add_in_characteristic(BLE_GATT_HANDLE_INVALID,
+                                              &nordicUUID,
+                                              p_char->getProperties(),
+                                              p_char->getRequiredSecurity(),
+                                              p_char->getValueAttribute().getValuePtr(),
+                                              p_char->getValueAttribute().getLength(),
+                                              p_char->getValueAttribute().getMaxLength(),
+                                              p_char->getValueAttribute().hasVariableLength(),
+                                              userDescriptionDescriptorValuePtr,
+                                              userDescriptionDescriptorValueLen,
+                                              p_char->isReadAuthorizationEnabled(),
+                                              p_char->isWriteAuthorizationEnabled(),
+                                              &nrfCharacteristicHandles[characteristicCount]),
+                 BLE_ERROR_PARAM_OUT_OF_RANGE );
+
+        /* Update the characteristic handle */
+        p_characteristics[characteristicCount] = p_char;
+        p_char->getValueAttribute().setHandle(nrfCharacteristicHandles[characteristicCount].value_handle);
+        characteristicCount++;
+
+        /* Add optional descriptors if any */
+        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
+            if (descriptorCount >= BLE_TOTAL_DESCRIPTORS) {
+                return BLE_ERROR_NO_MEM;
+            }
+
+            GattAttribute *p_desc = p_char->getDescriptor(j);
+            /* skip the user-description-descriptor here; this has already been handled when adding the characteristic (above). */
+            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
+                continue;
+            }
+
+            nordicUUID = custom_convert_to_nordic_uuid(p_desc->getUUID());
+
+            ASSERT(ERROR_NONE ==
+                   custom_add_in_descriptor(BLE_GATT_HANDLE_INVALID,
+                                            &nordicUUID,
+                                            p_desc->getValuePtr(),
+                                            p_desc->getLength(),
+                                            p_desc->getMaxLength(),
+                                            p_desc->hasVariableLength(),
+                                            &nrfDescriptorHandles[descriptorCount]),
+                BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+            p_descriptors[descriptorCount] = p_desc;
+            p_desc->setHandle(nrfDescriptorHandles[descriptorCount]);
+            descriptorCount++;
+        }
+    }
+
+    serviceCount++;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Reads the value of a characteristic, based on the service
+            and characteristic index fields
+
+    @param[in]  attributeHandle
+                The handle of the GattCharacteristic to read from
+    @param[in]  buffer
+                Buffer to hold the the characteristic's value
+                (raw byte array in LSB format)
+    @param[in/out] len
+                input:  Length in bytes to be read.
+                output: Total length of attribute value upon successful return.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
+{
+    return read(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, lengthP);
+}
+
+ble_error_t nRF5xGattServer::read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
+{
+    ble_gatts_value_t value = {
+        .len     = *lengthP,
+        .offset  = 0,
+        .p_value = buffer,
+    };
+
+    ASSERT( ERROR_NONE ==
+            sd_ble_gatts_value_get(connectionHandle, attributeHandle, &value),
+            BLE_ERROR_PARAM_OUT_OF_RANGE);
+    *lengthP = value.len;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Updates the value of a characteristic, based on the service
+            and characteristic index fields
+
+    @param[in]  charHandle
+                The handle of the GattCharacteristic to write to
+    @param[in]  buffer
+                Data to use when updating the characteristic's value
+                (raw byte array in LSB format)
+    @param[in]  len
+                The number of bytes in buffer
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::write(GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
+{
+    return write(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, len, localOnly);
+}
+
+ble_error_t nRF5xGattServer::write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
+{
+    ble_error_t returnValue = BLE_ERROR_NONE;
+
+    ble_gatts_value_t value = {
+        .len     = len,
+        .offset  = 0,
+        .p_value = const_cast<uint8_t *>(buffer),
+    };
+
+    if (localOnly) {
+        /* Only update locally regardless of notify/indicate */
+        ASSERT_INT( ERROR_NONE,
+                    sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
+                    BLE_ERROR_PARAM_OUT_OF_RANGE );
+        return BLE_ERROR_NONE;
+    }
+
+    int characteristicIndex = resolveValueHandleToCharIndex(attributeHandle);
+    if ((characteristicIndex != -1) &&
+        (p_characteristics[characteristicIndex]->getProperties() & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
+        /* HVX update for the characteristic value */
+        ble_gatts_hvx_params_t hvx_params;
+
+        hvx_params.handle = attributeHandle;
+        hvx_params.type   =
+            (p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) ? BLE_GATT_HVX_NOTIFICATION : BLE_GATT_HVX_INDICATION;
+        hvx_params.offset = 0;
+        hvx_params.p_data = const_cast<uint8_t *>(buffer);
+        hvx_params.p_len  = &len;
+
+        if (connectionHandle == BLE_CONN_HANDLE_INVALID) { /* use the default connection handle if the caller hasn't specified a valid connectionHandle. */
+            nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+            connectionHandle = gap.getConnectionHandle();
+        }
+        error_t error = (error_t) sd_ble_gatts_hvx(connectionHandle, &hvx_params);
+        if (error != ERROR_NONE) {
+            switch (error) {
+                case ERROR_BLE_NO_TX_BUFFERS: /*  Notifications consume application buffers. The return value can be used for resending notifications. */
+                case ERROR_BUSY:
+                    returnValue = BLE_STACK_BUSY;
+                    break;
+
+                case ERROR_INVALID_STATE:
+                case ERROR_BLEGATTS_SYS_ATTR_MISSING:
+                    returnValue = BLE_ERROR_INVALID_STATE;
+                    break;
+
+                default :
+                    ASSERT_INT( ERROR_NONE,
+                                sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
+                                BLE_ERROR_PARAM_OUT_OF_RANGE );
+
+                    /* Notifications consume application buffers. The return value can
+                     * be used for resending notifications. */
+                    returnValue = BLE_STACK_BUSY;
+                    break;
+            }
+        }
+    } else {
+        uint32_t err = sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value);
+        switch(err) {
+            case NRF_SUCCESS:
+                returnValue = BLE_ERROR_NONE;
+                break;
+            case NRF_ERROR_INVALID_ADDR:
+            case NRF_ERROR_INVALID_PARAM:
+                returnValue = BLE_ERROR_INVALID_PARAM;
+                break;
+            case NRF_ERROR_NOT_FOUND:
+            case NRF_ERROR_DATA_SIZE:
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case BLE_ERROR_GATTS_INVALID_ATTR_TYPE:
+                returnValue = BLE_ERROR_PARAM_OUT_OF_RANGE;
+                break;
+            case NRF_ERROR_FORBIDDEN:
+                returnValue = BLE_ERROR_OPERATION_NOT_PERMITTED;
+                break;
+            default:
+                returnValue = BLE_ERROR_UNSPECIFIED;
+                break;
+        }
+    }
+
+    return returnValue;
+}
+
+ble_error_t nRF5xGattServer::areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP)
+{
+    /* Forward the call with the default connection handle. */
+    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+    return areUpdatesEnabled(gap.getConnectionHandle(), characteristic, enabledP);
+}
+
+ble_error_t nRF5xGattServer::areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP)
+{
+    int characteristicIndex = resolveValueHandleToCharIndex(characteristic.getValueHandle());
+    if (characteristicIndex == -1) {
+        return BLE_ERROR_INVALID_PARAM;
+    }
+
+    /* Read the cccd value from the GATT server. */
+    GattAttribute::Handle_t cccdHandle = nrfCharacteristicHandles[characteristicIndex].cccd_handle;
+    uint16_t cccdValue;
+    uint16_t length = sizeof(cccdValue);
+    ble_error_t rc = read(connectionHandle, cccdHandle, reinterpret_cast<uint8_t *>(&cccdValue), &length);
+    if (rc != BLE_ERROR_NONE) {
+        return rc;
+    }
+    if (length != sizeof(cccdValue)) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Check for NOTFICATION or INDICATION in CCCD. */
+    if ((cccdValue & BLE_GATT_HVX_NOTIFICATION) || (cccdValue & BLE_GATT_HVX_INDICATION)) {
+        *enabledP = true;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Clear nRF5xGattServer's state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::reset(void)
+{
+    /* Clear all state that is from the parent, including private members */
+    if (GattServer::reset() != BLE_ERROR_NONE) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Clear derived class members */
+    memset(p_characteristics,        0, sizeof(p_characteristics));
+    memset(p_descriptors,            0, sizeof(p_descriptors));
+    memset(nrfCharacteristicHandles, 0, sizeof(ble_gatts_char_handles_t));
+    memset(nrfDescriptorHandles,     0, sizeof(nrfDescriptorHandles));
+    descriptorCount = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Callback handler for events getting pushed up from the SD
+*/
+/**************************************************************************/
+void nRF5xGattServer::hwCallback(ble_evt_t *p_ble_evt)
+{
+    GattAttribute::Handle_t        handle_value;
+    GattServerEvents::gattEvent_t  eventType;
+    const ble_gatts_evt_t         *gattsEventP = &p_ble_evt->evt.gatts_evt;
+
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GATTS_EVT_WRITE: {
+                /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */
+
+                /* 1.) Handle CCCD changes */
+                handle_value = gattsEventP->params.write.handle;
+                int characteristicIndex = resolveCCCDHandleToCharIndex(handle_value);
+                if ((characteristicIndex != -1) &&
+                    (p_characteristics[characteristicIndex]->getProperties() &
+                        (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
+
+                    uint16_t cccd_value = (gattsEventP->params.write.data[1] << 8) | gattsEventP->params.write.data[0]; /* Little Endian but M0 may be mis-aligned */
+
+                    if (((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION)) ||
+                        ((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) {
+                        eventType = GattServerEvents::GATT_EVENT_UPDATES_ENABLED;
+                    } else {
+                        eventType = GattServerEvents::GATT_EVENT_UPDATES_DISABLED;
+                    }
+
+                    handleEvent(eventType, p_characteristics[characteristicIndex]->getValueHandle());
+                    return;
+                }
+
+                /* 2.) Changes to the characteristic value will be handled with other events below */
+                eventType = GattServerEvents::GATT_EVENT_DATA_WRITTEN;
+            }
+            break;
+
+        case BLE_GATTS_EVT_HVC:
+            /* Indication confirmation received */
+            eventType    = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED;
+            handle_value = gattsEventP->params.hvc.handle;
+            break;
+
+        case BLE_EVT_TX_COMPLETE: {
+            handleDataSentEvent(p_ble_evt->evt.common_evt.params.tx_complete.count);
+            return;
+        }
+
+        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
+            sd_ble_gatts_sys_attr_set(gattsEventP->conn_handle, NULL, 0, 0);
+            return;
+
+        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
+            switch (gattsEventP->params.authorize_request.type) {
+                case BLE_GATTS_AUTHORIZE_TYPE_READ:
+                    eventType    = GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ;
+                    handle_value = gattsEventP->params.authorize_request.request.read.handle;
+                    break;
+                case BLE_GATTS_AUTHORIZE_TYPE_WRITE:
+                    eventType    = GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ;
+                    handle_value = gattsEventP->params.authorize_request.request.write.handle;
+                    break;
+                default:
+                    return;
+            }
+            break;
+
+        default:
+            return;
+    }
+
+    int characteristicIndex = resolveValueHandleToCharIndex(handle_value);
+    if (characteristicIndex == -1) {
+        return;
+    }
+
+    /* Find index (charHandle) in the pool */
+    switch (eventType) {
+        case GattServerEvents::GATT_EVENT_DATA_WRITTEN: {
+            GattWriteCallbackParams cbParams = {
+                .connHandle = gattsEventP->conn_handle,
+                .handle     = handle_value,
+                .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.write.op),
+                .offset     = gattsEventP->params.write.offset,
+                .len        = gattsEventP->params.write.len,
+                .data       = gattsEventP->params.write.data
+            };
+            handleDataWrittenEvent(&cbParams);
+            break;
+        }
+        case GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ: {
+            GattWriteAuthCallbackParams cbParams = {
+                .connHandle = gattsEventP->conn_handle,
+                .handle     = handle_value,
+                .offset     = gattsEventP->params.authorize_request.request.write.offset,
+                .len        = gattsEventP->params.authorize_request.request.write.len,
+                .data       = gattsEventP->params.authorize_request.request.write.data,
+                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
+                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
+                                                                   * request is to proceed. */
+            };
+            ble_gatts_rw_authorize_reply_params_t reply = {
+                .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE,
+                .params = {
+                    .write = {
+                        .gatt_status = p_characteristics[characteristicIndex]->authorizeWrite(&cbParams)
+                    }
+                }
+            };
+            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
+
+            /*
+             * If write-authorization is enabled for a characteristic,
+             * AUTHORIZATION_REQ event (if replied with true) is *not*
+             * followed by another DATA_WRITTEN event; so we still need
+             * to invoke handleDataWritten(), much the same as we would
+             * have done if write-authorization had not been enabled.
+             */
+            if (reply.params.write.gatt_status == BLE_GATT_STATUS_SUCCESS) {
+                GattWriteCallbackParams cbParams = {
+                    .connHandle = gattsEventP->conn_handle,
+                    .handle     = handle_value,
+                    .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.authorize_request.request.write.op),
+                    .offset     = gattsEventP->params.authorize_request.request.write.offset,
+                    .len        = gattsEventP->params.authorize_request.request.write.len,
+                    .data       = gattsEventP->params.authorize_request.request.write.data,
+                };
+                handleDataWrittenEvent(&cbParams);
+            }
+            break;
+        }
+        case GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ: {
+            GattReadAuthCallbackParams cbParams = {
+                .connHandle         = gattsEventP->conn_handle,
+                .handle             = handle_value,
+                .offset             = gattsEventP->params.authorize_request.request.read.offset,
+                .len                = 0,
+                .data               = NULL,
+                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
+                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
+                                                                   * request is to proceed. */
+            };
+
+            ble_gatts_rw_authorize_reply_params_t reply = {
+                .type = BLE_GATTS_AUTHORIZE_TYPE_READ,
+                .params = {
+                    .read = {
+                        .gatt_status = p_characteristics[characteristicIndex]->authorizeRead(&cbParams)
+                    }
+                }
+            };
+
+            if (cbParams.authorizationReply == BLE_GATT_STATUS_SUCCESS) {
+                if (cbParams.data != NULL) {
+                    reply.params.read.update = 1;
+                    reply.params.read.offset = cbParams.offset;
+                    reply.params.read.len    = cbParams.len;
+                    reply.params.read.p_data = cbParams.data;
+                }
+            }
+
+            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
+            break;
+        }
+
+        default:
+            handleEvent(eventType, handle_value);
+            break;
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xGattServer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xGattServer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,103 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_GATT_SERVER_H__
+#define __NRF51822_GATT_SERVER_H__
+
+#include <stddef.h>
+
+#include "ble/blecommon.h"
+#include "nrf_ble.h" /* nordic ble */
+#include "ble/Gap.h"
+#include "ble/GattServer.h"
+
+class nRF5xGattServer : public GattServer
+{
+public:
+    /* Functions that must be implemented from GattServer */
+    virtual ble_error_t addService(GattService &);
+    virtual ble_error_t read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
+    virtual ble_error_t read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
+    virtual ble_error_t write(GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
+    virtual ble_error_t write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
+    virtual ble_error_t areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP);
+    virtual ble_error_t areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP);
+    virtual ble_error_t reset(void);
+
+    /* nRF51 Functions */
+    void eventCallback(void);
+    void hwCallback(ble_evt_t *p_ble_evt);
+
+
+private:
+    const static unsigned BLE_TOTAL_CHARACTERISTICS = 20;
+    const static unsigned BLE_TOTAL_DESCRIPTORS     = 8;
+
+private:
+    /**
+     * resolve a value attribute to its owning characteristic.
+     * @param  valueHandle the value handle to be resolved.
+     * @return             characteristic index if a resolution is found, else -1.
+     */
+    int resolveValueHandleToCharIndex(GattAttribute::Handle_t valueHandle) const {
+        unsigned charIndex;
+        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
+            if (nrfCharacteristicHandles[charIndex].value_handle == valueHandle) {
+                return charIndex;
+            }
+        }
+
+        return -1;
+    }
+
+    /**
+     * resolve a CCCD attribute handle to its owning characteristic.
+     * @param  cccdHandle the CCCD handle to be resolved.
+     * @return             characteristic index if a resolution is found, else -1.
+     */
+    int resolveCCCDHandleToCharIndex(GattAttribute::Handle_t cccdHandle) const {
+        unsigned charIndex;
+        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
+            if (nrfCharacteristicHandles[charIndex].cccd_handle == cccdHandle) {
+                return charIndex;
+            }
+        }
+
+        return -1;
+    }
+
+private:
+    GattCharacteristic       *p_characteristics[BLE_TOTAL_CHARACTERISTICS];
+    ble_gatts_char_handles_t  nrfCharacteristicHandles[BLE_TOTAL_CHARACTERISTICS];
+    GattAttribute            *p_descriptors[BLE_TOTAL_DESCRIPTORS];
+    uint8_t                   descriptorCount;
+    uint16_t                  nrfDescriptorHandles[BLE_TOTAL_DESCRIPTORS];
+
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGattServer() : GattServer(), p_characteristics(), nrfCharacteristicHandles(), p_descriptors(), descriptorCount(0), nrfDescriptorHandles() {
+        /* empty */
+    }
+
+private:
+    nRF5xGattServer(const nRF5xGattServer &);
+    const nRF5xGattServer& operator=(const nRF5xGattServer &);
+};
+
+#endif // ifndef __NRF51822_GATT_SERVER_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xSecurityManager.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xSecurityManager.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,174 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_SECURITY_MANAGER_H__
+#define __NRF51822_SECURITY_MANAGER_H__
+
+#include <stddef.h>
+
+#include "nRF5xGap.h"
+#include "ble/SecurityManager.h"
+#include "btle_security.h"
+
+class nRF5xSecurityManager : public SecurityManager
+{
+public:
+    /* Functions that must be implemented from SecurityManager */
+    virtual ble_error_t init(bool                     enableBonding,
+                             bool                     requireMITM,
+                             SecurityIOCapabilities_t iocaps,
+                             const Passkey_t          passkey) {
+        return btle_initializeSecurity(enableBonding, requireMITM, iocaps, passkey);
+    }
+
+    virtual ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, LinkSecurityStatus_t *securityStatusP) {
+        return btle_getLinkSecurity(connectionHandle, securityStatusP);
+    }
+
+    virtual ble_error_t setLinkSecurity(Gap::Handle_t connectionHandle, SecurityMode_t securityMode) {
+        return btle_setLinkSecurity(connectionHandle, securityMode);
+    }
+
+    virtual ble_error_t purgeAllBondingState(void) {
+        return btle_purgeAllBondingState();
+    }
+
+    /**
+     * @brief  Returns a list of addresses from peers in the stacks bond table.
+     *
+     * @param[in/out]   addresses
+     *                  (on input) @ref Gap::Whitelist_t structure where at
+     *                  most addresses.capacity addresses from bonded peers will
+     *                  be stored.
+     *                  (on output) A copy of the addresses from bonded peers.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const {
+        uint8_t i;
+
+        ble_gap_whitelist_t  whitelistFromBondTable;
+        ble_gap_addr_t      *addressPtr[YOTTA_CFG_WHITELIST_MAX_SIZE];
+        ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+
+        /* Initialize the structure so that we get as many addreses as the whitelist can hold */
+        whitelistFromBondTable.addr_count = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_addrs   = addressPtr;
+        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_irks    = irkPtr;
+
+        ble_error_t error = createWhitelistFromBondTable(whitelistFromBondTable);
+        if (error != BLE_ERROR_NONE) {
+            addresses.size = 0;
+            return error;
+        }
+
+        /* Put all the addresses in the structure */
+        for (i = 0; i < whitelistFromBondTable.addr_count; ++i) {
+            if (i >= addresses.capacity) {
+                /* Ran out of space in the output Gap::Whitelist_t */
+                addresses.size = i;
+                return BLE_ERROR_NONE;
+            }
+            memcpy(&addresses.addresses[i], whitelistFromBondTable.pp_addrs[i], sizeof(BLEProtocol::Address_t));
+        }
+
+        /* Update the current address count */
+        addresses.size = i;
+
+        /* The assumption here is that the underlying implementation of
+         * createWhitelistFromBondTable()  will not return the private resolvable
+         * addresses (which is the case in the SoftDevice). Rather it returns the
+         * IRKs, so we need to generate the private resolvable address by ourselves.
+         */
+        for (i = 0; i < whitelistFromBondTable.irk_count; ++i) {
+            if (i + addresses.size >= addresses.capacity) {
+                /* Ran out of space in the output Gap::Whitelist_t */
+                addresses.size += i;
+                return BLE_ERROR_NONE;
+            }
+            btle_generateResolvableAddress(
+                *whitelistFromBondTable.pp_irks[i],
+                (ble_gap_addr_t &) addresses.addresses[i + addresses.size]
+            );
+        }
+
+        /* Update the current address count */
+        addresses.size += i;
+
+        return BLE_ERROR_NONE;
+    }
+
+    /**
+     * @brief  Clear nRF5xSecurityManager's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void)
+    {
+        if (SecurityManager::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        return BLE_ERROR_NONE;
+    }
+
+    bool hasInitialized(void) const {
+        return btle_hasInitializedSecurity();
+    }
+
+public:
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xSecurityManager() {
+        /* empty */
+    }
+
+private:
+    nRF5xSecurityManager(const nRF5xSecurityManager &);
+    const nRF5xSecurityManager& operator=(const nRF5xSecurityManager &);
+
+    /*
+     * Expose an interface that allows us to query the SoftDevice bond table
+     * and extract a whitelist.
+     */
+    ble_error_t createWhitelistFromBondTable(ble_gap_whitelist_t &whitelistFromBondTable) const {
+        return btle_createWhitelistFromBondTable(&whitelistFromBondTable);
+    }
+
+    /*
+     * Given a BLE address and a IRK this function check whether the address
+     * can be generated from the IRK. To do so, this function uses the hash
+     * function and algorithm described in the Bluetooth low Energy
+     * Specification. Internally, Nordic SDK functions are used.
+     */
+    bool matchAddressAndIrk(ble_gap_addr_t *address, ble_gap_irk_t *irk) const {
+        return btle_matchAddressAndIrk(address, irk);
+    }
+
+    /*
+     * Give nRF5xGap access to createWhitelistFromBondTable() and
+     * matchAddressAndIrk()
+     */
+    friend class nRF5xGap;
+};
+
+#endif // ifndef __NRF51822_SECURITY_MANAGER_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,310 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xServiceDiscovery.h"
+
+ble_error_t
+nRF5xServiceDiscovery::launchCharacteristicDiscovery(Gap::Handle_t connectionHandle,
+                                                     Gap::Handle_t startHandle,
+                                                     Gap::Handle_t endHandle)
+{
+    characteristicDiscoveryStarted(connectionHandle);
+
+    ble_gattc_handle_range_t handleRange = {
+        .start_handle = startHandle,
+        .end_handle   = endHandle
+    };
+    uint32_t rc = sd_ble_gattc_characteristics_discover(connectionHandle, &handleRange);
+    ble_error_t err = BLE_ERROR_NONE;
+
+    switch (rc) {
+        case NRF_SUCCESS:
+            err = BLE_ERROR_NONE;
+            break;
+        case BLE_ERROR_INVALID_CONN_HANDLE:
+        case NRF_ERROR_INVALID_ADDR:
+            err = BLE_ERROR_INVALID_PARAM;
+            break;
+        case NRF_ERROR_BUSY:
+            err = BLE_STACK_BUSY;
+            break;
+        case NRF_ERROR_INVALID_STATE:
+            err = BLE_ERROR_INVALID_STATE;
+            break;
+        default:
+            err = BLE_ERROR_UNSPECIFIED;
+            break;
+    }
+
+    if (err) {
+        terminateCharacteristicDiscovery(err);
+    }
+    return err;
+}
+
+void
+nRF5xServiceDiscovery::setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response)
+{
+    serviceIndex = 0;
+    numServices  = response->count;
+
+    /* Account for the limitation on the number of discovered services we can handle at a time. */
+    if (numServices > BLE_DB_DISCOVERY_MAX_SRV) {
+        numServices = BLE_DB_DISCOVERY_MAX_SRV;
+    }
+
+    serviceUUIDDiscoveryQueue.reset();
+    for (unsigned serviceIndex = 0; serviceIndex < numServices; serviceIndex++) {
+        if (response->services[serviceIndex].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
+            serviceUUIDDiscoveryQueue.enqueue(serviceIndex);
+            services[serviceIndex].setup(response->services[serviceIndex].handle_range.start_handle,
+                                         response->services[serviceIndex].handle_range.end_handle);
+        } else {
+            services[serviceIndex].setup(response->services[serviceIndex].uuid.uuid,
+                                         response->services[serviceIndex].handle_range.start_handle,
+                                         response->services[serviceIndex].handle_range.end_handle);
+        }
+    }
+
+    /* Trigger discovery of service UUID if necessary. */
+    if (serviceUUIDDiscoveryQueue.getCount()) {
+        serviceUUIDDiscoveryQueue.triggerFirst();
+    }
+}
+
+void
+nRF5xServiceDiscovery::setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response)
+{
+    numCharacteristics  = response->count;
+
+    /* Account for the limitation on the number of discovered characteristics we can handle at a time. */
+    if (numCharacteristics > BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV) {
+        numCharacteristics = BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV;
+    }
+
+    charUUIDDiscoveryQueue.reset();
+    for (unsigned charIndex = 0; charIndex < numCharacteristics; charIndex++) {
+        if (response->chars[charIndex].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
+            charUUIDDiscoveryQueue.enqueue(charIndex);
+            characteristics[charIndex].setup(gattc,
+                                             connHandle,
+                                             response->chars[charIndex].char_props,
+                                             response->chars[charIndex].handle_decl,
+                                             response->chars[charIndex].handle_value);
+        } else {
+            characteristics[charIndex].setup(gattc,
+                                             connHandle,
+                                             response->chars[charIndex].uuid.uuid,
+                                             response->chars[charIndex].char_props,
+                                             response->chars[charIndex].handle_decl,
+                                             response->chars[charIndex].handle_value);
+        }
+    }
+
+    /* Trigger discovery of char UUID if necessary. */
+    if (charUUIDDiscoveryQueue.getCount()) {
+        charUUIDDiscoveryQueue.triggerFirst();
+    }
+}
+
+void
+nRF5xServiceDiscovery::progressCharacteristicDiscovery(void)
+{
+    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+        return;
+    }
+
+    if ((discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) && (numCharacteristics > 0)) {
+        discoveredCharacteristic.setLastHandle(characteristics[0].getDeclHandle() - 1);
+
+        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
+             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+            if (characteristicCallback) {
+                characteristicCallback(&discoveredCharacteristic);
+            }
+        }
+    }
+
+    for (uint8_t i = 0; i < numCharacteristics; ++i) {
+        if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+            return;
+        }
+
+        if (i == (numCharacteristics - 1)) {
+            discoveredCharacteristic = characteristics[i];
+            break;
+        } else {
+            characteristics[i].setLastHandle(characteristics[i + 1].getDeclHandle() - 1);
+        }
+
+        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            ((matchingCharacteristicUUID == characteristics[i].getUUID()) &&
+             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+            if (characteristicCallback) {
+                characteristicCallback(&characteristics[i]);
+            }
+        }
+    }
+
+    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+        return;
+    }
+
+    Gap::Handle_t startHandle = (numCharacteristics > 0) ? characteristics[numCharacteristics - 1].getValueHandle() + 1 : SRV_DISC_END_HANDLE;
+    Gap::Handle_t endHandle   = services[serviceIndex].getEndHandle();
+    resetDiscoveredCharacteristics(); /* Note: resetDiscoveredCharacteristics() must come after fetching start and end Handles. */
+
+    if (startHandle < endHandle) {
+        ble_gattc_handle_range_t handleRange = {
+            .start_handle = startHandle,
+            .end_handle   = endHandle
+        };
+        if (sd_ble_gattc_characteristics_discover(connHandle, &handleRange) != NRF_SUCCESS) {
+            terminateCharacteristicDiscovery(BLE_ERROR_UNSPECIFIED);
+        }
+    } else {
+        terminateCharacteristicDiscovery(BLE_ERROR_NONE);
+    }
+}
+
+void
+nRF5xServiceDiscovery::progressServiceDiscovery(void)
+{
+    /* Iterate through the previously discovered services cached in services[]. */
+    while ((state == SERVICE_DISCOVERY_ACTIVE) && (serviceIndex < numServices)) {
+        if ((matchingServiceUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            (matchingServiceUUID == services[serviceIndex].getUUID())) {
+
+            if (serviceCallback && (matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN))) {
+                serviceCallback(&services[serviceIndex]);
+            }
+
+            if ((state == SERVICE_DISCOVERY_ACTIVE) && characteristicCallback) {
+                launchCharacteristicDiscovery(connHandle, services[serviceIndex].getStartHandle(), services[serviceIndex].getEndHandle());
+            } else {
+                serviceIndex++;
+            }
+        } else {
+            serviceIndex++;
+        }
+    }
+
+    /* Relaunch discovery of new services beyond the last entry cached in services[]. */
+    if ((state == SERVICE_DISCOVERY_ACTIVE) && (numServices > 0) && (serviceIndex > 0)) {
+        /* Determine the ending handle of the last cached service. */
+        Gap::Handle_t endHandle = services[serviceIndex - 1].getEndHandle();
+        resetDiscoveredServices(); /* Note: resetDiscoveredServices() must come after fetching endHandle. */
+
+        if (endHandle == SRV_DISC_END_HANDLE) {
+            terminateServiceDiscovery();
+        } else {
+            if (sd_ble_gattc_primary_services_discover(connHandle, endHandle, NULL) != NRF_SUCCESS) {
+                terminateServiceDiscovery();
+            }
+        }
+    }
+}
+
+void
+nRF5xServiceDiscovery::ServiceUUIDDiscoveryQueue::triggerFirst(void)
+{
+    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
+        parentDiscoveryObject->state = DISCOVER_SERVICE_UUIDS;
+
+        unsigned serviceIndex = getFirst();
+        ble_uuid_t uuid = {
+            .uuid = BLE_UUID_SERVICE_PRIMARY,
+            .type = BLE_UUID_TYPE_BLE,
+        };
+        ble_gattc_handle_range_t handleRange = {
+            .start_handle = parentDiscoveryObject->services[serviceIndex].getStartHandle(),
+            .end_handle   = parentDiscoveryObject->services[serviceIndex].getEndHandle(),
+        };
+        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
+            return;
+        }
+
+        /* Skip this service if we fail to launch a read for its service-declaration
+         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
+        dequeue();
+    }
+
+    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
+    if (parentDiscoveryObject->state == DISCOVER_SERVICE_UUIDS) {
+        parentDiscoveryObject->state = SERVICE_DISCOVERY_ACTIVE;
+    }
+}
+
+void
+nRF5xServiceDiscovery::CharUUIDDiscoveryQueue::triggerFirst(void)
+{
+    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
+        parentDiscoveryObject->state = DISCOVER_CHARACTERISTIC_UUIDS;
+
+        unsigned charIndex = getFirst();
+        ble_uuid_t uuid = {
+            .uuid = BLE_UUID_CHARACTERISTIC,
+            .type = BLE_UUID_TYPE_BLE,
+        };
+        ble_gattc_handle_range_t handleRange = { };
+        handleRange.start_handle = parentDiscoveryObject->characteristics[charIndex].getDeclHandle();
+        handleRange.end_handle   = parentDiscoveryObject->characteristics[charIndex].getDeclHandle() + 1;
+        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
+            return;
+        }
+
+        /* Skip this service if we fail to launch a read for its service-declaration
+         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
+        dequeue();
+    }
+
+    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
+    if (parentDiscoveryObject->state == DISCOVER_CHARACTERISTIC_UUIDS) {
+        parentDiscoveryObject->state = CHARACTERISTIC_DISCOVERY_ACTIVE;
+    }
+}
+
+void
+nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response)
+{
+    if (state == DISCOVER_SERVICE_UUIDS) {
+        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID)) {
+            UUID::LongUUIDBytes_t uuid;
+            memcpy(uuid, response->handle_value[0].p_value, UUID::LENGTH_OF_LONG_UUID);
+
+            unsigned serviceIndex = serviceUUIDDiscoveryQueue.dequeue();
+            services[serviceIndex].setupLongUUID(uuid, UUID::LSB);
+
+            serviceUUIDDiscoveryQueue.triggerFirst();
+        } else {
+            serviceUUIDDiscoveryQueue.dequeue();
+        }
+    } else if (state == DISCOVER_CHARACTERISTIC_UUIDS) {
+        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID + 1 /* props */ + 2 /* value handle */)) {
+            UUID::LongUUIDBytes_t uuid;
+
+            memcpy(uuid, &(response->handle_value[0].p_value[3]), UUID::LENGTH_OF_LONG_UUID);
+
+            unsigned charIndex = charUUIDDiscoveryQueue.dequeue();
+            characteristics[charIndex].setupLongUUID(uuid, UUID::LSB);
+
+            charUUIDDiscoveryQueue.triggerFirst();
+        } else {
+            charUUIDDiscoveryQueue.dequeue();
+        }
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xServiceDiscovery.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,366 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_SERVICE_DISCOVERY_H__
+#define __NRF_SERVICE_DISCOVERY_H__
+
+#include "ble/ServiceDiscovery.h"
+#include "ble/DiscoveredService.h"
+#include "nRF5xDiscoveredCharacteristic.h"
+
+#include "nrf_ble.h"
+#include "ble_gattc.h"
+
+class nRF5xGattClient; /* forward declaration */
+
+class nRF5xServiceDiscovery : public ServiceDiscovery
+{
+public:
+    static const uint16_t SRV_DISC_START_HANDLE             = 0x0001; /**< The start handle value used during service discovery. */
+    static const uint16_t SRV_DISC_END_HANDLE               = 0xFFFF; /**< The end handle value used during service discovery. */
+
+public:
+    static const unsigned BLE_DB_DISCOVERY_MAX_SRV          = 4;      /**< Maximum number of services we can retain information for after a single discovery. */
+    static const unsigned BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV = 4;      /**< Maximum number of characteristics per service we can retain information for. */
+
+public:
+    nRF5xServiceDiscovery(nRF5xGattClient *gattcIn) :
+        gattc(gattcIn),
+        serviceIndex(0),
+        numServices(0),
+        numCharacteristics(0),
+        state(INACTIVE),
+        services(),
+        characteristics(),
+        serviceUUIDDiscoveryQueue(this),
+        charUUIDDiscoveryQueue(this),
+        onTerminationCallback(NULL) {
+        /* empty */
+    }
+
+    virtual ble_error_t launch(Gap::Handle_t                               connectionHandle,
+                               ServiceDiscovery::ServiceCallback_t         sc,
+                               ServiceDiscovery::CharacteristicCallback_t  cc,
+                               const UUID                                 &matchingServiceUUIDIn,
+                               const UUID                                 &matchingCharacteristicUUIDIn)
+    {
+        if (isActive()) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        serviceCallback            = sc;
+        characteristicCallback     = cc;
+        matchingServiceUUID        = matchingServiceUUIDIn;
+        matchingCharacteristicUUID = matchingCharacteristicUUIDIn;
+
+        serviceDiscoveryStarted(connectionHandle);
+
+        uint32_t rc;
+        if ((rc = sd_ble_gattc_primary_services_discover(connectionHandle, SRV_DISC_START_HANDLE, NULL)) != NRF_SUCCESS) {
+            terminate();
+            switch (rc) {
+                case NRF_ERROR_INVALID_PARAM:
+                case BLE_ERROR_INVALID_CONN_HANDLE:
+                    return BLE_ERROR_INVALID_PARAM;
+                case NRF_ERROR_BUSY:
+                    return BLE_STACK_BUSY;
+                default:
+                case NRF_ERROR_INVALID_STATE:
+                    return BLE_ERROR_INVALID_STATE;
+            }
+        }
+
+        return BLE_ERROR_NONE;
+    }
+
+    virtual bool isActive(void) const {
+        return state != INACTIVE;
+    }
+
+    virtual void terminate(void) {
+        terminateServiceDiscovery();
+    }
+
+    void terminate(Gap::Handle_t connectionHandle) {
+        if(connHandle == connectionHandle) {
+            terminate();
+        }
+    }
+
+    virtual void onTermination(ServiceDiscovery::TerminationCallback_t callback) {
+        onTerminationCallback = callback;
+    }
+
+    /**
+     * @brief  Clear nRF5xServiceDiscovery's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void) {
+        /* Clear all state that is from the parent, including private members */
+        if (ServiceDiscovery::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        /* Clear derived class members */
+        serviceIndex = 0;
+        numServices = 0;
+        numCharacteristics = 0;
+
+        state = INACTIVE;
+
+        serviceUUIDDiscoveryQueue.reset();
+        charUUIDDiscoveryQueue.reset();
+
+        onTerminationCallback = NULL;
+
+        return BLE_ERROR_NONE;
+    }
+
+private:
+    ble_error_t launchCharacteristicDiscovery(Gap::Handle_t connectionHandle, Gap::Handle_t startHandle, Gap::Handle_t endHandle);
+
+private:
+    void setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response);
+    void setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response);
+
+    void triggerServiceUUIDDiscovery(void);
+    void processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response);
+    void removeFirstServiceNeedingUUIDDiscovery(void);
+
+    void terminateServiceDiscovery(void) {
+        discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
+
+        bool wasActive = isActive();
+        state = INACTIVE;
+
+        if (wasActive && onTerminationCallback) {
+            onTerminationCallback(connHandle);
+        }
+    }
+
+    void terminateCharacteristicDiscovery(ble_error_t err) {
+        if (state == CHARACTERISTIC_DISCOVERY_ACTIVE) {
+            if(discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) {
+               if(err == BLE_ERROR_NONE) {
+                    // fullfill the last characteristic
+                    discoveredCharacteristic.setLastHandle(services[serviceIndex].getEndHandle());
+
+                    if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+                        ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
+                         (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+                        if (characteristicCallback) {
+                            characteristicCallback(&discoveredCharacteristic);
+                        }
+                    }
+               }
+               discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
+            }
+
+            state = SERVICE_DISCOVERY_ACTIVE;
+        }
+        serviceIndex++; /* Progress service index to keep discovery alive. */
+    }
+
+private:
+    void resetDiscoveredServices(void) {
+        numServices  = 0;
+        serviceIndex = 0;
+    }
+
+    void resetDiscoveredCharacteristics(void) {
+        numCharacteristics  = 0;
+    }
+
+private:
+    void serviceDiscoveryStarted(Gap::Handle_t connectionHandle) {
+        connHandle = connectionHandle;
+        resetDiscoveredServices();
+        state = SERVICE_DISCOVERY_ACTIVE;
+    }
+
+private:
+    void characteristicDiscoveryStarted(Gap::Handle_t connectionHandle) {
+        connHandle = connectionHandle;
+        resetDiscoveredCharacteristics();
+        state = CHARACTERISTIC_DISCOVERY_ACTIVE;
+    }
+
+private:
+    /**
+     * A datatype to contain service-indices for which long UUIDs need to be
+     * discovered using read_val_by_uuid().
+     */
+    class ServiceUUIDDiscoveryQueue {
+    public:
+        ServiceUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
+            numIndices(0),
+            serviceIndices(),
+            parentDiscoveryObject(parent) {
+            /* empty */
+        }
+
+    public:
+        void reset(void) {
+            numIndices = 0;
+            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
+                serviceIndices[i] = INVALID_INDEX;
+            }
+        }
+        void enqueue(int serviceIndex) {
+            serviceIndices[numIndices++] = serviceIndex;
+        }
+        int dequeue(void) {
+            if (numIndices == 0) {
+                return INVALID_INDEX;
+            }
+
+            unsigned valueToReturn = serviceIndices[0];
+            numIndices--;
+            for (unsigned i = 0; i < numIndices; i++) {
+                serviceIndices[i] = serviceIndices[i + 1];
+            }
+
+            return valueToReturn;
+        }
+        unsigned getFirst(void) const {
+            return serviceIndices[0];
+        }
+        size_t getCount(void) const {
+            return numIndices;
+        }
+
+        /**
+         * Trigger UUID discovery for the first of the enqueued ServiceIndices.
+         */
+        void triggerFirst(void);
+
+    private:
+        static const int INVALID_INDEX = -1;
+
+    private:
+        size_t numIndices;
+        int    serviceIndices[BLE_DB_DISCOVERY_MAX_SRV];
+
+        nRF5xServiceDiscovery *parentDiscoveryObject;
+    };
+    friend class ServiceUUIDDiscoveryQueue;
+
+    /**
+     * A datatype to contain characteristic-indices for which long UUIDs need to
+     * be discovered using read_val_by_uuid().
+     */
+    class CharUUIDDiscoveryQueue {
+    public:
+        CharUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
+            numIndices(0),
+            charIndices(),
+            parentDiscoveryObject(parent) {
+            /* empty */
+        }
+
+    public:
+        void reset(void) {
+            numIndices = 0;
+            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
+                charIndices[i] = INVALID_INDEX;
+            }
+        }
+        void enqueue(int serviceIndex) {
+            charIndices[numIndices++] = serviceIndex;
+        }
+        int dequeue(void) {
+            if (numIndices == 0) {
+                return INVALID_INDEX;
+            }
+
+            unsigned valueToReturn = charIndices[0];
+            numIndices--;
+            for (unsigned i = 0; i < numIndices; i++) {
+                charIndices[i] = charIndices[i + 1];
+            }
+
+            return valueToReturn;
+        }
+        unsigned getFirst(void) const {
+            return charIndices[0];
+        }
+        size_t getCount(void) const {
+            return numIndices;
+        }
+
+        /**
+         * Trigger UUID discovery for the first of the enqueued charIndices.
+         */
+        void triggerFirst(void);
+
+    private:
+        static const int INVALID_INDEX = -1;
+
+    private:
+        size_t numIndices;
+        int    charIndices[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
+
+        nRF5xServiceDiscovery *parentDiscoveryObject;
+    };
+    friend class CharUUIDDiscoveryQueue;
+
+private:
+    friend void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
+    void progressCharacteristicDiscovery(void);
+    void progressServiceDiscovery(void);
+
+private:
+    nRF5xGattClient *gattc;
+
+private:
+    uint8_t  serviceIndex;        /**< Index of the current service being discovered. This is intended for internal use during service discovery.*/
+    uint8_t  numServices;         /**< Number of services at the peers GATT database.*/
+    uint8_t  numCharacteristics;  /**< Number of characteristics within the service.*/
+
+    enum State_t {
+        INACTIVE,
+        SERVICE_DISCOVERY_ACTIVE,
+        CHARACTERISTIC_DISCOVERY_ACTIVE,
+        DISCOVER_SERVICE_UUIDS,
+        DISCOVER_CHARACTERISTIC_UUIDS,
+    } state;
+
+    DiscoveredService           services[BLE_DB_DISCOVERY_MAX_SRV];  /**< Information related to the current service being discovered.
+                                                                      *  This is intended for internal use during service discovery. */
+    nRF5xDiscoveredCharacteristic characteristics[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
+
+    ServiceUUIDDiscoveryQueue   serviceUUIDDiscoveryQueue;
+    CharUUIDDiscoveryQueue      charUUIDDiscoveryQueue;
+
+    TerminationCallback_t       onTerminationCallback;
+
+    /*
+     * The currently discovered characteristic. Discovery of a characteristic
+     * is a two phase process.
+     * First, declaration handle is fetched, it provide the UUID, the value handle and
+     * the properties of a characteristic.
+     * Second, the next declaration handle is fetched, with its declaration handle, it is
+     * possible to compute the last handle of the discovered characteristic and fill the
+     * missing part of the object.
+     * If there is no remaining characteristic to discover, the last handle of the
+     * discovered characteristic will be set to the last handle of its enclosing service.
+     */
+    nRF5xDiscoveredCharacteristic discoveredCharacteristic;
+};
+
+#endif /*__NRF_SERVICE_DISCOVERY_H__*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xn.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xn.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,217 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#include "nRF5xn.h"
+#include "ble/blecommon.h"
+#include "nrf_soc.h"
+
+#include "btle/btle.h"
+#include "nrf_delay.h"
+
+extern "C" {
+#include "softdevice_handler.h"
+}
+
+/**
+ * The singleton which represents the nRF51822 transport for the BLE.
+ */
+static nRF5xn deviceInstance;
+
+/**
+ * BLE-API requires an implementation of the following function in order to
+ * obtain its transport handle.
+ */
+BLEInstanceBase *
+createBLEInstance(void)
+{
+    return &nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+}
+
+nRF5xn& nRF5xn::Instance(BLE::InstanceID_t instanceId)
+{
+    return deviceInstance;
+}
+
+nRF5xn::nRF5xn(void) :
+    initialized(false),
+    instanceID(BLE::DEFAULT_INSTANCE),
+    gapInstance(),
+    gattServerInstance(NULL),
+    gattClientInstance(NULL),
+    securityManagerInstance(NULL)
+{
+}
+
+nRF5xn::~nRF5xn(void)
+{
+}
+
+const char *nRF5xn::getVersion(void)
+{
+    if (!initialized) {
+        return "INITIALIZATION_INCOMPLETE";
+    }
+
+    static char versionString[32];
+    static bool versionFetched = false;
+
+    if (!versionFetched) {
+        ble_version_t version;
+        if ((sd_ble_version_get(&version) == NRF_SUCCESS) && (version.company_id == 0x0059)) {
+            switch (version.version_number) {
+                case 0x07:
+                case 0x08:
+                    snprintf(versionString, sizeof(versionString), "Nordic BLE4.1 ver:%u fw:%04x", version.version_number, version.subversion_number);
+                    break;
+                default:
+                    snprintf(versionString, sizeof(versionString), "Nordic (spec unknown) ver:%u fw:%04x", version.version_number, version.subversion_number);
+                    break;
+            }
+            versionFetched = true;
+        } else {
+            strncpy(versionString, "unknown", sizeof(versionString));
+        }
+    }
+
+    return versionString;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Initialize the BLE stack.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE if everything executed properly and
+                BLE_ERROR_ALREADY_INITIALIZED if the stack has already
+                been initialized (possibly through a call to nRF5xn::init()).
+                BLE_ERROR_INTERNAL_STACK_FAILURE is returned if initialization
+                of the internal stack (SoftDevice) failed.
+
+*/
+/**************************************************************************/
+ble_error_t nRF5xn::init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback)
+{
+    if (initialized) {
+        BLE::InitializationCompleteCallbackContext context = {
+            BLE::Instance(instanceID),
+            BLE_ERROR_ALREADY_INITIALIZED
+        };
+        callback.call(&context);
+        return BLE_ERROR_ALREADY_INITIALIZED;
+    }
+
+    instanceID   = instanceID;
+
+    /* ToDo: Clear memory contents, reset the SD, etc. */
+    if (btle_init() != ERROR_NONE) {
+        return BLE_ERROR_INTERNAL_STACK_FAILURE;
+    }
+
+    initialized = true;
+    BLE::InitializationCompleteCallbackContext context = {
+        BLE::Instance(instanceID),
+        BLE_ERROR_NONE
+    };
+    callback.call(&context);
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Purge the BLE stack of GATT and GAP state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @note  When using S110, GattClient::shutdown() will not be called
+           since Gatt client features are not supported.
+*/
+/**************************************************************************/
+ble_error_t nRF5xn::shutdown(void)
+{
+    if (!initialized) {
+        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
+    }
+
+    /*
+     * Shutdown the SoftDevice first. This is because we need to disable all
+     * interrupts. Otherwise if we clear the BLE API and glue code first there
+     * will be many NULL references and no config information which could lead
+     * to errors if the shutdown process is interrupted.
+     */
+    if (softdevice_handler_sd_disable() != NRF_SUCCESS) {
+        return BLE_STACK_BUSY;
+    }
+
+
+    /* Shutdown the BLE API and nRF51 glue code */
+    ble_error_t error;
+
+    if (gattServerInstance != NULL) {
+        error = gattServerInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    if (securityManagerInstance != NULL) {
+        error = securityManagerInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    /* S110 does not support BLE client features, nothing to reset. */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    if (gattClientInstance != NULL) {
+        error = gattClientInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+#endif
+
+    /* Gap instance is always present */
+    error = gapInstance.reset();
+    if (error != BLE_ERROR_NONE) {
+        return error;
+    }
+
+    initialized = false;
+    return BLE_ERROR_NONE;
+}
+
+void
+nRF5xn::waitForEvent(void)
+{
+    processEvents();
+    sd_app_evt_wait();
+}
+
+void nRF5xn::processEvents() {
+    if (isEventsSignaled) {
+        isEventsSignaled = false;
+        intern_softdevice_events_execute();
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/nRF5xn.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/nRF5xn.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,184 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_H__
+#define __NRF51822_H__
+
+#include "ble/BLE.h"
+#include "ble/blecommon.h"
+#include "ble/BLEInstanceBase.h"
+
+#include "nRF5xGap.h"
+#include "nRF5xGattServer.h"
+#include "nRF5xGattClient.h"
+#include "nRF5xSecurityManager.h"
+
+#include "btle.h"
+
+class nRF5xn : public BLEInstanceBase
+{
+public:
+    nRF5xn(void);
+    virtual ~nRF5xn(void);
+
+    virtual ble_error_t init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback);
+    virtual bool        hasInitialized(void) const {
+        return initialized;
+    }
+    virtual ble_error_t shutdown(void);
+    virtual const char *getVersion(void);
+
+    /**
+     * Accessors to GAP. This function checks whether gapInstance points to an
+     * object. If if does not, then the gapInstance is updated to
+     * &_getInstance before returning.
+     *
+     * @return  A reference to GattServer.
+     *
+     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
+     *        always needed in a BLE application. Therefore it is allocated
+     *        statically.
+     */
+    virtual Gap &getGap() {
+        return gapInstance;
+    };
+
+    /**
+     * Accessors to GATT Server. This function checks whether a GattServer
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattServer.
+     */
+    virtual GattServer &getGattServer() {
+        if (gattServerInstance == NULL) {
+            gattServerInstance = new nRF5xGattServer();
+        }
+        return *gattServerInstance;
+    };
+
+    /**
+     * Accessors to GATT Client. This function checks whether a GattClient
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattClient.
+     */
+    virtual nRF5xGattClient &getGattClient() {
+        if (gattClientInstance == NULL) {
+            gattClientInstance = new nRF5xGattClient();
+        }
+        return *gattClientInstance;
+    }
+
+    /**
+     * Accessors to Security Manager. This function checks whether a SecurityManager
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattServer.
+     */
+    virtual nRF5xSecurityManager &getSecurityManager() {
+        if (securityManagerInstance == NULL) {
+            securityManagerInstance = new nRF5xSecurityManager();
+        }
+        return *securityManagerInstance;
+    }
+
+    /**
+     * Accessors to GAP. This function checks whether gapInstance points to an
+     * object. If if does not, then the gapInstance is updated to
+     * &_getInstance before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
+     *        always needed in a BLE application. Therefore it is allocated
+     *        statically.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xGap &getGap() const  {
+        return gapInstance;
+    };
+
+    /**
+     * Accessors to GATT Server. This function checks whether a GattServer
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xGattServer &getGattServer() const {
+        if (gattServerInstance == NULL) {
+            gattServerInstance = new nRF5xGattServer();
+        }
+        return *gattServerInstance;
+    };
+
+    /**
+     * Accessors to Security Manager. This function checks whether a SecurityManager
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xSecurityManager &getSecurityManager() const {
+        if (securityManagerInstance == NULL) {
+            securityManagerInstance = new nRF5xSecurityManager();
+        }
+        return *securityManagerInstance;
+    }
+
+    virtual void waitForEvent(void);
+
+    virtual void processEvents();
+
+public:
+    static nRF5xn& Instance(BLE::InstanceID_t instanceId);
+
+private:
+    bool              initialized;
+    BLE::InstanceID_t instanceID;
+
+private:
+    mutable nRF5xGap gapInstance; /**< Gap instance whose reference is returned from a call to
+                                   * getGap(). Unlike the GattClient, GattServer and
+                                   * SecurityManager, Gap is always needed in a BLE application. */
+
+private:
+    mutable nRF5xGattServer      *gattServerInstance;      /**< Pointer to the GattServer object instance.
+                                                            *   If NULL, then GattServer has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+    mutable nRF5xGattClient      *gattClientInstance;      /**< Pointer to the GattClient object instance.
+                                                            *   If NULL, then GattClient has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+    mutable nRF5xSecurityManager *securityManagerInstance; /**< Pointer to the SecurityManager object instance.
+                                                            *   If NULL, then SecurityManager has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+};
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/projectconfig.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/projectconfig.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,136 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _PROJECTCONFIG_H_
+#define _PROJECTCONFIG_H_
+
+#include "ble/GapAdvertisingData.h"
+
+/*=========================================================================
+    MCU & BOARD SELCTION
+
+    CFG_BOARD is one of the value defined in board.h
+    -----------------------------------------------------------------------*/
+    #define CFG_BOARD                                  BOARD_PCA10001
+    #define CFG_MCU_STRING                             "nRF51822"
+/*=========================================================================*/
+
+
+/*=========================================================================
+    CODE BASE VERSION SETTINGS
+
+    Please do not modify this version number.  To set a version number
+    for your project or firmware, change the values in your 'boards/'
+    config file.
+    -----------------------------------------------------------------------*/
+    #define CFG_CODEBASE_VERSION_MAJOR                 0
+    #define CFG_CODEBASE_VERSION_MINOR                 1
+    #define CFG_CODEBASE_VERSION_REVISION              0
+/*=========================================================================*/
+
+
+/*=========================================================================
+    FIRMWARE VERSION SETTINGS
+    -----------------------------------------------------------------------*/
+    #define CFG_FIRMWARE_VERSION_MAJOR                 0
+    #define CFG_FIRMWARE_VERSION_MINOR                 0
+    #define CFG_FIRMWARE_VERSION_REVISION              0
+/*=========================================================================*/
+
+
+/*=========================================================================
+    DEBUG LEVEL
+    -----------------------------------------------------------------------
+
+    CFG_DEBUG                 Level 3: Full debug output, any failed assert
+                                       will produce a breakpoint for the
+                                       debugger
+                              Level 2: ATTR_ALWAYS_INLINE is null, ASSERT
+                                       has text
+                              Level 1: ATTR_ALWAYS_INLINE is an attribute,
+                                       ASSERT has no text
+                              Level 0: No debug information generated
+
+    -----------------------------------------------------------------------*/
+    #define CFG_DEBUG                                  (1)
+
+    #if (CFG_DEBUG > 3) || (CFG_DEBUG < 0)
+      #error "CFG_DEBUG must be a value between 0 (no debug) and 3"
+    #endif
+/*=========================================================================*/
+
+
+/*=========================================================================
+    GENERAL NRF51 PERIPHERAL SETTINGS
+    -----------------------------------------------------------------------
+
+    CFG_SCHEDULER_ENABLE      Set this to 'true' or 'false' depending on
+                              if you use the event scheduler or not
+
+    -----------------------------------------------------------------------*/
+    #define CFG_SCHEDULER_ENABLE                       false
+
+    /*------------------------------- GPIOTE ------------------------------*/
+    #define CFG_GPIOTE_MAX_USERS                       1                        /**< Maximum number of users of the GPIOTE handler. */
+
+    /*-------------------------------- TIMER ------------------------------*/
+    #define CFG_TIMER_PRESCALER                        0                        /**< Value of the RTC1 PRESCALER register. freq = (32768/(PRESCALER+1)) */
+    #define CFG_TIMER_MAX_INSTANCE                     1                        /**< Maximum number of simultaneously created timers. */
+    #define CFG_TIMER_OPERATION_QUEUE_SIZE             2                        /**< Size of timer operation queues. */
+/*=========================================================================*/
+
+
+/*=========================================================================
+    BTLE SETTINGS
+    -----------------------------------------------------------------------*/
+
+    #define CFG_BLE_TX_POWER_LEVEL                     0                        /**< in dBm (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
+
+    /*---------------------------- BOND MANAGER ---------------------------*/
+    #define CFG_BLE_BOND_FLASH_PAGE_BOND               (BLE_FLASH_PAGE_END-1)   /**< Flash page used for bond manager bonding information.*/
+    #define CFG_BLE_BOND_FLASH_PAGE_SYS_ATTR           (BLE_FLASH_PAGE_END-3)   /**< Flash page used for bond manager system attribute information. TODO check if we can use BLE_FLASH_PAGE_END-2*/
+    #define CFG_BLE_BOND_DELETE_BUTTON_NUM             0                        /**< Button to press to delete bond details during init */
+
+    /*------------------------------ SECURITY -----------------------------*/
+    #define CFG_BLE_SEC_PARAM_MITM                     0                        /**< Man In The Middle protection not required. */
+    #define CFG_BLE_SEC_PARAM_IO_CAPABILITIES          BLE_GAP_IO_CAPS_NONE     /**< No I/O capabilities. */
+    #define CFG_BLE_SEC_PARAM_OOB                      0                        /**< Out Of Band data not available. */
+    #define CFG_BLE_SEC_PARAM_MIN_KEY_SIZE             7                        /**< Minimum encryption key size. */
+    #define CFG_BLE_SEC_PARAM_MAX_KEY_SIZE             16
+
+    /*--------------------------------- GAP -------------------------------*/
+    #define CFG_GAP_APPEARANCE                         GapAdvertisingData::GENERIC_TAG
+    #define CFG_GAP_LOCAL_NAME                         "nRF5x"
+
+    #define CFG_GAP_CONNECTION_MIN_INTERVAL_MS           50                     /**< Minimum acceptable connection interval */
+    #define CFG_GAP_CONNECTION_MAX_INTERVAL_MS          500                     /**< Maximum acceptable connection interval */
+    #define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS  4000                     /**< Connection supervisory timeout */
+    #define CFG_GAP_CONNECTION_SLAVE_LATENCY           0                        /**< Slave Latency in number of connection events. */
+
+    #define CFG_GAP_ADV_INTERVAL_MS                    25                       /**< The advertising interval in miliseconds, should be multiply of 0.625 */
+    #define CFG_GAP_ADV_TIMEOUT_S                      180                      /**< The advertising timeout in units of seconds. */
+/*=========================================================================*/
+
+
+/*=========================================================================
+    VALIDATION
+    -----------------------------------------------------------------------*/
+    #if CFG_BLE_TX_POWER_LEVEL != -40 && CFG_BLE_TX_POWER_LEVEL != -20 && CFG_BLE_TX_POWER_LEVEL != -16 && CFG_BLE_TX_POWER_LEVEL != -12 && CFG_BLE_TX_POWER_LEVEL != -8  && CFG_BLE_TX_POWER_LEVEL != -4  && CFG_BLE_TX_POWER_LEVEL != 0   && CFG_BLE_TX_POWER_LEVEL != 4
+        #error "CFG_BLE_TX_POWER_LEVEL must be -40, -20, -16, -12, -8, -4, 0 or 4"
+    #endif
+/*=========================================================================*/
+
+#endif /* _PROJECTCONFIG_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_MCU_NRF51822/source/supress-warnings.cmake
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_MCU_NRF51822/source/supress-warnings.cmake	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,21 @@
+# Copyright 2015 ARM Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+message("suppressing warnings from ble-nrf51822")
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+    set_target_properties(ble-nrf51822
+        PROPERTIES COMPILE_FLAGS "-Wno-sign-compare -Wno-unused-variable -Wno-unused-parameter -Wno-unused-function -Wno-missing-field-initializers"
+    )
+endif()
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/CHANGELOG.md
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/CHANGELOG.md	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,344 @@
+# Change Log
+
+## [v2.5.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.3) (2016-02-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.2...v2.5.3)
+
+**Merged pull requests:**
+
+- Fix for compilation errors with S110 softdevice in btle.cpp [\#109](https://github.com/ARMmbed/ble-nrf51822/pull/109) ([ddavidebor](https://github.com/ddavidebor))
+
+## [v2.5.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.2) (2016-02-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.1...v2.5.2)
+
+**Merged pull requests:**
+
+- Sync develop against master [\#113](https://github.com/ARMmbed/ble-nrf51822/pull/113) ([pan-](https://github.com/pan-))
+- Fix incorrect handles of characteristics descriptors. [\#112](https://github.com/ARMmbed/ble-nrf51822/pull/112) ([pan-](https://github.com/pan-))
+
+## [v2.5.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.1) (2016-01-27)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.5.0...v2.5.1)
+
+**Merged pull requests:**
+
+- Remove Gap::state updates from this module [\#108](https://github.com/ARMmbed/ble-nrf51822/pull/108) ([andresag01](https://github.com/andresag01))
+- merge version  [\#106](https://github.com/ARMmbed/ble-nrf51822/pull/106) ([pan-](https://github.com/pan-))
+
+## [v2.5.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.5.0) (2016-01-12)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.1...v2.5.0)
+
+**Merged pull requests:**
+
+- Fix access to enum member [\#105](https://github.com/ARMmbed/ble-nrf51822/pull/105) ([pan-](https://github.com/pan-))
+- Hotfix dependency [\#104](https://github.com/ARMmbed/ble-nrf51822/pull/104) ([pan-](https://github.com/pan-))
+- Finish implementation of getAddressesFromBondTable [\#103](https://github.com/ARMmbed/ble-nrf51822/pull/103) ([andresag01](https://github.com/andresag01))
+
+## [v2.4.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.1) (2016-01-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.4.0...v2.4.1)
+
+**Merged pull requests:**
+
+- merge branch develop \(v2.4.0\) [\#100](https://github.com/ARMmbed/ble-nrf51822/pull/100) ([pan-](https://github.com/pan-))
+
+## [v2.4.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.4.0) (2016-01-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.1...v2.4.0)
+
+**Merged pull requests:**
+
+- Add implementation of experimental whitelisting API [\#99](https://github.com/ARMmbed/ble-nrf51822/pull/99) ([andresag01](https://github.com/andresag01))
+
+## [v2.3.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.1) (2016-01-07)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.3.0...v2.3.1)
+
+**Merged pull requests:**
+
+- Update yotta module dependencies [\#98](https://github.com/ARMmbed/ble-nrf51822/pull/98) ([pan-](https://github.com/pan-))
+
+## [v2.3.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.3.0) (2015-12-23)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.10...v2.3.0)
+
+**Merged pull requests:**
+
+- Implementation of Characteristic descriptor discovery [\#74](https://github.com/ARMmbed/ble-nrf51822/pull/74) ([pan-](https://github.com/pan-))
+
+## [v2.2.10](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.10) (2015-12-23)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.9...v2.2.10)
+
+**Fixed bugs:**
+
+- nRF5xn::init don't verify if errors have occurred during btle\_init [\#59](https://github.com/ARMmbed/ble-nrf51822/issues/59)
+
+**Closed issues:**
+
+- A call to shutdown does not clear the state of some components of BLE API [\#85](https://github.com/ARMmbed/ble-nrf51822/issues/85)
+- Memory allocation issue on the NRF51DK board. [\#76](https://github.com/ARMmbed/ble-nrf51822/issues/76)
+- Terrible handling of initLen / minLen and variable length characteristics. [\#56](https://github.com/ARMmbed/ble-nrf51822/issues/56)
+
+**Merged pull requests:**
+
+- Fix shutdown of Gap instance to avoid NULL refs [\#96](https://github.com/ARMmbed/ble-nrf51822/pull/96) ([andresag01](https://github.com/andresag01))
+- Add check for return code of ble\_init [\#95](https://github.com/ARMmbed/ble-nrf51822/pull/95) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.9](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.9) (2015-12-18)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.8...v2.2.9)
+
+**Closed issues:**
+
+- Cannot open source input file "system\_nrf51.h" [\#52](https://github.com/ARMmbed/ble-nrf51822/issues/52)
+
+**Merged pull requests:**
+
+- Remove occurrence of deprecated appearance enum [\#92](https://github.com/ARMmbed/ble-nrf51822/pull/92) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.8) (2015-12-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.7...v2.2.8)
+
+## [v2.2.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.7) (2015-12-15)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.6...v2.2.7)
+
+**Merged pull requests:**
+
+- Replace deprecated inclusions of mbed.h [\#89](https://github.com/ARMmbed/ble-nrf51822/pull/89) ([andresag01](https://github.com/andresag01))
+- Improve shutdown to clear BLE API and not just SD [\#87](https://github.com/ARMmbed/ble-nrf51822/pull/87) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.6) (2015-12-15)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.5...v2.2.6)
+
+**Merged pull requests:**
+
+- follow the extraction of address related types from Gap.h into BLEProtocol.h [\#88](https://github.com/ARMmbed/ble-nrf51822/pull/88) ([rgrover](https://github.com/rgrover))
+
+## [v2.2.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.5) (2015-12-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.3...v2.2.5)
+
+**Merged pull requests:**
+
+- Added SecurityManager::setLinkSecurity call for elevating security settings on a particular connection. [\#86](https://github.com/ARMmbed/ble-nrf51822/pull/86) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.2.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.3) (2015-12-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.2...v2.2.3)
+
+## [v2.2.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.2) (2015-12-08)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.1...v2.2.2)
+
+**Merged pull requests:**
+
+- Add -Wno-unused-function to supress-warnings.cmake [\#83](https://github.com/ARMmbed/ble-nrf51822/pull/83) ([andresag01](https://github.com/andresag01))
+
+## [v2.2.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.1) (2015-12-08)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.2.0...v2.2.1)
+
+**Merged pull requests:**
+
+- WIP: UUID endian change [\#82](https://github.com/ARMmbed/ble-nrf51822/pull/82) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.2.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.2.0) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.4...v2.2.0)
+
+## [v2.1.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.4) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.3...v2.1.4)
+
+## [v2.1.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.3) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.2...v2.1.3)
+
+## [v2.1.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.2) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.1...v2.1.2)
+
+**Merged pull requests:**
+
+- Allow GattAttributes to have variable length [\#81](https://github.com/ARMmbed/ble-nrf51822/pull/81) ([andresag01](https://github.com/andresag01))
+
+## [v2.1.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.1) (2015-12-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.1.0...v2.1.1)
+
+**Merged pull requests:**
+
+- Fixed endianness bug in nRF5xServiceDiscovery::processDiscoverUUIDResponse so it is consistent with BLE API. [\#80](https://github.com/ARMmbed/ble-nrf51822/pull/80) ([marcuschangarm](https://github.com/marcuschangarm))
+- Fixed bug in nRF5xGap.setAddress where random adresses where not set properly. [\#79](https://github.com/ARMmbed/ble-nrf51822/pull/79) ([marcuschangarm](https://github.com/marcuschangarm))
+- Separate concept of minlen and len for BLE chars [\#78](https://github.com/ARMmbed/ble-nrf51822/pull/78) ([andresag01](https://github.com/andresag01))
+- Split nordic sdk into its own module [\#75](https://github.com/ARMmbed/ble-nrf51822/pull/75) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.1.0) (2015-11-27)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.8...v2.1.0)
+
+**Merged pull requests:**
+
+- Update to sdk 8.1 [\#77](https://github.com/ARMmbed/ble-nrf51822/pull/77) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.0.8](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.8) (2015-11-26)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.7...v2.0.8)
+
+## [v2.0.7](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.7) (2015-11-26)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.6...v2.0.7)
+
+**Closed issues:**
+
+- test2000 [\#72](https://github.com/ARMmbed/ble-nrf51822/issues/72)
+- test1000000 [\#71](https://github.com/ARMmbed/ble-nrf51822/issues/71)
+- test4 [\#70](https://github.com/ARMmbed/ble-nrf51822/issues/70)
+- test3 [\#69](https://github.com/ARMmbed/ble-nrf51822/issues/69)
+- test2 [\#68](https://github.com/ARMmbed/ble-nrf51822/issues/68)
+
+**Merged pull requests:**
+
+- use Extern c around \#include to use nordic sdk headers implemented in C [\#73](https://github.com/ARMmbed/ble-nrf51822/pull/73) ([LiyouZhou](https://github.com/LiyouZhou))
+
+## [v2.0.6](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.6) (2015-11-17)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.5...v2.0.6)
+
+**Closed issues:**
+
+- test [\#66](https://github.com/ARMmbed/ble-nrf51822/issues/66)
+
+**Merged pull requests:**
+
+- add Nordic's license agreement. [\#67](https://github.com/ARMmbed/ble-nrf51822/pull/67) ([rgrover](https://github.com/rgrover))
+
+## [v2.0.5](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.5) (2015-11-16)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.4...v2.0.5)
+
+**Merged pull requests:**
+
+- Post radio notification callback through minar [\#65](https://github.com/ARMmbed/ble-nrf51822/pull/65) ([andresag01](https://github.com/andresag01))
+
+## [v2.0.4](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.4) (2015-11-13)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.3...v2.0.4)
+
+**Merged pull requests:**
+
+- Fix assembly sequence to start bootloader in GCC [\#64](https://github.com/ARMmbed/ble-nrf51822/pull/64) ([andresag01](https://github.com/andresag01))
+
+## [v2.0.3](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.3) (2015-11-09)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.2...v2.0.3)
+
+**Merged pull requests:**
+
+- Added watchdog header file from Nordic SDK 8.1 [\#62](https://github.com/ARMmbed/ble-nrf51822/pull/62) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v2.0.2](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.2) (2015-11-03)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-release-15-11...v2.0.2)
+
+## [mbedos-release-15-11](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-release-15-11) (2015-11-03)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.1...mbedos-release-15-11)
+
+## [v2.0.1](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.1) (2015-11-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v2.0.0...v2.0.1)
+
+**Merged pull requests:**
+
+- Ensure that the initialization flags is set to false if the BLE stack is shutdown properly. [\#58](https://github.com/ARMmbed/ble-nrf51822/pull/58) ([pan-](https://github.com/pan-))
+
+## [v2.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v2.0.0) (2015-11-02)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.1.0...v2.0.0)
+
+**Closed issues:**
+
+- Nordic SDK and SoftDevice [\#57](https://github.com/ARMmbed/ble-nrf51822/issues/57)
+- shouldn't eab6631cb be merged into master? [\#54](https://github.com/ARMmbed/ble-nrf51822/issues/54)
+
+**Merged pull requests:**
+
+- Introduced changes for memory savings [\#55](https://github.com/ARMmbed/ble-nrf51822/pull/55) ([andresag01](https://github.com/andresag01))
+
+## [v1.1.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.1.0) (2015-10-28)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v1.0.0...v1.1.0)
+
+**Closed issues:**
+
+- target dependencies in module.json [\#50](https://github.com/ARMmbed/ble-nrf51822/issues/50)
+
+**Merged pull requests:**
+
+- When connecting, if no scanning parameters are passed, use values from Gap parent. [\#53](https://github.com/ARMmbed/ble-nrf51822/pull/53) ([marcuschangarm](https://github.com/marcuschangarm))
+
+## [v1.0.0](https://github.com/ARMmbed/ble-nrf51822/tree/v1.0.0) (2015-10-19)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/mbedos-techcon-oob2...v1.0.0)
+
+## [mbedos-techcon-oob2](https://github.com/ARMmbed/ble-nrf51822/tree/mbedos-techcon-oob2) (2015-10-19)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.8...mbedos-techcon-oob2)
+
+**Closed issues:**
+
+- rename the bootloader files with \_fota in the name? [\#51](https://github.com/ARMmbed/ble-nrf51822/issues/51)
+
+**Merged pull requests:**
+
+- Update S110 detection macros, again [\#49](https://github.com/ARMmbed/ble-nrf51822/pull/49) ([jpbrucker](https://github.com/jpbrucker))
+- Error check number of characteristics [\#48](https://github.com/ARMmbed/ble-nrf51822/pull/48) ([Timmmm](https://github.com/Timmmm))
+
+## [v0.4.8](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.8) (2015-09-25)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.7...v0.4.8)
+
+**Closed issues:**
+
+- Error real cause loss in nRF5xGattServer.cpp [\#44](https://github.com/ARMmbed/ble-nrf51822/issues/44)
+
+**Merged pull requests:**
+
+- rgrover patch fixed [\#47](https://github.com/ARMmbed/ble-nrf51822/pull/47) ([fabiencomte](https://github.com/fabiencomte))
+- Update S110 detection macros [\#43](https://github.com/ARMmbed/ble-nrf51822/pull/43) ([jpbrucker](https://github.com/jpbrucker))
+- remove some unnecessary include paths [\#42](https://github.com/ARMmbed/ble-nrf51822/pull/42) ([autopulated](https://github.com/autopulated))
+- Add FOTA bootloader image [\#41](https://github.com/ARMmbed/ble-nrf51822/pull/41) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.7](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.7) (2015-08-13)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.6...v0.4.7)
+
+## [v0.4.6](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.6) (2015-08-11)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.5...v0.4.6)
+
+**Closed issues:**
+
+- remove duplication of global static variable BLE\_EVT\_BUFFER [\#39](https://github.com/ARMmbed/ble-nrf51822/issues/39)
+- clearScanResponse\(\)  [\#30](https://github.com/ARMmbed/ble-nrf51822/issues/30)
+- Debug builds fail due to missing bsp.h [\#11](https://github.com/ARMmbed/ble-nrf51822/issues/11)
+
+**Merged pull requests:**
+
+- Disable GattClient features when using S110 SoftDevice [\#38](https://github.com/ARMmbed/ble-nrf51822/pull/38) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.5](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.5) (2015-08-10)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.4...v0.4.5)
+
+## [v0.4.4](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.4) (2015-08-07)
+[Full Changelog](https://github.com/ARMmbed/ble-nrf51822/compare/v0.4.3...v0.4.4)
+
+**Closed issues:**
+
+- nrf51822 hangs after calling sd\_flash\_page\_erase\(\) [\#35](https://github.com/ARMmbed/ble-nrf51822/issues/35)
+- nRF5xn::getVersion return \(Unknown\) with version 8 soft device [\#29](https://github.com/ARMmbed/ble-nrf51822/issues/29)
+
+**Merged pull requests:**
+
+- Changed Gap:: to GapAdvertisingParams:: because of change in BLE [\#34](https://github.com/ARMmbed/ble-nrf51822/pull/34) ([jslater8](https://github.com/jslater8))
+- Select the clock source dynamically on SoftDevice initialisation [\#32](https://github.com/ARMmbed/ble-nrf51822/pull/32) ([jpbrucker](https://github.com/jpbrucker))
+- Add S110 SoftDevice compatibility [\#28](https://github.com/ARMmbed/ble-nrf51822/pull/28) ([jpbrucker](https://github.com/jpbrucker))
+
+## [v0.4.3](https://github.com/ARMmbed/ble-nrf51822/tree/v0.4.3) (2015-07-22)
+**Closed issues:**
+
+- Target polling failed [\#24](https://github.com/ARMmbed/ble-nrf51822/issues/24)
+- support  handling of HVX Events \(notifications and indications\). [\#22](https://github.com/ARMmbed/ble-nrf51822/issues/22)
+- provide an implementation for GattServer::areUpdatesEnabled\(\) [\#21](https://github.com/ARMmbed/ble-nrf51822/issues/21)
+- getValueHandle\(\) returns characteristicIndex instead of attribute-handle [\#20](https://github.com/ARMmbed/ble-nrf51822/issues/20)
+- Clash With Definition And Enum Naming [\#16](https://github.com/ARMmbed/ble-nrf51822/issues/16)
+- Errors in GCC build [\#14](https://github.com/ARMmbed/ble-nrf51822/issues/14)
+- bring s110 support back [\#10](https://github.com/ARMmbed/ble-nrf51822/issues/10)
+- Allow adding a User Description descriptor to a GattCharacteristic. [\#9](https://github.com/ARMmbed/ble-nrf51822/issues/9)
+- device\_manager\_peripheral.c includes app\_trace.h [\#7](https://github.com/ARMmbed/ble-nrf51822/issues/7)
+- linking esb\_gcc.a \(nrf51822 enhanced shock burst\) with mbed [\#5](https://github.com/ARMmbed/ble-nrf51822/issues/5)
+- The app\_timer usage may conflict [\#2](https://github.com/ARMmbed/ble-nrf51822/issues/2)
+- Nordic License [\#1](https://github.com/ARMmbed/ble-nrf51822/issues/1)
+
+**Merged pull requests:**
+
+- Develop [\#25](https://github.com/ARMmbed/ble-nrf51822/pull/25) ([zoujixing](https://github.com/zoujixing))
+- Remove unnecessary 'compiler\_abstraction.h' to get rid of duplicate '… [\#23](https://github.com/ARMmbed/ble-nrf51822/pull/23) ([adfernandes](https://github.com/adfernandes))
+- restructure for minimal yotta compatibility [\#15](https://github.com/ARMmbed/ble-nrf51822/pull/15) ([autopulated](https://github.com/autopulated))
+- Fix various GCC compilation issues. [\#12](https://github.com/ARMmbed/ble-nrf51822/pull/12) ([adfernandes](https://github.com/adfernandes))
+- Fix for GCC lost in SDK v8.0 update [\#8](https://github.com/ARMmbed/ble-nrf51822/pull/8) ([rosterloh](https://github.com/rosterloh))
+- new target DELTA\_DFCM\_NNN40 with nrf51822 chip, config internal RC crystal. [\#6](https://github.com/ARMmbed/ble-nrf51822/pull/6) ([Marcomissyou](https://github.com/Marcomissyou))
+- Updated return value for nRF51GattServer::updateValue. Will now report w... [\#4](https://github.com/ARMmbed/ble-nrf51822/pull/4) ([marcuschangarm](https://github.com/marcuschangarm))
+- Added optional data and length fields to the return struct for authorize... [\#3](https://github.com/ARMmbed/ble-nrf51822/pull/3) ([marcuschangarm](https://github.com/marcuschangarm))
+
+
+
+\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/LICENSE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/LICENSE	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,6 @@
+This module contains softdevice which comes with The Nordic Softdevice License Agreement,
+a BSD-like licence for binary distributions, offered by Nordic for use in mbed. Some
+other files come from the mbed SDK, and are licensed under Apache-2.0. Unless
+specifically indicated otherwise in a file, files are licensed under the
+Apache 2.0 license, as can be found in: apache-2.0.txt. The Nordic Semiconductor Softdevice
+License Agreement can be found in softdevice_nrf51822_licence_agreement.txt.
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/apache-2.0.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/apache-2.0.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,13 @@
+Copyright (c) 2015 ARM Limited
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/module.json
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/module.json	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,36 @@
+{
+  "name": "ble-nrf51822",
+  "version": "2.7.1",
+  "description": "Nordic stack and drivers for the mbed BLE API.",
+  "keywords": [
+    "Bluetooth",
+    "BLE",
+    "mbed",
+    "mbed-official"
+  ],
+  "author": "Rohit Grover",
+  "repository": {
+    "url": "git@github.com:ARMmbed/ble-nRF51822.git",
+    "type": "git"
+  },
+  "homepage": "https://developer.mbed.org/teams/Nordic-Semiconductor/",
+  "licenses": [
+    {
+      "url": "https://spdx.org/licenses/Apache-2.0",
+      "type": "Apache-2.0"
+    },
+    {
+      "type": "LicenseRef-softdevice_nrf51822_licence_agreement.txt"
+    }
+  ],
+  "dependencies": {
+    "ble": "^2.6.0",
+    "nrf51-sdk": "^2.4.0"
+  },
+  "extraIncludes": [
+    "source/btle",
+    "source/btle/custom",
+    "source/common"
+  ],
+  "targetDependencies": {}
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/softdevice_nrf51822_licence_agreement.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/softdevice_nrf51822_licence_agreement.txt	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,30 @@
+/*
+ * S110/S120/S130 License Agreement
+ *
+ * Copyright (c) 2015, Nordic Semiconductor ASA, All rights reserved.
+ *
+ * Redistribution. Redistribution and use in binary form, without modification,
+ * are permitted provided that the following conditions are met:
+ *
+ * • Redistributions must reproduce the above copyright notice and the following
+ *   disclaimer in the documentation and/or other materials provided with the
+ *   distribution.
+ * • Neither the name of the copyright holder nor the names of its contributors
+ *   may be used to endorse or promote products derived from this software
+ *   without specific prior written permission.
+ * • No reverse engineering, decompilation, or disassembly of this software is
+ *   permitted.
+ *
+ * DISCLAIMER.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * /
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,278 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "common/common.h"
+#include "nordic_common.h"
+
+#include "btle.h"
+#include "btle_clock.h"
+
+#include "ble_flash.h"
+#include "ble_conn_params.h"
+
+#include "btle_gap.h"
+#include "btle_advertising.h"
+#include "custom/custom_helper.h"
+
+#include "ble/GapEvents.h"
+#include "nRF5xn.h"
+
+extern "C" {
+#include "pstorage.h"
+#include "device_manager.h"
+#include "softdevice_handler.h"
+#include "ble_stack_handler_types.h"
+}
+
+#include "nrf_ble_hci.h"
+#include "btle_discovery.h"
+
+#include "nRF5xGattClient.h"
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+
+bool isEventsSignaled = false;
+
+extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name);
+void            app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name);
+
+static void btle_handler(ble_evt_t *p_ble_evt);
+
+#if 0
+#define CENTRAL_LINK_COUNT    (YOTTA_CFG_NORDIC_BLE_CENTRAL_LINKS)  /**<number of central links used by the application. When changing this number remember to adjust the RAM settings */
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_PERIPHERAL_LINKS was used, ram settings are adjusted by the yotta target module. */
+#define PERIPHERAL_LINK_COUNT (YOTTA_CFG_NORDIC_BLE_PERIPHERAL_LINKS)     /**<number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_CENTRAL_LINKS was used, ram settings are adjusted by the yotta target module. */
+#define GATTS_ATTR_TAB_SIZE (YOTTA_CFG_NORDIC_BLE_GATTS_ATTR_TAB_SIZE) /**< GATTS attribite table size. */
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_GATTS_ATTR_TAB_SIZE was used, ram settings are adjusted by the yotta target module. */
+#else
+#define CENTRAL_LINK_COUNT    3  /**<number of central links used by the application. When changing this number remember to adjust the RAM settings */
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_PERIPHERAL_LINKS was used, ram settings are adjusted by the yotta target module. */
+#define PERIPHERAL_LINK_COUNT 1     /**<number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_CENTRAL_LINKS was used, ram settings are adjusted by the yotta target module. */
+#define GATTS_ATTR_TAB_SIZE 0x600 /**< GATTS attribite table size. */
+                                                                       /** If value for YOTTA_CFG_NORDIC_BLE_GATTS_ATTR_TAB_SIZE was used, ram settings are adjusted by the yotta target module. */
+
+#endif
+
+static void sys_evt_dispatch(uint32_t sys_evt)
+{
+    pstorage_sys_event_handler(sys_evt);
+}
+
+/**
+ * This function is called in interrupt context to handle BLE events; i.e. pull
+ * system and user events out of the pending events-queue of the BLE stack. The
+ * BLE stack signals the availability of events by the triggering the SWI2
+ * interrupt, which forwards the handling to this function.
+ *
+ * The event processing loop is implemented in intern_softdevice_events_execute().
+ *
+ * This function will signal to the user code by calling signalEventsToProcess
+ * that their is events to process and BLE::processEvents should be called.
+ */
+static uint32_t signalEvent()
+{
+    if(isEventsSignaled == false) {
+        isEventsSignaled = true;
+        nRF5xn::Instance(BLE::DEFAULT_INSTANCE).signalEventsToProcess(BLE::DEFAULT_INSTANCE);
+    }
+    return NRF_SUCCESS;
+}
+
+error_t btle_init(void)
+{
+    nrf_clock_lf_cfg_t clockConfiguration;
+
+    // Configure the LF clock according to values provided by btle_clock.h.
+    // It is input from the chain of the yotta configuration system.
+    clockConfiguration.source        = LFCLK_CONF_SOURCE;
+    clockConfiguration.xtal_accuracy = LFCLK_CONF_ACCURACY;
+    clockConfiguration.rc_ctiv       = LFCLK_CONF_RC_CTIV;
+    clockConfiguration.rc_temp_ctiv  = LFCLK_CONF_RC_TEMP_CTIV;
+
+    SOFTDEVICE_HANDLER_INIT(&clockConfiguration, signalEvent);
+
+    // Enable BLE stack
+    /**
+     * Using this call, the application can select whether to include the
+     * Service Changed characteristic in the GATT Server. The default in all
+     * previous releases has been to include the Service Changed characteristic,
+     * but this affects how GATT clients behave. Specifically, it requires
+     * clients to subscribe to this attribute and not to cache attribute handles
+     * between connections unless the devices are bonded. If the application
+     * does not need to change the structure of the GATT server attributes at
+     * runtime this adds unnecessary complexity to the interaction with peer
+     * clients. If the SoftDevice is enabled with the Service Changed
+     * Characteristics turned off, then clients are allowed to cache attribute
+     * handles making applications simpler on both sides.
+     */
+    static const bool IS_SRVC_CHANGED_CHARACT_PRESENT = true;
+
+    ble_enable_params_t ble_enable_params;
+    uint32_t err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT,
+                                                    PERIPHERAL_LINK_COUNT,
+                                                    &ble_enable_params);
+
+    ble_enable_params.gatts_enable_params.attr_tab_size  = GATTS_ATTR_TAB_SIZE;
+    ble_enable_params.gatts_enable_params.service_changed  = IS_SRVC_CHANGED_CHARACT_PRESENT;
+    ble_enable_params.common_enable_params.vs_uuid_count = UUID_TABLE_MAX_ENTRIES;
+
+    if(err_code  != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+
+    if (softdevice_enable(&ble_enable_params) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+
+    ble_gap_addr_t addr;
+    if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+    if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) {
+        return ERROR_INVALID_PARAM;
+    }
+
+    ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler));
+    ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch));
+
+    return btle_gap_init();
+}
+
+static void btle_handler(ble_evt_t *p_ble_evt)
+{
+    /* Library service handlers */
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+    ble_conn_params_on_ble_evt(p_ble_evt);
+#endif
+
+    dm_ble_evt_handler(p_ble_evt);
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    bleGattcEventHandler(p_ble_evt);
+#endif
+
+    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xGap             &gap             = (nRF5xGap &) ble.getGap();
+    nRF5xGattServer      &gattServer      = (nRF5xGattServer &) ble.getGattServer();
+    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
+
+    /* Custom event handler */
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GAP_EVT_CONNECTED: {
+            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
+#if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110)
+            /* Only peripheral role is supported by S110 */
+            Gap::Role_t role = Gap::PERIPHERAL;
+#else
+            Gap::Role_t role = static_cast<Gap::Role_t>(p_ble_evt->evt.gap_evt.params.connected.role);
+#endif
+            gap.setConnectionHandle(handle);
+            const Gap::ConnectionParams_t *params = reinterpret_cast<Gap::ConnectionParams_t *>(&(p_ble_evt->evt.gap_evt.params.connected.conn_params));
+            const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr;
+            const ble_gap_addr_t *own  = &p_ble_evt->evt.gap_evt.params.connected.own_addr;
+            gap.processConnectionEvent(handle,
+                                                           role,
+                                                           static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr,
+                                                           static_cast<BLEProtocol::AddressType_t>(own->addr_type),  own->addr,
+                                                           params);
+            break;
+        }
+
+        case BLE_GAP_EVT_DISCONNECTED: {
+            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
+            // Since we are not in a connection and have not started advertising,
+            // store bonds
+            gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID);
+
+            Gap::DisconnectionReason_t reason;
+            switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) {
+                case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION:
+                    reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION;
+                    break;
+                case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION:
+                    reason = Gap::REMOTE_USER_TERMINATED_CONNECTION;
+                    break;
+                case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE:
+                    reason = Gap::CONN_INTERVAL_UNACCEPTABLE;
+                    break;
+                default:
+                    /* Please refer to the underlying transport library for an
+                     * interpretion of this reason's value. */
+                    reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason);
+                    break;
+            }
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+            // Close all pending discoveries for this connection
+            nRF5xGattClient& gattClient = ble.getGattClient();
+            gattClient.characteristicDescriptorDiscoverer().terminate(handle, BLE_ERROR_INVALID_STATE);
+            gattClient.discovery().terminate(handle);
+#endif
+
+            gap.processDisconnectionEvent(handle, reason);
+            break;
+        }
+
+        case BLE_GAP_EVT_PASSKEY_DISPLAY:
+            securityManager.processPasskeyDisplayEvent(p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->evt.gap_evt.params.passkey_display.passkey);
+            break;
+
+        case BLE_GAP_EVT_TIMEOUT:
+            gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src));
+            break;
+
+        case BLE_GATTC_EVT_TIMEOUT:
+        case BLE_GATTS_EVT_TIMEOUT:
+            // Disconnect on GATT Server and Client timeout events.
+            // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle,
+            // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION));
+            break;
+
+        case BLE_GAP_EVT_ADV_REPORT: {
+            const ble_gap_evt_adv_report_t *advReport = &p_ble_evt->evt.gap_evt.params.adv_report;
+            gap.processAdvertisementReport(advReport->peer_addr.addr,
+                                           advReport->rssi,
+                                           advReport->scan_rsp,
+                                           static_cast<GapAdvertisingParams::AdvertisingType_t>(advReport->type),
+                                           advReport->dlen,
+                                           advReport->data);
+            break;
+        }
+
+        default:
+            break;
+    }
+
+    gattServer.hwCallback(p_ble_evt);
+}
+
+/*! @brief      Callback when an error occurs inside the SoftDevice */
+void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name)
+{
+    ASSERT(false, (void) 0);
+}
+
+/*!
+    @brief      Handler for general errors above the SoftDevice layer.
+                Typically we can' recover from this so we do a reset.
+*/
+void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name)
+{
+    ASSERT_STATUS_RET_VOID( error_code );
+    NVIC_SystemReset();
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,41 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_H_
+#define _BTLE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "common/common.h"
+
+#include "ble_srv_common.h"
+#include "nrf_ble.h"
+
+error_t     btle_init(void);
+
+// flag indicating if events have been signaled or not
+// It is used by processEvents and signalEventsToProcess
+// signalEventsToProcess raise the flag and processEvents
+// clears it.
+extern bool isEventsSignaled;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ifndef _BTLE_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_advertising.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_advertising.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,46 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "common/common.h"
+
+#include "ble_advdata.h"
+#include "btle.h"
+
+/**************************************************************************/
+/*!
+    @brief      Starts the advertising process
+
+    @returns
+*/
+/**************************************************************************/
+error_t btle_advertising_start(void)
+{
+    ble_gap_adv_params_t adv_para = {0};
+
+    /* Set the default advertising parameters */
+    adv_para.type        = BLE_GAP_ADV_TYPE_ADV_IND;
+    adv_para.p_peer_addr = NULL; /* Undirected advertising */
+    adv_para.fp          = BLE_GAP_ADV_FP_ANY;
+    adv_para.p_whitelist = NULL;
+    adv_para.interval    = (CFG_GAP_ADV_INTERVAL_MS * 8) / 5; /* Advertising
+                                                               * interval in
+                                                               * units of 0.625
+                                                               * ms */
+    adv_para.timeout     = CFG_GAP_ADV_TIMEOUT_S;
+
+    ASSERT_STATUS( sd_ble_gap_adv_start(&adv_para));
+
+    return ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_advertising.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_advertising.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,24 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_ADVERTISING_H_
+#define _BTLE_ADVERTISING_H_
+
+#include "common/common.h"
+
+error_t btle_advertising_start(void);
+
+#endif // ifndef _BTLE_ADVERTISING_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_clock.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_clock.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,133 @@
+/* 
+ * Copyright (c) 2016 Nordic Semiconductor ASA
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * 
+ *   1. Redistributions of source code must retain the above copyright notice, this list 
+ *      of conditions and the following disclaimer.
+ *
+ *   2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA 
+ *      integrated circuit in a product or a software update for such product, must reproduce 
+ *      the above copyright notice, this list of conditions and the following disclaimer in 
+ *      the documentation and/or other materials provided with the distribution.
+ *
+ *   3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be 
+ *      used to endorse or promote products derived from this software without specific prior 
+ *      written permission.
+ *
+ *   4. This software, with or without modification, must only be used with a 
+ *      Nordic Semiconductor ASA integrated circuit.
+ *
+ *   5. Any software provided in binary or object form under this license must not be reverse 
+ *      engineered, decompiled, modified and/or disassembled. 
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+#ifndef _BTLE_CLOCK_H_
+#define _BTLE_CLOCK_H_
+
+#include "nrf5x_lf_clk_helper.h"
+
+/**
+ * @brief Module that generates settings for the low-frequency (LF) clock configuration.
+ *
+ * This module provides macros that are generated from the mbed config system macros.
+ *
+ *
+ *
+ * As a result, this module provides the following: @n
+ * - literal value LFCLK_CONF_SOURCE @n
+ * - literal value LFCLK_CONF_ACCURACY @n
+ * - literal value LFCLK_CONF_RC_CTIV @n
+ * - literal value LFCLK_CONF_RC_TEMP_CTIV
+ */
+
+
+
+#include "nrf_sdm.h"
+
+#define DEFAULT_LFCLK_CONF_ACCURACY NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM
+
+#ifdef NRF52
+    #define MAX_LFCLK_CONF_RC_CTIV    32
+#else
+    #define MAX_LFCLK_CONF_RC_CTIV    64
+#endif
+
+#define MAX_LFCLK_CONF_RC_TEMP_CTIV   33
+
+#define DEFAULT_LFCLK_CONF_RC_CTIV 16     // Check temperature every 16 * 250ms.
+#define DEFAULT_LFCLK_CONF_RC_TEMP_CTIV 1 // Only calibrate if temperature has changed.
+
+#define NRF_LF_SRC_XTAL  2 
+#define NRF_LF_SRC_SYNTH 3 
+#define NRF_LF_SRC_RC    4
+
+#if MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC == NRF_LF_SRC_RC
+    #define LFCLK_CONF_SOURCE       NRF_CLOCK_LF_SRC_RC
+    
+    #ifdef MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_TIMER_INTERVAL
+        #define LFCLK_CONF_RC_CTIV MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_TIMER_INTERVAL
+    #else
+        #define LFCLK_CONF_RC_CTIV DEFAULT_LFCLK_CONF_RC_CTIV
+    #endif
+    
+    #ifdef MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_MODE_CONFIG
+        #define LFCLK_CONF_RC_TEMP_CTIV MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_MODE_CONFIG
+    #else
+        #define LFCLK_CONF_RC_TEMP_CTIV DEFAULT_LFCLK_CONF_RC_TEMP_CTIV
+    #endif
+    
+    #if (LFCLK_CONF_RC_CTIV < 1) || (LFCLK_CONF_RC_CTIV > MAX_LFCLK_CONF_RC_CTIV)
+        #error Calibration timer interval out of range!
+    #endif
+    
+    #if (LFCLK_CONF_RC_TEMP_CTIV < 0 ) || (LFCLK_CONF_RC_TEMP_CTIV > 33)
+        #error Number/mode of LF RC calibration intervals out of range!
+    #endif
+    
+#elif MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC == NRF_LF_SRC_SYNTH
+    #define LFCLK_CONF_SOURCE       NRF_CLOCK_LF_SRC_SYNTH
+    #define LFCLK_CONF_RC_CTIV      0 // Must be 0 if source is not NRF_CLOCK_LF_SRC_RC.
+    #define LFCLK_CONF_RC_TEMP_CTIV 0 // Must be 0 if source is not NRF_CLOCK_LF_SRC_RC.
+    
+    #ifdef MBED_CONF_NORDIC_LF_CLOCK_HF_SYNTH_ACCURACY
+        #define LFCLK_CONF_ACCURACY MBED_CONF_NORDIC_LF_CLOCK_HF_SYNTH_ACCURACY
+    #endif
+    
+#else //  default is NRF_LF_SRC_SYNTH
+    #define LFCLK_CONF_SOURCE NRF_CLOCK_LF_SRC_XTAL
+    #define LFCLK_CONF_RC_CTIV      0 // Must be 0 if source is not NRF_CLOCK_LF_SRC_RC.
+    #define LFCLK_CONF_RC_TEMP_CTIV 0 // Must be 0 if source is not NRF_CLOCK_LF_SRC_RC.
+    
+    #ifdef MBED_CONF_NORDIC_LF_CLOCK_XTAL_ACCURACY
+        #define LFCLK_CONF_ACCURACY MBED_CONF_NORDIC_LF_CLOCK_XTAL_ACCURACY
+    #endif
+
+#endif
+
+#ifndef LFCLK_CONF_ACCURACY
+    #define LFCLK_CONF_ACCURACY DEFAULT_LFCLK_CONF_ACCURACY
+#endif
+
+#if (LFCLK_CONF_ACCURACY > NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM) || (LFCLK_CONF_ACCURACY < NRF_CLOCK_LF_XTAL_ACCURACY_250_PPM)
+    #error Low frequency clock accuracy out of range!
+#endif
+
+
+#endif //_BTLE_CLOCK_H_
+
+
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_discovery.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_discovery.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,147 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+#include "nRF5xGattClient.h"
+#include "nRF5xn.h"
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+void bleGattcEventHandler(const ble_evt_t *p_ble_evt)
+{
+    nRF5xn                &ble         = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xGap              &gap         = (nRF5xGap &) ble.getGap();
+    nRF5xGattClient       &gattClient  = (nRF5xGattClient &) ble.getGattClient();
+    nRF5xServiceDiscovery &sdSingleton = gattClient.discovery();
+    nRF5xCharacteristicDescriptorDiscoverer &characteristicDescriptorDiscoverer =
+        gattClient.characteristicDescriptorDiscoverer();
+
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
+            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    sdSingleton.setupDiscoveredServices(&p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp);
+                    break;
+
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                default:
+                    sdSingleton.terminate();
+                    break;
+            }
+            break;
+
+        case BLE_GATTC_EVT_CHAR_DISC_RSP:
+            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    sdSingleton.setupDiscoveredCharacteristics(&p_ble_evt->evt.gattc_evt.params.char_disc_rsp);
+                    break;
+
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                default:
+                    sdSingleton.terminateCharacteristicDiscovery(BLE_ERROR_NONE);
+                    break;
+            }
+            break;
+
+        case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP:
+            if (sdSingleton.isActive()) {
+                sdSingleton.processDiscoverUUIDResponse(&p_ble_evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp);
+            }
+            break;
+
+        case BLE_GATTC_EVT_READ_RSP: {
+                GattReadCallbackParams response = {
+                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
+                    .handle     = p_ble_evt->evt.gattc_evt.params.read_rsp.handle,
+                    .offset     = p_ble_evt->evt.gattc_evt.params.read_rsp.offset,
+                    .len        = p_ble_evt->evt.gattc_evt.params.read_rsp.len,
+                    .data       = p_ble_evt->evt.gattc_evt.params.read_rsp.data,
+                };
+                gattClient.processReadResponse(&response);
+            }
+            break;
+
+        case BLE_GATTC_EVT_WRITE_RSP: {
+                GattWriteCallbackParams response = {
+                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
+                    .handle     = p_ble_evt->evt.gattc_evt.params.write_rsp.handle,
+                    .writeOp    = (GattWriteCallbackParams::WriteOp_t)(p_ble_evt->evt.gattc_evt.params.write_rsp.write_op),
+                    .offset     = p_ble_evt->evt.gattc_evt.params.write_rsp.offset,
+                    .len        = p_ble_evt->evt.gattc_evt.params.write_rsp.len,
+                    .data       = p_ble_evt->evt.gattc_evt.params.write_rsp.data,
+                };
+                gattClient.processWriteResponse(&response);
+            }
+            break;
+
+        case BLE_GATTC_EVT_HVX: {
+                GattHVXCallbackParams params;
+                params.connHandle = p_ble_evt->evt.gattc_evt.conn_handle;
+                params.handle     = p_ble_evt->evt.gattc_evt.params.hvx.handle;
+                params.type       = static_cast<HVXType_t>(p_ble_evt->evt.gattc_evt.params.hvx.type);
+                params.len        = p_ble_evt->evt.gattc_evt.params.hvx.len;
+                params.data       = p_ble_evt->evt.gattc_evt.params.hvx.data;
+
+                gattClient.processHVXEvent(&params);
+            }
+            break;
+
+        case BLE_GATTC_EVT_DESC_DISC_RSP: {
+            uint16_t conn_handle = p_ble_evt->evt.gattc_evt.conn_handle;
+            uint16_t status = p_ble_evt->evt.gattc_evt.gatt_status;
+            const ble_gattc_evt_desc_disc_rsp_t& discovered_descriptors = p_ble_evt->evt.gattc_evt.params.desc_disc_rsp;
+
+            switch(status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    characteristicDescriptorDiscoverer.process(
+                        conn_handle,
+                        discovered_descriptors
+                    );
+                    break;
+                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
+                    // end of discovery
+                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_NONE);
+                    break;
+                default:
+                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_UNSPECIFIED);
+                    break;
+            }
+        }   break;
+
+        case BLE_GATTC_EVT_ATTR_INFO_DISC_RSP : {
+            uint16_t conn_handle = p_ble_evt->evt.gattc_evt.conn_handle;
+            uint16_t status = p_ble_evt->evt.gattc_evt.gatt_status;
+            const ble_gattc_evt_attr_info_disc_rsp_t& infos = p_ble_evt->evt.gattc_evt.params.attr_info_disc_rsp;
+
+            switch(status) {
+                case BLE_GATT_STATUS_SUCCESS:
+                    characteristicDescriptorDiscoverer.processAttributeInformation(
+                        conn_handle,
+                        infos
+                    );
+                    break;
+                default:
+                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_UNSPECIFIED);
+                    break;
+            }
+
+        } break;
+    }
+
+    sdSingleton.progressCharacteristicDiscovery();
+    sdSingleton.progressServiceDiscovery();
+}
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_discovery.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_discovery.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,22 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_DISCOVERY_H_
+#define _BTLE_DISCOVERY_H_
+
+void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
+
+#endif /*_BTLE_DISCOVERY_H_*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_gap.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_gap.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,99 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "common/common.h"
+
+#include "nrf_ble_gap.h"
+#include "ble_conn_params.h"
+
+static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) ATTR_ALWAYS_INLINE ATTR_CONST;
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+static void   error_callback(uint32_t nrf_error);
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
+
+/**************************************************************************/
+/*!
+    @brief      Initialise GAP in the underlying SoftDevice
+
+    @returns
+*/
+/**************************************************************************/
+error_t btle_gap_init(void)
+{
+    ble_gap_conn_params_t gap_conn_params = {0};
+
+    gap_conn_params.min_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MIN_INTERVAL_MS);  // in 1.25ms units
+    gap_conn_params.max_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MAX_INTERVAL_MS);  // in 1.25ms unit
+    gap_conn_params.slave_latency     = CFG_GAP_CONNECTION_SLAVE_LATENCY;
+    gap_conn_params.conn_sup_timeout  = CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS / 10; // in 10ms unit
+
+    ble_gap_conn_sec_mode_t sec_mode;
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
+
+    ASSERT_STATUS( sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *) CFG_GAP_LOCAL_NAME, strlen(CFG_GAP_LOCAL_NAME)));
+    ASSERT_STATUS( sd_ble_gap_appearance_set(CFG_GAP_APPEARANCE));
+    ASSERT_STATUS( sd_ble_gap_ppcp_set(&gap_conn_params));
+    ASSERT_STATUS( sd_ble_gap_tx_power_set(CFG_BLE_TX_POWER_LEVEL));
+
+    /**
+     * Call to conn_params_init() is not necessary; and so is disabled by default.
+     * This API should be exposed to the user to be invoked when necessary.
+     */
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+    /* Connection Parameters */
+    enum {
+        FIRST_UPDATE_DELAY = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
+        NEXT_UPDATE_DELAY  = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
+        MAX_UPDATE_COUNT   = 3
+    };
+
+    ble_conn_params_init_t cp_init = {0};
+
+    cp_init.p_conn_params                  = NULL;
+    cp_init.first_conn_params_update_delay = FIRST_UPDATE_DELAY;
+    cp_init.next_conn_params_update_delay  = NEXT_UPDATE_DELAY;
+    cp_init.max_conn_params_update_count   = MAX_UPDATE_COUNT;
+    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
+    cp_init.disconnect_on_fail             = true;
+    cp_init.evt_handler                    = NULL;
+    cp_init.error_handler                  = error_callback;
+
+    ASSERT_STATUS ( ble_conn_params_init(&cp_init));
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
+
+    return ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Converts msecs to an integer representing 1.25ms units
+
+    @param[in]  ms
+                The number of milliseconds to conver to 1.25ms units
+
+    @returns    The number of 1.25ms units in the supplied number of ms
+*/
+/**************************************************************************/
+static inline uint32_t msec_to_1_25msec(uint32_t interval_ms)
+{
+    return (interval_ms * 4) / 5;
+}
+
+#if SDK_CONN_PARAMS_MODULE_ENABLE
+static void error_callback(uint32_t nrf_error)
+{
+    ASSERT_STATUS_RET_VOID( nrf_error );
+}
+#endif // SDK_CONN_PARAMS_MODULE_ENABLE
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_gap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_gap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,24 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_GAP_H_
+#define _BTLE_GAP_H_
+
+#include "common/common.h"
+
+error_t btle_gap_init(void);
+
+#endif // ifndef _BTLE_GAP_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_security.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_security.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,325 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "btle.h"
+
+#include "nRF5xn.h"
+
+extern "C" {
+#include "pstorage.h"
+#include "device_manager.h"
+#include "id_manager.h"
+}
+
+#include "btle_security.h"
+
+static dm_application_instance_t applicationInstance;
+static bool                      initialized = false;
+static ret_code_t dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result);
+
+// default security parameters. Avoid "holes" between member assigments in order to compile by gcc++11.
+static ble_gap_sec_params_t securityParameters = {
+    .bond          = true,         /**< Perform bonding. */
+    .mitm          = true,         /**< Man In The Middle protection required. */
+    .lesc          = false,        /**< Enable LE Secure Connection pairing. */
+    .keypress      = false,        /**< Enable generation of keypress notifications. */
+    .io_caps       = SecurityManager::IO_CAPS_NONE, /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */
+    .oob           = 0,            /**< Out Of Band data available. */
+    .min_key_size  = 16,           /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */
+    .max_key_size  = 16,           /**< Maximum encryption key size in octets between min_key_size and 16. */
+    .kdist_own  = {
+      .enc  = 0,                   /**< Long Term Key and Master Identification. */
+      .id   = 0,                   /**< Identity Resolving Key and Identity Address Information. */
+      .sign = 0,                   /**< Connection Signature Resolving Key. */
+      .link = 0                    /**< Derive the Link Key from the LTK. */
+    },                             /**< Key distribution bitmap: keys that the local device will distribute. */
+    .kdist_peer  = {
+      .enc  = 1,                   /**< Long Term Key and Master Identification. */
+      .id   = 1,                   /**< Identity Resolving Key and Identity Address Information. */
+      .sign = 1,                   /**< Connection Signature Resolving Key. */
+      .link = 0                    /**< Derive the Link Key from the LTK. */
+    }                              /**< Key distribution bitmap: keys that the peripheral device will distribute. */
+};
+
+bool
+btle_hasInitializedSecurity(void)
+{
+    return initialized;
+}
+
+ble_error_t
+btle_initializeSecurity(bool                                      enableBonding,
+                        bool                                      requireMITM,
+                        SecurityManager::SecurityIOCapabilities_t iocaps,
+                        const SecurityManager::Passkey_t          passkey)
+{
+    /* guard against multiple initializations */
+    if (initialized) {
+        return BLE_ERROR_NONE;
+    }
+
+    if (pstorage_init() != NRF_SUCCESS) {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+    ret_code_t rc;
+    if (passkey) {
+        ble_opt_t opts;
+        opts.gap_opt.passkey.p_passkey = const_cast<uint8_t *>(passkey);
+        if ((rc = sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opts)) != NRF_SUCCESS) {
+            switch (rc) {
+                case BLE_ERROR_INVALID_CONN_HANDLE:
+                case NRF_ERROR_INVALID_ADDR:
+                case NRF_ERROR_INVALID_PARAM:
+                default:
+                    return BLE_ERROR_INVALID_PARAM;
+                case NRF_ERROR_INVALID_STATE:
+                    return BLE_ERROR_INVALID_STATE;
+                case NRF_ERROR_BUSY:
+                    return BLE_STACK_BUSY;
+            }
+        }
+    }
+
+    dm_init_param_t dm_init_param = {
+        .clear_persistent_data = false /* Set to true in case the module should clear all persistent data. */
+    };
+    if (dm_init(&dm_init_param) != NRF_SUCCESS) {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+    // update default security parameters with function call parameters
+    securityParameters.bond = enableBonding;
+    securityParameters.mitm = requireMITM;
+    securityParameters.io_caps = iocaps;
+
+    const dm_application_param_t dm_param = {
+        .evt_handler  = dm_handler,
+        .service_type = DM_PROTOCOL_CNTXT_GATT_CLI_ID,
+        .sec_param    = securityParameters
+    };
+
+    if ((rc = dm_register(&applicationInstance, &dm_param)) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_INVALID_STATE:
+                return BLE_ERROR_INVALID_STATE;
+            case NRF_ERROR_NO_MEM:
+                return BLE_ERROR_NO_MEM;
+            default:
+                return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    initialized = true;
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t
+btle_purgeAllBondingState(void)
+{
+    ret_code_t rc;
+    if ((rc = dm_device_delete_all(&applicationInstance)) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+
+    switch (rc) {
+        case NRF_ERROR_INVALID_STATE:
+            return BLE_ERROR_INVALID_STATE;
+        case NRF_ERROR_NO_MEM:
+            return BLE_ERROR_NO_MEM;
+        default:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ble_error_t
+btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP)
+{
+    ret_code_t rc;
+    dm_handle_t dmHandle = {
+        .appl_id = applicationInstance,
+    };
+    if ((rc = dm_handle_get(connectionHandle, &dmHandle)) != NRF_SUCCESS) {
+        if (rc == NRF_ERROR_NOT_FOUND) {
+            return BLE_ERROR_INVALID_PARAM;
+        } else {
+            return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    if ((rc = dm_security_status_req(&dmHandle, reinterpret_cast<dm_security_status_t *>(securityStatusP))) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_INVALID_STATE:
+                return BLE_ERROR_INVALID_STATE;
+            case NRF_ERROR_NO_MEM:
+                return BLE_ERROR_NO_MEM;
+            default:
+                return BLE_ERROR_UNSPECIFIED;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t
+btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode)
+{
+    // use default and updated parameters as starting point
+    // and modify structure based on security mode.
+    ble_gap_sec_params_t params = securityParameters;
+
+    switch (securityMode) {
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK:
+            /**< Require no protection, open link. */
+            securityParameters.bond = false;
+            securityParameters.mitm = false;
+            break;
+
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM:
+            /**< Require encryption, but no MITM protection. */
+            securityParameters.bond = true;
+            securityParameters.mitm = false;
+            break;
+
+        // not yet implemented security modes
+        case SecurityManager::SECURITY_MODE_NO_ACCESS:
+        case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM:
+            /**< Require encryption and MITM protection. */
+        case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM:
+            /**< Require signing or encryption, but no MITM protection. */
+        case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM:
+            /**< Require signing or encryption, and MITM protection. */
+        default:
+            return BLE_ERROR_NOT_IMPLEMENTED;
+    }
+
+    // update security settings for given connection
+    uint32_t result = sd_ble_gap_authenticate(connectionHandle, &params);
+
+    if (result == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ret_code_t
+dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result)
+{
+    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
+
+    switch (p_event->event_id) {
+        case DM_EVT_SECURITY_SETUP: /* started */ {
+            const ble_gap_sec_params_t *peerParams = &p_event->event_param.p_gap_param->params.sec_params_request.peer_params;
+            securityManager.processSecuritySetupInitiatedEvent(p_event->event_param.p_gap_param->conn_handle,
+                                                                                   peerParams->bond,
+                                                                                   peerParams->mitm,
+                                                                                   (SecurityManager::SecurityIOCapabilities_t)peerParams->io_caps);
+            break;
+        }
+        case DM_EVT_SECURITY_SETUP_COMPLETE:
+            securityManager.
+                processSecuritySetupCompletedEvent(p_event->event_param.p_gap_param->conn_handle,
+                                                   (SecurityManager::SecurityCompletionStatus_t)(p_event->event_param.p_gap_param->params.auth_status.auth_status));
+            break;
+        case DM_EVT_LINK_SECURED: {
+            unsigned securityMode                    = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.sm;
+            unsigned level                           = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.lv;
+            SecurityManager::SecurityMode_t resolvedSecurityMode = SecurityManager::SECURITY_MODE_NO_ACCESS;
+            switch (securityMode) {
+                case 1:
+                    switch (level) {
+                        case 1:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK;
+                            break;
+                        case 2:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM;
+                            break;
+                        case 3:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM;
+                            break;
+                    }
+                    break;
+                case 2:
+                    switch (level) {
+                        case 1:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_NO_MITM;
+                            break;
+                        case 2:
+                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM;
+                            break;
+                    }
+                    break;
+            }
+
+            securityManager.processLinkSecuredEvent(p_event->event_param.p_gap_param->conn_handle, resolvedSecurityMode);
+            break;
+        }
+        case DM_EVT_DEVICE_CONTEXT_STORED:
+            securityManager.processSecurityContextStoredEvent(p_event->event_param.p_gap_param->conn_handle);
+            break;
+        default:
+            break;
+    }
+
+    return NRF_SUCCESS;
+}
+
+ble_error_t
+btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist)
+{
+    if (!btle_hasInitializedSecurity()) {
+        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
+    }
+    ret_code_t err = dm_whitelist_create(&applicationInstance, p_whitelist);
+    if (err == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else if (err == NRF_ERROR_NULL) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    } else {
+        return BLE_ERROR_INVALID_STATE;
+    }
+}
+
+
+bool
+btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk)
+{
+    /*
+     * Use a helper function from the Nordic SDK to test whether the BLE
+     * address can be generated using the IRK.
+     */
+    return im_address_resolve(p_addr, p_irk);
+}
+
+void
+btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address)
+{
+    /* Set type to resolvable */
+    address.addr_type = BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
+
+    /*
+     * Assign a random number to the most significant 3 bytes
+     * of the address.
+     */
+    address.addr[BLE_GAP_ADDR_LEN - 3] = 0x8E;
+    address.addr[BLE_GAP_ADDR_LEN - 2] = 0x4F;
+    address.addr[BLE_GAP_ADDR_LEN - 1] = 0x7C;
+
+    /* Calculate the hash and store it in the top half of the address */
+    ah(irk.irk, &address.addr[BLE_GAP_ADDR_LEN - 3], address.addr);
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/btle_security.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/btle_security.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,128 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _BTLE_SECURITY_H_
+#define _BTLE_SECURITY_H_
+
+#include "ble/Gap.h"
+#include "ble/SecurityManager.h"
+
+/**
+ * Function to test whether the SecurityManager has been initialized.
+ * Possible by a call to @ref btle_initializeSecurity().
+ *
+ * @return True if the SecurityManager was previously initialized, false
+ *         otherwise.
+ */
+bool btle_hasInitializedSecurity(void);
+
+/**
+ * Enable Nordic's Device Manager, which brings in functionality from the
+ * stack's Security Manager. The Security Manager implements the actual
+ * cryptographic algorithms and protocol exchanges that allow two devices to
+ * securely exchange data and privately detect each other.
+ *
+ * @param[in]  enableBonding Allow for bonding.
+ * @param[in]  requireMITM   Require protection for man-in-the-middle attacks.
+ * @param[in]  iocaps        To specify IO capabilities of this peripheral,
+ *                           such as availability of a display or keyboard to
+ *                           support out-of-band exchanges of security data.
+ * @param[in]  passkey       To specify a static passkey.
+ *
+ * @return BLE_ERROR_NONE on success.
+ */
+ble_error_t btle_initializeSecurity(bool                                      enableBonding = true,
+                                    bool                                      requireMITM   = true,
+                                    SecurityManager::SecurityIOCapabilities_t iocaps        = SecurityManager::IO_CAPS_NONE,
+                                    const SecurityManager::Passkey_t          passkey       = NULL);
+
+/**
+ * Get the security status of a link.
+ *
+ * @param[in]  connectionHandle
+ *               Handle to identify the connection.
+ * @param[out] securityStatusP
+ *               security status.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP);
+
+/**
+ * Set the security mode on a connection. Useful for elevating the security mode
+ * once certain conditions are met, e.g., a particular service is found.
+ *
+ * @param[in]  connectionHandle
+ *               Handle to identify the connection.
+ * @param[in]  securityMode
+ *               security mode.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode);
+
+/**
+ * Function for deleting all peer device context and all related bonding
+ * information from the database.
+ *
+ * @retval BLE_ERROR_NONE             On success, else an error code indicating reason for failure.
+ * @retval BLE_ERROR_INVALID_STATE    If the API is called without module initialization and/or
+ *                                    application registration.
+ */
+ble_error_t btle_purgeAllBondingState(void);
+
+/**
+ * Query the SoftDevice bond table to extract a whitelist containing the BLE
+ * addresses and IRKs of bonded devices.
+ *
+ * @param[in/out]  p_whitelist
+ *                  (on input) p_whitelist->addr_count and
+ *                  p_whitelist->irk_count specify the maximum number of
+ *                  addresses and IRKs added to the whitelist structure.
+ *                  (on output) *p_whitelist is a whitelist containing the
+ *                  addresses and IRKs of the bonded devices.
+ *
+ * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
+ */
+ble_error_t btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist);
+
+/**
+ * Function to test whether a BLE address is generated using an IRK.
+ *
+ * @param[in]   p_addr
+ *                  Pointer to a BLE address.
+ * @param[in]   p_irk
+ *                  Pointer to an IRK.
+ *
+ * @return True if p_addr can be generated using p_irk, false otherwise.
+ */
+bool btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk);
+
+/**
+ * Function to generate a private resolvable BLE address.
+ *
+ * @param[out]  p_addr
+ *                  The output address.
+ * @param[in]   p_irk
+ *                  A reference to a IRK.
+ *
+ * @note This function does not generate a secure address since the prand number in the
+ *       resolvable address is not truly random. Therefore, the output of this function
+ *       is only meant to be used by the application internally but never exported.
+ */
+void btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address);
+
+#endif /* _BTLE_SECURITY_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/custom/custom_helper.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/custom/custom_helper.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,364 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "custom_helper.h"
+
+/*
+ * The current version of the soft-device doesn't handle duplicate 128-bit UUIDs
+ * very  well. It is therefore necessary to filter away duplicates before
+ * passing long UUIDs to sd_ble_uuid_vs_add(). The following types and data
+ * structures involved in maintaining a local cache of 128-bit UUIDs.
+ */
+typedef struct {
+    UUID::LongUUIDBytes_t uuid;
+    uint8_t         type;
+} converted_uuid_table_entry_t;
+
+static unsigned uuidTableEntries = 0; /* current usage of the table */
+converted_uuid_table_entry_t convertedUUIDTable[UUID_TABLE_MAX_ENTRIES];
+
+void custom_reset_128bits_uuid_table() {
+    uuidTableEntries = 0;
+}
+
+/**
+ * lookup the cache of previously converted 128-bit UUIDs to find a type value.
+ * @param  uuid          base 128-bit UUID
+ * @param  recoveredType the type field of the 3-byte nRF's uuid.
+ * @return               true if a match is found.
+ */
+static bool
+lookupConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t *recoveredType)
+{
+    unsigned i;
+    for (i = 0; i < uuidTableEntries; i++) {
+        unsigned byteIndex;
+        for (byteIndex = 0; byteIndex < UUID::LENGTH_OF_LONG_UUID; byteIndex++) {
+            /* Skip bytes 2 and 3, because they contain the shortUUID (16-bit) version of the
+             * long UUID; and we're comparing against the remainder. */
+            if ((byteIndex == 2) || (byteIndex == 3)) {
+                continue;
+            }
+
+            if (convertedUUIDTable[i].uuid[byteIndex] != uuid[byteIndex]) {
+                break;
+            }
+        }
+
+        if (byteIndex == UUID::LENGTH_OF_LONG_UUID) {
+            *recoveredType = convertedUUIDTable[i].type;
+            return true;
+        }
+    }
+
+    return false;
+}
+
+static void
+addToConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t type)
+{
+    if (uuidTableEntries == UUID_TABLE_MAX_ENTRIES) {
+        return; /* recovery needed; or at least the user should be warned about this fact.*/
+    }
+
+    memcpy(convertedUUIDTable[uuidTableEntries].uuid, uuid, UUID::LENGTH_OF_LONG_UUID);
+    convertedUUIDTable[uuidTableEntries].uuid[2] = 0;
+    convertedUUIDTable[uuidTableEntries].uuid[3] = 0;
+    convertedUUIDTable[uuidTableEntries].type    = type;
+    uuidTableEntries++;
+}
+
+/**
+ * The nRF transport has its own 3-byte representation of a UUID. If the user-
+ * specified UUID is 128-bits wide, then the UUID base needs to be added to the
+ * soft-device and converted to a 3-byte handle before being used further. This
+ * function is responsible for this translation of user-specified UUIDs into
+ * nRF's representation.
+ *
+ * @param[in]  uuid
+ *                 user-specified UUID
+ * @return nRF
+ *              3-byte UUID (containing a type and 16-bit UUID) representation
+ *              to be used with SVC calls.
+ */
+ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid)
+{
+    ble_uuid_t nordicUUID;
+    nordicUUID.uuid = uuid.getShortUUID();
+    nordicUUID.type = BLE_UUID_TYPE_UNKNOWN; /* to be set below */
+
+    if (uuid.shortOrLong() == UUID::UUID_TYPE_SHORT) {
+        nordicUUID.type = BLE_UUID_TYPE_BLE;
+    } else {
+        if (!lookupConvertedUUIDTable(uuid.getBaseUUID(), &nordicUUID.type)) {
+            nordicUUID.type = custom_add_uuid_base(uuid.getBaseUUID());
+            addToConvertedUUIDTable(uuid.getBaseUUID(), nordicUUID.type);
+        }
+    }
+
+    return nordicUUID;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Adds the base UUID to the custom service. All UUIDs used
+                by this service are based on this 128-bit UUID.
+
+    @note       This UUID needs to be added to the SoftDevice stack before
+                adding the service's primary service via
+                'sd_ble_gatts_service_add'
+
+    @param[in]  p_uuid_base   A pointer to the 128-bit UUID array (8*16)
+
+    @returns    The UUID type.
+                A return value of 0 should be considered an error.
+
+    @retval     0x00    BLE_UUID_TYPE_UNKNOWN
+    @retval     0x01    BLE_UUID_TYPE_BLE
+    @retval     0x02    BLE_UUID_TYPE_VENDOR_BEGIN
+
+    @section EXAMPLE
+    @code
+
+    // Take note that bytes 2/3 are blank since these are used to identify
+    // the primary service and individual characteristics
+    #define CFG_CUSTOM_UUID_BASE  "\x6E\x40\x00\x00\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E"
+
+    uint8_t uuid_type = custom_add_uuid_base(CFG_CUSTOM_UUID_BASE);
+    ASSERT(uuid_type > 0, ERROR_NOT_FOUND);
+
+    // We can now safely add the primary service and any characteristics
+    // for our custom service ...
+
+    @endcode
+*/
+/**************************************************************************/
+uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base)
+{
+    ble_uuid128_t base_uuid;
+    uint8_t       uuid_type = 0;
+
+    for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
+        base_uuid.uuid128[i] = p_uuid_base[i];
+    }
+
+    ASSERT_INT( ERROR_NONE, sd_ble_uuid_vs_add( &base_uuid, &uuid_type ), 0);
+
+    return uuid_type;
+}
+
+/**************************************************************************/
+/*!
+
+*/
+/**************************************************************************/
+error_t custom_decode_uuid_base(uint8_t const *const p_uuid_base,
+                                ble_uuid_t          *p_uuid)
+{
+    UUID::LongUUIDBytes_t uuid_base_le;
+
+    for (uint8_t i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
+        uuid_base_le[i] = p_uuid_base[i];
+    }
+
+    ASSERT_STATUS( sd_ble_uuid_decode(UUID::LENGTH_OF_LONG_UUID, uuid_base_le, p_uuid));
+
+    return ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Adds a new characteristic to the custom service, assigning
+                properties, a UUID add-on value, etc.
+
+    @param[in]  service_handle
+    @param[in]  p_uuid            The 16-bit value to add to the base UUID
+                                  for this characteristic (normally >1
+                                  since 1 is typically used by the primary
+                                  service).
+    @param[in]  char_props        The characteristic properties, as
+                                  defined by ble_gatt_char_props_t
+    @param[in]  max_length        The maximum length of this characeristic
+    @param[in]  has_variable_len  Whether the characteristic data has
+                                  variable length.
+    @param[out] p_char_handle
+
+    @returns
+    @retval     ERROR_NONE        Everything executed normally
+*/
+/**************************************************************************/
+error_t custom_add_in_characteristic(uint16_t                  service_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                   properties,
+                                     SecurityManager::SecurityMode_t       requiredSecurity,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     const uint8_t            *userDescriptionDescriptorValuePtr,
+                                     uint16_t                  userDescriptionDescriptorValueLen,
+                                     bool                      readAuthorization,
+                                     bool                      writeAuthorization,
+                                     ble_gatts_char_handles_t *p_char_handle)
+{
+    /* Characteristic metadata */
+    ble_gatts_attr_md_t   cccd_md;
+    ble_gatt_char_props_t char_props;
+
+    memcpy(&char_props, &properties, 1);
+
+    if (char_props.notify || char_props.indicate) {
+        /* Notification requires cccd */
+        memclr_( &cccd_md, sizeof(ble_gatts_attr_md_t));
+        cccd_md.vloc = BLE_GATTS_VLOC_STACK;
+        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
+        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
+    }
+
+    ble_gatts_char_md_t char_md = {0};
+
+    char_md.char_props = char_props;
+    char_md.p_cccd_md  =
+        (char_props.notify || char_props.indicate) ? &cccd_md : NULL;
+    if ((userDescriptionDescriptorValueLen > 0) && (userDescriptionDescriptorValuePtr != NULL)) {
+        char_md.p_char_user_desc        = const_cast<uint8_t *>(userDescriptionDescriptorValuePtr);
+        char_md.char_user_desc_max_size = userDescriptionDescriptorValueLen;
+        char_md.char_user_desc_size     = userDescriptionDescriptorValueLen;
+    }
+
+    /* Attribute declaration */
+    ble_gatts_attr_md_t attr_md = {0};
+
+    attr_md.rd_auth = readAuthorization;
+    attr_md.wr_auth = writeAuthorization;
+
+    attr_md.vloc = BLE_GATTS_VLOC_STACK;
+    /* Always set variable size */
+    attr_md.vlen = has_variable_len;
+
+    if (char_props.read || char_props.notify || char_props.indicate) {
+        switch (requiredSecurity) {
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
+                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.read_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.read_perm);
+                break;
+            default:
+                break;
+        };
+    }
+
+    if (char_props.write || char_props.write_wo_resp) {
+        switch (requiredSecurity) {
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
+                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.write_perm);
+                break;
+            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
+                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.write_perm);
+                break;
+            default:
+                break;
+        };
+    }
+
+    ble_gatts_attr_t attr_char_value = {0};
+
+    attr_char_value.p_uuid    = p_uuid;
+    attr_char_value.p_attr_md = &attr_md;
+    attr_char_value.init_len  = length;
+    attr_char_value.max_len   = max_length;
+    attr_char_value.p_value   = p_data;
+
+    ASSERT_STATUS ( sd_ble_gatts_characteristic_add(service_handle,
+                                                    &char_md,
+                                                    &attr_char_value,
+                                                    p_char_handle));
+
+    return ERROR_NONE;
+}
+
+
+
+/**************************************************************************/
+/*!
+    @brief      Adds a new descriptor to the custom service, assigning
+                value, a UUID add-on value, etc.
+
+    @param[in]  char_handle
+    @param[in]  p_uuid            The 16-bit value to add to the base UUID
+                                  for this descriptor (normally >1
+                                  since 1 is typically used by the primary
+                                  service).
+    @param[in]  max_length        The maximum length of this descriptor
+    @param[in]  has_variable_len  Whether the characteristic data has
+                                  variable length.
+
+    @returns
+    @retval     ERROR_NONE        Everything executed normally
+*/
+/**************************************************************************/
+error_t custom_add_in_descriptor(uint16_t    char_handle,
+                                 ble_uuid_t *p_uuid,
+                                 uint8_t    *p_data,
+                                 uint16_t    length,
+                                 uint16_t    max_length,
+                                 bool        has_variable_len,
+                                 uint16_t   *p_desc_handle)
+{
+    /* Descriptor metadata */
+    ble_gatts_attr_md_t   desc_md = {0};
+
+    desc_md.vloc = BLE_GATTS_VLOC_STACK;
+    /* Always set variable size */
+    desc_md.vlen = has_variable_len;
+
+    /* Make it readable and writable */
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.read_perm);
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.write_perm);
+
+    ble_gatts_attr_t attr_desc = {0};
+
+    attr_desc.p_uuid    = p_uuid;
+    attr_desc.p_attr_md = &desc_md;
+    attr_desc.init_len  = length;
+    attr_desc.max_len   = max_length;
+    attr_desc.p_value   = p_data;
+
+    ASSERT_STATUS ( sd_ble_gatts_descriptor_add(char_handle,
+                                                &attr_desc,
+                                                p_desc_handle));
+
+    return ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/btle/custom/custom_helper.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/btle/custom/custom_helper.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,71 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _CUSTOM_HELPER_H_
+#define _CUSTOM_HELPER_H_
+
+#include "common/common.h"
+#include "nrf_ble.h"
+#include "ble/UUID.h"
+#include "ble/GattCharacteristic.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define UUID_TABLE_MAX_ENTRIES  (4) /* This is the maximum number of 128-bit UUIDs with distinct bases that
+                                                   * we expect to be in use; increase this limit if needed. */
+
+/**
+ * Reset the table of 128bits uuids.
+ * This table is used to keep track of vendors uuids added to the softdevice.
+ * It is important to reset it before disabling the softdevice otherwise the
+ * next time the softdevice will be enabled, this table will not be synchronmized
+ * with the softdevice table.
+ */
+void custom_reset_128bits_uuid_table();
+uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base);
+error_t custom_decode_uuid(uint8_t const *const p_uuid_base,
+                           ble_uuid_t          *p_uuid);
+ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid);
+
+error_t custom_add_in_characteristic(uint16_t                  service_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                   properties,
+                                     SecurityManager::SecurityMode_t requiredSecurity,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     const uint8_t            *userDescriptionDescriptorValuePtr,
+                                     uint16_t                  userDescriptionDescriptorValueLen,
+                                     bool                      readAuthorization,
+                                     bool                      writeAuthorization,
+                                     ble_gatts_char_handles_t *p_char_handle);
+
+error_t custom_add_in_descriptor(uint16_t                      char_handle,
+                                     ble_uuid_t               *p_uuid,
+                                     uint8_t                  *p_data,
+                                     uint16_t                  length,
+                                     uint16_t                  max_length,
+                                     bool                      has_variable_len,
+                                     uint16_t                 *p_desc_handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ifndef _CUSTOM_HELPER_H_
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/ansi_escape.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/ansi_escape.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,103 @@
+/**************************************************************************/
+/*!
+    @file     ansi_esc_code.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, hathach (tinyusb.org)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+    This file is part of the tinyusb stack.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief TBD
+ *
+ *  \note TBD
+ */
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _ANSI_ESC_CODE_H_
+#define _ANSI_ESC_CODE_H_
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CSI_CODE(seq)   "\33[" seq
+#define CSI_SGR(x)      CSI_CODE(#x) "m"
+
+//------------- Cursor movement -------------//
+#define ANSI_CURSOR_UP(n)        CSI_CODE(#n "A")
+#define ANSI_CURSOR_DOWN(n)      CSI_CODE(#n "B")
+#define ANSI_CURSOR_FORWARD(n)   CSI_CODE(#n "C")
+#define ANSI_CURSOR_BACKWARD(n)  CSI_CODE(#n "D")
+#define ANSI_CURSOR_LINE_DOWN(n) CSI_CODE(#n "E")
+#define ANSI_CURSOR_LINE_UP(n)   CSI_CODE(#n "F")
+#define ANSI_CURSOR_POSITION(n, m) CSI_CODE(#n ";" #m "H")
+
+#define ANSI_ERASE_SCREEN(n)     CSI_CODE(#n "J")
+#define ANSI_ERASE_LINE(n)       CSI_CODE(#n "K")
+
+/** text color */
+#define ANSI_TEXT_BLACK          CSI_SGR(30)
+#define ANSI_TEXT_RED            CSI_SGR(31)
+#define ANSI_TEXT_GREEN          CSI_SGR(32)
+#define ANSI_TEXT_YELLOW         CSI_SGR(33)
+#define ANSI_TEXT_BLUE           CSI_SGR(34)
+#define ANSI_TEXT_MAGENTA        CSI_SGR(35)
+#define ANSI_TEXT_CYAN           CSI_SGR(36)
+#define ANSI_TEXT_WHITE          CSI_SGR(37)
+#define ANSI_TEXT_DEFAULT        CSI_SGR(39)
+
+/** background color */
+#define ANSI_BG_BLACK            CSI_SGR(40)
+#define ANSI_BG_RED              CSI_SGR(41)
+#define ANSI_BG_GREEN            CSI_SGR(42)
+#define ANSI_BG_YELLOW           CSI_SGR(43)
+#define ANSI_BG_BLUE             CSI_SGR(44)
+#define ANSI_BG_MAGENTA          CSI_SGR(45)
+#define ANSI_BG_CYAN             CSI_SGR(46)
+#define ANSI_BG_WHITE            CSI_SGR(47)
+#define ANSI_BG_DEFAULT          CSI_SGR(49)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TUSB_ANSI_ESC_CODE_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/assertion.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/assertion.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,198 @@
+/**************************************************************************/
+/*!
+    @file     assertion.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief TBD
+ *
+ *  \note TBD
+ */
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _ASSERTION_H_
+#define _ASSERTION_H_
+
+#include "projectconfig.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+static inline void debugger_breakpoint(void) ATTR_ALWAYS_INLINE;
+static inline void debugger_breakpoint(void)
+{
+#ifndef _TEST_
+  __asm("BKPT #0\n");
+#endif
+}
+
+//--------------------------------------------------------------------+
+// Compile-time Assert
+//--------------------------------------------------------------------+
+#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
+  #define _ASSERT_COUNTER __COUNTER__
+#else
+  #define _ASSERT_COUNTER __LINE__
+#endif
+
+#define ASSERT_STATIC(const_expr, message) enum { XSTRING_CONCAT_(static_assert_, _ASSERT_COUNTER) = 1/(!!(const_expr)) }
+
+//--------------------------------------------------------------------+
+// Assert Helper
+//--------------------------------------------------------------------+
+//#ifndef _TEST_
+//  #define ASSERT_MESSAGE(format, ...) _PRINTF("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
+//#else
+//  #define ASSERT_MESSAGE(format, ...) _PRINTF("%d:note: Assert " format "\n", __LINE__, __VA_ARGS__)
+//#endif
+
+#if CFG_DEBUG == 3
+  #define ASSERT_MESSAGE(format, ...) debugger_breakpoint()
+#elif CFG_DEBUG == 2
+  #define ASSERT_MESSAGE(format, ...) printf("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
+#else
+  #define ASSERT_MESSAGE(format, ...)
+#endif
+
+#define ASSERT_ERROR_HANDLER(x, para)  \
+    return (x)
+
+#define ASSERT_DEFINE_WITH_HANDLER(error_handler, handler_para, setup_statement, condition, error, format, ...) \
+  do{\
+    setup_statement;\
+	  if (!(condition)) {\
+	    ASSERT_MESSAGE(format, __VA_ARGS__);\
+	    error_handler(error, handler_para);\
+	  }\
+	}while(0)
+
+#define ASSERT_DEFINE(...) ASSERT_DEFINE_WITH_HANDLER(ASSERT_ERROR_HANDLER, NULL, __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// error_t Status Assert TODO use ASSERT_DEFINE
+//--------------------------------------------------------------------+
+#define ASSERT_STATUS_MESSAGE(sts, message) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, status, "%s: %s", ErrorStr[status], message)
+
+#define ASSERT_STATUS(sts) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, status, "error = %d", status)
+
+#define ASSERT_STATUS_RET_VOID(sts) \
+    ASSERT_DEFINE(error_t status = (error_t)(sts),\
+                  ERROR_NONE == status, (void) 0, "error = %d", status)
+
+//--------------------------------------------------------------------+
+// Logical Assert
+//--------------------------------------------------------------------+
+#define ASSERT(...)                      ASSERT_TRUE(__VA_ARGS__)
+#define ASSERT_TRUE(condition  , error)  ASSERT_DEFINE( , (condition), error, "%s", "evaluated to false")
+#define ASSERT_FALSE(condition , error)  ASSERT_DEFINE( ,!(condition), error, "%s", "evaluated to true")
+
+//--------------------------------------------------------------------+
+// Pointer Assert
+//--------------------------------------------------------------------+
+#define ASSERT_PTR(...)                    ASSERT_PTR_NOT_NULL(__VA_ARGS__)
+#define ASSERT_PTR_NOT_NULL(pointer, error) ASSERT_DEFINE( , NULL != (pointer), error, "%s", "pointer is NULL")
+#define ASSERT_PTR_NULL(pointer, error)    ASSERT_DEFINE( , NULL == (pointer), error, "%s", "pointer is not NULL")
+
+//--------------------------------------------------------------------+
+// Integral Assert
+//--------------------------------------------------------------------+
+#define ASSERT_XXX_EQUAL(type_format, expected, actual, error) \
+    ASSERT_DEFINE(\
+                  uint32_t exp = (expected); uint32_t act = (actual),\
+                  exp==act,\
+                  error,\
+                  "expected " type_format ", actual " type_format, exp, act)
+
+#define ASSERT_XXX_WITHIN(type_format, lower, upper, actual, error) \
+    ASSERT_DEFINE(\
+                  uint32_t low = (lower); uint32_t up = (upper); uint32_t act = (actual),\
+                  (low <= act) && (act <= up),\
+                  error,\
+                  "expected within " type_format " - " type_format ", actual " type_format, low, up, act)
+
+//--------------------------------------------------------------------+
+// Integer Assert
+//--------------------------------------------------------------------+
+#define ASSERT_INT(...)        ASSERT_INT_EQUAL(__VA_ARGS__)
+#define ASSERT_INT_EQUAL(...)  ASSERT_XXX_EQUAL("%d", __VA_ARGS__)
+#define ASSERT_INT_WITHIN(...) ASSERT_XXX_WITHIN("%d", __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Hex Assert
+//--------------------------------------------------------------------+
+#define ASSERT_HEX(...)        ASSERT_HEX_EQUAL(__VA_ARGS__)
+#define ASSERT_HEX_EQUAL(...)  ASSERT_XXX_EQUAL("0x%x", __VA_ARGS__)
+#define ASSERT_HEX_WITHIN(...) ASSERT_XXX_WITHIN("0x%x", __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Bin Assert
+//--------------------------------------------------------------------+
+#define BIN8_PRINTF_PATTERN "%d%d%d%d%d%d%d%d"
+#define BIN8_PRINTF_CONVERT(byte)  \
+  ((byte) & 0x80 ? 1 : 0), \
+  ((byte) & 0x40 ? 1 : 0), \
+  ((byte) & 0x20 ? 1 : 0), \
+  ((byte) & 0x10 ? 1 : 0), \
+  ((byte) & 0x08 ? 1 : 0), \
+  ((byte) & 0x04 ? 1 : 0), \
+  ((byte) & 0x02 ? 1 : 0), \
+  ((byte) & 0x01 ? 1 : 0)
+
+#define ASSERT_BIN8(...)        ASSERT_BIN8_EQUAL(__VA_ARGS__)
+#define ASSERT_BIN8_EQUAL(expected, actual, error)\
+    ASSERT_DEFINE(\
+                  uint8_t exp = (expected); uint8_t act = (actual),\
+                  exp==act,\
+                  error,\
+                  "expected " BIN8_PRINTF_PATTERN ", actual " BIN8_PRINTF_PATTERN, BIN8_PRINTF_CONVERT(exp), BIN8_PRINTF_CONVERT(act) )
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ASSERTION_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/binary.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/binary.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,96 @@
+/**************************************************************************/
+/*!
+    @file     binary.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \ingroup TBD
+ *  \defgroup TBD
+ *  \brief TBD
+ *
+ *  @{
+ */
+
+#ifndef _BINARY_H_
+#define _BINARY_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/// n-th Bit
+#define BIT(n) (1 << (n))
+
+/// set n-th bit of x to 1
+#define BIT_SET(x, n) ( (x) | BIT(n) )
+
+/// clear n-th bit of x
+#define BIT_CLR(x, n) ( (x) & (~BIT(n)) )
+
+/// test n-th bit of x
+#define BIT_TEST(x, n) ( (x) & BIT(n) )
+
+#if defined(__GNUC__) && !defined(__CC_ARM) // keil does not support binary format
+
+#define BIN8(x)               ((uint8_t)  (0b##x))
+#define BIN16(b1, b2)         ((uint16_t) (0b##b1##b2))
+#define BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
+
+#else
+
+//  internal macro of B8, B16, B32
+#define _B8__(x) (((x&0x0000000FUL)?1:0) \
+                +((x&0x000000F0UL)?2:0) \
+                +((x&0x00000F00UL)?4:0) \
+                +((x&0x0000F000UL)?8:0) \
+                +((x&0x000F0000UL)?16:0) \
+                +((x&0x00F00000UL)?32:0) \
+                +((x&0x0F000000UL)?64:0) \
+                +((x&0xF0000000UL)?128:0))
+
+#define BIN8(d) ((uint8_t) _B8__(0x##d##UL))
+#define BIN16(dmsb,dlsb) (((uint16_t)BIN8(dmsb)<<8) + BIN8(dlsb))
+#define BIN32(dmsb,db2,db3,dlsb) \
+            (((uint32_t)BIN8(dmsb)<<24) \
+            + ((uint32_t)BIN8(db2)<<16) \
+            + ((uint32_t)BIN8(db3)<<8) \
+            + BIN8(dlsb))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _BINARY_H_ */
+
+/** @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/ble_error.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/ble_error.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,151 @@
+/**************************************************************************/
+/*!
+    @file     ble_error.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief Error Header
+ *
+ *  \note TBD
+ */
+
+/** \ingroup Group_Common
+ *  \defgroup Group_Error Error Codes
+ *  @{
+ */
+
+#ifndef _BLE_ERROR_H_
+#define _BLE_ERROR_H_
+
+#include "projectconfig.h"
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+typedef enum 
+{
+  /*=======================================================================
+    NORDIC GLOBAL ERRORS                                   0x0000 .. 0x00FF
+    -----------------------------------------------------------------------
+    Errors mapped from nrf_error.h
+    -----------------------------------------------------------------------*/
+    ERROR_NONE                                    = 0x0000 , ///< Successful command
+    ERROR_SVC_HANDLER_MISSING                     = 0x0001 , ///< SVC handler is missing
+    ERROR_SOFTDEVICE_NOT_ENABLED                  = 0x0002 , ///< SoftDevice has not been enabled
+    ERROR_INTERNAL                                = 0x0003 , ///< Internal Error
+    ERROR_NO_MEM                                  = 0x0004 , ///< No Memory for operation
+    ERROR_NOT_FOUND                               = 0x0005 , ///< Not found
+    ERROR_NOT_SUPPORTED                           = 0x0006 , ///< Not supported
+    ERROR_INVALID_PARAM                           = 0x0007 , ///< Invalid Parameter
+    ERROR_INVALID_STATE                           = 0x0008 , ///< Invalid state, operation disallowed in this state
+    ERROR_INVALID_LENGTH                          = 0x0009 , ///< Invalid Length
+    ERROR_INVALID_FLAGS                           = 0x000A , ///< Invalid Flags
+    ERROR_INVALID_DATA                            = 0x000B , ///< Invalid Data
+    ERROR_DATA_SIZE                               = 0x000C , ///< Data size exceeds limit
+    ERROR_TIMEOUT                                 = 0x000D , ///< Operation timed out
+    ERROR_NULL                                    = 0x000E , ///< Null Pointer
+    ERROR_FORBIDDEN                               = 0x000F , ///< Forbidden Operation
+    ERROR_INVALID_ADDR                            = 0x0010 , ///< Bad Memory Address
+    ERROR_BUSY                                    = 0x0011 , ///< Busy
+  /*=======================================================================*/
+
+  ERROR_INVALIDPARAMETER                        = 0x0100 , /**< An invalid parameter value was provided */
+  ERROR_I2C_XFER_FAILED                         = 0x0101 , /**< an failed attempt to make I2C transfer */
+
+  /*=======================================================================
+    SIMPLE BINARY PROTOCOL ERRORS                          0x0120 .. 0x013F
+    -----------------------------------------------------------------------
+    Errors relating to the simple binary protocol (/src//protocol)
+    -----------------------------------------------------------------------*/
+    ERROR_PROT_INVALIDMSGTYPE                   = 0x121,  /**< Unexpected msg type encountered */
+    ERROR_PROT_INVALIDCOMMANDID                 = 0x122,  /**< Unknown or out of range command ID */
+    ERROR_PROT_INVALIDPAYLOAD                   = 0x123,  /**< Message payload has a problem (invalid len, etc.) */
+  /*=======================================================================*/
+
+  //------------- based on Nordic SDM nrf_error_sdm.h -------------//
+  ERROR_SDM_LFCLK_SOURCE_UNKNOWN                = 0x1000 , ///< Unknown lfclk source
+  ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION   = 0x1001 , ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts)
+  ERROR_SDM_INCORRECT_CLENR0                    = 0x1002 , ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing)
+
+  //------------- based on Nordic SOC nrf_error_soc.h -------------//
+  /* Mutex Errors */
+  ERROR_SOC_MUTEX_ALREADY_TAKEN                 = 0x2000 ,  ///< Mutex already taken
+
+  /* NVIC errors */
+  ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE        = 0x2001 ,  ///< NVIC interrupt not available
+  ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED = 0x2002 ,  ///< NVIC interrupt priority not allowed
+  ERROR_SOC_NVIC_SHOULD_NOT_RETURN              = 0x2003 ,  ///< NVIC should not return
+
+  /* Power errors */
+  ERROR_SOC_POWER_MODE_UNKNOWN                  = 0x2004 ,  ///< Power mode unknown
+  ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN         = 0x2005 ,  ///< Power POF threshold unknown
+  ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN         = 0x2006 ,  ///< Power off should not return
+
+  /* Rand errors */
+  ERROR_SOC_RAND_NOT_ENOUGH_VALUES              = 0x2007 ,  ///< RAND not enough values
+
+  /* PPI errors */
+  ERROR_SOC_PPI_INVALID_CHANNEL                 = 0x2008 ,  ///< Invalid PPI Channel
+  ERROR_SOC_PPI_INVALID_GROUP                   = 0x2009 ,  ///< Invalid PPI Group
+
+  //------------- based on Nordic STK (ble) ble_err.h -------------//
+  ERROR_BLE_INVALID_CONN_HANDLE                 = 0x3001 , /**< Invalid connection handle. */
+  ERROR_BLE_INVALID_ATTR_HANDLE                 = 0x3002 , /**< Invalid attribute handle. */
+  ERROR_BLE_NO_TX_BUFFERS                       = 0x3003 , /**< Buffer capacity exceeded. */
+
+  // L2CAP
+  ERROR_BLE_L2CAP_CID_IN_USE                    = 0x3100 , /**< CID already in use. */
+
+  // GAP
+  ERROR_BLE_GAP_UUID_LIST_MISMATCH              = 0x3200 , /**< UUID list does not contain an integral number of UUIDs. */
+  ERROR_BLE_GAP_DISCOVERABLE_WITH_WHITELIST     = 0x3201 , /**< Use of Whitelist not permitted with discoverable advertising. */
+  ERROR_BLE_GAP_INVALID_BLE_ADDR                = 0x3202 , /**< The upper two bits of the address do not correspond to the specified address type. */
+
+  // GATTC
+  ERROR_BLE_GATTC_PROC_NOT_PERMITTED            = 0x3300 ,
+
+  // GATTS
+  ERROR_BLEGATTS_INVALID_ATTR_TYPE              = 0x3400 , /**< Invalid attribute type. */
+  ERROR_BLEGATTS_SYS_ATTR_MISSING               = 0x3401 , /**< System Attributes missing. */
+
+}error_t;
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _BLE_ERROR_H_ */
+
+ /**  @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/common.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,236 @@
+/**************************************************************************/
+/*!
+    @file     common.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \defgroup Group_Common Common Files
+ * @{
+ *
+ *  \defgroup Group_CommonH common.h
+ *
+ *  @{
+ */
+
+#ifndef _COMMON_H_
+#define _COMMON_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// INCLUDES
+//--------------------------------------------------------------------+
+
+//------------- Standard Header -------------//
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <string.h>
+#include <stdio.h>
+
+//------------- General Header -------------//
+#include "projectconfig.h"
+#include "compiler.h"
+#include "assertion.h"
+#include "binary.h"
+#include "ble_error.h"
+
+//------------- MCU header -------------//
+//#include "nrf.h"
+
+//--------------------------------------------------------------------+
+// TYPEDEFS
+//--------------------------------------------------------------------+
+typedef unsigned char byte_t;
+typedef float  float32_t;
+typedef double float64_t;
+
+//--------------------------------------------------------------------+
+// MACROS
+//--------------------------------------------------------------------+
+#define STRING_(x)  #x                             // stringify without expand
+#define XSTRING_(x) STRING_(x)                     // expand then stringify
+#define STRING_CONCAT_(a, b) a##b                  // concat without expand
+#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) // expand then concat
+
+#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
+#define U16_LOW_U8(u16)  ((uint8_t) ((u16)       & 0x00ff))
+#define U16_TO_U8S_BE(u16)  U16_HIGH_U8(u16), U16_LOW_U8(u16)
+#define U16_TO_U8S_LE(u16)  U16_LOW_U8(u16), U16_HIGH_U8(u16)
+
+#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB
+#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff))
+#define U32_B3_U8(u32) ((uint8_t) (((u32) >>  8) & 0x000000ff))
+#define U32_B4_U8(u32) ((uint8_t) ((u32)        & 0x000000ff)) // LSB
+
+#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32)
+#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32)
+
+//--------------------------------------------------------------------+
+// INLINE FUNCTION
+//--------------------------------------------------------------------+
+#define memclr_(buffer, size)  memset(buffer, 0, size)
+
+//------------- Conversion -------------//
+/// form an uint32_t from 4 x uint8_t
+static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4)
+{
+  return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
+}
+
+static inline uint8_t u16_high_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint8_t u16_high_u8(uint16_t u16)
+{
+  return (uint8_t) ((u16 >> 8) & 0x00ff);
+}
+
+static inline uint8_t u16_low_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
+static inline uint8_t u16_low_u8(uint16_t u16)
+{
+  return (uint8_t) (u16 & 0x00ff);
+}
+
+//------------- Min -------------//
+static inline uint8_t min8_of(uint8_t x, uint8_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t min8_of(uint8_t x, uint8_t y)
+{
+  return (x < y) ? x : y;
+}
+
+static inline uint16_t min16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint16_t min16_of(uint16_t x, uint16_t y)
+{
+  return (x < y) ? x : y;
+}
+
+static inline uint32_t min32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t min32_of(uint32_t x, uint32_t y)
+{
+  return (x < y) ? x : y;
+}
+
+//------------- Max -------------//
+static inline uint32_t max32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t max32_of(uint32_t x, uint32_t y)
+{
+  return (x > y) ? x : y;
+}
+
+//------------- Align -------------//
+static inline uint32_t align32 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align32 (uint32_t value)
+{
+	return (value & 0xFFFFFFE0UL);
+}
+
+static inline uint32_t align16 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align16 (uint32_t value)
+{
+	return (value & 0xFFFFFFF0UL);
+}
+
+static inline uint32_t align_n (uint32_t alignment, uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align_n (uint32_t alignment, uint32_t value)
+{
+	return value & (~(alignment-1));
+}
+
+static inline uint32_t align4k (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t align4k (uint32_t value)
+{
+	return (value & 0xFFFFF000UL);
+}
+
+static inline uint32_t offset4k(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint32_t offset4k(uint32_t value)
+{
+	return (value & 0xFFFUL);
+}
+
+//------------- Mathematics -------------//
+/// inclusive range checking
+static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper)
+{
+  return (lower <= value) && (value <= upper);
+}
+
+/// exclusive range checking
+static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper)
+{
+  return (lower < value) && (value < upper);
+}
+
+static inline uint8_t log2_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t log2_of(uint32_t value)
+{
+  uint8_t result = 0; // log2 of a value is its MSB's position
+
+  while (value >>= 1)
+  {
+    result++;
+  }
+  return result;
+}
+
+// return the number of set bits in value
+static inline uint8_t cardinality_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
+static inline uint8_t cardinality_of(uint32_t value)
+{
+  // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only
+  // the high bit set, then it will only go once through the loop
+  // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie)
+  // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method
+  // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and
+  // published in 1964 in a book edited by Beckenbach.)"
+  uint8_t count;
+  for (count = 0; value; count++)
+  {
+    value &= value - 1; // clear the least significant bit set
+  }
+
+  return count;
+}
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _COMMON_H_ */
+
+/**  @} */
+/**  @} */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/common/compiler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/common/compiler.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,160 @@
+/**************************************************************************/
+/*!
+    @file     compiler.h
+    @author   hathach (tinyusb.org)
+
+    @section LICENSE
+
+    Software License Agreement (BSD License)
+
+    Copyright (c) 2013, K. Townsend (microBuilder.eu)
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are met:
+    1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+    3. Neither the name of the copyright holders nor the
+    names of its contributors may be used to endorse or promote products
+    derived from this software without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
+    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
+    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+/**************************************************************************/
+
+/** \file
+ *  \brief GCC Header
+ */
+
+/** \ingroup Group_Compiler
+ *  \defgroup Group_GCC GNU GCC
+ *  @{
+ */
+
+#ifndef _COMPILER_GCC_H_
+#define _COMPILER_GCC_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#include "projectconfig.h"
+
+//#ifndef __GNUC__
+//  #define ATTR_ALWAYS_INLINE
+//  #define ATTR_CONST
+//#else
+
+#ifdef _TEST_
+  #define ATTR_ALWAYS_INLINE
+  #define STATIC_
+  #define INLINE_
+#else
+  #define STATIC_ static
+  #define INLINE_ inline
+
+  #if CFG_DEBUG == 3
+    #define ATTR_ALWAYS_INLINE  // no inline for debug = 3
+  #endif
+#endif
+
+
+#ifdef __GNUC__
+
+#define ALIGN_OF(x)                __alignof__(x)
+
+/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section
+#define ATTR_SECTION(section)      __attribute__ ((#section))
+
+/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking
+#define ATTR_ERROR(Message)        __attribute__ ((error(Message)))
+
+/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking
+#define ATTR_WARNING(Message)      __attribute__ ((warning(Message)))
+
+/**
+ *  \defgroup Group_VariableAttr Variable Attributes
+ *  @{
+ */
+
+/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes
+#define ATTR_ALIGNED(Bytes)        __attribute__ ((aligned(Bytes)))
+
+/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute
+#define ATTR_PACKED                __attribute__ ((packed))
+
+#define ATTR_PREPACKED
+
+#define ATTR_PACKED_STRUCT(x)    x __attribute__ ((packed))
+/** @} */
+
+/**
+ *  \defgroup Group_FuncAttr Function Attributes
+ *  @{
+ */
+
+#ifndef ATTR_ALWAYS_INLINE
+/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified
+#define ATTR_ALWAYS_INLINE         __attribute__ ((always_inline))
+#endif
+
+/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null
+#define ATTR_NON_NULL              __attribute__ ((nonull))
+
+/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure
+#define ATTR_PURE                  __attribute__ ((pure))
+
+/// Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
+/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void
+#define ATTR_CONST                 __attribute__ ((const))
+
+/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses
+#define ATTR_DEPRECATED            __attribute__ ((deprecated))
+
+/// Same as the deprecated attribute with optional message in the warning
+#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess)))
+
+/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code
+#define ATTR_WEAK                  __attribute__ ((weak))
+
+/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified
+#define ATTR_ALIAS(func)           __attribute__ ((alias(#func)))
+
+/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static
+#define ATTR_WEAKREF(func)         __attribute__ ((weakref(#func)))
+
+/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug
+#define ATTR_WARN_UNUSED_RESULT    __attribute__ ((warn_unused_result))
+
+/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.
+#define ATTR_USED                  __attribute__ ((used))
+
+/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function.
+#define ATTR_UNUSED                __attribute__ ((unused))
+
+#elif defined (__ICCARM__) //IAR
+  #define ATTR_ALWAYS_INLINE // IAR dosn't provide such a syntax extension in function's prototypes.
+  #define ATTR_CONST         // IAR dosn't provide such a syntax extension in function's prototypes.
+#endif
+
+/** @} */
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* _COMPILER_GCC_H_ */
+
+/// @}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,303 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2015 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+#include "nrf_ble_err.h"
+#include "ble/DiscoveredCharacteristicDescriptor.h"
+
+nRF5xCharacteristicDescriptorDiscoverer::nRF5xCharacteristicDescriptorDiscoverer() :
+    discoveryRunning() {
+    // nothing to do
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::~nRF5xCharacteristicDescriptorDiscoverer() {
+    // nothing to do
+}
+
+ble_error_t nRF5xCharacteristicDescriptorDiscoverer::launch(
+    const DiscoveredCharacteristic& characteristic,
+    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
+) {
+    Gap::Handle_t connHandle = characteristic.getConnectionHandle();
+    // it is ok to deduce that the start handle for descriptors is after
+    // the characteristic declaration and the characteristic value declaration
+    // see BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] (3.3)
+    Gap::Handle_t descriptorStartHandle = characteristic.getDeclHandle() + 2;
+    Gap::Handle_t descriptorEndHandle = characteristic.getLastHandle();
+
+    // check if there is any descriptor to discover
+    if (descriptorEndHandle < descriptorStartHandle) {
+        CharacteristicDescriptorDiscovery::TerminationCallbackParams_t termParams = {
+            characteristic,
+            BLE_ERROR_NONE
+        };
+        terminationCallback.call(&termParams);
+        return BLE_ERROR_NONE;
+    }
+
+    // check if we can run this discovery
+    if (isConnectionInUse(connHandle)) {
+        return BLE_STACK_BUSY;
+    }
+
+    // get a new discovery slot, if none are available, just return
+    Discovery* discovery = getAvailableDiscoverySlot();
+    if(discovery == NULL) {
+        return BLE_STACK_BUSY;
+    }
+
+    // try to launch the discovery
+    ble_error_t err = gattc_descriptors_discover(connHandle, descriptorStartHandle, descriptorEndHandle);
+    if(!err) {
+        // commit the new discovery to its slot
+        *discovery = Discovery(characteristic, discoveryCallback, terminationCallback);
+    }
+
+    return err;
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::isActive(const DiscoveredCharacteristic& characteristic) const {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if(discoveryRunning[i].getCharacteristic() == characteristic) {
+            return true;
+        }
+    }
+    return false;
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::requestTerminate(const DiscoveredCharacteristic& characteristic) {
+    Discovery* discovery = findRunningDiscovery(characteristic);
+    if(discovery) {
+        // call terminate anyway
+        terminate(discovery, BLE_ERROR_NONE);
+    }
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors) {
+    Discovery* discovery = findRunningDiscovery(connectionHandle);
+    // the discovery has been removed
+    if(!discovery) {
+        return;
+    }
+
+    for (uint16_t i = 0; i < descriptors.count; ++i) {
+        const ble_gattc_desc_t& desc = descriptors.descs[i];
+        const ble_uuid_t& uuid = desc.uuid;
+
+        if (uuid.type == BLE_UUID_TYPE_BLE) {
+            discovery->process(
+                desc.handle, UUID(uuid.uuid)
+            );
+        } else {
+            // discover attribute infos of the descriptor
+            ble_error_t err = gattc_attr_info_discover(connectionHandle, desc.handle, desc.handle);
+            if (err) {
+                terminate(discovery, err);
+            }
+
+            return;
+        }
+    }
+
+    // prepare the next discovery request (if needed)
+    uint16_t startHandle = descriptors.descs[descriptors.count - 1].handle + 1;
+    uint16_t endHandle = discovery->getCharacteristic().getLastHandle();
+
+    if(startHandle > endHandle) {
+        terminate(discovery, BLE_ERROR_NONE);
+        return;
+    }
+
+    ble_error_t err = gattc_descriptors_discover(connectionHandle, startHandle, endHandle);
+    if(err) {
+        terminate(discovery, err);
+        return;
+    }
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::processAttributeInformation(
+    uint16_t connectionHandle, const ble_gattc_evt_attr_info_disc_rsp_t& infos) {
+    Discovery* discovery = findRunningDiscovery(connectionHandle);
+    // the discovery has been removed
+    if(!discovery) {
+        return;
+    }
+
+    // for all UUIDS found, process the discovery
+    for (uint16_t i = 0; i < infos.count; ++i) {
+        bool use_16bits_uuids = infos.format == BLE_GATTC_ATTR_INFO_FORMAT_16BIT;
+        const ble_gattc_attr_info_t& attr_info = infos.attr_info[i];
+        UUID uuid = use_16bits_uuids ? UUID(attr_info.info.uuid16.uuid) : UUID(attr_info.info.uuid128.uuid128,  UUID::LSB);
+        discovery->process(attr_info.handle, uuid);
+    }
+
+    // prepare the next round of descriptors discovery
+    uint16_t startHandle = infos.attr_info[infos.count - 1].handle + 1;
+    uint16_t endHandle = discovery->getCharacteristic().getLastHandle();
+
+    if(startHandle > endHandle) {
+        terminate(discovery, BLE_ERROR_NONE);
+        return;
+    }
+
+    ble_error_t err = gattc_descriptors_discover(connectionHandle, startHandle, endHandle);
+    if(err) {
+        terminate(discovery, err);
+        return;
+    }
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::terminate(uint16_t handle, ble_error_t err) {
+    Discovery* discovery = findRunningDiscovery(handle);
+    // the discovery has already been terminated
+    if(!discovery) {
+        return;
+    }
+
+    terminate(discovery, err);
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::terminate(Discovery* discovery, ble_error_t err) {
+    // temporary copy, user code can try to launch a new discovery in the onTerminate
+    // callback. So, this discovery should not appear in such case.
+    Discovery tmp = *discovery;
+    *discovery = Discovery();
+    tmp.terminate(err);
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(const DiscoveredCharacteristic& characteristic) {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if((discoveryRunning[i].getCharacteristic() == characteristic) &&
+           (discoveryRunning[i].isEmpty() == false)) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(uint16_t handle) {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if((discoveryRunning[i].getCharacteristic().getConnectionHandle() == handle) &&
+           (discoveryRunning[i].isEmpty() == false)) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery*
+nRF5xCharacteristicDescriptorDiscoverer::getAvailableDiscoverySlot() {
+    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
+        if(discoveryRunning[i].isEmpty()) {
+            return &discoveryRunning[i];
+        }
+    }
+    return NULL;
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::isConnectionInUse(uint16_t connHandle) {
+     return findRunningDiscovery(connHandle) != NULL;
+}
+
+ble_error_t nRF5xCharacteristicDescriptorDiscoverer::gattc_descriptors_discover(
+    uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle) {
+
+    ble_gattc_handle_range_t discoveryRange = {
+        start_handle,
+        end_handle
+    };
+    uint32_t err = sd_ble_gattc_descriptors_discover(connection_handle, &discoveryRange);
+
+    switch(err) {
+        case NRF_SUCCESS:
+            return BLE_ERROR_NONE;
+        case BLE_ERROR_INVALID_CONN_HANDLE:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_ADDR:
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        case NRF_ERROR_BUSY:
+            return BLE_STACK_BUSY;
+        default:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ble_error_t nRF5xCharacteristicDescriptorDiscoverer::gattc_attr_info_discover(
+    uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle) {
+    ble_gattc_handle_range_t handle_range = { start_handle, end_handle };
+    uint32_t err = sd_ble_gattc_attr_info_discover(connection_handle, &handle_range);
+
+    switch(err) {
+        case NRF_SUCCESS:
+            return BLE_ERROR_NONE;
+        case BLE_ERROR_INVALID_CONN_HANDLE:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_ADDR:
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        case NRF_ERROR_BUSY:
+            return BLE_STACK_BUSY;
+        case NRF_ERROR_INVALID_STATE:
+            return BLE_ERROR_INVALID_STATE;
+        default:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+
+
+// implementation of nRF5xCharacteristicDescriptorDiscoverer::Discovery
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery() :
+    characteristic(), onDiscovery(), onTerminate() {
+}
+
+nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery(
+    const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb) :
+    characteristic(c), onDiscovery(dCb), onTerminate(tCb) {
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::Discovery::process(
+    GattAttribute::Handle_t handle, const UUID& uuid) {
+    CharacteristicDescriptorDiscovery::DiscoveryCallbackParams_t params = {
+        characteristic,
+        DiscoveredCharacteristicDescriptor(
+            characteristic.getGattClient(),
+            characteristic.getConnectionHandle(),
+            handle,
+            uuid
+        )
+    };
+    onDiscovery.call(&params);
+}
+
+void nRF5xCharacteristicDescriptorDiscoverer::Discovery::terminate(ble_error_t err) {
+    CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = {
+        characteristic,
+        err
+    };
+
+    onTerminate.call(&params);
+}
+
+bool nRF5xCharacteristicDescriptorDiscoverer::Discovery::isEmpty() const {
+    return *this == Discovery();
+}
+
+const DiscoveredCharacteristic& nRF5xCharacteristicDescriptorDiscoverer::Discovery::getCharacteristic() const {
+    return characteristic;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,227 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2015 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
+#define __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
+
+#include "ble/Gap.h"
+#include "ble/DiscoveredCharacteristic.h"
+#include "ble/CharacteristicDescriptorDiscovery.h"
+#include "ble/GattClient.h"
+#include "nrf_ble_gattc.h"
+
+/**
+ * @brief Manage the discovery of Characteristic descriptors
+ * @details is a bridge between BLE API and Nordic stack regarding Characteristic
+ * Descriptor discovery. The BLE API can launch, monitor and ask for termination
+ * of a discovery. The Nordic stack will provide new descriptors and indicate when
+ * the discovery is done.
+ */
+class nRF5xCharacteristicDescriptorDiscoverer
+{
+    typedef CharacteristicDescriptorDiscovery::DiscoveryCallback_t DiscoveryCallback_t;
+    typedef CharacteristicDescriptorDiscovery::TerminationCallback_t TerminationCallback_t;
+
+public:
+    /**
+     * @brief Construct a new characteristic descriptor discoverer.
+     */
+    nRF5xCharacteristicDescriptorDiscoverer();
+
+    /**
+     * @brief Destroy a characteristic descriptor discoverer.
+     */
+    ~nRF5xCharacteristicDescriptorDiscoverer();
+
+    /**
+     * Launch a new characteristic descriptor discovery for a given DiscoveredCharacteristic.
+     * @param characteristic The characteristic owning the descriptors to discover.
+     * @param discoveryCallback The callback called when a descriptor is discovered.
+     * @param terminationCallback The callback called when the discovery process end.
+     * @return BLE_ERROR_NONE if characteristic descriptor discovery is launched successfully;
+     *         else an appropriate error.
+     * @note: this will be called by BLE API side.
+     */
+    ble_error_t launch(
+        const DiscoveredCharacteristic& characteristic,
+        const DiscoveryCallback_t& discoveryCallback,
+        const TerminationCallback_t& terminationCallback
+    );
+
+    /**
+     * @brief indicate if a characteristic descriptor discovery is active for a
+     * given DiscoveredCharacteristic.
+     * @param characteristic The characteristic for whom the descriptor might be
+     * currently discovered.
+     * @return true if descriptors of characteristic are discovered, false otherwise.
+     * @note: this will be called by BLE API side.
+     */
+    bool isActive(const DiscoveredCharacteristic& characteristic) const;
+
+    /**
+     * @brief request the termination of characteristic descriptor discovery
+     * for a give DiscoveredCharacteristic
+     * @param characteristic The characteristic for whom the descriptor discovery
+     * should be stopped.
+     * @note: this will be called by BLE API side.
+     */
+    void requestTerminate(const DiscoveredCharacteristic& characteristic);
+
+    /**
+     * @brief process descriptors discovered from the Nordic stack.
+     * @param connectionHandle The connection handle upon which descriptors has been
+     * discovered.
+     * @param descriptors Discovered descriptors.
+     * @note This will be called by the Nordic stack.
+     */
+    void process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors);
+
+    /**
+     * @brief Called by the Nordic stack when the discovery is over.
+     * @param The connection handle upon which the discovery process is done.
+     * @param err An error if the termination is due to an error.
+     */
+    void terminate(uint16_t connectionHandle, ble_error_t err);
+
+    /**
+    * @brief process attribute informations from the Nordic stack.
+    * @param connectionHandle The connection handle upon which
+    * attribute informations has been fetch.
+    * @param infos Informations around attribute, in that case the
+    * 128bit UUID of a descriptor.
+    * @note This will be called by the Nordic stack.
+     */
+    void processAttributeInformation(uint16_t handle, const ble_gattc_evt_attr_info_disc_rsp_t& infos);
+
+private:
+    // protection against copy construction and assignment
+    nRF5xCharacteristicDescriptorDiscoverer(const nRF5xCharacteristicDescriptorDiscoverer&);
+    nRF5xCharacteristicDescriptorDiscoverer& operator=(const nRF5xCharacteristicDescriptorDiscoverer&);
+
+    /**
+     * @brief Discovery process, it store the DiscoveredCharacteristic, the
+     * discovery callback and the termination callback.
+     */
+    class Discovery {
+    public:
+        /**
+         * @brief Construct an empty discovery, such can be considerate as a not running discovery.
+         * @note #isEmpty function will return true
+         */
+        Discovery();
+
+        /**
+         * @brief Construct a valid discovery process.
+         *
+         * @param c the characteristic from whom descriptors will be discovered.
+         * @param dCb The discovery callback called each time a descriptor is discovered.
+         * @param tCb The termination callback called when the discovery terminate.
+         *
+         * @note #isEmpty function will return false
+         */
+        Discovery(const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb);
+
+        /**
+         * @brief Process the discovery of a descriptor.
+         *
+         * @param handle The attribute handle of the descriptor found
+         * @param uuid The UUID of the descriptor found.
+         */
+        void process(GattAttribute::Handle_t handle, const UUID& uuid);
+
+        /**
+         * @brief Terminate the discovery process.
+         *
+         * @param err Error associate with the termination
+         * @note after this call #isEmpty function will return true.
+         */
+        void terminate(ble_error_t err);
+
+        /**
+         * @brief check if the discovery process is empty or not. Empty discovery are
+         * not running.
+         *
+         * @detail Discovery are empty after:
+         *     - a default construction
+         *     - a copy construction form a default constructed
+         *     - an assignment from a default constructed Discovery
+         * @return true if the Discovery is empty and false otherwise.
+         */
+        bool isEmpty() const;
+
+        /**
+         * @brief return the characteristic from whom descriptors are discovered.
+         * @return the characteristic from whom descriptors are discovered.
+         */
+        const DiscoveredCharacteristic& getCharacteristic() const;
+
+        /**
+         * @brief equal to operator, test if two discovery process are equal
+         *
+         * @param lhs left hand side of the expression
+         * @param rhs right hand side of the expression
+         * @return true if lhs == rhs
+         */
+        friend bool operator==(const Discovery& lhs, const Discovery& rhs) {
+            return lhs.characteristic == rhs.characteristic &&
+                   lhs.onDiscovery == rhs.onDiscovery &&
+                   lhs.onTerminate == rhs.onTerminate;
+        }
+
+        /**
+         * @brief not equal to operator, test if two discovery process are not equal
+         *
+         * @param lhs left hand side of the expression
+         * @param rhs right hand side of the expression
+         * @return true if lhs != rhs
+         */
+        friend bool operator!=(const Discovery& lhs, const Discovery& rhs) {
+            return !(lhs == rhs);
+        }
+
+    private:
+        DiscoveredCharacteristic characteristic;
+        DiscoveryCallback_t onDiscovery;
+        TerminationCallback_t onTerminate;
+    };
+
+    // find a running discovery process
+    Discovery* findRunningDiscovery(const DiscoveredCharacteristic& characteristic);
+    Discovery* findRunningDiscovery(uint16_t handle);
+
+    // Called to terminate a discovery is over.
+    void terminate(Discovery* discovery, ble_error_t err);
+
+    // get one slot for a discovery process
+    Discovery* getAvailableDiscoverySlot();
+
+    // indicate if a connection is already running a discovery
+    bool isConnectionInUse(uint16_t connHandle);
+
+    // low level start of a discovery
+    static ble_error_t gattc_descriptors_discover(uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle);
+
+    // discovery of 128bits UUIDS
+    static ble_error_t gattc_attr_info_discover(uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle);
+
+    // count of concurrent connections which can run a descriptor discovery process
+    static const size_t MAXIMUM_CONCURRENT_CONNECTIONS_COUNT = 3;
+
+    // array of running discoveries
+    Discovery discoveryRunning[MAXIMUM_CONCURRENT_CONNECTIONS_COUNT];
+};
+
+#endif /*__NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,63 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xDiscoveredCharacteristic.h"
+#include "nRF5xGattClient.h"
+#include "nrf_ble_gatt.h"
+
+void
+nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
+                                     Gap::Handle_t            connectionHandleIn,
+                                     ble_gatt_char_props_t    propsIn,
+                                     GattAttribute::Handle_t  declHandleIn,
+                                     GattAttribute::Handle_t  valueHandleIn)
+{
+    gattc       = gattcIn;
+    connHandle  = connectionHandleIn;
+    declHandle  = declHandleIn;
+    valueHandle = valueHandleIn;
+
+    props._broadcast       = propsIn.broadcast;
+    props._read            = propsIn.read;
+    props._writeWoResp     = propsIn.write_wo_resp;
+    props._write           = propsIn.write;
+    props._notify          = propsIn.notify;
+    props._indicate        = propsIn.indicate;
+    props._authSignedWrite = propsIn.auth_signed_wr;
+}
+
+void
+nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
+                                      Gap::Handle_t            connectionHandleIn,
+                                     UUID::ShortUUIDBytes_t   uuidIn,
+                                     ble_gatt_char_props_t    propsIn,
+                                     GattAttribute::Handle_t  declHandleIn,
+                                     GattAttribute::Handle_t  valueHandleIn)
+{
+    gattc       = gattcIn;
+    connHandle  = connectionHandleIn;
+    uuid        = uuidIn;
+    declHandle  = declHandleIn;
+    valueHandle = valueHandleIn;
+
+    props._broadcast       = propsIn.broadcast;
+    props._read            = propsIn.read;
+    props._writeWoResp     = propsIn.write_wo_resp;
+    props._write           = propsIn.write;
+    props._notify          = propsIn.notify;
+    props._indicate        = propsIn.indicate;
+    props._authSignedWrite = propsIn.auth_signed_wr;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,45 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_DISCOVERED_CHARACTERISTIC_H__
+#define __NRF_DISCOVERED_CHARACTERISTIC_H__
+
+#include "ble/DiscoveredCharacteristic.h"
+#include "nrf_ble_gatt.h"
+
+class nRF5xGattClient; /* forward declaration */
+
+class nRF5xDiscoveredCharacteristic : public DiscoveredCharacteristic {
+public:
+    void setup(nRF5xGattClient         *gattcIn,
+               Gap::Handle_t            connectionHandleIn,
+               ble_gatt_char_props_t    propsIn,
+               GattAttribute::Handle_t  declHandleIn,
+               GattAttribute::Handle_t  valueHandleIn);
+
+    void setup(nRF5xGattClient         *gattcIn,
+               Gap::Handle_t            connectionHandleIn,
+               UUID::ShortUUIDBytes_t   uuidIn,
+               ble_gatt_char_props_t    propsIn,
+               GattAttribute::Handle_t  declHandleIn,
+               GattAttribute::Handle_t  valueHandleIn);
+
+    void setLastHandle(GattAttribute::Handle_t last) {
+      lastHandle = last;
+    }
+};
+
+#endif /* __NRF_DISCOVERED_CHARACTERISTIC_H__ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGap.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGap.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,947 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xn.h"
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#include "ble/BLE.h"
+
+#include "common/common.h"
+#include "ble_advdata.h"
+#include "nrf_ble_hci.h"
+
+void radioNotificationStaticCallback(bool param) {
+    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+    gap.processRadioNotificationEvent(param);
+}
+
+/**************************************************************************/
+/*!
+    @brief  Sets the advertising parameters and payload for the device
+
+    @param[in]  params
+                Basic advertising details, including the advertising
+                delay, timeout and how the device should be advertised
+    @params[in] advData
+                The primary advertising data payload
+    @params[in] scanResponse
+                The optional Scan Response payload if the advertising
+                type is set to \ref GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED
+                in \ref GapAdveritinngParams
+
+    @returns    \ref ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @retval     BLE_ERROR_BUFFER_OVERFLOW
+                The proposed action would cause a buffer overflow.  All
+                advertising payloads must be <= 31 bytes, for example.
+
+    @retval     BLE_ERROR_NOT_IMPLEMENTED
+                A feature was requested that is not yet supported in the
+                nRF51 firmware or hardware.
+
+    @retval     BLE_ERROR_PARAM_OUT_OF_RANGE
+                One of the proposed values is outside the valid range.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse)
+{
+    /* Make sure we don't exceed the advertising payload length */
+    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) {
+        return BLE_ERROR_BUFFER_OVERFLOW;
+    }
+
+    /* Make sure we have a payload! */
+    if (advData.getPayloadLen() == 0) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Check the scan response payload limits */
+    //if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED))
+    //{
+    //    /* Check if we're within the upper limit */
+    //    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD)
+    //    {
+    //        return BLE_ERROR_BUFFER_OVERFLOW;
+    //    }
+    //    /* Make sure we have a payload! */
+    //    if (advData.getPayloadLen() == 0)
+    //    {
+    //        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    //    }
+    //}
+
+    /* Send advertising data! */
+    ASSERT(ERROR_NONE ==
+           sd_ble_gap_adv_data_set(advData.getPayload(),
+                                   advData.getPayloadLen(),
+                                   scanResponse.getPayload(),
+                                   scanResponse.getPayloadLen()),
+           BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    /* Make sure the GAP Service appearance value is aligned with the
+     *appearance from GapAdvertisingData */
+    ASSERT(ERROR_NONE == sd_ble_gap_appearance_set(advData.getAppearance()),
+           BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    /* ToDo: Perform some checks on the payload, for example the Scan Response can't */
+    /* contains a flags AD type, etc. */
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Starts the BLE HW, initialising any services that were
+            added before this function was called.
+
+    @note   All services must be added before calling this function!
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams &params)
+{
+    /* Make sure we support the advertising type */
+    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) {
+        /* ToDo: This requires a propery security implementation, etc. */
+        return BLE_ERROR_NOT_IMPLEMENTED;
+    }
+
+    /* Check interval range */
+    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED) {
+        /* Min delay is slightly longer for unconnectable devices */
+        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) ||
+            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    } else {
+        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN) ||
+            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    }
+
+    /* Check timeout is zero for Connectable Directed */
+    if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) && (params.getTimeout() != 0)) {
+        /* Timeout must be 0 with this type, although we'll never get here */
+        /* since this isn't implemented yet anyway */
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Check timeout for other advertising types */
+    if ((params.getAdvertisingType() != GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) &&
+        (params.getTimeout() > GapAdvertisingParams::GAP_ADV_PARAMS_TIMEOUT_MAX)) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (advertisingPolicyMode != Gap::ADV_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    /* Start Advertising */
+    ble_gap_adv_params_t adv_para = {0};
+
+    adv_para.type        = params.getAdvertisingType();
+    adv_para.p_peer_addr = NULL;                           // Undirected advertisement
+    adv_para.fp          = advertisingPolicyMode;
+    adv_para.p_whitelist = &whitelist;
+    adv_para.interval    = params.getIntervalInADVUnits(); // advertising interval (in units of 0.625 ms)
+    adv_para.timeout     = params.getTimeout();
+
+    uint32_t err = sd_ble_gap_adv_start(&adv_para);
+    switch(err) {
+        case ERROR_NONE:
+            return BLE_ERROR_NONE;
+        case NRF_ERROR_NO_MEM:
+            return BLE_ERROR_NO_MEM;
+        default:
+            return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+ble_error_t nRF5xGap::startRadioScan(const GapScanningParams &scanningParams)
+{
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+    
+    ble_gap_scan_params_t scanParams;
+    
+    scanParams.active      = scanningParams.getActiveScanning(); /**< If 1, perform active scanning (scan requests). */
+    scanParams.selective   = scanningPolicyMode;    /**< If 1, ignore unknown devices (non whitelisted). */
+    scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */
+    scanParams.interval    = scanningParams.getInterval();  /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+    scanParams.window      = scanningParams.getWindow();    /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+    scanParams.timeout     = scanningParams.getTimeout();   /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+
+    if (sd_ble_gap_scan_start(&scanParams) != NRF_SUCCESS) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::stopScan(void) {
+    if (sd_ble_gap_scan_stop() == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+
+    return BLE_STACK_BUSY;
+}
+#endif
+
+/**************************************************************************/
+/*!
+    @brief  Stops the BLE HW and disconnects from any devices
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::stopAdvertising(void)
+{
+    /* Stop Advertising */
+    ASSERT(ERROR_NONE == sd_ble_gap_adv_stop(), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    state.advertising = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::connect(const Address_t             peerAddr,
+                              BLEProtocol::AddressType_t  peerAddrType,
+                              const ConnectionParams_t   *connectionParams,
+                              const GapScanningParams    *scanParamsIn)
+{
+    ble_gap_addr_t addr;
+    addr.addr_type = peerAddrType;
+    memcpy(addr.addr, peerAddr, Gap::ADDR_LEN);
+
+    ble_gap_conn_params_t connParams;
+    if (connectionParams != NULL) {
+        connParams.min_conn_interval = connectionParams->minConnectionInterval;
+        connParams.max_conn_interval = connectionParams->maxConnectionInterval;
+        connParams.slave_latency     = connectionParams->slaveLatency;
+        connParams.conn_sup_timeout  = connectionParams->connectionSupervisionTimeout;
+    } else {
+        connParams.min_conn_interval = 50;
+        connParams.max_conn_interval = 100;
+        connParams.slave_latency     = 0;
+        connParams.conn_sup_timeout  = 600;
+    }
+
+    /* Allocate the stack's whitelist statically */
+    ble_gap_whitelist_t  whitelist;
+    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
+    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+    /* Initialize the whitelist */
+    whitelist.pp_addrs   = whitelistAddressPtrs;
+    whitelist.pp_irks    = whitelistIrkPtrs;
+    whitelist.addr_count = 0;
+    whitelist.irk_count  = 0;
+
+    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
+    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
+        ble_error_t error = generateStackWhitelist(whitelist);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    ble_gap_scan_params_t scanParams;
+    scanParams.selective   = scanningPolicyMode;    /**< If 1, ignore unknown devices (non whitelisted). */
+    scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */
+    if (scanParamsIn != NULL) {
+        scanParams.active      = scanParamsIn->getActiveScanning();   /**< If 1, perform active scanning (scan requests). */
+        scanParams.interval    = scanParamsIn->getInterval();         /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.window      = scanParamsIn->getWindow();           /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.timeout     = scanParamsIn->getTimeout();          /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+    } else {
+        scanParams.active      = _scanningParams.getActiveScanning(); /**< If 1, perform active scanning (scan requests). */
+        scanParams.interval    = _scanningParams.getInterval();       /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.window      = _scanningParams.getWindow();         /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
+        scanParams.timeout     = _scanningParams.getTimeout();        /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
+    }
+
+    uint32_t rc = sd_ble_gap_connect(&addr, &scanParams, &connParams);
+    if (rc == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    }
+    switch (rc) {
+        case NRF_ERROR_INVALID_ADDR:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_PARAM:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_INVALID_STATE:
+            return BLE_ERROR_INVALID_STATE;
+        case BLE_ERROR_GAP_INVALID_BLE_ADDR:
+            return BLE_ERROR_INVALID_PARAM;
+        case NRF_ERROR_NO_MEM:
+            return BLE_ERROR_NO_MEM;
+        case NRF_ERROR_BUSY:
+            return BLE_STACK_BUSY;
+        default:
+        case BLE_ERROR_GAP_WHITELIST_IN_USE:
+            return BLE_ERROR_UNSPECIFIED;
+    }
+}
+
+ble_error_t nRF5xGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason)
+{
+    uint8_t code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
+    switch (reason) {
+        case REMOTE_USER_TERMINATED_CONNECTION:
+            code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
+            break;
+        case CONN_INTERVAL_UNACCEPTABLE:
+            code = BLE_HCI_CONN_INTERVAL_UNACCEPTABLE;
+            break;
+        default:
+            break;
+    }
+
+    /* Disconnect if we are connected to a central device */
+    ASSERT_INT(ERROR_NONE, sd_ble_gap_disconnect(connectionHandle, code), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+/*!
+    @brief  Disconnects if we are connected to a central device
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+ble_error_t nRF5xGap::disconnect(DisconnectionReason_t reason)
+{
+    return disconnect(m_connectionHandle, reason);
+}
+
+ble_error_t nRF5xGap::getPreferredConnectionParams(ConnectionParams_t *params)
+{
+    ASSERT_INT(NRF_SUCCESS,
+        sd_ble_gap_ppcp_get(reinterpret_cast<ble_gap_conn_params_t *>(params)),
+        BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::setPreferredConnectionParams(const ConnectionParams_t *params)
+{
+    ASSERT_INT(NRF_SUCCESS,
+        sd_ble_gap_ppcp_set(reinterpret_cast<const ble_gap_conn_params_t *>(params)),
+        BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::updateConnectionParams(Handle_t handle, const ConnectionParams_t *newParams)
+{
+    uint32_t rc;
+
+    rc = sd_ble_gap_conn_param_update(handle, reinterpret_cast<ble_gap_conn_params_t *>(const_cast<ConnectionParams_t*>(newParams)));
+    if (rc == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+/**************************************************************************/
+/*!
+    @brief  Clear nRF5xGap's state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::reset(void)
+{
+    /* Clear all state that is from the parent, including private members */
+    if (Gap::reset() != BLE_ERROR_NONE) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Clear derived class members */
+    m_connectionHandle = BLE_CONN_HANDLE_INVALID;
+
+    /* Set the whitelist policy filter modes to IGNORE_WHITELIST */
+    advertisingPolicyMode = Gap::ADV_POLICY_IGNORE_WHITELIST;
+    scanningPolicyMode    = Gap::SCAN_POLICY_IGNORE_WHITELIST;
+
+    /* Clear the internal whitelist */
+    whitelistAddressesSize = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Sets the 16-bit connection handle
+*/
+/**************************************************************************/
+void nRF5xGap::setConnectionHandle(uint16_t con_handle)
+{
+    m_connectionHandle = con_handle;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Gets the 16-bit connection handle
+*/
+/**************************************************************************/
+uint16_t nRF5xGap::getConnectionHandle(void)
+{
+    return m_connectionHandle;
+}
+
+/**************************************************************************/
+/*!
+    @brief      Sets the BLE device address
+
+    @returns    ble_error_t
+
+    @section EXAMPLE
+
+    @code
+
+    uint8_t device_address[6] = { 0xca, 0xfe, 0xf0, 0xf0, 0xf0, 0xf0 };
+    nrf.getGap().setAddress(Gap::BLEProtocol::AddressType::RANDOM_STATIC, device_address);
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address)
+{
+    uint8_t cycle_mode;
+    ble_gap_addr_t dev_addr;
+
+    /* When using Public or Static addresses, the cycle mode must be None.
+       When using Random Private addresses, the cycle mode must be Auto.
+       In auto mode, the given address is ignored.
+    */
+    if ((type == BLEProtocol::AddressType::PUBLIC) || (type == BLEProtocol::AddressType::RANDOM_STATIC))
+    {
+        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_NONE;
+        memcpy(dev_addr.addr, address, ADDR_LEN);
+    }
+    else if ((type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) || (type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE))
+    {
+        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_AUTO;
+        // address is ignored when in auto mode
+    }
+    else
+    {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    dev_addr.addr_type = type;
+    ASSERT_INT(ERROR_NONE, sd_ble_gap_address_set(cycle_mode, &dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::getAddress(AddressType_t *typeP, Address_t address)
+{
+    ble_gap_addr_t dev_addr;
+    if (sd_ble_gap_address_get(&dev_addr) != NRF_SUCCESS) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    if (typeP != NULL) {
+        *typeP = static_cast<AddressType_t>(dev_addr.addr_type);
+    }
+    if (address != NULL) {
+        memcpy(address, dev_addr.addr, ADDR_LEN);
+    }
+    return BLE_ERROR_NONE;
+}
+
+ble_error_t nRF5xGap::setDeviceName(const uint8_t *deviceName)
+{
+    ble_gap_conn_sec_mode_t sec_mode;
+    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
+
+    if (sd_ble_gap_device_name_set(&sec_mode, deviceName, strlen((const char *)deviceName)) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::getDeviceName(uint8_t *deviceName, unsigned *lengthP)
+{
+    if (sd_ble_gap_device_name_get(deviceName, (uint16_t *)lengthP) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::setAppearance(GapAdvertisingData::Appearance appearance)
+{
+    if (sd_ble_gap_appearance_set(appearance) == NRF_SUCCESS) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+ble_error_t nRF5xGap::getAppearance(GapAdvertisingData::Appearance *appearanceP)
+{
+    if ((sd_ble_gap_appearance_get(reinterpret_cast<uint16_t *>(appearanceP)) == NRF_SUCCESS)) {
+        return BLE_ERROR_NONE;
+    } else {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+}
+
+/* (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
+ble_error_t nRF5xGap::setTxPower(int8_t txPower)
+{
+    unsigned rc;
+    if ((rc = sd_ble_gap_tx_power_set(txPower)) != NRF_SUCCESS) {
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case NRF_ERROR_INVALID_PARAM:
+            default:
+                return BLE_ERROR_PARAM_OUT_OF_RANGE;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+void nRF5xGap::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP)
+{
+#if defined(NRF51)
+    static const int8_t permittedTxValues[] = {
+        -30, -20, -16, -12, -8, -4, 0, 4
+    };
+#elif defined(NRF52)
+    static const int8_t permittedTxValues[] = {
+        -40, -20, -16, -12, -8, -4, 0, 4
+    };
+#else
+#error permitted TX power values unknown for this SOC
+#endif
+
+    *valueArrayPP = permittedTxValues;
+    *countP = sizeof(permittedTxValues) / sizeof(int8_t);
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the capacity of the internal whitelist maintained by this
+            implementation.
+
+    @returns    The capacity of the internal whitelist.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+uint8_t nRF5xGap::getMaxWhitelistSize(void) const
+{
+    return YOTTA_CFG_WHITELIST_MAX_SIZE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get a copy of the implementation's internal whitelist.
+
+    @param[out] whitelistOut
+                A \ref Gap::Whitelist_t structure containing a copy of the
+                addresses in the implemenetation's internal whitelist.
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::getWhitelist(Gap::Whitelist_t &whitelistOut) const
+{
+    uint8_t i;
+    for (i = 0; i < whitelistAddressesSize && i < whitelistOut.capacity; ++i) {
+        memcpy(&whitelistOut.addresses[i], &whitelistAddresses[i], sizeof(BLEProtocol::Address_t));
+    }
+    whitelistOut.size = i;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the whitelist that will be used in the next call to
+            startAdvertising().
+
+    @param[in]  whitelistIn
+                A reference to a \ref Gap::Whitelist_t structure
+                representing a whitelist containing all the white listed
+                BLE addresses.
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_INVALID_PARAM
+                The supplied whitelist contains a private non-resolvable
+                address
+
+                BLE_ERROR_PARAM_OUT_OF_RANGE
+                The size of the supplied whitelist exceeds the maximum
+                capacity of the implementation's internal whitelist.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setWhitelist(const Gap::Whitelist_t &whitelistIn)
+{
+    if (whitelistIn.size > getMaxWhitelistSize()) {
+        return BLE_ERROR_PARAM_OUT_OF_RANGE;
+    }
+
+    /* Test for invalid parameters before we change the internal state */
+    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
+        if (whitelistIn.addresses[i].type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE) {
+            /* This is not allowed because it is completely meaningless */
+            return BLE_ERROR_INVALID_PARAM;
+        }
+    }
+
+    whitelistAddressesSize = 0;
+    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
+        memcpy(&whitelistAddresses[whitelistAddressesSize], &whitelistIn.addresses[i], sizeof(BLEProtocol::Address_t));
+        whitelistAddressesSize++;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the advertising policy filter mode that will be used in
+            the next call to startAdvertising().
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setAdvertisingPolicyMode(Gap::AdvertisingPolicyMode_t mode)
+{
+    advertisingPolicyMode = mode;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the scanning policy filter mode that will be used in
+            the next call to startAdvertising().
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setScanningPolicyMode(Gap::ScanningPolicyMode_t mode)
+{
+    scanningPolicyMode = mode;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Set the initiator policy filter mode that will be used in
+            the next call to startAdvertising()
+
+    @returns    \ref ble_errror_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly.
+
+                BLE_ERROR_NOT_IMPLEMENTED
+                This feature is currently note implemented.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::setInitiatorPolicyMode(Gap::InitiatorPolicyMode_t mode)
+{
+    return BLE_ERROR_NOT_IMPLEMENTED;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current advertising policy filter mode.
+
+    @returns    The advertising policy filter mode.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::AdvertisingPolicyMode_t nRF5xGap::getAdvertisingPolicyMode(void) const
+{
+    return advertisingPolicyMode;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current scanning policy filter mode.
+
+    @returns    The scanning policy filter mode.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::ScanningPolicyMode_t nRF5xGap::getScanningPolicyMode(void) const
+{
+    return scanningPolicyMode;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Get the current initiator policy filter mode.
+
+    @returns    The initiator policy filter mode.
+
+    @note   Currently initiator filtering using the whitelist is not
+            implemented in this module.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+Gap::InitiatorPolicyMode_t nRF5xGap::getInitiatorPolicyMode(void) const
+{
+    return Gap::INIT_POLICY_IGNORE_WHITELIST;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Helper function used to populate the ble_gap_whitelist_t that
+            will be used by the SoftDevice for filtering requests.
+
+    @returns    \ref ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @retval     BLE_ERROR_INVALID_STATE
+                The internal stack was not initialized correctly.
+
+    @note  Both the SecurityManager and Gap must initialize correctly for
+           this function to succeed.
+
+    @note  This function is needed because for the BLE API the whitelist
+           is just a collection of keys, but for the stack it also includes
+           the IRK table.
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGap::generateStackWhitelist(ble_gap_whitelist_t &whitelist)
+{
+    ble_gap_whitelist_t  whitelistFromBondTable;
+    ble_gap_addr_t      *addressPtr[1];
+    ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+
+    nRF5xSecurityManager& securityManager = (nRF5xSecurityManager&) nRF5xn::Instance(0).getSecurityManager();
+
+    if (securityManager.hasInitialized()) {
+        /* We do not care about the addresses, set the count to 0 */
+        whitelistFromBondTable.addr_count = 0;
+        /* The Nordic SDK will return a failure if we set pp_addr to NULL */
+        whitelistFromBondTable.pp_addrs   = addressPtr;
+        /* We want all the IRKs we can get because we do not know which ones match the addresses */
+        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_irks    = irkPtr;
+
+        /* Use the security manager to get the IRKs from the bond table */
+        ble_error_t error = securityManager.createWhitelistFromBondTable(whitelistFromBondTable);
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    } else  {
+        /**
+         * If there is no security manager then we cannot access the bond table,
+         * so disable IRK matching
+         */
+        whitelistFromBondTable.addr_count = 0;
+        whitelistFromBondTable.irk_count  = 0;
+    }
+
+    /**
+     * For every private resolvable address in the local whitelist check if
+     * there is an IRK for said address in the bond table and add it to the
+     * local IRK list.
+     */
+    whitelist.irk_count  = 0;
+    whitelist.addr_count = 0;
+    for (uint8_t i = 0; i < whitelistAddressesSize; ++i) {
+        if (whitelistAddresses[i].addr_type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) {
+            /* Test if there is a matching IRK for this private resolvable address */
+            for (uint8_t j = 0; j < whitelistFromBondTable.irk_count; ++j) {
+                if (securityManager.matchAddressAndIrk(&whitelistAddresses[i], whitelistFromBondTable.pp_irks[j])) {
+                    /* Found the corresponding IRK, add it to our local whitelist */
+                    whitelist.pp_irks[whitelist.irk_count] = whitelistFromBondTable.pp_irks[j];
+                    whitelist.irk_count++;
+                    /* Make sure we do not look at this IRK again */
+                    if (j != whitelistFromBondTable.irk_count - 1) {
+                        /**
+                         * This is not the last IRK, so replace the pointer
+                         * with the last pointer in the array
+                         */
+                        whitelistFromBondTable.pp_irks[j] =
+                            whitelistFromBondTable.pp_irks[whitelistFromBondTable.irk_count - 1];
+                    }
+                    /**
+                     * If the IRK is the last pointer in the array simply
+                     * decrement the total IRK count
+                     */
+                    whitelistFromBondTable.irk_count--;
+                    break;
+                }
+            }
+        } else {
+            /* Include the address into the whitelist */
+            whitelist.pp_addrs[whitelist.addr_count] = &whitelistAddresses[i];
+            whitelist.addr_count++;
+        }
+    }
+
+    return BLE_ERROR_NONE;
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGap.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,247 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF5x_GAP_H__
+#define __NRF5x_GAP_H__
+
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#ifndef YOTTA_CFG_WHITELIST_MAX_SIZE
+    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+#elif YOTTA_CFG_WHITELIST_MAX_SIZE > BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+    #undef YOTTA_CFG_WHITELIST_MAX_SIZE
+    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
+#endif
+#ifndef YOTTA_CFG_IRK_TABLE_MAX_SIZE
+    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
+#elif YOTTA_CFG_IRK_TABLE_MAX_SIZE > BLE_GAP_WHITELIST_IRK_MAX_COUNT
+    #undef YOTTA_CFG_IRK_TABLE_MAX_SIZE
+    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
+#endif
+#include "ble/blecommon.h"
+#include "nrf_ble.h"
+#include "ble/GapAdvertisingParams.h"
+#include "ble/GapAdvertisingData.h"
+#include "ble/Gap.h"
+#include "ble/GapScanningParams.h"
+
+#include "nrf_soc.h"
+
+extern "C" {
+#include "ble_radio_notification.h"
+#include "app_util_platform.h"
+}
+
+#include "btle_security.h"
+
+void radioNotificationStaticCallback(bool param);
+
+/**************************************************************************/
+/*!
+    \brief
+
+*/
+/**************************************************************************/
+class nRF5xGap : public Gap
+{
+public:
+    /* Functions that must be implemented from Gap */
+    virtual ble_error_t setAddress(AddressType_t  type,  const Address_t address);
+    virtual ble_error_t getAddress(AddressType_t *typeP, Address_t address);
+    virtual ble_error_t setAdvertisingData(const GapAdvertisingData &, const GapAdvertisingData &);
+
+    virtual uint16_t    getMinAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MIN);}
+    virtual uint16_t    getMinNonConnectableAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_NONCON_INTERVAL_MIN);}
+    virtual uint16_t    getMaxAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MAX);}
+
+    virtual ble_error_t startAdvertising(const GapAdvertisingParams &);
+    virtual ble_error_t stopAdvertising(void);
+    virtual ble_error_t connect(const Address_t, BLEProtocol::AddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams);
+    virtual ble_error_t disconnect(Handle_t connectionHandle, DisconnectionReason_t reason);
+    virtual ble_error_t disconnect(DisconnectionReason_t reason);
+
+    virtual ble_error_t setDeviceName(const uint8_t *deviceName);
+    virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP);
+    virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance);
+    virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP);
+
+    virtual ble_error_t setTxPower(int8_t txPower);
+    virtual void        getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP);
+
+    void     setConnectionHandle(uint16_t con_handle);
+    uint16_t getConnectionHandle(void);
+
+    virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params);
+    virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params);
+    virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params);
+
+    virtual ble_error_t reset(void);
+
+    /*
+     * The following functions are part of the whitelisting experimental API.
+     * Therefore, this functionality can change in the near future.
+     */
+    virtual uint8_t getMaxWhitelistSize(void) const;
+    virtual ble_error_t getWhitelist(Gap::Whitelist_t &whitelistOut) const;
+    virtual ble_error_t setWhitelist(const Gap::Whitelist_t &whitelistIn);
+
+    virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode);
+    virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode);
+    virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode);
+    virtual Gap::AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const;
+    virtual Gap::ScanningPolicyMode_t getScanningPolicyMode(void) const;
+    virtual Gap::InitiatorPolicyMode_t getInitiatorPolicyMode(void) const;
+
+    virtual ble_error_t initRadioNotification(void) {
+        if (ble_radio_notification_init(APP_IRQ_PRIORITY_HIGH /*MID*/, NRF_RADIO_NOTIFICATION_DISTANCE_800US, radioNotificationStaticCallback) == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+
+        return BLE_ERROR_UNSPECIFIED;
+    }
+
+/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams);
+    virtual ble_error_t stopScan(void);
+#endif
+
+private:
+    /*
+     * Whitelisting API related structures and helper functions.
+     */
+
+    /* Policy modes set by the user. By default these are set to ignore the whitelist */
+    Gap::AdvertisingPolicyMode_t advertisingPolicyMode;
+    Gap::ScanningPolicyMode_t    scanningPolicyMode;
+
+    /* Internal representation of a whitelist */
+    uint8_t         whitelistAddressesSize;
+    ble_gap_addr_t  whitelistAddresses[YOTTA_CFG_WHITELIST_MAX_SIZE];
+
+    /*
+     * An internal function used to populate the ble_gap_whitelist_t that will be used by
+     * the SoftDevice for filtering requests. This function is needed because for the BLE
+     * API the whitelist is just a collection of keys, but for the stack it also includes
+     * the IRK table.
+     */
+    ble_error_t generateStackWhitelist(ble_gap_whitelist_t &whitelist);
+
+private:
+    bool    radioNotificationCallbackParam; /* parameter to be passed into the Timeout-generated radio notification callback. */
+    Timeout radioNotificationTimeout;
+
+    /*
+     * A helper function to post radio notification callbacks with low interrupt priority.
+     */
+    void postRadioNotificationCallback(void) {
+#ifdef YOTTA_CFG_MBED_OS
+        /*
+         * In mbed OS, all user-facing BLE events (interrupts) are posted to the
+         * MINAR scheduler to be executed as callbacks in thread mode. MINAR guards
+         * its critical sections from interrupts by acquiring CriticalSectionLock,
+         * which results in a call to sd_nvic_critical_region_enter(). Thus, it is
+         * safe to invoke MINAR APIs from interrupt context as long as those
+         * interrupts are blocked by sd_nvic_critical_region_enter().
+         *
+         * Radio notifications are a special case for the above. The Radio
+         * Notification IRQ is handled at a very high priority--higher than the
+         * level blocked by sd_nvic_critical_region_enter(). Thus Radio Notification
+         * events can preempt MINAR's critical sections. Using MINAR APIs (such as
+         * posting an event) directly in processRadioNotification() may result in a
+         * race condition ending in a hard-fault.
+         *
+         * The solution is to *not* call MINAR APIs directly from the Radio
+         * Notification handling; i.e. to do the bulk of RadioNotification
+         * processing at a reduced priority which respects MINAR's critical
+         * sections. Unfortunately, on a cortex-M0, there is no clean way to demote
+         * priority for the currently executing interrupt--we wouldn't want to
+         * demote the radio notification handling anyway because it is sensitive to
+         * timing, and the system expects to finish this handling very quickly. The
+         * workaround is to employ a Timeout to trigger
+         * postRadioNotificationCallback() after a very short delay (~0 us) and post
+         * the MINAR callback that context.
+         *
+         * !!!WARNING!!! Radio notifications are very time critical events. The
+         * current solution is expected to work under the assumption that
+         * postRadioNotificationCalback() will be executed BEFORE the next radio
+         * notification event is generated.
+         */
+        minar::Scheduler::postCallback(
+            mbed::util::FunctionPointer1<void, bool>(&radioNotificationCallback, &FunctionPointerWithContext<bool>::call).bind(radioNotificationCallbackParam)
+        );
+#else
+        /*
+         * In mbed classic, all user-facing BLE events execute callbacks in interrupt
+         * mode. Radio Notifications are a special case because its IRQ is handled at
+         * a very high priority. Thus Radio Notification events can preempt other
+         * operations that require interaction with the SoftDevice such as advertising
+         * payload updates and changing the Gap state. Therefore, executing a Radio
+         * Notification callback directly from processRadioNotification() may result
+         * in a race condition ending in a hard-fault.
+         *
+         * The solution is to *not* execute the Radio Notification callback directly
+         * from the Radio Notification handling; i.e. to do the bulk of the
+         * Radio Notification processing at a reduced priority. Unfortunately, on a
+         * cortex-M0, there is no clean way to demote priority for the currently
+         * executing interrupt--we wouldn't want to demote the radio notification
+         * handling anyway because it is sensitive to timing, and the system expects
+         * to finish this handling very quickly. The workaround is to employ a Timeout
+         * to trigger postRadioNotificationCallback() after a very short delay (~0 us)
+         * and execute the callback in that context.
+         *
+         * !!!WARNING!!! Radio notifications are very time critical events. The
+         * current solution is expected to work under the assumption that
+         * postRadioNotificationCalback() will be executed BEFORE the next radio
+         * notification event is generated.
+         */
+        radioNotificationCallback.call(radioNotificationCallbackParam);
+#endif /* #ifdef YOTTA_CFG_MBED_OS */
+    }
+
+    /**
+     * A helper function to process radio-notification events; to be called internally.
+     * @param param [description]
+     */
+    void processRadioNotificationEvent(bool param) {
+        radioNotificationCallbackParam = param;
+        radioNotificationTimeout.attach_us(this, &nRF5xGap::postRadioNotificationCallback, 0);
+    }
+    friend void radioNotificationStaticCallback(bool param); /* allow invocations of processRadioNotificationEvent() */
+
+private:
+    uint16_t m_connectionHandle;
+
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGap() :
+        advertisingPolicyMode(Gap::ADV_POLICY_IGNORE_WHITELIST),
+        scanningPolicyMode(Gap::SCAN_POLICY_IGNORE_WHITELIST),
+        whitelistAddressesSize(0) {
+        m_connectionHandle = BLE_CONN_HANDLE_INVALID;
+    }
+
+    nRF5xGap(nRF5xGap const &);
+    void operator=(nRF5xGap const &);
+};
+
+#endif // ifndef __NRF5x_GAP_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGattClient.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGattClient.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,50 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xGattClient.h"
+
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+ble_error_t
+nRF5xGattClient::launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
+                                        ServiceDiscovery::ServiceCallback_t         sc,
+                                        ServiceDiscovery::CharacteristicCallback_t  cc,
+                                        const UUID                                 &matchingServiceUUIDIn,
+                                        const UUID                                 &matchingCharacteristicUUIDIn)
+{
+    return _discovery.launch(connectionHandle, sc, cc, matchingServiceUUIDIn, matchingCharacteristicUUIDIn);
+}
+
+ble_error_t nRF5xGattClient::discoverCharacteristicDescriptors(
+    const DiscoveredCharacteristic& characteristic,
+    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback)
+{
+    return _characteristicDescriptorDiscoverer.launch(
+        characteristic, 
+        discoveryCallback, 
+        terminationCallback
+    );
+}
+
+bool nRF5xGattClient::isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const {
+    return _characteristicDescriptorDiscoverer.isActive(characteristic);   
+}
+
+void nRF5xGattClient::terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic) { 
+    return _characteristicDescriptorDiscoverer.requestTerminate(characteristic);
+}
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGattClient.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGattClient.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,218 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_GATT_CLIENT_H__
+#define __NRF51822_GATT_CLIENT_H__
+
+#include "ble/GattClient.h"
+#include "nRF5xServiceDiscovery.h"
+#include "nRF5xCharacteristicDescriptorDiscoverer.h"
+
+class nRF5xGattClient : public GattClient
+{
+public:
+    /**
+     * When using S110, all Gatt client features will return
+     * BLE_ERROR_NOT_IMPLEMENTED
+     */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+
+    /**
+     * Launch service discovery. Once launched, service discovery will remain
+     * active with callbacks being issued back into the application for matching
+     * services/characteristics. isActive() can be used to determine status; and
+     * a termination callback (if setup) will be invoked at the end. Service
+     * discovery can be terminated prematurely if needed using terminate().
+     *
+     * @param  connectionHandle
+     *           Handle for the connection with the peer.
+     * @param  sc
+     *           This is the application callback for matching service. Taken as
+     *           NULL by default. Note: service discovery may still be active
+     *           when this callback is issued; calling asynchronous BLE-stack
+     *           APIs from within this application callback might cause the
+     *           stack to abort service discovery. If this becomes an issue, it
+     *           may be better to make local copy of the discoveredService and
+     *           wait for service discovery to terminate before operating on the
+     *           service.
+     * @param  cc
+     *           This is the application callback for matching characteristic.
+     *           Taken as NULL by default. Note: service discovery may still be
+     *           active when this callback is issued; calling asynchronous
+     *           BLE-stack APIs from within this application callback might cause
+     *           the stack to abort service discovery. If this becomes an issue,
+     *           it may be better to make local copy of the discoveredCharacteristic
+     *           and wait for service discovery to terminate before operating on the
+     *           characteristic.
+     * @param  matchingServiceUUID
+     *           UUID based filter for specifying a service in which the application is
+     *           interested. By default it is set as the wildcard UUID_UNKNOWN,
+     *           in which case it matches all services. If characteristic-UUID
+     *           filter (below) is set to the wildcard value, then a service
+     *           callback will be invoked for the matching service (or for every
+     *           service if the service filter is a wildcard).
+     * @param  matchingCharacteristicUUIDIn
+     *           UUID based filter for specifying characteristic in which the application
+     *           is interested. By default it is set as the wildcard UUID_UKNOWN
+     *           to match against any characteristic. If both service-UUID
+     *           filter and characteristic-UUID filter are used with non- wildcard
+     *           values, then only a single characteristic callback is
+     *           invoked for the matching characteristic.
+     *
+     * @Note     Using wildcard values for both service-UUID and characteristic-
+     *           UUID will result in complete service discovery--callbacks being
+     *           called for every service and characteristic.
+     *
+     * @return
+     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
+     */
+    virtual ble_error_t launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
+                                               ServiceDiscovery::ServiceCallback_t         sc = NULL,
+                                               ServiceDiscovery::CharacteristicCallback_t  cc = NULL,
+                                               const UUID                                 &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN),
+                                               const UUID                                 &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN));
+
+    virtual void onServiceDiscoveryTermination(ServiceDiscovery::TerminationCallback_t callback) {
+        _discovery.onTermination(callback);
+    }
+
+    /**
+     * Is service-discovery currently active?
+     */
+    virtual bool isServiceDiscoveryActive(void) const {
+        return _discovery.isActive();
+    }
+
+    /**
+     * Terminate an ongoing service-discovery. This should result in an
+     * invocation of the TerminationCallback if service-discovery is active.
+     */
+    virtual void terminateServiceDiscovery(void) {
+        _discovery.terminate();
+    }
+
+    /**
+     * @brief Implementation of GattClient::discoverCharacteristicDescriptors
+     * @see GattClient::discoverCharacteristicDescriptors
+     */
+    virtual ble_error_t discoverCharacteristicDescriptors(
+        const DiscoveredCharacteristic& characteristic,
+        const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
+        const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
+    );
+
+    /**
+     * @brief Implementation of GattClient::isCharacteristicDiscoveryActive
+     * @see GattClient::isCharacteristicDiscoveryActive
+     */
+    virtual bool isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const;
+
+    /**
+     * @brief Implementation of GattClient::terminateCharacteristicDiscovery
+     * @see GattClient::terminateCharacteristicDiscovery
+     */
+    virtual void terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic);
+
+    virtual ble_error_t read(Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset) const {
+        uint32_t rc = sd_ble_gattc_read(connHandle, attributeHandle, offset);
+        if (rc == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case NRF_ERROR_INVALID_STATE:
+            case NRF_ERROR_INVALID_ADDR:
+            default:
+                return BLE_ERROR_INVALID_STATE;
+        }
+    }
+
+    virtual ble_error_t write(GattClient::WriteOp_t cmd, Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value) const {
+        ble_gattc_write_params_t writeParams;
+        writeParams.write_op = cmd;
+        writeParams.flags    = 0; /* this is inconsequential */
+        writeParams.handle   = attributeHandle;
+        writeParams.offset   = 0;
+        writeParams.len      = length;
+        writeParams.p_value  = const_cast<uint8_t *>(value);
+
+        uint32_t rc = sd_ble_gattc_write(connHandle, &writeParams);
+        if (rc == NRF_SUCCESS) {
+            return BLE_ERROR_NONE;
+        }
+        switch (rc) {
+            case NRF_ERROR_BUSY:
+                return BLE_STACK_BUSY;
+            case BLE_ERROR_NO_TX_PACKETS:
+                return BLE_ERROR_NO_MEM;
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case NRF_ERROR_INVALID_STATE:
+            case NRF_ERROR_INVALID_ADDR:
+            default:
+                return BLE_ERROR_INVALID_STATE;
+        }
+    }
+
+    /**
+     * @brief  Clear nRF5xGattClient's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void) {
+        /* Clear all state that is from the parent, including private members */
+        if (GattClient::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        /* Clear derived class members */
+        _discovery.reset();
+
+        return BLE_ERROR_NONE;
+    }
+
+public:
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGattClient() : _discovery(this) {
+        /* empty */
+    }
+
+    nRF5xServiceDiscovery& discovery() {
+        return _discovery;
+    }
+
+    nRF5xCharacteristicDescriptorDiscoverer& characteristicDescriptorDiscoverer() {
+        return _characteristicDescriptorDiscoverer;
+    }
+
+private:
+    nRF5xGattClient(const nRF5xGattClient &);
+    const nRF5xGattClient& operator=(const nRF5xGattClient &);
+
+private:
+    nRF5xServiceDiscovery _discovery;
+    nRF5xCharacteristicDescriptorDiscoverer _characteristicDescriptorDiscoverer;
+
+#endif // if !S110
+};
+
+#endif // ifndef __NRF51822_GATT_CLIENT_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGattServer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGattServer.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,543 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xGattServer.h"
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+
+#include "common/common.h"
+#include "btle/custom/custom_helper.h"
+
+#include "nRF5xn.h"
+
+/**************************************************************************/
+/*!
+    @brief  Adds a new service to the GATT table on the peripheral
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @section EXAMPLE
+
+    @code
+
+    @endcode
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::addService(GattService &service)
+{
+    /* ToDo: Make sure this service UUID doesn't already exist (?) */
+    /* ToDo: Basic validation */
+
+    /* Add the service to the nRF51 */
+    ble_uuid_t nordicUUID;
+    nordicUUID = custom_convert_to_nordic_uuid(service.getUUID());
+
+    uint16_t serviceHandle;
+    ASSERT( ERROR_NONE ==
+            sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
+                                     &nordicUUID,
+                                     &serviceHandle),
+            BLE_ERROR_PARAM_OUT_OF_RANGE );
+    service.setHandle(serviceHandle);
+
+    /* Add characteristics to the service */
+    for (uint8_t i = 0; i < service.getCharacteristicCount(); i++) {
+        if (characteristicCount >= BLE_TOTAL_CHARACTERISTICS) {
+            return BLE_ERROR_NO_MEM;
+        }
+        GattCharacteristic *p_char = service.getCharacteristic(i);
+
+        /* Skip any incompletely defined, read-only characteristics. */
+        if ((p_char->getValueAttribute().getValuePtr() == NULL) &&
+            (p_char->getValueAttribute().getLength() == 0) &&
+            (p_char->getProperties() == GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ)) {
+            continue;
+        }
+
+        nordicUUID = custom_convert_to_nordic_uuid(p_char->getValueAttribute().getUUID());
+
+        /* The user-description descriptor is a special case which needs to be
+         * handled at the time of adding the characteristic. The following block
+         * is meant to discover its presence. */
+        const uint8_t *userDescriptionDescriptorValuePtr = NULL;
+        uint16_t userDescriptionDescriptorValueLen = 0;
+        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
+            GattAttribute *p_desc = p_char->getDescriptor(j);
+            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
+                userDescriptionDescriptorValuePtr = p_desc->getValuePtr();
+                userDescriptionDescriptorValueLen = p_desc->getLength();
+            }
+        }
+
+        ASSERT ( ERROR_NONE ==
+                 custom_add_in_characteristic(BLE_GATT_HANDLE_INVALID,
+                                              &nordicUUID,
+                                              p_char->getProperties(),
+                                              p_char->getRequiredSecurity(),
+                                              p_char->getValueAttribute().getValuePtr(),
+                                              p_char->getValueAttribute().getLength(),
+                                              p_char->getValueAttribute().getMaxLength(),
+                                              p_char->getValueAttribute().hasVariableLength(),
+                                              userDescriptionDescriptorValuePtr,
+                                              userDescriptionDescriptorValueLen,
+                                              p_char->isReadAuthorizationEnabled(),
+                                              p_char->isWriteAuthorizationEnabled(),
+                                              &nrfCharacteristicHandles[characteristicCount]),
+                 BLE_ERROR_PARAM_OUT_OF_RANGE );
+
+        /* Update the characteristic handle */
+        p_characteristics[characteristicCount] = p_char;
+        p_char->getValueAttribute().setHandle(nrfCharacteristicHandles[characteristicCount].value_handle);
+        characteristicCount++;
+
+        /* Add optional descriptors if any */
+        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
+            if (descriptorCount >= BLE_TOTAL_DESCRIPTORS) {
+                return BLE_ERROR_NO_MEM;
+            }
+
+            GattAttribute *p_desc = p_char->getDescriptor(j);
+            /* skip the user-description-descriptor here; this has already been handled when adding the characteristic (above). */
+            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
+                continue;
+            }
+
+            nordicUUID = custom_convert_to_nordic_uuid(p_desc->getUUID());
+
+            ASSERT(ERROR_NONE ==
+                   custom_add_in_descriptor(BLE_GATT_HANDLE_INVALID,
+                                            &nordicUUID,
+                                            p_desc->getValuePtr(),
+                                            p_desc->getLength(),
+                                            p_desc->getMaxLength(),
+                                            p_desc->hasVariableLength(),
+                                            &nrfDescriptorHandles[descriptorCount]),
+                BLE_ERROR_PARAM_OUT_OF_RANGE);
+
+            p_descriptors[descriptorCount] = p_desc;
+            p_desc->setHandle(nrfDescriptorHandles[descriptorCount]);
+            descriptorCount++;
+        }
+    }
+
+    serviceCount++;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Reads the value of a characteristic, based on the service
+            and characteristic index fields
+
+    @param[in]  attributeHandle
+                The handle of the GattCharacteristic to read from
+    @param[in]  buffer
+                Buffer to hold the the characteristic's value
+                (raw byte array in LSB format)
+    @param[in/out] len
+                input:  Length in bytes to be read.
+                output: Total length of attribute value upon successful return.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
+{
+    return read(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, lengthP);
+}
+
+ble_error_t nRF5xGattServer::read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
+{
+    ble_gatts_value_t value = {
+        .len     = *lengthP,
+        .offset  = 0,
+        .p_value = buffer,
+    };
+
+    ASSERT( ERROR_NONE ==
+            sd_ble_gatts_value_get(connectionHandle, attributeHandle, &value),
+            BLE_ERROR_PARAM_OUT_OF_RANGE);
+    *lengthP = value.len;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Updates the value of a characteristic, based on the service
+            and characteristic index fields
+
+    @param[in]  charHandle
+                The handle of the GattCharacteristic to write to
+    @param[in]  buffer
+                Data to use when updating the characteristic's value
+                (raw byte array in LSB format)
+    @param[in]  len
+                The number of bytes in buffer
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::write(GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
+{
+    return write(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, len, localOnly);
+}
+
+ble_error_t nRF5xGattServer::write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
+{
+    ble_error_t returnValue = BLE_ERROR_NONE;
+
+    ble_gatts_value_t value = {
+        .len     = len,
+        .offset  = 0,
+        .p_value = const_cast<uint8_t *>(buffer),
+    };
+
+    if (localOnly) {
+        /* Only update locally regardless of notify/indicate */
+        ASSERT_INT( ERROR_NONE,
+                    sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
+                    BLE_ERROR_PARAM_OUT_OF_RANGE );
+        return BLE_ERROR_NONE;
+    }
+
+    int characteristicIndex = resolveValueHandleToCharIndex(attributeHandle);
+    if ((characteristicIndex != -1) &&
+        (p_characteristics[characteristicIndex]->getProperties() & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
+        /* HVX update for the characteristic value */
+        ble_gatts_hvx_params_t hvx_params;
+
+        hvx_params.handle = attributeHandle;
+        hvx_params.type   =
+            (p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) ? BLE_GATT_HVX_NOTIFICATION : BLE_GATT_HVX_INDICATION;
+        hvx_params.offset = 0;
+        hvx_params.p_data = const_cast<uint8_t *>(buffer);
+        hvx_params.p_len  = &len;
+
+        if (connectionHandle == BLE_CONN_HANDLE_INVALID) { /* use the default connection handle if the caller hasn't specified a valid connectionHandle. */
+            nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+            connectionHandle = gap.getConnectionHandle();
+        }
+        error_t error = (error_t) sd_ble_gatts_hvx(connectionHandle, &hvx_params);
+        if (error != ERROR_NONE) {
+            switch (error) {
+                case ERROR_BLE_NO_TX_BUFFERS: /*  Notifications consume application buffers. The return value can be used for resending notifications. */
+                case ERROR_BUSY:
+                    returnValue = BLE_STACK_BUSY;
+                    break;
+
+                case ERROR_INVALID_STATE:
+                case ERROR_BLEGATTS_SYS_ATTR_MISSING:
+                    returnValue = BLE_ERROR_INVALID_STATE;
+                    break;
+
+                default :
+                    ASSERT_INT( ERROR_NONE,
+                                sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
+                                BLE_ERROR_PARAM_OUT_OF_RANGE );
+
+                    /* Notifications consume application buffers. The return value can
+                     * be used for resending notifications. */
+                    returnValue = BLE_STACK_BUSY;
+                    break;
+            }
+        }
+    } else {
+        uint32_t err = sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value);
+        switch(err) {
+            case NRF_SUCCESS:
+                returnValue = BLE_ERROR_NONE;
+                break;
+            case NRF_ERROR_INVALID_ADDR:
+            case NRF_ERROR_INVALID_PARAM:
+                returnValue = BLE_ERROR_INVALID_PARAM;
+                break;
+            case NRF_ERROR_NOT_FOUND:
+            case NRF_ERROR_DATA_SIZE:
+            case BLE_ERROR_INVALID_CONN_HANDLE:
+            case BLE_ERROR_GATTS_INVALID_ATTR_TYPE:
+                returnValue = BLE_ERROR_PARAM_OUT_OF_RANGE;
+                break;
+            case NRF_ERROR_FORBIDDEN:
+                returnValue = BLE_ERROR_OPERATION_NOT_PERMITTED;
+                break;
+            default:
+                returnValue = BLE_ERROR_UNSPECIFIED;
+                break;
+        }
+    }
+
+    return returnValue;
+}
+
+ble_error_t nRF5xGattServer::areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP)
+{
+    /* Forward the call with the default connection handle. */
+    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
+    return areUpdatesEnabled(gap.getConnectionHandle(), characteristic, enabledP);
+}
+
+ble_error_t nRF5xGattServer::areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP)
+{
+    int characteristicIndex = resolveValueHandleToCharIndex(characteristic.getValueHandle());
+    if (characteristicIndex == -1) {
+        return BLE_ERROR_INVALID_PARAM;
+    }
+
+    /* Read the cccd value from the GATT server. */
+    GattAttribute::Handle_t cccdHandle = nrfCharacteristicHandles[characteristicIndex].cccd_handle;
+    uint16_t cccdValue;
+    uint16_t length = sizeof(cccdValue);
+    ble_error_t rc = read(connectionHandle, cccdHandle, reinterpret_cast<uint8_t *>(&cccdValue), &length);
+    if (rc != BLE_ERROR_NONE) {
+        return rc;
+    }
+    if (length != sizeof(cccdValue)) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Check for NOTFICATION or INDICATION in CCCD. */
+    if ((cccdValue & BLE_GATT_HVX_NOTIFICATION) || (cccdValue & BLE_GATT_HVX_INDICATION)) {
+        *enabledP = true;
+    }
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Clear nRF5xGattServer's state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+*/
+/**************************************************************************/
+ble_error_t nRF5xGattServer::reset(void)
+{
+    /* Clear all state that is from the parent, including private members */
+    if (GattServer::reset() != BLE_ERROR_NONE) {
+        return BLE_ERROR_INVALID_STATE;
+    }
+
+    /* Clear derived class members */
+    memset(p_characteristics,        0, sizeof(p_characteristics));
+    memset(p_descriptors,            0, sizeof(p_descriptors));
+    memset(nrfCharacteristicHandles, 0, sizeof(ble_gatts_char_handles_t));
+    memset(nrfDescriptorHandles,     0, sizeof(nrfDescriptorHandles));
+    descriptorCount = 0;
+
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Callback handler for events getting pushed up from the SD
+*/
+/**************************************************************************/
+void nRF5xGattServer::hwCallback(ble_evt_t *p_ble_evt)
+{
+    GattAttribute::Handle_t        handle_value;
+    GattServerEvents::gattEvent_t  eventType;
+    const ble_gatts_evt_t         *gattsEventP = &p_ble_evt->evt.gatts_evt;
+
+    switch (p_ble_evt->header.evt_id) {
+        case BLE_GATTS_EVT_WRITE: {
+                /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */
+
+                /* 1.) Handle CCCD changes */
+                handle_value = gattsEventP->params.write.handle;
+                int characteristicIndex = resolveCCCDHandleToCharIndex(handle_value);
+                if ((characteristicIndex != -1) &&
+                    (p_characteristics[characteristicIndex]->getProperties() &
+                        (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
+
+                    uint16_t cccd_value = (gattsEventP->params.write.data[1] << 8) | gattsEventP->params.write.data[0]; /* Little Endian but M0 may be mis-aligned */
+
+                    if (((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION)) ||
+                        ((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) {
+                        eventType = GattServerEvents::GATT_EVENT_UPDATES_ENABLED;
+                    } else {
+                        eventType = GattServerEvents::GATT_EVENT_UPDATES_DISABLED;
+                    }
+
+                    handleEvent(eventType, p_characteristics[characteristicIndex]->getValueHandle());
+                    return;
+                }
+
+                /* 2.) Changes to the characteristic value will be handled with other events below */
+                eventType = GattServerEvents::GATT_EVENT_DATA_WRITTEN;
+            }
+            break;
+
+        case BLE_GATTS_EVT_HVC:
+            /* Indication confirmation received */
+            eventType    = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED;
+            handle_value = gattsEventP->params.hvc.handle;
+            break;
+
+        case BLE_EVT_TX_COMPLETE: {
+            handleDataSentEvent(p_ble_evt->evt.common_evt.params.tx_complete.count);
+            return;
+        }
+
+        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
+            sd_ble_gatts_sys_attr_set(gattsEventP->conn_handle, NULL, 0, 0);
+            return;
+
+        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
+            switch (gattsEventP->params.authorize_request.type) {
+                case BLE_GATTS_AUTHORIZE_TYPE_READ:
+                    eventType    = GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ;
+                    handle_value = gattsEventP->params.authorize_request.request.read.handle;
+                    break;
+                case BLE_GATTS_AUTHORIZE_TYPE_WRITE:
+                    eventType    = GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ;
+                    handle_value = gattsEventP->params.authorize_request.request.write.handle;
+                    break;
+                default:
+                    return;
+            }
+            break;
+
+        default:
+            return;
+    }
+
+    int characteristicIndex = resolveValueHandleToCharIndex(handle_value);
+    if (characteristicIndex == -1) {
+        return;
+    }
+
+    /* Find index (charHandle) in the pool */
+    switch (eventType) {
+        case GattServerEvents::GATT_EVENT_DATA_WRITTEN: {
+            GattWriteCallbackParams cbParams = {
+                .connHandle = gattsEventP->conn_handle,
+                .handle     = handle_value,
+                .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.write.op),
+                .offset     = gattsEventP->params.write.offset,
+                .len        = gattsEventP->params.write.len,
+                .data       = gattsEventP->params.write.data
+            };
+            handleDataWrittenEvent(&cbParams);
+            break;
+        }
+        case GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ: {
+            GattWriteAuthCallbackParams cbParams = {
+                .connHandle = gattsEventP->conn_handle,
+                .handle     = handle_value,
+                .offset     = gattsEventP->params.authorize_request.request.write.offset,
+                .len        = gattsEventP->params.authorize_request.request.write.len,
+                .data       = gattsEventP->params.authorize_request.request.write.data,
+                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
+                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
+                                                                   * request is to proceed. */
+            };
+            
+            ble_gatts_rw_authorize_reply_params_t reply = {
+                .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE,
+                .params = {
+                    .write = {
+                        .gatt_status = p_characteristics[characteristicIndex]->authorizeWrite(&cbParams),
+                        .update = 1,
+                        .offset = cbParams.offset,
+                        .len = cbParams.len,
+                        .p_data = cbParams.data
+                    }
+                }
+            };
+            
+            if (reply.params.write.gatt_status != BLE_GATT_STATUS_SUCCESS)
+            {
+                reply.params.write.update = 0;
+            }
+            
+            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
+
+            /*
+             * If write-authorization is enabled for a characteristic,
+             * AUTHORIZATION_REQ event (if replied with true) is *not*
+             * followed by another DATA_WRITTEN event; so we still need
+             * to invoke handleDataWritten(), much the same as we would
+             * have done if write-authorization had not been enabled.
+             */
+            if (reply.params.write.gatt_status == BLE_GATT_STATUS_SUCCESS) {
+                GattWriteCallbackParams cbParams = {
+                    .connHandle = gattsEventP->conn_handle,
+                    .handle     = handle_value,
+                    .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.authorize_request.request.write.op),
+                    .offset     = gattsEventP->params.authorize_request.request.write.offset,
+                    .len        = gattsEventP->params.authorize_request.request.write.len,
+                    .data       = gattsEventP->params.authorize_request.request.write.data,
+                };
+                handleDataWrittenEvent(&cbParams);
+            }
+            break;
+        }
+        case GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ: {
+            GattReadAuthCallbackParams cbParams = {
+                .connHandle         = gattsEventP->conn_handle,
+                .handle             = handle_value,
+                .offset             = gattsEventP->params.authorize_request.request.read.offset,
+                .len                = 0,
+                .data               = NULL,
+                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
+                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
+                                                                   * request is to proceed. */
+            };
+
+            ble_gatts_rw_authorize_reply_params_t reply = {
+                .type = BLE_GATTS_AUTHORIZE_TYPE_READ,
+                .params = {
+                    .read = {
+                        .gatt_status = p_characteristics[characteristicIndex]->authorizeRead(&cbParams)
+                    }
+                }
+            };
+
+            if (cbParams.authorizationReply == BLE_GATT_STATUS_SUCCESS) {
+                if (cbParams.data != NULL) {
+                    reply.params.read.update = 1;
+                    reply.params.read.offset = cbParams.offset;
+                    reply.params.read.len    = cbParams.len;
+                    reply.params.read.p_data = cbParams.data;
+                }
+            }
+
+            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
+            break;
+        }
+
+        default:
+            handleEvent(eventType, handle_value);
+            break;
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xGattServer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xGattServer.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,103 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_GATT_SERVER_H__
+#define __NRF51822_GATT_SERVER_H__
+
+#include <stddef.h>
+
+#include "ble/blecommon.h"
+#include "nrf_ble.h" /* nordic ble */
+#include "ble/Gap.h"
+#include "ble/GattServer.h"
+
+class nRF5xGattServer : public GattServer
+{
+public:
+    /* Functions that must be implemented from GattServer */
+    virtual ble_error_t addService(GattService &);
+    virtual ble_error_t read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
+    virtual ble_error_t read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
+    virtual ble_error_t write(GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
+    virtual ble_error_t write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
+    virtual ble_error_t areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP);
+    virtual ble_error_t areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP);
+    virtual ble_error_t reset(void);
+
+    /* nRF51 Functions */
+    void eventCallback(void);
+    void hwCallback(ble_evt_t *p_ble_evt);
+
+
+private:
+    const static unsigned BLE_TOTAL_CHARACTERISTICS = 20;
+    const static unsigned BLE_TOTAL_DESCRIPTORS     = 8;
+
+private:
+    /**
+     * resolve a value attribute to its owning characteristic.
+     * @param  valueHandle the value handle to be resolved.
+     * @return             characteristic index if a resolution is found, else -1.
+     */
+    int resolveValueHandleToCharIndex(GattAttribute::Handle_t valueHandle) const {
+        unsigned charIndex;
+        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
+            if (nrfCharacteristicHandles[charIndex].value_handle == valueHandle) {
+                return charIndex;
+            }
+        }
+
+        return -1;
+    }
+
+    /**
+     * resolve a CCCD attribute handle to its owning characteristic.
+     * @param  cccdHandle the CCCD handle to be resolved.
+     * @return             characteristic index if a resolution is found, else -1.
+     */
+    int resolveCCCDHandleToCharIndex(GattAttribute::Handle_t cccdHandle) const {
+        unsigned charIndex;
+        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
+            if (nrfCharacteristicHandles[charIndex].cccd_handle == cccdHandle) {
+                return charIndex;
+            }
+        }
+
+        return -1;
+    }
+
+private:
+    GattCharacteristic       *p_characteristics[BLE_TOTAL_CHARACTERISTICS];
+    ble_gatts_char_handles_t  nrfCharacteristicHandles[BLE_TOTAL_CHARACTERISTICS];
+    GattAttribute            *p_descriptors[BLE_TOTAL_DESCRIPTORS];
+    uint8_t                   descriptorCount;
+    uint16_t                  nrfDescriptorHandles[BLE_TOTAL_DESCRIPTORS];
+
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xGattServer() : GattServer(), p_characteristics(), nrfCharacteristicHandles(), p_descriptors(), descriptorCount(0), nrfDescriptorHandles() {
+        /* empty */
+    }
+
+private:
+    nRF5xGattServer(const nRF5xGattServer &);
+    const nRF5xGattServer& operator=(const nRF5xGattServer &);
+};
+
+#endif // ifndef __NRF51822_GATT_SERVER_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xSecurityManager.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xSecurityManager.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,174 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_SECURITY_MANAGER_H__
+#define __NRF51822_SECURITY_MANAGER_H__
+
+#include <stddef.h>
+
+#include "nRF5xGap.h"
+#include "ble/SecurityManager.h"
+#include "btle_security.h"
+
+class nRF5xSecurityManager : public SecurityManager
+{
+public:
+    /* Functions that must be implemented from SecurityManager */
+    virtual ble_error_t init(bool                     enableBonding,
+                             bool                     requireMITM,
+                             SecurityIOCapabilities_t iocaps,
+                             const Passkey_t          passkey) {
+        return btle_initializeSecurity(enableBonding, requireMITM, iocaps, passkey);
+    }
+
+    virtual ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, LinkSecurityStatus_t *securityStatusP) {
+        return btle_getLinkSecurity(connectionHandle, securityStatusP);
+    }
+
+    virtual ble_error_t setLinkSecurity(Gap::Handle_t connectionHandle, SecurityMode_t securityMode) {
+        return btle_setLinkSecurity(connectionHandle, securityMode);
+    }
+
+    virtual ble_error_t purgeAllBondingState(void) {
+        return btle_purgeAllBondingState();
+    }
+
+    /**
+     * @brief  Returns a list of addresses from peers in the stacks bond table.
+     *
+     * @param[in/out]   addresses
+     *                  (on input) @ref Gap::Whitelist_t structure where at
+     *                  most addresses.capacity addresses from bonded peers will
+     *                  be stored.
+     *                  (on output) A copy of the addresses from bonded peers.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const {
+        uint8_t i;
+
+        ble_gap_whitelist_t  whitelistFromBondTable;
+        ble_gap_addr_t      *addressPtr[YOTTA_CFG_WHITELIST_MAX_SIZE];
+        ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
+
+        /* Initialize the structure so that we get as many addreses as the whitelist can hold */
+        whitelistFromBondTable.addr_count = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_addrs   = addressPtr;
+        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
+        whitelistFromBondTable.pp_irks    = irkPtr;
+
+        ble_error_t error = createWhitelistFromBondTable(whitelistFromBondTable);
+        if (error != BLE_ERROR_NONE) {
+            addresses.size = 0;
+            return error;
+        }
+
+        /* Put all the addresses in the structure */
+        for (i = 0; i < whitelistFromBondTable.addr_count; ++i) {
+            if (i >= addresses.capacity) {
+                /* Ran out of space in the output Gap::Whitelist_t */
+                addresses.size = i;
+                return BLE_ERROR_NONE;
+            }
+            memcpy(&addresses.addresses[i], whitelistFromBondTable.pp_addrs[i], sizeof(BLEProtocol::Address_t));
+        }
+
+        /* Update the current address count */
+        addresses.size = i;
+
+        /* The assumption here is that the underlying implementation of
+         * createWhitelistFromBondTable()  will not return the private resolvable
+         * addresses (which is the case in the SoftDevice). Rather it returns the
+         * IRKs, so we need to generate the private resolvable address by ourselves.
+         */
+        for (i = 0; i < whitelistFromBondTable.irk_count; ++i) {
+            if (i + addresses.size >= addresses.capacity) {
+                /* Ran out of space in the output Gap::Whitelist_t */
+                addresses.size += i;
+                return BLE_ERROR_NONE;
+            }
+            btle_generateResolvableAddress(
+                *whitelistFromBondTable.pp_irks[i],
+                (ble_gap_addr_t &) addresses.addresses[i + addresses.size]
+            );
+        }
+
+        /* Update the current address count */
+        addresses.size += i;
+
+        return BLE_ERROR_NONE;
+    }
+
+    /**
+     * @brief  Clear nRF5xSecurityManager's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void)
+    {
+        if (SecurityManager::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        return BLE_ERROR_NONE;
+    }
+
+    bool hasInitialized(void) const {
+        return btle_hasInitializedSecurity();
+    }
+
+public:
+    /*
+     * Allow instantiation from nRF5xn when required.
+     */
+    friend class nRF5xn;
+
+    nRF5xSecurityManager() {
+        /* empty */
+    }
+
+private:
+    nRF5xSecurityManager(const nRF5xSecurityManager &);
+    const nRF5xSecurityManager& operator=(const nRF5xSecurityManager &);
+
+    /*
+     * Expose an interface that allows us to query the SoftDevice bond table
+     * and extract a whitelist.
+     */
+    ble_error_t createWhitelistFromBondTable(ble_gap_whitelist_t &whitelistFromBondTable) const {
+        return btle_createWhitelistFromBondTable(&whitelistFromBondTable);
+    }
+
+    /*
+     * Given a BLE address and a IRK this function check whether the address
+     * can be generated from the IRK. To do so, this function uses the hash
+     * function and algorithm described in the Bluetooth low Energy
+     * Specification. Internally, Nordic SDK functions are used.
+     */
+    bool matchAddressAndIrk(ble_gap_addr_t *address, ble_gap_irk_t *irk) const {
+        return btle_matchAddressAndIrk(address, irk);
+    }
+
+    /*
+     * Give nRF5xGap access to createWhitelistFromBondTable() and
+     * matchAddressAndIrk()
+     */
+    friend class nRF5xGap;
+};
+
+#endif // ifndef __NRF51822_SECURITY_MANAGER_H__
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xServiceDiscovery.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xServiceDiscovery.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,312 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "nRF5xServiceDiscovery.h"
+
+ble_error_t
+nRF5xServiceDiscovery::launchCharacteristicDiscovery(Gap::Handle_t connectionHandle,
+                                                     Gap::Handle_t startHandle,
+                                                     Gap::Handle_t endHandle)
+{
+    characteristicDiscoveryStarted(connectionHandle);
+
+    ble_gattc_handle_range_t handleRange = {
+        .start_handle = startHandle,
+        .end_handle   = endHandle
+    };
+    uint32_t rc = sd_ble_gattc_characteristics_discover(connectionHandle, &handleRange);
+    ble_error_t err = BLE_ERROR_NONE;
+
+    switch (rc) {
+        case NRF_SUCCESS:
+            err = BLE_ERROR_NONE;
+            break;
+        case BLE_ERROR_INVALID_CONN_HANDLE:
+        case NRF_ERROR_INVALID_ADDR:
+            err = BLE_ERROR_INVALID_PARAM;
+            break;
+        case NRF_ERROR_BUSY:
+            err = BLE_STACK_BUSY;
+            break;
+        case NRF_ERROR_INVALID_STATE:
+            err = BLE_ERROR_INVALID_STATE;
+            break;
+        default:
+            err = BLE_ERROR_UNSPECIFIED;
+            break;
+    }
+
+    if (err) {
+        terminateCharacteristicDiscovery(err);
+    }
+    return err;
+}
+
+void
+nRF5xServiceDiscovery::setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response)
+{
+    serviceIndex = 0;
+    numServices  = response->count;
+
+    /* Account for the limitation on the number of discovered services we can handle at a time. */
+    if (numServices > BLE_DB_DISCOVERY_MAX_SRV) {
+        numServices = BLE_DB_DISCOVERY_MAX_SRV;
+    }
+
+    serviceUUIDDiscoveryQueue.reset();
+    for (unsigned i = 0; i < numServices; ++i) {
+        if (response->services[i].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
+            serviceUUIDDiscoveryQueue.enqueue(i);
+            services[i].setup(response->services[i].handle_range.start_handle,
+                                         response->services[i].handle_range.end_handle);
+        } else {
+            services[i].setup(response->services[i].uuid.uuid,
+                                         response->services[i].handle_range.start_handle,
+                                         response->services[i].handle_range.end_handle);
+        }
+    }
+
+    /* Trigger discovery of service UUID if necessary. */
+    if (serviceUUIDDiscoveryQueue.getCount()) {
+        serviceUUIDDiscoveryQueue.triggerFirst();
+    }
+}
+
+void
+nRF5xServiceDiscovery::setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response)
+{
+    numCharacteristics  = response->count;
+
+    /* Account for the limitation on the number of discovered characteristics we can handle at a time. */
+    if (numCharacteristics > BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV) {
+        numCharacteristics = BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV;
+    }
+
+    charUUIDDiscoveryQueue.reset();
+    for (unsigned charIndex = 0; charIndex < numCharacteristics; charIndex++) {
+        if (response->chars[charIndex].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
+            charUUIDDiscoveryQueue.enqueue(charIndex);
+            characteristics[charIndex].setup(gattc,
+                                             connHandle,
+                                             response->chars[charIndex].char_props,
+                                             response->chars[charIndex].handle_decl,
+                                             response->chars[charIndex].handle_value);
+        } else {
+            characteristics[charIndex].setup(gattc,
+                                             connHandle,
+                                             response->chars[charIndex].uuid.uuid,
+                                             response->chars[charIndex].char_props,
+                                             response->chars[charIndex].handle_decl,
+                                             response->chars[charIndex].handle_value);
+        }
+    }
+
+    /* Trigger discovery of char UUID if necessary. */
+    if (charUUIDDiscoveryQueue.getCount()) {
+        charUUIDDiscoveryQueue.triggerFirst();
+    }
+}
+
+void
+nRF5xServiceDiscovery::progressCharacteristicDiscovery(void)
+{
+    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+        return;
+    }
+
+    if ((discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) && (numCharacteristics > 0)) {
+        discoveredCharacteristic.setLastHandle(characteristics[0].getDeclHandle() - 1);
+
+        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
+             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+            if (characteristicCallback) {
+                characteristicCallback(&discoveredCharacteristic);
+            }
+        }
+    }
+
+    for (uint8_t i = 0; i < numCharacteristics; ++i) {
+        if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+            return;
+        }
+
+        if (i == (numCharacteristics - 1)) {
+            discoveredCharacteristic = characteristics[i];
+            break;
+        } else {
+            characteristics[i].setLastHandle(characteristics[i + 1].getDeclHandle() - 1);
+        }
+
+        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            ((matchingCharacteristicUUID == characteristics[i].getUUID()) &&
+             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+            if (characteristicCallback) {
+                characteristicCallback(&characteristics[i]);
+            }
+        }
+    }
+
+    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
+        return;
+    }
+
+    Gap::Handle_t startHandle = (numCharacteristics > 0) ? characteristics[numCharacteristics - 1].getValueHandle() + 1 : SRV_DISC_END_HANDLE;
+    Gap::Handle_t endHandle   = services[serviceIndex].getEndHandle();
+    resetDiscoveredCharacteristics(); /* Note: resetDiscoveredCharacteristics() must come after fetching start and end Handles. */
+
+    if (startHandle < endHandle) {
+        ble_gattc_handle_range_t handleRange = {
+            .start_handle = startHandle,
+            .end_handle   = endHandle
+        };
+        if (sd_ble_gattc_characteristics_discover(connHandle, &handleRange) != NRF_SUCCESS) {
+            terminateCharacteristicDiscovery(BLE_ERROR_UNSPECIFIED);
+        }
+    } else {
+        terminateCharacteristicDiscovery(BLE_ERROR_NONE);
+    }
+}
+
+void
+nRF5xServiceDiscovery::progressServiceDiscovery(void)
+{
+    /* Iterate through the previously discovered services cached in services[]. */
+    while ((state == SERVICE_DISCOVERY_ACTIVE) && (serviceIndex < numServices)) {
+        if ((matchingServiceUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+            (matchingServiceUUID == services[serviceIndex].getUUID())) {
+
+            if (serviceCallback && (matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN))) {
+                serviceCallback(&services[serviceIndex]);
+            }
+
+            if ((state == SERVICE_DISCOVERY_ACTIVE) && characteristicCallback) {
+                launchCharacteristicDiscovery(connHandle, services[serviceIndex].getStartHandle(), services[serviceIndex].getEndHandle());
+            } else {
+                serviceIndex++;
+            }
+        } else {
+            serviceIndex++;
+        }
+    }
+
+    /* Relaunch discovery of new services beyond the last entry cached in services[]. */
+    if ((state == SERVICE_DISCOVERY_ACTIVE) && (numServices > 0) && (serviceIndex > 0)) {
+        /* Determine the ending handle of the last cached service. */
+        Gap::Handle_t endHandle = services[serviceIndex - 1].getEndHandle();
+        resetDiscoveredServices(); /* Note: resetDiscoveredServices() must come after fetching endHandle. */
+
+        if (endHandle == SRV_DISC_END_HANDLE) {
+            terminateServiceDiscovery();
+        } else {
+            // the next service is located after the last handle discovered
+            // Launch a new discovery from [endHandle + 1 : 0xFFFF]
+            if (sd_ble_gattc_primary_services_discover(connHandle, endHandle + 1, NULL) != NRF_SUCCESS) {
+                terminateServiceDiscovery();
+            }
+        }
+    }
+}
+
+void
+nRF5xServiceDiscovery::ServiceUUIDDiscoveryQueue::triggerFirst(void)
+{
+    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
+        parentDiscoveryObject->state = DISCOVER_SERVICE_UUIDS;
+
+        unsigned serviceIndex = getFirst();
+        ble_uuid_t uuid = {
+            .uuid = BLE_UUID_SERVICE_PRIMARY,
+            .type = BLE_UUID_TYPE_BLE,
+        };
+        ble_gattc_handle_range_t handleRange = {
+            .start_handle = parentDiscoveryObject->services[serviceIndex].getStartHandle(),
+            .end_handle   = parentDiscoveryObject->services[serviceIndex].getEndHandle(),
+        };
+        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
+            return;
+        }
+
+        /* Skip this service if we fail to launch a read for its service-declaration
+         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
+        dequeue();
+    }
+
+    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
+    if (parentDiscoveryObject->state == DISCOVER_SERVICE_UUIDS) {
+        parentDiscoveryObject->state = SERVICE_DISCOVERY_ACTIVE;
+    }
+}
+
+void
+nRF5xServiceDiscovery::CharUUIDDiscoveryQueue::triggerFirst(void)
+{
+    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
+        parentDiscoveryObject->state = DISCOVER_CHARACTERISTIC_UUIDS;
+
+        unsigned charIndex = getFirst();
+        ble_uuid_t uuid = {
+            .uuid = BLE_UUID_CHARACTERISTIC,
+            .type = BLE_UUID_TYPE_BLE,
+        };
+        ble_gattc_handle_range_t handleRange = { };
+        handleRange.start_handle = parentDiscoveryObject->characteristics[charIndex].getDeclHandle();
+        handleRange.end_handle   = parentDiscoveryObject->characteristics[charIndex].getDeclHandle() + 1;
+        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
+            return;
+        }
+
+        /* Skip this service if we fail to launch a read for its service-declaration
+         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
+        dequeue();
+    }
+
+    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
+    if (parentDiscoveryObject->state == DISCOVER_CHARACTERISTIC_UUIDS) {
+        parentDiscoveryObject->state = CHARACTERISTIC_DISCOVERY_ACTIVE;
+    }
+}
+
+void
+nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response)
+{
+    if (state == DISCOVER_SERVICE_UUIDS) {
+        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID)) {
+            UUID::LongUUIDBytes_t uuid;
+            memcpy(uuid, response->handle_value[0].p_value, UUID::LENGTH_OF_LONG_UUID);
+
+            unsigned serviceIndex = serviceUUIDDiscoveryQueue.dequeue();
+            services[serviceIndex].setupLongUUID(uuid, UUID::LSB);
+
+            serviceUUIDDiscoveryQueue.triggerFirst();
+        } else {
+            serviceUUIDDiscoveryQueue.dequeue();
+        }
+    } else if (state == DISCOVER_CHARACTERISTIC_UUIDS) {
+        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID + 1 /* props */ + 2 /* value handle */)) {
+            UUID::LongUUIDBytes_t uuid;
+
+            memcpy(uuid, &(response->handle_value[0].p_value[3]), UUID::LENGTH_OF_LONG_UUID);
+
+            unsigned charIndex = charUUIDDiscoveryQueue.dequeue();
+            characteristics[charIndex].setupLongUUID(uuid, UUID::LSB);
+
+            charUUIDDiscoveryQueue.triggerFirst();
+        } else {
+            charUUIDDiscoveryQueue.dequeue();
+        }
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xServiceDiscovery.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xServiceDiscovery.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,366 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF_SERVICE_DISCOVERY_H__
+#define __NRF_SERVICE_DISCOVERY_H__
+
+#include "ble/ServiceDiscovery.h"
+#include "ble/DiscoveredService.h"
+#include "nRF5xDiscoveredCharacteristic.h"
+
+#include "nrf_ble.h"
+#include "nrf_ble_gattc.h"
+
+class nRF5xGattClient; /* forward declaration */
+
+class nRF5xServiceDiscovery : public ServiceDiscovery
+{
+public:
+    static const uint16_t SRV_DISC_START_HANDLE             = 0x0001; /**< The start handle value used during service discovery. */
+    static const uint16_t SRV_DISC_END_HANDLE               = 0xFFFF; /**< The end handle value used during service discovery. */
+
+public:
+    static const unsigned BLE_DB_DISCOVERY_MAX_SRV          = 4;      /**< Maximum number of services we can retain information for after a single discovery. */
+    static const unsigned BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV = 4;      /**< Maximum number of characteristics per service we can retain information for. */
+
+public:
+    nRF5xServiceDiscovery(nRF5xGattClient *gattcIn) :
+        gattc(gattcIn),
+        serviceIndex(0),
+        numServices(0),
+        numCharacteristics(0),
+        state(INACTIVE),
+        services(),
+        characteristics(),
+        serviceUUIDDiscoveryQueue(this),
+        charUUIDDiscoveryQueue(this),
+        onTerminationCallback(NULL) {
+        /* empty */
+    }
+
+    virtual ble_error_t launch(Gap::Handle_t                               connectionHandle,
+                               ServiceDiscovery::ServiceCallback_t         sc,
+                               ServiceDiscovery::CharacteristicCallback_t  cc,
+                               const UUID                                 &matchingServiceUUIDIn,
+                               const UUID                                 &matchingCharacteristicUUIDIn)
+    {
+        if (isActive()) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        serviceCallback            = sc;
+        characteristicCallback     = cc;
+        matchingServiceUUID        = matchingServiceUUIDIn;
+        matchingCharacteristicUUID = matchingCharacteristicUUIDIn;
+
+        serviceDiscoveryStarted(connectionHandle);
+
+        uint32_t rc;
+        if ((rc = sd_ble_gattc_primary_services_discover(connectionHandle, SRV_DISC_START_HANDLE, NULL)) != NRF_SUCCESS) {
+            terminate();
+            switch (rc) {
+                case NRF_ERROR_INVALID_PARAM:
+                case BLE_ERROR_INVALID_CONN_HANDLE:
+                    return BLE_ERROR_INVALID_PARAM;
+                case NRF_ERROR_BUSY:
+                    return BLE_STACK_BUSY;
+                default:
+                case NRF_ERROR_INVALID_STATE:
+                    return BLE_ERROR_INVALID_STATE;
+            }
+        }
+
+        return BLE_ERROR_NONE;
+    }
+
+    virtual bool isActive(void) const {
+        return state != INACTIVE;
+    }
+
+    virtual void terminate(void) {
+        terminateServiceDiscovery();
+    }
+
+    void terminate(Gap::Handle_t connectionHandle) {
+        if(connHandle == connectionHandle) {
+            terminate();
+        }
+    }
+
+    virtual void onTermination(ServiceDiscovery::TerminationCallback_t callback) {
+        onTerminationCallback = callback;
+    }
+
+    /**
+     * @brief  Clear nRF5xServiceDiscovery's state.
+     *
+     * @return
+     *           BLE_ERROR_NONE if successful.
+     */
+    virtual ble_error_t reset(void) {
+        /* Clear all state that is from the parent, including private members */
+        if (ServiceDiscovery::reset() != BLE_ERROR_NONE) {
+            return BLE_ERROR_INVALID_STATE;
+        }
+
+        /* Clear derived class members */
+        serviceIndex = 0;
+        numServices = 0;
+        numCharacteristics = 0;
+
+        state = INACTIVE;
+
+        serviceUUIDDiscoveryQueue.reset();
+        charUUIDDiscoveryQueue.reset();
+
+        onTerminationCallback = NULL;
+
+        return BLE_ERROR_NONE;
+    }
+
+private:
+    ble_error_t launchCharacteristicDiscovery(Gap::Handle_t connectionHandle, Gap::Handle_t startHandle, Gap::Handle_t endHandle);
+
+private:
+    void setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response);
+    void setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response);
+
+    void triggerServiceUUIDDiscovery(void);
+    void processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response);
+    void removeFirstServiceNeedingUUIDDiscovery(void);
+
+    void terminateServiceDiscovery(void) {
+        discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
+
+        bool wasActive = isActive();
+        state = INACTIVE;
+
+        if (wasActive && onTerminationCallback) {
+            onTerminationCallback(connHandle);
+        }
+    }
+
+    void terminateCharacteristicDiscovery(ble_error_t err) {
+        if (state == CHARACTERISTIC_DISCOVERY_ACTIVE) {
+            if(discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) {
+               if(err == BLE_ERROR_NONE) {
+                    // fullfill the last characteristic
+                    discoveredCharacteristic.setLastHandle(services[serviceIndex].getEndHandle());
+
+                    if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
+                        ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
+                         (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
+                        if (characteristicCallback) {
+                            characteristicCallback(&discoveredCharacteristic);
+                        }
+                    }
+               }
+               discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
+            }
+
+            state = SERVICE_DISCOVERY_ACTIVE;
+        }
+        serviceIndex++; /* Progress service index to keep discovery alive. */
+    }
+
+private:
+    void resetDiscoveredServices(void) {
+        numServices  = 0;
+        serviceIndex = 0;
+    }
+
+    void resetDiscoveredCharacteristics(void) {
+        numCharacteristics  = 0;
+    }
+
+private:
+    void serviceDiscoveryStarted(Gap::Handle_t connectionHandle) {
+        connHandle = connectionHandle;
+        resetDiscoveredServices();
+        state = SERVICE_DISCOVERY_ACTIVE;
+    }
+
+private:
+    void characteristicDiscoveryStarted(Gap::Handle_t connectionHandle) {
+        connHandle = connectionHandle;
+        resetDiscoveredCharacteristics();
+        state = CHARACTERISTIC_DISCOVERY_ACTIVE;
+    }
+
+private:
+    /**
+     * A datatype to contain service-indices for which long UUIDs need to be
+     * discovered using read_val_by_uuid().
+     */
+    class ServiceUUIDDiscoveryQueue {
+    public:
+        ServiceUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
+            numIndices(0),
+            serviceIndices(),
+            parentDiscoveryObject(parent) {
+            /* empty */
+        }
+
+    public:
+        void reset(void) {
+            numIndices = 0;
+            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
+                serviceIndices[i] = INVALID_INDEX;
+            }
+        }
+        void enqueue(int serviceIndex) {
+            serviceIndices[numIndices++] = serviceIndex;
+        }
+        int dequeue(void) {
+            if (numIndices == 0) {
+                return INVALID_INDEX;
+            }
+
+            unsigned valueToReturn = serviceIndices[0];
+            numIndices--;
+            for (unsigned i = 0; i < numIndices; i++) {
+                serviceIndices[i] = serviceIndices[i + 1];
+            }
+
+            return valueToReturn;
+        }
+        unsigned getFirst(void) const {
+            return serviceIndices[0];
+        }
+        size_t getCount(void) const {
+            return numIndices;
+        }
+
+        /**
+         * Trigger UUID discovery for the first of the enqueued ServiceIndices.
+         */
+        void triggerFirst(void);
+
+    private:
+        static const int INVALID_INDEX = -1;
+
+    private:
+        size_t numIndices;
+        int    serviceIndices[BLE_DB_DISCOVERY_MAX_SRV];
+
+        nRF5xServiceDiscovery *parentDiscoveryObject;
+    };
+    friend class ServiceUUIDDiscoveryQueue;
+
+    /**
+     * A datatype to contain characteristic-indices for which long UUIDs need to
+     * be discovered using read_val_by_uuid().
+     */
+    class CharUUIDDiscoveryQueue {
+    public:
+        CharUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
+            numIndices(0),
+            charIndices(),
+            parentDiscoveryObject(parent) {
+            /* empty */
+        }
+
+    public:
+        void reset(void) {
+            numIndices = 0;
+            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
+                charIndices[i] = INVALID_INDEX;
+            }
+        }
+        void enqueue(int serviceIndex) {
+            charIndices[numIndices++] = serviceIndex;
+        }
+        int dequeue(void) {
+            if (numIndices == 0) {
+                return INVALID_INDEX;
+            }
+
+            unsigned valueToReturn = charIndices[0];
+            numIndices--;
+            for (unsigned i = 0; i < numIndices; i++) {
+                charIndices[i] = charIndices[i + 1];
+            }
+
+            return valueToReturn;
+        }
+        unsigned getFirst(void) const {
+            return charIndices[0];
+        }
+        size_t getCount(void) const {
+            return numIndices;
+        }
+
+        /**
+         * Trigger UUID discovery for the first of the enqueued charIndices.
+         */
+        void triggerFirst(void);
+
+    private:
+        static const int INVALID_INDEX = -1;
+
+    private:
+        size_t numIndices;
+        int    charIndices[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
+
+        nRF5xServiceDiscovery *parentDiscoveryObject;
+    };
+    friend class CharUUIDDiscoveryQueue;
+
+private:
+    friend void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
+    void progressCharacteristicDiscovery(void);
+    void progressServiceDiscovery(void);
+
+private:
+    nRF5xGattClient *gattc;
+
+private:
+    uint8_t  serviceIndex;        /**< Index of the current service being discovered. This is intended for internal use during service discovery.*/
+    uint8_t  numServices;         /**< Number of services at the peers GATT database.*/
+    uint8_t  numCharacteristics;  /**< Number of characteristics within the service.*/
+
+    enum State_t {
+        INACTIVE,
+        SERVICE_DISCOVERY_ACTIVE,
+        CHARACTERISTIC_DISCOVERY_ACTIVE,
+        DISCOVER_SERVICE_UUIDS,
+        DISCOVER_CHARACTERISTIC_UUIDS,
+    } state;
+
+    DiscoveredService           services[BLE_DB_DISCOVERY_MAX_SRV];  /**< Information related to the current service being discovered.
+                                                                      *  This is intended for internal use during service discovery. */
+    nRF5xDiscoveredCharacteristic characteristics[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
+
+    ServiceUUIDDiscoveryQueue   serviceUUIDDiscoveryQueue;
+    CharUUIDDiscoveryQueue      charUUIDDiscoveryQueue;
+
+    TerminationCallback_t       onTerminationCallback;
+
+    /*
+     * The currently discovered characteristic. Discovery of a characteristic
+     * is a two phase process.
+     * First, declaration handle is fetched, it provide the UUID, the value handle and
+     * the properties of a characteristic.
+     * Second, the next declaration handle is fetched, with its declaration handle, it is
+     * possible to compute the last handle of the discovered characteristic and fill the
+     * missing part of the object.
+     * If there is no remaining characteristic to discover, the last handle of the
+     * discovered characteristic will be set to the last handle of its enclosing service.
+     */
+    nRF5xDiscoveredCharacteristic discoveredCharacteristic;
+};
+
+#endif /*__NRF_SERVICE_DISCOVERY_H__*/
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xn.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xn.cpp	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,220 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifdef YOTTA_CFG_MBED_OS
+    #include "mbed-drivers/mbed.h"
+#else
+    #include "mbed.h"
+#endif
+#include "nRF5xn.h"
+#include "ble/blecommon.h"
+#include "nrf_soc.h"
+
+#include "btle/btle.h"
+#include "btle/custom/custom_helper.h"
+#include "nrf_delay.h"
+
+extern "C" {
+#include "softdevice_handler.h"
+}
+
+/**
+ * The singleton which represents the nRF51822 transport for the BLE.
+ */
+static nRF5xn deviceInstance;
+
+/**
+ * BLE-API requires an implementation of the following function in order to
+ * obtain its transport handle.
+ */
+BLEInstanceBase *
+createBLEInstance(void)
+{
+    return &nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
+}
+
+nRF5xn& nRF5xn::Instance(BLE::InstanceID_t instanceId)
+{
+    return deviceInstance;
+}
+
+nRF5xn::nRF5xn(void) :
+    initialized(false),
+    instanceID(BLE::DEFAULT_INSTANCE),
+    gapInstance(),
+    gattServerInstance(NULL),
+    gattClientInstance(NULL),
+    securityManagerInstance(NULL)
+{
+}
+
+nRF5xn::~nRF5xn(void)
+{
+}
+
+const char *nRF5xn::getVersion(void)
+{
+    if (!initialized) {
+        return "INITIALIZATION_INCOMPLETE";
+    }
+
+    static char versionString[32];
+    static bool versionFetched = false;
+
+    if (!versionFetched) {
+        ble_version_t version;
+        if ((sd_ble_version_get(&version) == NRF_SUCCESS) && (version.company_id == 0x0059)) {
+            switch (version.version_number) {
+                case 0x07:
+                case 0x08:
+                    snprintf(versionString, sizeof(versionString), "Nordic BLE4.1 ver:%u fw:%04x", version.version_number, version.subversion_number);
+                    break;
+                default:
+                    snprintf(versionString, sizeof(versionString), "Nordic (spec unknown) ver:%u fw:%04x", version.version_number, version.subversion_number);
+                    break;
+            }
+            versionFetched = true;
+        } else {
+            strncpy(versionString, "unknown", sizeof(versionString));
+        }
+    }
+
+    return versionString;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Initialize the BLE stack.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE if everything executed properly and
+                BLE_ERROR_ALREADY_INITIALIZED if the stack has already
+                been initialized (possibly through a call to nRF5xn::init()).
+                BLE_ERROR_INTERNAL_STACK_FAILURE is returned if initialization
+                of the internal stack (SoftDevice) failed.
+
+*/
+/**************************************************************************/
+ble_error_t nRF5xn::init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback)
+{
+    if (initialized) {
+        BLE::InitializationCompleteCallbackContext context = {
+            BLE::Instance(instanceID),
+            BLE_ERROR_ALREADY_INITIALIZED
+        };
+        callback.call(&context);
+        return BLE_ERROR_ALREADY_INITIALIZED;
+    }
+
+    instanceID   = instanceID;
+
+    /* ToDo: Clear memory contents, reset the SD, etc. */
+    if (btle_init() != ERROR_NONE) {
+        return BLE_ERROR_INTERNAL_STACK_FAILURE;
+    }
+
+    initialized = true;
+    BLE::InitializationCompleteCallbackContext context = {
+        BLE::Instance(instanceID),
+        BLE_ERROR_NONE
+    };
+    callback.call(&context);
+    return BLE_ERROR_NONE;
+}
+
+/**************************************************************************/
+/*!
+    @brief  Purge the BLE stack of GATT and GAP state.
+
+    @returns    ble_error_t
+
+    @retval     BLE_ERROR_NONE
+                Everything executed properly
+
+    @note  When using S110, GattClient::shutdown() will not be called
+           since Gatt client features are not supported.
+*/
+/**************************************************************************/
+ble_error_t nRF5xn::shutdown(void)
+{
+    if (!initialized) {
+        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
+    }
+
+    /*
+     * Shutdown the SoftDevice first. This is because we need to disable all
+     * interrupts. Otherwise if we clear the BLE API and glue code first there
+     * will be many NULL references and no config information which could lead
+     * to errors if the shutdown process is interrupted.
+     */
+    if (softdevice_handler_sd_disable() != NRF_SUCCESS) {
+        return BLE_STACK_BUSY;
+    }
+
+
+    /* Shutdown the BLE API and nRF51 glue code */
+    ble_error_t error;
+
+    if (gattServerInstance != NULL) {
+        error = gattServerInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    if (securityManagerInstance != NULL) {
+        error = securityManagerInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+
+    /* S110 does not support BLE client features, nothing to reset. */
+#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
+    if (gattClientInstance != NULL) {
+        error = gattClientInstance->reset();
+        if (error != BLE_ERROR_NONE) {
+            return error;
+        }
+    }
+#endif
+
+    /* Gap instance is always present */
+    error = gapInstance.reset();
+    if (error != BLE_ERROR_NONE) {
+        return error;
+    }
+
+    custom_reset_128bits_uuid_table();
+
+    initialized = false;
+    return BLE_ERROR_NONE;
+}
+
+void
+nRF5xn::waitForEvent(void)
+{
+    processEvents();
+    sd_app_evt_wait();
+}
+
+void nRF5xn::processEvents() {
+    if (isEventsSignaled) {
+        isEventsSignaled = false;
+        intern_softdevice_events_execute();
+    }
+}
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/nRF5xn.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/nRF5xn.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,184 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __NRF51822_H__
+#define __NRF51822_H__
+
+#include "ble/BLE.h"
+#include "ble/blecommon.h"
+#include "ble/BLEInstanceBase.h"
+
+#include "nRF5xGap.h"
+#include "nRF5xGattServer.h"
+#include "nRF5xGattClient.h"
+#include "nRF5xSecurityManager.h"
+
+#include "btle.h"
+
+class nRF5xn : public BLEInstanceBase
+{
+public:
+    nRF5xn(void);
+    virtual ~nRF5xn(void);
+
+    virtual ble_error_t init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback);
+    virtual bool        hasInitialized(void) const {
+        return initialized;
+    }
+    virtual ble_error_t shutdown(void);
+    virtual const char *getVersion(void);
+
+    /**
+     * Accessors to GAP. This function checks whether gapInstance points to an
+     * object. If if does not, then the gapInstance is updated to
+     * &_getInstance before returning.
+     *
+     * @return  A reference to GattServer.
+     *
+     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
+     *        always needed in a BLE application. Therefore it is allocated
+     *        statically.
+     */
+    virtual Gap &getGap() {
+        return gapInstance;
+    };
+
+    /**
+     * Accessors to GATT Server. This function checks whether a GattServer
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattServer.
+     */
+    virtual GattServer &getGattServer() {
+        if (gattServerInstance == NULL) {
+            gattServerInstance = new nRF5xGattServer();
+        }
+        return *gattServerInstance;
+    };
+
+    /**
+     * Accessors to GATT Client. This function checks whether a GattClient
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattClient.
+     */
+    virtual nRF5xGattClient &getGattClient() {
+        if (gattClientInstance == NULL) {
+            gattClientInstance = new nRF5xGattClient();
+        }
+        return *gattClientInstance;
+    }
+
+    /**
+     * Accessors to Security Manager. This function checks whether a SecurityManager
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A reference to GattServer.
+     */
+    virtual nRF5xSecurityManager &getSecurityManager() {
+        if (securityManagerInstance == NULL) {
+            securityManagerInstance = new nRF5xSecurityManager();
+        }
+        return *securityManagerInstance;
+    }
+
+    /**
+     * Accessors to GAP. This function checks whether gapInstance points to an
+     * object. If if does not, then the gapInstance is updated to
+     * &_getInstance before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
+     *        always needed in a BLE application. Therefore it is allocated
+     *        statically.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xGap &getGap() const  {
+        return gapInstance;
+    };
+
+    /**
+     * Accessors to GATT Server. This function checks whether a GattServer
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xGattServer &getGattServer() const {
+        if (gattServerInstance == NULL) {
+            gattServerInstance = new nRF5xGattServer();
+        }
+        return *gattServerInstance;
+    };
+
+    /**
+     * Accessors to Security Manager. This function checks whether a SecurityManager
+     * object was previously instantiated. If such object does not exist, then
+     * it is created before returning.
+     *
+     * @return  A const reference to GattServer.
+     *
+     * @note  The accessor is able to modify the object's state because the
+     *        internal pointer has been declared mutable.
+     */
+    virtual const nRF5xSecurityManager &getSecurityManager() const {
+        if (securityManagerInstance == NULL) {
+            securityManagerInstance = new nRF5xSecurityManager();
+        }
+        return *securityManagerInstance;
+    }
+
+    virtual void waitForEvent(void);
+
+    virtual void processEvents();
+
+public:
+    static nRF5xn& Instance(BLE::InstanceID_t instanceId);
+
+private:
+    bool              initialized;
+    BLE::InstanceID_t instanceID;
+
+private:
+    mutable nRF5xGap gapInstance; /**< Gap instance whose reference is returned from a call to
+                                   * getGap(). Unlike the GattClient, GattServer and
+                                   * SecurityManager, Gap is always needed in a BLE application. */
+
+private:
+    mutable nRF5xGattServer      *gattServerInstance;      /**< Pointer to the GattServer object instance.
+                                                            *   If NULL, then GattServer has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+    mutable nRF5xGattClient      *gattClientInstance;      /**< Pointer to the GattClient object instance.
+                                                            *   If NULL, then GattClient has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+    mutable nRF5xSecurityManager *securityManagerInstance; /**< Pointer to the SecurityManager object instance.
+                                                            *   If NULL, then SecurityManager has not been initialized.
+                                                            *   The pointer has been declared as 'mutable' so that
+                                                            *   it can be assigned inside a 'const' function. */
+};
+
+#endif
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/projectconfig.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/projectconfig.h	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,136 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _PROJECTCONFIG_H_
+#define _PROJECTCONFIG_H_
+
+#include "ble/GapAdvertisingData.h"
+
+/*=========================================================================
+    MCU & BOARD SELCTION
+
+    CFG_BOARD is one of the value defined in board.h
+    -----------------------------------------------------------------------*/
+    #define CFG_BOARD                                  BOARD_PCA10001
+    #define CFG_MCU_STRING                             "nRF51822"
+/*=========================================================================*/
+
+
+/*=========================================================================
+    CODE BASE VERSION SETTINGS
+
+    Please do not modify this version number.  To set a version number
+    for your project or firmware, change the values in your 'boards/'
+    config file.
+    -----------------------------------------------------------------------*/
+    #define CFG_CODEBASE_VERSION_MAJOR                 0
+    #define CFG_CODEBASE_VERSION_MINOR                 1
+    #define CFG_CODEBASE_VERSION_REVISION              0
+/*=========================================================================*/
+
+
+/*=========================================================================
+    FIRMWARE VERSION SETTINGS
+    -----------------------------------------------------------------------*/
+    #define CFG_FIRMWARE_VERSION_MAJOR                 0
+    #define CFG_FIRMWARE_VERSION_MINOR                 0
+    #define CFG_FIRMWARE_VERSION_REVISION              0
+/*=========================================================================*/
+
+
+/*=========================================================================
+    DEBUG LEVEL
+    -----------------------------------------------------------------------
+
+    CFG_DEBUG                 Level 3: Full debug output, any failed assert
+                                       will produce a breakpoint for the
+                                       debugger
+                              Level 2: ATTR_ALWAYS_INLINE is null, ASSERT
+                                       has text
+                              Level 1: ATTR_ALWAYS_INLINE is an attribute,
+                                       ASSERT has no text
+                              Level 0: No debug information generated
+
+    -----------------------------------------------------------------------*/
+    #define CFG_DEBUG                                  (1)
+
+    #if (CFG_DEBUG > 3) || (CFG_DEBUG < 0)
+      #error "CFG_DEBUG must be a value between 0 (no debug) and 3"
+    #endif
+/*=========================================================================*/
+
+
+/*=========================================================================
+    GENERAL NRF51 PERIPHERAL SETTINGS
+    -----------------------------------------------------------------------
+
+    CFG_SCHEDULER_ENABLE      Set this to 'true' or 'false' depending on
+                              if you use the event scheduler or not
+
+    -----------------------------------------------------------------------*/
+    #define CFG_SCHEDULER_ENABLE                       false
+
+    /*------------------------------- GPIOTE ------------------------------*/
+    #define CFG_GPIOTE_MAX_USERS                       1                        /**< Maximum number of users of the GPIOTE handler. */
+
+    /*-------------------------------- TIMER ------------------------------*/
+    #define CFG_TIMER_PRESCALER                        0                        /**< Value of the RTC1 PRESCALER register. freq = (32768/(PRESCALER+1)) */
+    #define CFG_TIMER_MAX_INSTANCE                     1                        /**< Maximum number of simultaneously created timers. */
+    #define CFG_TIMER_OPERATION_QUEUE_SIZE             2                        /**< Size of timer operation queues. */
+/*=========================================================================*/
+
+
+/*=========================================================================
+    BTLE SETTINGS
+    -----------------------------------------------------------------------*/
+
+    #define CFG_BLE_TX_POWER_LEVEL                     0                        /**< in dBm (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
+
+    /*---------------------------- BOND MANAGER ---------------------------*/
+    #define CFG_BLE_BOND_FLASH_PAGE_BOND               (BLE_FLASH_PAGE_END-1)   /**< Flash page used for bond manager bonding information.*/
+    #define CFG_BLE_BOND_FLASH_PAGE_SYS_ATTR           (BLE_FLASH_PAGE_END-3)   /**< Flash page used for bond manager system attribute information. TODO check if we can use BLE_FLASH_PAGE_END-2*/
+    #define CFG_BLE_BOND_DELETE_BUTTON_NUM             0                        /**< Button to press to delete bond details during init */
+
+    /*------------------------------ SECURITY -----------------------------*/
+    #define CFG_BLE_SEC_PARAM_MITM                     0                        /**< Man In The Middle protection not required. */
+    #define CFG_BLE_SEC_PARAM_IO_CAPABILITIES          BLE_GAP_IO_CAPS_NONE     /**< No I/O capabilities. */
+    #define CFG_BLE_SEC_PARAM_OOB                      0                        /**< Out Of Band data not available. */
+    #define CFG_BLE_SEC_PARAM_MIN_KEY_SIZE             7                        /**< Minimum encryption key size. */
+    #define CFG_BLE_SEC_PARAM_MAX_KEY_SIZE             16
+
+    /*--------------------------------- GAP -------------------------------*/
+    #define CFG_GAP_APPEARANCE                         GapAdvertisingData::GENERIC_TAG
+    #define CFG_GAP_LOCAL_NAME                         "nRF5x"
+
+    #define CFG_GAP_CONNECTION_MIN_INTERVAL_MS           50                     /**< Minimum acceptable connection interval */
+    #define CFG_GAP_CONNECTION_MAX_INTERVAL_MS          500                     /**< Maximum acceptable connection interval */
+    #define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS  4000                     /**< Connection supervisory timeout */
+    #define CFG_GAP_CONNECTION_SLAVE_LATENCY           0                        /**< Slave Latency in number of connection events. */
+
+    #define CFG_GAP_ADV_INTERVAL_MS                    25                       /**< The advertising interval in miliseconds, should be multiply of 0.625 */
+    #define CFG_GAP_ADV_TIMEOUT_S                      180                      /**< The advertising timeout in units of seconds. */
+/*=========================================================================*/
+
+
+/*=========================================================================
+    VALIDATION
+    -----------------------------------------------------------------------*/
+    #if CFG_BLE_TX_POWER_LEVEL != -40 && CFG_BLE_TX_POWER_LEVEL != -20 && CFG_BLE_TX_POWER_LEVEL != -16 && CFG_BLE_TX_POWER_LEVEL != -12 && CFG_BLE_TX_POWER_LEVEL != -8  && CFG_BLE_TX_POWER_LEVEL != -4  && CFG_BLE_TX_POWER_LEVEL != 0   && CFG_BLE_TX_POWER_LEVEL != 4
+        #error "CFG_BLE_TX_POWER_LEVEL must be -40, -20, -16, -12, -8, -4, 0 or 4"
+    #endif
+/*=========================================================================*/
+
+#endif /* _PROJECTCONFIG_H_ */
diff -r f7faad332abc -r c90ae1400bf2 TARGET_NRF5/source/supress-warnings.cmake
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/TARGET_NRF5/source/supress-warnings.cmake	Wed Sep 14 14:39:43 2016 +0100
@@ -0,0 +1,21 @@
+# Copyright 2015 ARM Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+message("suppressing warnings from ble-nrf51822")
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+    set_target_properties(ble-nrf51822
+        PROPERTIES COMPILE_FLAGS "-Wno-sign-compare -Wno-unused-variable -Wno-unused-parameter -Wno-unused-function -Wno-missing-field-initializers"
+    )
+endif()
diff -r f7faad332abc -r c90ae1400bf2 apache-2.0.txt
--- a/apache-2.0.txt	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-Copyright (c) 2015 ARM Limited
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 bootloader/s110_nrf51822_8.0.0_bootloader.hex
--- a/bootloader/s110_nrf51822_8.0.0_bootloader.hex	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,463 +0,0 @@
-:020000040003F7
-:20C00000983C002005DD030017DD030019DD03000000000000000000000000000000000057
-:20C0200000000000000000000000000069C1030000000000000000001DDD03001FDD0300D7
-:20C0400021DD030021DD030021DD030021DD030021DD03000000000021DD030021DD0300D9
-:20C0600021DD030021DD030021DD030021DD030021DD030021DD030021DD030021DD0300B8
-:20C0800021DD030057D8030021DD030021DD03006DD8030021DD03004DF4030021DD0300DD
-:20C0A00021DD030021DD03000000000000000000000000000000000000000000000000007E
-:20C0C00000F002F800F040F80CA030C8083824182D18A246671EAB4654465D46AC4201D18E
-:20C0E00000F032F87E460F3E0FCCB6460126334200D0FB1AA246AB463343184710370000C8
-:20C1000030370000103A02D378C878C1FAD8520701D330C830C101D504680C6070470000D3
-:20C120000023002400250026103A01D378C1FBD8520700D330C100D50B6070471FB5C04655
-:20C14000C0461FBD10B510BD03F0E3FA1146FFF7F5FF00F0D3F803F0FBFA03B4FFF7F2FF19
-:20C1600003BC03F0FFFA00000648704502D1EFF3098101E0EFF30881886902380078024A97
-:20C1800010470000FDFFFFFF39D50300401E00BF00BF00BF00BF00BF00BF00BF00BF00BF28
-:20C1A00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BFB4
-:20C1C00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BF94
-:20C1E00000BF00BF00BFF1D170470000056885F3088846680A4AEFF305839A42304602D183
-:20C20000084CA6463047074C064D0646064FF0B4034C034D024E024FF0B404480047000005
-:20C2200000000000FFFFFFFF00000021F9FFFFFF70B505460C46164602E00FCC0FC5103EEE
-:20C24000102EFAD2082E02D303CC03C5083E042E07D301CC01C5361F03E021782970641C63
-:20C260006D1C761EF9D270BD0A4610B50146664803F064F810BD10B502F078FC10BD10B5C6
-:20C28000624C86B01ECC03946C460EC4002807D0684618DF002803D00022114603F04EF864
-:20C2A0000F20800313DF002803D00022114603F045F8574B48225749092003F0A3F80028AB
-:20C2C00003D00022114603F039F800200490059001206946087404A860DF002803D0002251
-:20C2E000114603F02BF84C4803F0A8F8002803D00022114603F022F806B010BD08B547485A
-:20C30000C169B12943D0002445480F2140698903884204D000221146104603F00FF8012068
-:20C320000007006901218902884204D000221146104603F003F83B4800903B4B05220321A1
-:20C34000002001F0BAFA002803D00022114602F0F5FF00F067FC00F0AAFC012500281AD09D
-:20C3600000F0B4FC002803D00022114602F0E6FF20466840FFF783FF00F038F800F0CCFC74
-:20C3800000280ED00022114602F0D8FF09E001240021C161B8E720466840FFF770FF00F002
-:20C3A00025F803252D03002C04D1A86800F090FB002807D100F047FC002803D000221146D5
-:20C3C00002F0BCFFA86800F083FB002806D000F06EFC002802D1A86800F041FCBFF34F8F12
-:20C3E00013491248C860BFF34F8FFEE7094A10B548321421082002F00BFF002803D00022E2
-:20C40000114602F09BFF10BDEFBEADDE8CF703006BF30300342B002077C20300000500404D
-:20C4200000100010EFDC0300F42800200400FA0500ED00E070B5FC4C1E46A06815460229A3
-:20C4400002D0042916D108E0052813D1A369002B10D03246294604200BE002280AD1F348B0
-:20C46000406880470320A060A369002B02D0324629469847280003D00022114602F05EFF98
-:20C4800070BD4CB5E84E0120307005200195009400F058FB4CBD10B5E34C2078002801D057
-:20C4A000082010BD206901F0F4FA002803D00022114602F043FF0F2100228904206901F01E
-:20C4C000ABFA040003D00022114602F037FF204610BDD54910B5D448243141610221816012
-:20C4E000C168243002F059FD002803D00022114602F024FF10BDCC4910B5CB481C31416145
-:20C50000022181600320000380680F218903081A4108C5481C3002F040FD002803D000223D
-:20C52000114602F00BFF10BD704700B589B01822BF4902A8FFF77CFE06980799009001917A
-:20C5400002A80FC800F0FEFA09B000BD00B5B64987B049886A461181032109038968069146
-:20C56000B249012050394A6803928A680492C9680591069A0091019202A90EC900F0E2FA6E
-:20C58000002007B000BD30B5A84CA748503C89B02430E16802F001FD002803D00022114679
-:20C5A00002F0CCFEA048E2681C3041680023083002F0C3FC050012D1182102A802F0E6FFEA
-:20C5C00000209949029049886A469181E1680691079A0091019203A90EC900F0B3FA284601
-:20C5E00009B030BD00B5904987B049886A4611818E49032050394A6803928A680492C9683A
-:20C600000591069A0091019202A90EC900F09AFA0020B6E73EB5864A6B46183207CA07C3A4
-:20C62000814D00246C7029466C802431684602F068FC002801D0AC603EBD03207A4900038F
-:20C6400080682431486024390A46526ACA610F218903091A490840187349764A1C31486068
-:20C6600071480021103001F07BF9002803D00022114602F063FE0F2100228904286901F013
-:20C68000CBF9002803D00022114602F057FE01206C60A86000203EBD63498861704770B59A
-:20C6A000426862481468536891685038D26804604360C26081600078440701D5840705D130
-:20C6C0009C0703D18C0701D1940701D0062070BD5B189A18544D0F239B02EA60994213D81A
-:20C6E0005549564B514CC60709D08868181A90420AD3534820605348606053480FE08968F6
-:20C70000591A4908914201D20C2070BD4F4921604F496160800701D54E4800E04E48A0607B
-:20C72000A868012802D00826304670BDFFF7B3FE0600FAD12168E8688847F5E770B50500F7
-:20C7400004D0287A800703D0102070BD0E2070BD354CA068032805D0042801D0052803D0CB
-:20C76000082070BD0520A0606868E168860060688019884204D90020C04360600C2070BD5C
-:20C78000FFF789FE0028FAD1A96832466368606902F0D3FB0028F2D1616889196160E268EB
-:20C7A0009142ECD0092070BD10B51F4C08206168002900D010BDA1680429FBD11B4861786F
-:20C7C000403802F021FC002802D00021617010BD0521A16010BDF8B5134C0746A068032899
-:20C7E00004D0042804D008252846F8BD0420A0606068002801D00820F8BDFFF74CFE05000E
-:20C80000FAD17868860060788119402901D90920F8BD064AB968403A1018324602F057FE82
-:20C82000607880196070DFE7002800201C2D00209CF7030083C403000030000000C003006D
-:20C84000D3C403002BC503004DC50300F7C4030029C50300E5C5030087C5030010B5894CF1
-:20C86000A068052813D1E168606888420FD10620A060FFF710FE002808D16069E1684068FF
-:20C8800002F0FCFB002801D10721A16010BD082010BD10B57B488168072901D0082010BD63
-:20C8A000006901F0F6F8002803D00022114602F045FD75488068804710BD1CB506200195C2
-:20C8C000009400F03FF91CBDF8B51C4617460D46064600F0C1F8002817D001200003854215
-:20C8E00007D92346291B301B1A46FFF7EDFF00280BD13A462946304600F0B9F8002804D117
-:20C900003A462946304600F0A7F8F8BDF0B589B0684600F015FA049800282AD001210903F7
-:20C92000079A4018904226D9501A45081046049A0C468718024668001618001908900320DF
-:20C9400000038068049988420DD261190846042200F08DF800280CD121460422084600F073
-:20C9600086F8002805D1BA1B2B4630460899FFF7ABFF09B0F0BD049A079800F078F8F8E75C
-:20C9800000B58DB004A800F0DBF9099800280DD0089800280CD008990B984018019000219D
-:20C9A0000998009180080290684618DF0DB000BD0320000380680F218903091A4908ECE7FB
-:20C9C00000B58DB004A800F0BBF909980028EDD00F210898890300280CD0089A0B98019158
-:20C9E0008018029003220998009280080390684618DFDBE70320000380680A1A5208EEE7D2
-:20CA000030B591B0684600F09BF90498002814D001210903079A4018904214D9501A43087B
-:20CA20001046049A5C0082180019611803242403A468049DAC4202D20E2011B030BD121AB5
-:20CA4000FFF742FFF9E703200CAB07C3049880080F900CA818DFF0E71FB5032301909008B3
-:20CA6000039000930291684618DF04B010BD1FB5012301909008039000930291684618DF58
-:20CA8000F3E70000002800201C2D002010B5BB480368012B02D1022900D10160100003D099
-:20CAA0000022114602F04AFC10BD10B5B34C48DF002803D00022114602F040FC02F0FCFB82
-:20CAC0002068022803D0032801D00428EFD110BD38B50068401C19D00024684600F058F96F
-:20CAE00000980168012910D1818800290AD0C168032000038068002202F0CEFA0099898861
-:20CB0000814201D1012400E00024204638BD10B504469A482021001D02F0B9F9002803D00E
-:20CB20000022114602F00AFC9448002320222146001D02F01BF9002803D00022114602F053
-:20CB4000FDFB10BD0FB4F8B5684600F021F96846818B069D0122894CFF238948002D13D090
-:20CB6000012D17D0032D2BD00021022D37D02A46052D46D0042D4ED0062A01D10420206071
-:20CB8000F8BC08BC04B0184781800A9983600260C16010E08180099D089949190A9D49195D
-:20CBA000C160A52183600160089901610999856141610B99C16122607148FFF7A8FFDFE7B9
-:20CBC00000990B6803608B888380C968C160AA21816008990161099941610A990BE0009D60
-:20CBE0002E68A52E09D00660AE888680ED68C5600161836041618161DDE781800360C160C5
-:20CC0000F6E700F085F9002803D00022114602F095FB0320B3E781800360C1600099896807
-:20CC20008160C9E70EB557480090202001900120029002F001F8002804D150496846091D98
-:20CC400002F023F80EBD10B5FFF7E4FC002805D100F02FFB0446FFF728FF204610BD70B58A
-:20CC600011DF002803D00022114602F067FB464900200B68444C012180340A4682401A4206
-:20CC800004D0C506ED0E0A46AA402260401C2028F3D303242403A06813DF002803D000226F
-:20CCA000114602F04BFBA06802F0F2F970BD08B5684600F06DF800980168A52904D0806888
-:20CCC000AA2801D0002008BD012008BD10B5FFF797FE002803D1FFF773FE00281BD064209C
-:20CCE00001F0F2FDFFF712FE002803D00022114602F024FBFFF784FE002803D000221146DD
-:20CD000002F01CFBFFF73CFE040003D00022114602F014FB204610BD00B589B018221B49CA
-:20CD200002A8FFF785FA069807990090019102A80FC8FFF707FFFFF7B8FE002009B000BDB5
-:20CD400010B50E4988B0044600232022091D684602F04FF80098206068468088A08003983A
-:20CD6000E0600298A06004982061059860610698A0610798E06108B010BD00002C280020E6
-:20CD8000282D00208DCA030000E100E0C0F70300014901607047000000FC030008280CD0DC
-:20CDA00004DC002807D006280FD108E00B280AD00C280AD105E001207047022070470320C9
-:20CDC000704704207047042901D0062070470520704770B515460A46032823D0042820D1FF
-:20CDE000FE4C002906D0E088FD49884219D0132176DF10E0284602F0A3F9002803D00022F7
-:20CE0000114602F09BFAE069A8420AD101220321F44801F003F8002803D00022114602F051
-:20CE20008DFA70BD01211046FFF7B8FF02460121EEE7F0B5054608790E4685B081070CD07C
-:20CE400003221146284600F0E9FF002803D00022114602F073FA05B0F0BDE04900901831D9
-:20CE600002F047F9010011D1DC4CB168009AA06902F02DFB009802F097F9010006D1204647
-:20CE80006946183002F09CF9010003D0284600F0AFFAE0E704200190009880080290A06902
-:20CEA000039001A8FFF74AFC07000BD0092F10D0A06902F045F9010002D0284600F098FA04
-:20CEC0003946E3E73079616940186061A069E061C1E7307961694118616160780028BAD073
-:20CEE0006089401E0004000C6081B4D1284601F0E9F8002803D00022114602F01FFA20890D
-:20CF00006081A8E710B50022114602F017FA10BD10B5B24C01202070E088B149884208D01B
-:20CF2000132176DF002810D00022114602F006FA0BE0A078002808D074DF002803D0002282
-:20CF4000114602F0FBF90020A07001F034FC002803D00022114602F0F1F9002010BD70B5E1
-:20CF60000D68044601209D4A2B0002F002FC0A2B3043061320575C466012FFF76FFC0421FD
-:20CF8000FFF70CFF024604212EE00022114602F0D5F970BDFFF7BCFF002803D0002211468A
-:20CFA00002F0CCF9FFF775FC002808D170BDFFF7AFFF002803D00022114602F0BFF9FFF76D
-:20CFC0007CFC70BD106188680078107170BD02201061886800780128F8D1FFF7E5FB02213F
-:20CFE000FFF7DCFE02460221204600F017FF0028CBD170BD0320106170BD12692046012ACC
-:20D0000006D0022A07D0032AF6D1FFF712FF70BD00F001FA70BD00F03BFA70BD50708888D5
-:20D020001081508170BD00205070108170BD2046516901F010F8DAE710B5044669488EB0EB
-:20D0400081796846817068490180342101A802F09DFA022001900021684641728472012131
-:20D0600001820590002101A801F03FFA002803D00022114602F062F90EB010BDF0B5574C10
-:20D080008BB0A07800283AD156481821183802F07DFA2046534CC078183C00250126002875
-:20D0A00037D02746483700950195029510226946F81D039502F0DEF9002822D0F81D08909D
-:20D0C00009976846067509A804906846067708A806900420FFF7B0FF25700220207204A813
-:20D0E000E060282020823F486582183873DF002803D00022114602F021F9384886700BB045
-:20D10000F0BD0520FFF798FF2670676025722582E9E70620FFF790FF257065602572E0E7E2
-:20D1200070B52E4C01880022E588A6B017290AD01EDC11293FD008DC022977D0102902D123
-:20D140008088E080A27026B070BD264C303426461836132951D01429F5D1C289638D002106
-:20D160009A4200D1314600238088E21D82DF1BE0512970D00EDC18296CD01929E3D18079F5
-:20D180000028E0D1A270E068401EE0604FD0FFF775FFD8E7522976D05529D4D18079002871
-:20D1A000D1D11321284676DF0028CCD00022114602F0C4F8C7E78020694688803220E06054
-:20D1C000012301AA06A92846AADF002803D00022114602F0B3F82078002807E038280020A2
-:20D1E000FFFF0000602D00203015000001D1FFF745FF0020C043E080A5E70722C14910A839
-:20D2000002F065F91022E11D0CA802F060F91C22314612A802F05BF90CA80A9012A8099039
-:20D2200006ABB94A852128467FDFBDE70DE01822B64906A8FEF7FCFF0A980B9900900191F8
-:20D2400006A80FC8FFF77EFC7DE70021284667DFAAE700E017E0817900299AD0807A042885
-:20D2600003D0062801D0052893D1022909D0012069460872FF208330888102A92846A8DF82
-:20D2800092E70220F4E700F08DF88DE710B5044601F0C2FA9B482146303800F09AFE2046D3
-:20D2A000FFF73EFF10BD10B50022114602F046F810BD30B5944D87B00024203D2C7094483D
-:20D2C0002C6102F0B3F800286AD19248FFF7E4F901F000FF002863D18A4800F059F900288C
-:20D2E00001D10120E87011206946087207228AA102A87CDF002803D00022114602F01EF8B4
-:20D3000000940C2168460194018018214180FF2184809131C1807ADF002803D0002211469A
-:20D3200002F00CF804206946009408807C4801907C4802907348303800F00BFE002803D046
-:20D340000022114601F0FAFF1C21684602F01EF9754801900120800302900094032168468C
-:20D360000173C4810474714806900594684601F0FEF9002803D00022114601F0DFFF624910
-:20D38000E12208784008400010400C30DF22104008700720487010208870FFF76FFE0020A3
-:20D3A00007B030BD70B5584C614D203CE088A84201D1082070BDE178002914D05149012359
-:20D3C00008223431A9DF0028F4D12A460C21E088A7DF5849884204D0082802D0891C88420E
-:20D3E000E8D1002070BD00231A461946A9DF70BD10B50A46044603211046FFF7CFFC0246AE
-:20D400000321204600F00AFD002803D00022114601F094FF10BD30B5054687B000200090AF
-:20D4200001900290039038486A46203800791070364A0C3A1068926804906846069205900E
-:20D4400008790C2806D003221BE00022114601F075FFA5E78C68204600F049F80190201D5E
-:20D4600000F045F802902046083000F040F8039004A8FFF714F9002892D00121FFF78EFCB9
-:20D4800002460121284600F0C9FC0028DDD187E7FEB50446087982070ED08207920F042385
-:20D4A0009B1A0022154604E08E683554401CC0B2521C9A42F8D30871012000908868029048
-:20D4C0000879800801906846FFF785F900280DD00221FFF763FC02460221204600F09EFCB8
-:20D4E000002803D00022114601F028FFFEBD10B5044602F04DF80002E178000A09060843E0
-:20D5000010BD0000902D002058280020E4F703008DD20300D3CD0300446675546172670031
-:20D520005FCF0300A7D20300CD0C000005CF0300FFFF00000230000010B50C46002802D04D
-:20D540000120086010BD2168002911D01C48421A814212D03C2A0DD23C303C3101220B78B9
-:20D5600003701346491E401E521C3C2BF7D904E00E200BE03C2201F0AAFF00223C211048A9
-:20D5800001F08AFD0E49891E08800020206010BD70B5054600223C21094801F07DFD084C21
-:20D5A000A41E2188884201D00B2070BD3C220449284601F08CFF2088401C2080002070BD87
-:20D5C000823F00208307FF22DB0E9A408907090E994000280BDA0007000F08388308FA484C
-:20D5E0009B001B18D86990430843D86170478308F6489B001B1818689043084318607047AA
-:20D6000070B50124F24960040860F24940108860F04940398860F04D6C602F20FEF7B6FDAC
-:20D62000AC60EE4D00242F206C61FEF7AFFD2C7170BDF0B5E94F2821BC6841430D19396962
-:20D640004A1C09D028224A431619AB68B268934204D8D21AB26069623861F0BD0A4602E066
-:20D660000A46796A9B1B4E1C0BD028264E433719BE689E42F4D328264E433619B768FF1A1A
-:20D68000B760AB60696228214A4311194862F0BD70B5D24C2269A5681346114606E0814212
-:20D6A00007D00A46282671434919496A4E1CF6D170BD002EFCD08A420CD1282043435819EC
-:20D6C000406A2061401C05D1C34B01209860002363616071282041434819282381685A4310
-:20D6E000406A52195062421CE2D028225043401982685118816070BDF8B5B84C2569681CF9
-:20D7000035D0B748002640686169401A07023F0A19E028204543A0682A189068B84214D8D0
-:20D72000A3693F1A8619556A002B09D0116AD0699847002807D00022114601F0FFFD02E048
-:20D74000D169106A8847681CE3D1A178E078814206D1401CC0B2E070022801D10020E07079
-:20D760009E490006800D1C310E5000F0BAF9F8BDF8B50446994800270169009146785CE038
-:20D780009648F100C2688D1851E0601C07D0934A28209268604321468018446A24E0287854
-:20D7A000182141436A68401CC0B252182870A978884200D12F70894B516828209B6848434C
-:20D7C000C0181368012B34D1037E002B31D19368C360D368036113694361526902627F4A52
-:20D7E0005279002A00D0C7607C4BC2685B6996469C46D31A1A027B4B120A9A4202D20369C3
-:20D80000D21808E0724663469A1A12020369120A934202D99A1A826000E08760C76001222E
-:20D8200007610276921E42620846FFF702FF601CABD1287869788842A7D13046761EF6B202
-:20D8400000289DD1654801690098814201D00120F8BD0020F8BD644900200860486088607F
-:20D86000C860614940390860486045E7FEB50020C0435A4D02906869019068462E6900F07B
-:20D8800035F9074600F04FF90446002F08D002AA0199009800F08FF90298FFF769FF06E050
-:20D8A0000298FFF765FF002801D1002C02D0304600F0AAF900206871FEBDFFB59807002448
-:20D8C00081B01E4615460F4600280BD1002E09D0FFF796FE41490A9888610F703246002042
-:20D8E0008E6008E0072005B0F0BD28234343D4509B181C76401CB842F7DB28204743BB19C1
-:20D90000032048700F461846CB6019461830002218232E465E43D3005B181C705C709D708A
-:20D9200058603018521C032AF5DB0020C0433861BC70FC7001242D482405046003211420A9
-:20D94000FFF740FE224880380460254C0198A06003211120FFF736FE606878610020C2E71A
-:20D9600070B51E4CA568002D06D0002A06D0002804D00023247809E0082070BD072070BDBB
-:20D9800028265E43AE59002E04D05B1CA342F7DB042070BD282401265C432E516419E261BF
-:20D9A00061600360002070BD07494868C005C00D2CD010381CD50207120F083A9208920097
-:20D9C0005118C96919E0000000ED00E000E400E080E100E040130140001001406028002054
-:20D9E00000150140FFFF7F004011014080E200E08108B14A8900891809688007C00EC1400B
-:20DA00000806800F012803D0032803D0022070470020704701207047FEB50446A74817469E
-:20DA200082680D46002A0CD001788C4201D2052D01D20720FEBD2146282359435358012B7D
-:20DA400001D00820FEBD8818406801281DD00026FFF7AAFFC00099490190C9684018694684
-:20DA600000F018F9002812D0012144600160944949680830E2C091490198C9684118009877
-:20DA8000487000F02EF80020FEBD2E46E0E70420FEBDF8B5894D0446A868002809D0297844
-:20DAA0008C4201D30720F8BD282161434058012801D00820F8BDFFF777FFC600E86869465B
-:20DAC000301800F0E7F8002809D0022112C0E86831180098487000F004F80020F8BD04206B
-:20DAE000F8BD0120774900050860704710B5734900238A78CC78A24212D0521CD2B28A70D0
-:20DB0000022A00D18B708A786C4B92001C339A580260486910180002000A4861012010BDA3
-:20DB20000360002010BDF8B5644801690091457833E06248E900C0680E1834782AE01820A2
-:20DB400060437168641C0818B178E4B2A14200D100240168022902D003291BD113E0574A00
-:20DB600040682821926841438F18397E002911D0FFF78EFD002038760CE028277843C018B1
-:20DB80000276406A03E04D4900228B680869471CF3D108617078A042D1D128466D1EEDB2D0
-:20DBA0000028C6D1454801690098814201D00120F8BD0020F8BDF7B5404C0025A7682369E0
-:20DBC0001EE028215943C9198E68864202D9301A886017E0801B751900268E600E764E6946
-:20DBE0009C464B6AB646002E0AD0019E76193602360ACE6076460E6116684E626146116045
-:20DC0000591CDED12361FEBDF8B52C4801694A1C3DD028225143826889188E6828494C681F
-:20DC200047690079E11B0D022D0AED1C002815D10120254A00045060234A403A506021491D
-:20DC4000400080310860214908602149012008602F20FEF79BFA194901200871B54200D208
-:20DC60003546E81900021649000A4031086014494968001B091B0902090A0002C91C000A88
-:20DC8000814203D901200F4940040860F8BDFFF7B7FCF8BD42788378521C934200D10022C2
-:20DCA0000378934201D1002070470A6041684078182250430818704700E400E06028002090
-:20DCC0000015014000E200E04013014000E100E00010014010B50446082904D000221146F9
-:20DCE000104601F02BFB21686068884710BD1CB501910090024A0821684601F09DFA1CBD53
-:20DD0000D5DC03000A48026803210A4302600948804709480047FEE7FEE7FEE7FEE7FEE797
-:20DD2000FEE7000005480649064A074B70470000240500404DDD0300C1C003009830002007
-:20DD4000983C00209834002098340020F8B500F035F82B4E002804D02A4870602A49F01300
-:20DD600088612A480124018CC9B201290DD1818C09070AD1018D0906090F042905D1808D56
-:20DD80000006000F01D1224884600027B461214D6F60A8058460686800280ED1C820FEF790
-:20DDA00005FA1D487F1C8742F5D30020B06101208007846068680028FCD0F8BD1348018CB5
-:20DDC000C9B2012917D1818C090714D1018D09060A0F03D1828D1206120F0ED0090F0129C2
-:20DDE00003D1828D1206120F07D0032903D1808D0006000F01D0002070470120704700008E
-:20DE000000050040DFFF07C0006C0040C00F00F000060040000100408813000030B585B071
-:20DE2000002822D00388FE4CA34220D0FD4B1B78002B1CD0FB4B10255B1C1D7059700024C0
-:20DE400001259A70032269460A820094019402940394028A0A808D708C8004A902910393E7
-:20DE600000886946A6DF05B030BD0E20FBE70820F9E7F0B58BB0044602276846077300268B
-:20DE800009968784C68408A80A900D46A18A208809AAA5DF002804D0E16A00291AD08847BE
-:20DEA00018E06846008CC007C00F13D068460682208803A9A8DF002813D1A97E28461B30BA
-:20DEC00001220B0001F055FC09430F1B202224263E284300FF20FE3069460882208803A94D
-:20DEE000A8DF0BB0F0BD00960AE0062219E069460A71029022E0204690470020F1E700920D
-:20DF00002B8B022BF3D2F0E700971DE003201AE0042018E0052016E0298B032905D20322BE
-:20DF200008212046FFF77AFFDBE741780278080210436946888003D006200090A26ADAE784
-:20DF40000720FAE7092000906946A26AD3E70322E7E730B585B00D46040038D0002D36D0EC
-:20DF60006868002833D00020C043AF4B20800FCB049301AB07C3AD4869460880891C01A888
-:20DF800063DF002822D1221D69460120A0DF00281CD168468078A071204600F0CEF8002886
-:20DFA00014D1204600F055F900280FD12946204600F002F9002809D16868A062A868002804
-:20DFC00000D0E06297490120087000204BE70E2049E73EB5002828D0002926D0826A002ABE
-:20DFE00023D00A88102A21D0112A30D0502A1FD0512A1AD104460846891D0A78022A14D196
-:20E000004A88238A9A4210D1807A04280DD006280BD0052809D0891C2046FFF72AFF002860
-:20E0200003D0E16A002900D088473EBD898810E0CA8803899A42F8D1082200928A7F6B4605
-:20E040001A7120310291826A694690473EBD0021C94301803EBDF0B585B00A4605002DD00F
-:20E0600028886F4988422BD06E480078002827D06C4C1020641C2070072060700127A770F8
-:20E080000321684601820026E11C104600F04CF801466846008A0918684601820096019680
-:20E0A00002960396298A01808770868004A80394029028886946A6DF05B0F0BD0E20FBE7D3
-:20E0C0000820F9E7F0B585B00A46050028D028885349884226D053480078002822D0514C3B
-:20E0E0001120641C20700127684607820026611C104600F019F801466846008A0918684638
-:20E1000001820096019602960396298A01808770868004A80394029028886946A6DFCBE782
-:20E120000E20C9E70820C7E70870020A4A70020C8A70000EC8700420704730B58FB0054655
-:20E140001C21684601F022FA694608780421084369460870002401940394049405940694E6
-:20E16000A87908A9887031486946801C0884601C00070794000F0C77103048778A7FF920B4
-:20E180000240921CE7200240012002438A77142109A801F0FBF908A8099007A80A906946D3
-:20E1A0008C851420CC8508860D942B46A888083309AAA2DF0FB030BDF0B58FB00F4605465A
-:20E1C0001C21684601F0E2F968460178022631430170002401940394049405940694A97917
-:20E1E00008A8817011496846091D0184601C0107090F103168460794017700200146684618
-:20E200004177817FF9200140891CE72001400120014368468177142109A801F0B7F907E086
-:20E22000FFFF000088280020FCF703003015000008A8099007A80A9068468685C4850686B5
-:20E240000D972B46A888203309AA6946A2DF0FB0F0BD30B58FB005461C21684601F096F9FD
-:20E2600069460878082108431022104369460870002401940394049405940694A87908A962
-:20E280008870144869460884601C00070794000F0C7710304877887FF9210840801CF72123
-:20E2A000084010430121084369468877142109A801F06CF908A8099007A80A9069468C851A
-:20E2C0001720CC8508860D942B46A888103309AAA2DF6FE731150000FFB583B0074600207F
-:20E2E0000C9C8646267805463AE07868A90041180A88684682804988C1800022694601A8F7
-:20E3000065DF002810D1684601780598814226D17046002801D0002200E002222078891824
-:20E3200041181F2902D90C2007B0F0BD7146002908D1401CC0B2411C069B049A21701A54AF
-:20E3400001208646217806980A18694601A865DF0028E9D1694620780978401820706D1CC0
-:20E360003888A842C1DC7046002804D020780699801B401E88550020D6E7F8B51546069C10
-:20E380001E46074602220094FFF7A6FF002806D133461022294638460094FFF79DFFF8BD07
-:20E3A000F7B582B000260546167000681446002805D02846039900F0CAF8060008D168794D
-:20E3C00000281ED02078039F001D1F2802D90C2005B0F0BD684679DF0028F9D1217803226A
-:20E3E000481C20707A5421781922481C20707A542078C1196846008800F0A4F821784018A0
-:20E400002070A8790223002810D02078039A411C2170135420780399471C012227700A54E5
-:20E420002078AA79471C039927700A54A868002815D00021415620788C460246C01C03992E
-:20E440001F28C4D8501C20708B5422780A23501C20708B5420786246431C23700A54A8899B
-:20E46000002809D028460094062202210C30039BFFF783FF0600ABD1A88A002809D02846D9
-:20E480000094072203211430039BFFF776FF06009ED1A88B002809D0284600941522142137
-:20E4A0001C30039BFFF769FF060091D1686A002805D02246039900F07FF8060088D1A86A01
-:20E4C000002805D02246039900F0B5F8060084D13020405D002806D022462846039900F0F6
-:20E4E000DCF80600C7D1304672E770B50C4692B000216A46117007251171002809D0817927
-:20E5000049070CD502A9FFF74BFF002808D102AE00E00026002C0ED0A079002802D028469D
-:20E5200012B070BD01AA0AA92046FFF739FF0028F6D10AAA00E0002268460379017830463C
-:20E5400072DFEDE70870000A487002207047F8B514780746A01C15460E461F2803D83879BF
-:20E56000801C1F2801D90C20F8BD1D20001B80B26946864608803019801C7DDF0028F3D143
-:20E580003868022805D168460088704501D8092107E038790821002801D0704501D96846F6
-:20E5A0000088421C3255641CE2B2B1542978801C081828700020F8BDF8B50D461178064636
-:20E5C000881D14461F2801D90C20F8BD33880720062BFAD31927FF01BB4202D94D4A9342D6
-:20E5E000F3D17288062AF0D3BA4202D9494FBA42EBD1484FBB4203D0BA4201D09342E4D87E
-:20E60000481C052220706A5420781222411C21702A54207841193088FFF794FF21784018C5
-:20E62000C0B2207041197088FFF78CFF2178401820700020F8BD70B5054600790E46801CD6
-:20E640001446C0B21178821C8A181F2A01D90C2070BD0A46491C401C2170B0542078FF224A
-:20E66000411C21703254207881192888FFF76AFF21784018C0B22070AA88002A09D0A968AC
-:20E68000002908D0801900F022FF2078297940182070002070BD072070BDF7B582B0029894
-:20E6A0001446C06A0F46002832D0029800252030009028E00298C16A0C2068430E18217855
-:20E6C00030794A1CC01C2270785421781622481C20707A542078C1193088FFF733FF217873
-:20E6E0004018C0B22070B288002A09D0B16800290ED0C01900F0EBFE207831794018207087
-:20E700006D1C0098EDB2007CA842D3D800205FE607205DE6FFFF000038B56749674A48883D
-:20E7200090420FD04A78664C521CD2B24A70237B934208D3083175DF002803D0A1690029FF
-:20E7400000D0884738BD00254D70217C002907D03B2176DF002803D0A169002900D0884728
-:20E7600061690029EED068460095884738BD70B5054601461C225248FDF75AFD4E4C002647
-:20E7800026702968002907D00822A01800F09FFE204608307ADF02E0474808307BDF0028C1
-:20E7A00008D1401E608044486670464A0021001DFFF7D6F870BD10B53F484068FFF769F9D5
-:20E7C00010BDF8B53C48103000F069F800263A4D3B4C002806D06169002919D001200090EB
-:20E7E000684614E02878002804D0616900290FD00096F5E7687800280CD0A16800226868B8
-:20E80000FFF70AF9002803D0A169002900D088472E70F8BD6168F1E7F8B5294C028800276B
-:20E82000254DE689102A18D029464968112A21D0122A2DD0502A0FD1801D0288B2420BD1FF
-:20E84000028B022A08D1C27E837E10021843C007C00F13D0FFF7B5FFF8BD81886980014667
-:20E86000154808221631103000F031FE6F70002EF0D0F8BD0020C04368806F700846FFF7BB
-:20E8800008F90028F5D0A1690029F2D08847F8BD811D09480822103000F019FEDAE7418827
-:20E8A000054808300288914204D34088814201D8012070470020704790280020FFFF0000B6
-:20E8C000CC2D002019E7030031B5054C04E0401E00902046FDF77AFC00980028F7D138BDC6
-:20E8E000E703000018225043FE4A00218018017181604161012281610261C1607047FFB577
-:20E9000081B0F94C049B039A054626691A4303200092002E03D1002A0ED001222261276919
-:20E92000039A0126360792003B0000F022FF072707162940526127000222EFE770693269FC
-:20E9400092B25043326933691204920C9BB2594329DF002812D102210FE0084628DF00286A
-:20E960000CD10399002901D0032106E00499002916D12978042946D017E0216105B0F0BDAE
-:20E980007069326992B25043326993B24B4301461846039A29DF0028F0D10499002901D0F4
-:20E9A0000421EAE72978042920D00521E5E773693069366980B2434368681B189B18B6B2C7
-:20E9C0004E43301880181946049A29DF0028E9D0D4E7306980B24843696880188A08696902
-:20E9E00029DF0028CAD1009900290CD00621C4E77069316989B24843316989B200F0D9FD08
-:20EA000028DF0028BAD10721B7E7F8B5B54918230A780F205A435418241DB3492278266970
-:20EA2000CF68022A1BD001252D07042A2AD0052A5BD1286981B2304600F0BBFD0146A36877
-:20EA400028699A1980B24843101A820860681818861928694B1C80B25843801B34E0B8023C
-:20EA600062686169121A0918A3683018181801239B029A4202D2920829DF31E0FF220132BA
-:20EA800029DF2DE0E268974914205043F4314018001D0BC8B04203D160685943814218D02E
-:20EAA000022A16D0286981B2304600F082FD0146286980B24843301A820828694B1C80B208
-:20EAC000584363689B19C01A83082046FFF717FF06E0286981B2304600F06BFDC01928DFED
-:20EAE000002802D17F4901228A70F8BDF8B57D4C069E65780A2D1DD027787D19EDB20A2D5B
-:20EB000001D30A3DEDB218277D432D192871AA6103C9EE60AB6069612861A1780020002978
-:20EB200004D1FFF772FF112800D100206178491C6170F8BD0420F8BD38B5024669481823B1
-:20EB400001785943081803690179022B0AD014246343644CF434E4588368009383691030F7
-:20EB6000A04738BD604B14331C68F5E7F8B55D4B9978012914D100255B499D700A69082A77
-:20EB800005D002280FD003280AD10D2006E0022807D00D7000F025FA002801D0FFF7CCFF37
-:20EBA000F8BD0D61F6E74F48182403784E496343CC681818641C001DCC600378022B05D11F
-:20EBC0004668A102B14201D3012700E00027052B01D1072A03D00021042B02D003E00121C1
-:20EBE000FAE7072A03D00026042B02D007E00126FAE74068A302834201D3002A1AD0002000
-:20EC0000314301433943C5D0374E28463561FFF793FF344C2078FFF765FEF5606078401E1E
-:20EC200060702078401CC0B220700A28B2D30A382070AFE70120E3E770B500252A4C2948D3
-:20EC4000E56025610570457085702E463046FFF749FE761C0A2EF9D3012212076560516952
-:20EC600028461269491E92B25143E560A1601D49F4310D608D600D61CD601B4914310D6090
-:20EC8000888001212170206170BDF8B5164A044610780E46002830D0002C30D0002E2ED058
-:20ECA000206800282BD0012000076768016989B28F4228D8102F26D3A168002923D09568E2
-:20ECC000794343694A19006980B243439A421AD801200007006980B2814212D901200007E1
-:20ECE000006903E0E82D0020A828002080B2394600F05FFC002906D103E00820F8BD0E20B9
-:20ED0000F8BDB80701D00720F8BDBD49486801281CD00F461421BB4A21C641438E18756092
-:20ED2000236853506168B160A168F160A268616800235143012212075B1C14699BB2A4B214
-:20ED40008C4205D21469A4B2091B02E00420F8BD00211469A4B265191469A4B28C42EBD985
-:20ED6000BD60401C336178600020F8BDF8B50446A3481E46007815460F46002807D0002F3D
-:20ED800007D0002C05D02068002817D103E00820F8BD0E20F8BD9B48016800290ED0C268E3
-:20EDA000816840684A4310186268904206D9002D04D0A94202D3A819884201D90720F8BD90
-:20EDC000384600F008F9002811D0304600F003F900280CD0606800F0FEF8002807D02B4637
-:20EDE0003A46214602200096FFF780FEF8BD1020F8BDFFB5824881B000781F4616460D462B
-:20EE0000002808D0002D08D00198002805D02868002817D103E00820B0E50E20AEE5794C91
-:20EE2000206800280ED0E168A0686268414389186A68914206D9002E04D0B04202D3F119AD
-:20EE4000814201D9072099E5019800F0C4F800281BD0384600F0BFF8002816D0686800F025
-:20EE6000BAF8002811D068683246C119019800F02EFB00962868142148432458002203215B
-:20EE80002846019BA047002078E5102076E5F8B505465B480F460078002805D0002D05D012
-:20EEA0002868002821D103E00820F8BD0E20F8BD544C00262068002817D0A168E0684843CC
-:20EEC00061684118686881420FD900F084F800280DD0296814225143091968684A68896834
-:20EEE000801A00F066FB002903D00720F8BD1020F8BD3B460022294604200096FFF7F6FDB5
-:20EF0000F8BD3F4A1278002A0DD000280DD000290BD00268002A08D0394A14321368002B3E
-:20EF200005D004207047082070470E20704702230B600068106000207047F8B504463048AF
-:20EF40001E46007817460D46002807D0002D07D0002C05D0206802281BD103E00820F8BDC3
-:20EF60000E20F8BD264814300068002811D0084600F031F800280ED0304600F02CF800286C
-:20EF800009D03B462A46214602200096FFF7AEFDF8BD0720F8BD1020F8BD08B5184A1278C8
-:20EFA000002A05D0002805D00268022A11D103E0082008BD0E2008BD114A14321268002AD5
-:20EFC00007D00B460022014604200092FFF78EFD08BD072008BD800701D000207047012068
-:20EFE0007047084910B5F43949780020002906D0FFF70BFD002802D0112800D1002010BD48
-:20F00000A8280020DC2E002070B500250C290ED304464318008941000919581A0A38C2B2BD
-:20F020001748022A027002D30A318B4201D2092070BD144800F04BFA134914480A8882422E
-:20F0400002D02388934217D14988814202D06088884211D10D4A0323521E20891B03A842DE
-:20F060000AD9690009194989914203D09E896D1CB142F4D1002070BD0B2070BD00207047C6
-:20F08000C4280020F02E002080100010FFFF000010B5FDF7ABF810BD10B50446002A02D054
-:20F0A0001088002210E00A48FBE7030A00020343A05C584003061B0F43401803584083B2EB
-:20F0C0001806C00C5840521C8A42EED310BD0000FFFF00004B48002101704C484A4A026039
-:20F0E0008160C160016108224161426081610846704710B500291DD000220A60434A5368A8
-:20F10000002B1BD0202817D85B1E5360D0682423401CD060106914684343E3180B60012366
-:20F1200083409169401C19434007400F91611061002010BD0E2010BD0C2010BD042010BD8F
-:20F14000F0B5324A0646916800292BD057691020791A4907490F14680B4624254D436519D6
-:20F16000B54206D1012495698C4065400020956104E0491C4907490F8F42EED1491C4E07DC
-:20F18000760F956901210C469C402B4623420AD19368002B07D05B1E936053685B1C53609D
-:20F1A0003346F0E70420F0BD184A2423117C1268491E4907490F594320315050002070470B
-:20F1C00070B500281AD0002918D0104AD368002B16D05B1ED360936824265B1C936053692A
-:20F1E00015681C467343EE1820330660E858641C08606007400F5061002070BD0E2070BD84
-:20F20000042070BDC5280020FC2E00201C30002030B5CB0008339DB293070024002B01D0E6
-:20F22000072030BD3B4B9A605219DA605C701C7058809980002030BDF7B5364C0E466088D5
-:20F24000814237D8344F00F069F822786078A188884201DA401C00E00020C0B2904202D155
-:20F2600000F062F824E065786078884201DA401C00E00020607000F057F8BD4218D0A0688C
-:20F28000EF000299C151009900290CD0002E0AD0608832464543E068281800F018F9A068B3
-:20F2A0003818868002E00021381881800020FEBD0420FEBD0920FEBD0EB504E068468188A8
-:20F2C000029A0098904702AA01A9684600F003F80028F3D00EBD70B50E4B05241D785E786C
-:20F2E000AE4215D01D781C789E88B44201DA641C00E000241C705C88DE686C43A41904600F
-:20F300009B68E800C418A4880C80185800241060204670BDCC280020FFFF000072B606484F
-:20F320000168491C0160704703490868401E086000D162B670470000DC280020BFF34F8F11
-:20F3400003490248C860BFF34F8FFEE70400FA0500ED00E010B5002904D000221146104619
-:20F36000FFF7ECFF00F010F810BD10B50021024A0846FFF761FF10BD55F3030010B50846E6
-:20F380001146FCF771FF10BDF8B5384C2078002837D02069002807D00026E068002805D0FB
-:20F3A0000025002E04D013E00126F6E70125F8E7684651DF052806D0002806D000221146D2
-:20F3C000FFF7BCFF04E0012602E0216900988847002D12D1608869460880A06861DF0528FA
-:20F3E00006D0002806D000221146FFF7A7FF04E0012502E0E168A0688847002ED8D0002D15
-:20F40000CFD0F8BD70B5002901D08C0701D0072070BD164C0125A16062801549636010DF46
-:20F420000028F5D1257016202EDF70BD002803D00E49C860002070470E207047002803D0A8
-:20F440000A490861002070470E20704710B507484068002807D08047002803D0002211463E
-:20F46000FFF76CFF10BDFFF78FFF10BDE02800207DF30300034610B50B439B070FD1042A66
-:20F480000DD308C810C9121FA342F8D018BA21BA884201D9012010BD0020C04310BD002AAC
-:20F4A00003D0D30703D0521C07E0002010BD03780C78401C491C1B1B07D103780C78401C61
-:20F4C000491C1B1B01D1921EF1D1184610BDF8B5042A2CD3830712D00B78491C0370401C25
-:20F4E000521E83070BD00B78491C0370401C521E830704D00B78491C0370401C521E8B07F9
-:20F500009B0F05D0C91ADF002023DE1B08C90AE0FCF78EFEF8BD1D4608C9FD401C46B440B8
-:20F520002C4310C0121F042AF5D2F308C91A521EF0D40B78491C0370401C521EEAD40B78EC
-:20F54000491C0370401C521EE4D409780170F8BD01E004C0091F0429FBD28B0701D50280F7
-:20F56000801CC90700D00270704700290BD0C30702D00270401C491E022904D3830702D5EE
-:20F580000280801C891EE3E70022EEE70022DFE70378C2781946437812061B0219438378A2
-:20F5A000C0781B04194311430902090A000608437047002203098B422CD3030A8B4211D366
-:20F5C00000239C464EE003460B433CD4002243088B4231D303098B421CD3030A8B4201D39D
-:20F5E00094463FE0C3098B4201D3CB01C01A524183098B4201D38B01C01A524143098B422D
-:20F6000001D34B01C01A524103098B4201D30B01C01A5241C3088B4201D3CB00C01A524193
-:20F6200083088B4201D38B00C01A524143088B4201D34B00C01A5241411A00D201465241FB
-:20F64000104670475DE0CA0F00D04942031000D34042534000229C4603098B422DD3030A47
-:20F660008B4212D3FC22890112BA030A8B420CD3890192118B4208D3890192118B4204D305
-:20F6800089013AD0921100E08909C3098B4201D3CB01C01A524183098B4201D38B01C01A88
-:20F6A000524143098B4201D34B01C01A524103098B4201D30B01C01A5241C3088B4201D37F
-:20F6C000CB00C01A524183088B4201D38B00C01A5241D9D243088B4201D34B00C01A52417F
-:20F6E000411A00D20146634652415B10104601D34042002B00D54942704763465B1000D31A
-:20F70000404201B50020C046C04602BD704770477047754600F022F8AE460500694653469B
-:20F72000C008C000854618B020B5FEF7FBFA60BC00274908B6460026C0C5C0C5C0C5C0C525
-:20F74000C0C5C0C5C0C5C0C5403D49008D4670470446C046C0462046FCF7FFFC004870479C
-:20F760003830002001491820ABBEFEE726000200704730B47446641E2578641CAB4200D256
-:20F780001D46635D5B00E31830BC184702000000000000000000000000000000040000009F
-:20F7A000000000000000000000000000000000000000000035C4030000000000000000004D
-:20F7C000020000000000000000000000000000000000000000000000030000000000000024
-:20F7E0000000000005000000000000000000000000000000000000000000000023D1BCEA6A
-:20F800005F782315DEEF1212000000002CF8030000280020F400000004C1030020F90300A1
-:20F82000F4280020A413000020C103000000000000000000000000000000000000000000F1
-:20F840000000000000000000000000000000000000000000000000000000000000000000A8
-:20F8600000000000000000000000FFFF000000003200000000000000000000000000000058
-:20F88000000000000000000000000000000000000000000000000000000000000000000068
-:20F8A000000000000000000000000000000000000024F40000000000000000000000000030
-:20F8C000000000000000000000000000000000000000000000000000000000000000000028
-:20F8E000000000000000000000000000000000000000000000000000000000000000000008
-:20F900000000000000000000000000000000000000000000000000000000000000000000E7
-:20FC00000100000000000000FE0000000000000000000000000000000000000000000000E5
-:020000041000EA
-:0410140000C0030015
-:040000050003C0C173
-:00000001FF
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 bootloader/s130_nrf51_1.0.0_bootloader.hex
--- a/bootloader/s130_nrf51_1.0.0_bootloader.hex	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,463 +0,0 @@
-:020000040003F7
-:20C00000983C002005DD030017DD030019DD03000000000000000000000000000000000057
-:20C0200000000000000000000000000069C1030000000000000000001DDD03001FDD0300D7
-:20C0400021DD030021DD030021DD030021DD030021DD03000000000021DD030021DD0300D9
-:20C0600021DD030021DD030021DD030021DD030021DD030021DD030021DD030021DD0300B8
-:20C0800021DD030057D8030021DD030021DD03006DD8030021DD03004DF4030021DD0300DD
-:20C0A00021DD030021DD03000000000000000000000000000000000000000000000000007E
-:20C0C00000F002F800F040F80CA030C8083824182D18A246671EAB4654465D46AC4201D18E
-:20C0E00000F032F87E460F3E0FCCB6460126334200D0FB1AA246AB463343184710370000C8
-:20C1000030370000103A02D378C878C1FAD8520701D330C830C101D504680C6070470000D3
-:20C120000023002400250026103A01D378C1FBD8520700D330C100D50B6070471FB5C04655
-:20C14000C0461FBD10B510BD03F0E3FA1146FFF7F5FF00F0D3F803F0FBFA03B4FFF7F2FF19
-:20C1600003BC03F0FFFA00000648704502D1EFF3098101E0EFF30881886902380078024A97
-:20C1800010470000FDFFFFFF39D50300401E00BF00BF00BF00BF00BF00BF00BF00BF00BF28
-:20C1A00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BFB4
-:20C1C00000BF00BF00BFF1D170470000401E00BF00BF00BF00BF00BF00BF00BF00BF00BF94
-:20C1E00000BF00BF00BFF1D170470000056885F3088846680A4AEFF305839A42304602D183
-:20C20000084CA6463047074C064D0646064FF0B4034C034D024E024FF0B404480047000005
-:20C2200000000000FFFFFFFF00000021F9FFFFFF70B505460C46164602E00FCC0FC5103EEE
-:20C24000102EFAD2082E02D303CC03C5083E042E07D301CC01C5361F03E021782970641C63
-:20C260006D1C761EF9D270BD0A4610B50146664803F064F810BD10B502F078FC10BD10B5C6
-:20C28000624C86B01ECC03946C460EC4002807D0684618DF002803D00022114603F04EF864
-:20C2A0000F20800313DF002803D00022114603F045F8574B48225749092003F0A3F80028AB
-:20C2C00003D00022114603F039F800200490059001206946087404A860DF002803D0002251
-:20C2E000114603F02BF84C4803F0A8F8002803D00022114603F022F806B010BD08B547485A
-:20C30000C169B12943D0002445480F2140698903884204D000221146104603F00FF8012068
-:20C320000007006901218902884204D000221146104603F003F83B4800903B4B05220321A1
-:20C34000002001F0BAFA002803D00022114602F0F5FF00F067FC00F0AAFC012500281AD09D
-:20C3600000F0B4FC002803D00022114602F0E6FF20466840FFF783FF00F038F800F0CCFC74
-:20C3800000280ED00022114602F0D8FF09E001240021C161B8E720466840FFF770FF00F002
-:20C3A00025F803252D03002C04D1A86800F090FB002807D100F047FC002803D000221146D5
-:20C3C00002F0BCFFA86800F083FB002806D000F06EFC002802D1A86800F041FCBFF34F8F12
-:20C3E00013491248C860BFF34F8FFEE7094A10B548321421082002F00BFF002803D00022E2
-:20C40000114602F09BFF10BDEFBEADDE8CF703006BF30300342B002077C20300000500404D
-:20C4200000100010EFDC0300F42800200400FA0500ED00E070B5FC4C1E46A06815460229A3
-:20C4400002D0042916D108E0052813D1A369002B10D03246294604200BE002280AD1F348B0
-:20C46000406880470320A060A369002B02D0324629469847280003D00022114602F05EFF98
-:20C4800070BD4CB5E84E0120307005200195009400F058FB4CBD10B5E34C2078002801D057
-:20C4A000082010BD206901F0F4FA002803D00022114602F043FF0F2100228904206901F01E
-:20C4C000ABFA040003D00022114602F037FF204610BDD54910B5D448243141610221816012
-:20C4E000C168243002F059FD002803D00022114602F024FF10BDCC4910B5CB481C31416145
-:20C50000022181600320000380680F218903081A4108C5481C3002F040FD002803D000223D
-:20C52000114602F00BFF10BD704700B589B01822BF4902A8FFF77CFE06980799009001917A
-:20C5400002A80FC800F0FEFA09B000BD00B5B64987B049886A461181032109038968069146
-:20C56000B249012050394A6803928A680492C9680591069A0091019202A90EC900F0E2FA6E
-:20C58000002007B000BD30B5A84CA748503C89B02430E16802F001FD002803D00022114679
-:20C5A00002F0CCFEA048E2681C3041680023083002F0C3FC050012D1182102A802F0E6FFEA
-:20C5C00000209949029049886A469181E1680691079A0091019203A90EC900F0B3FA284601
-:20C5E00009B030BD00B5904987B049886A4611818E49032050394A6803928A680492C9683A
-:20C600000591069A0091019202A90EC900F09AFA0020B6E73EB5864A6B46183207CA07C3A4
-:20C62000814D00246C7029466C802431684602F068FC002801D0AC603EBD03207A4900038F
-:20C6400080682431486024390A46526ACA610F218903091A490840187349764A1C31486068
-:20C6600071480021103001F07BF9002803D00022114602F063FE0F2100228904286901F013
-:20C68000CBF9002803D00022114602F057FE01206C60A86000203EBD63498861704770B59A
-:20C6A000426862481468536891685038D26804604360C26081600078440701D5840705D130
-:20C6C0009C0703D18C0701D1940701D0062070BD5B189A18544D0F239B02EA60994213D81A
-:20C6E0005549564B514CC60709D08868181A90420AD3534820605348606053480FE08968F6
-:20C70000591A4908914201D20C2070BD4F4921604F496160800701D54E4800E04E48A0607B
-:20C72000A868012802D00826304670BDFFF7B3FE0600FAD12168E8688847F5E770B50500F7
-:20C7400004D0287A800703D0102070BD0E2070BD354CA068032805D0042801D0052803D0CB
-:20C76000082070BD0520A0606868E168860060688019884204D90020C04360600C2070BD5C
-:20C78000FFF789FE0028FAD1A96832466368606902F0D3FB0028F2D1616889196160E268EB
-:20C7A0009142ECD0092070BD10B51F4C08206168002900D010BDA1680429FBD11B4861786F
-:20C7C000403802F021FC002802D00021617010BD0521A16010BDF8B5134C0746A068032899
-:20C7E00004D0042804D008252846F8BD0420A0606068002801D00820F8BDFFF74CFE05000E
-:20C80000FAD17868860060788119402901D90920F8BD064AB968403A1018324602F057FE82
-:20C82000607880196070DFE7002800201C2D00209CF7030083C403000030000000C003006D
-:20C84000D3C403002BC503004DC50300F7C4030029C50300E5C5030087C5030010B5894CF1
-:20C86000A068052813D1E168606888420FD10620A060FFF710FE002808D16069E1684068FF
-:20C8800002F0FCFB002801D10721A16010BD082010BD10B57B488168072901D0082010BD63
-:20C8A000006901F0F6F8002803D00022114602F045FD75488068804710BD1CB506200195C2
-:20C8C000009400F03FF91CBDF8B51C4617460D46064600F0C1F8002817D001200003854215
-:20C8E00007D92346291B301B1A46FFF7EDFF00280BD13A462946304600F0B9F8002804D117
-:20C900003A462946304600F0A7F8F8BDF0B589B0684600F015FA049800282AD001210903F7
-:20C92000079A4018904226D9501A45081046049A0C468718024668001618001908900320DF
-:20C9400000038068049988420DD261190846042200F08DF800280CD121460422084600F073
-:20C9600086F8002805D1BA1B2B4630460899FFF7ABFF09B0F0BD049A079800F078F8F8E75C
-:20C9800000B58DB004A800F0DBF9099800280DD0089800280CD008990B984018019000219D
-:20C9A0000998009180080290684618DF0DB000BD0320000380680F218903091A4908ECE7FB
-:20C9C00000B58DB004A800F0BBF909980028EDD00F210898890300280CD0089A0B98019158
-:20C9E0008018029003220998009280080390684618DFDBE70320000380680A1A5208EEE7D2
-:20CA000030B591B0684600F09BF90498002814D001210903079A4018904214D9501A43087B
-:20CA20001046049A5C0082180019611803242403A468049DAC4202D20E2011B030BD121AB5
-:20CA4000FFF742FFF9E703200CAB07C3049880080F900CA818DFF0E71FB5032301909008B3
-:20CA6000039000930291684618DF04B010BD1FB5012301909008039000930291684618DF58
-:20CA8000F3E70000002800201C2D002010B5BB480368012B02D1022900D10160100003D099
-:20CAA0000022114602F04AFC10BD10B5B34C48DF002803D00022114602F040FC02F0FCFB82
-:20CAC0002068022803D0032801D00428EFD110BD38B50068401C19D00024684600F058F96F
-:20CAE00000980168012910D1818800290AD0C168032000038068002202F0CEFA0099898861
-:20CB0000814201D1012400E00024204638BD10B504469A482021001D02F0B9F9002803D00E
-:20CB20000022114602F00AFC9448002320222146001D02F01BF9002803D00022114602F053
-:20CB4000FDFB10BD0FB4F8B5684600F021F96846818B069D0122894CFF238948002D13D090
-:20CB6000012D17D0032D2BD00021022D37D02A46052D46D0042D4ED0062A01D10420206071
-:20CB8000F8BC08BC04B0184781800A9983600260C16010E08180099D089949190A9D49195D
-:20CBA000C160A52183600160089901610999856141610B99C16122607148FFF7A8FFDFE7B9
-:20CBC00000990B6803608B888380C968C160AA21816008990161099941610A990BE0009D60
-:20CBE0002E68A52E09D00660AE888680ED68C5600161836041618161DDE781800360C160C5
-:20CC0000F6E700F085F9002803D00022114602F095FB0320B3E781800360C1600099896807
-:20CC20008160C9E70EB557480090202001900120029002F001F8002804D150496846091D98
-:20CC400002F023F80EBD10B5FFF7E4FC002805D100F02FFB0446FFF728FF204610BD70B58A
-:20CC600011DF002803D00022114602F067FB464900200B68444C012180340A4682401A4206
-:20CC800004D0C506ED0E0A46AA402260401C2028F3D303242403A06813DF002803D000226F
-:20CCA000114602F04BFBA06802F0F2F970BD08B5684600F06DF800980168A52904D0806888
-:20CCC000AA2801D0002008BD012008BD10B5FFF797FE002803D1FFF773FE00281BD064209C
-:20CCE00001F0F2FDFFF712FE002803D00022114602F024FBFFF784FE002803D000221146DD
-:20CD000002F01CFBFFF73CFE040003D00022114602F014FB204610BD00B589B018221B49CA
-:20CD200002A8FFF785FA069807990090019102A80FC8FFF707FFFFF7B8FE002009B000BDB5
-:20CD400010B50E4988B0044600232022091D684602F04FF80098206068468088A08003983A
-:20CD6000E0600298A06004982061059860610698A0610798E06108B010BD00002C280020E6
-:20CD8000282D00208DCA030000E100E0C0F70300014901607047000000FC030008280CD0DC
-:20CDA00004DC002807D006280FD108E00B280AD00C280AD105E001207047022070470320C9
-:20CDC000704704207047042901D0062070470520704770B515460A46032823D0042820D1FF
-:20CDE000FE4C002906D0E088FD49884219D0132176DF10E0284602F0A3F9002803D00022F7
-:20CE0000114602F09BFAE069A8420AD101220321F44801F003F8002803D00022114602F051
-:20CE20008DFA70BD01211046FFF7B8FF02460121EEE7F0B5054608790E4685B081070CD07C
-:20CE400003221146284600F0E9FF002803D00022114602F073FA05B0F0BDE04900901831D9
-:20CE600002F047F9010011D1DC4CB168009AA06902F02DFB009802F097F9010006D1204647
-:20CE80006946183002F09CF9010003D0284600F0AFFAE0E704200190009880080290A06902
-:20CEA000039001A8FFF74AFC07000BD0092F10D0A06902F045F9010002D0284600F098FA04
-:20CEC0003946E3E73079616940186061A069E061C1E7307961694118616160780028BAD073
-:20CEE0006089401E0004000C6081B4D1284601F0E9F8002803D00022114602F01FFA20890D
-:20CF00006081A8E710B50022114602F017FA10BD10B5B24C01202070E088B149884208D01B
-:20CF2000132176DF002810D00022114602F006FA0BE0A078002808D074DF002803D0002282
-:20CF4000114602F0FBF90020A07001F034FC002803D00022114602F0F1F9002010BD70B5E1
-:20CF60000D68044601209D4A2B0002F002FC0A2B3043061320575C466012FFF76FFC0421FD
-:20CF8000FFF70CFF024604212EE00022114602F0D5F970BDFFF7BCFF002803D0002211468A
-:20CFA00002F0CCF9FFF775FC002808D170BDFFF7AFFF002803D00022114602F0BFF9FFF76D
-:20CFC0007CFC70BD106188680078107170BD02201061886800780128F8D1FFF7E5FB02213F
-:20CFE000FFF7DCFE02460221204600F017FF0028CBD170BD0320106170BD12692046012ACC
-:20D0000006D0022A07D0032AF6D1FFF712FF70BD00F001FA70BD00F03BFA70BD50708888D5
-:20D020001081508170BD00205070108170BD2046516901F010F8DAE710B5044669488EB0EB
-:20D0400081796846817068490180342101A802F09DFA022001900021684641728472012131
-:20D0600001820590002101A801F03FFA002803D00022114602F062F90EB010BDF0B5574C10
-:20D080008BB0A07800283AD156481821183802F07DFA2046534CC078183C00250126002875
-:20D0A00037D02746483700950195029510226946F81D039502F0DEF9002822D0F81D08909D
-:20D0C00009976846067509A804906846067708A806900420FFF7B0FF25700220207204A813
-:20D0E000E060282020823F486582183873DF002803D00022114602F021F9384886700BB045
-:20D10000F0BD0520FFF798FF2670676025722582E9E70620FFF790FF257065602572E0E7E2
-:20D1200070B52E4C01880022E588A6B017290AD01EDC11293FD008DC022977D0102902D123
-:20D140008088E080A27026B070BD264C303426461836132951D01429F5D1C289638D002106
-:20D160009A4200D1314600238088E21D82DF1BE0512970D00EDC18296CD01929E3D18079F5
-:20D180000028E0D1A270E068401EE0604FD0FFF775FFD8E7522976D05529D4D18079002871
-:20D1A000D1D11321284676DF0028CCD00022114602F0C4F8C7E78020694688803220E06054
-:20D1C000012301AA06A92846AADF002803D00022114602F0B3F82078002807E038280020A2
-:20D1E000FFFF0000602D00203015000001D1FFF745FF0020C043E080A5E70722C14910A839
-:20D2000002F065F91022E11D0CA802F060F91C22314612A802F05BF90CA80A9012A8099039
-:20D2200006ABB94A852128467FDFBDE70DE01822B64906A8FEF7FCFF0A980B9900900191F8
-:20D2400006A80FC8FFF77EFC7DE70021284667DFAAE700E017E0817900299AD0807A042885
-:20D2600003D0062801D0052893D1022909D0012069460872FF208330888102A92846A8DF82
-:20D2800092E70220F4E700F08DF88DE710B5044601F0C2FA9B482146303800F09AFE2046D3
-:20D2A000FFF73EFF10BD10B50022114602F046F810BD30B5944D87B00024203D2C7094483D
-:20D2C0002C6102F0B3F800286AD19248FFF7E4F901F000FF002863D18A4800F059F900288C
-:20D2E00001D10120E87011206946087207228AA102A87CDF002803D00022114602F01EF8B4
-:20D3000000940C2168460194018018214180FF2184809131C1807ADF002803D0002211469A
-:20D3200002F00CF804206946009408807C4801907C4802907348303800F00BFE002803D046
-:20D340000022114601F0FAFF1C21684602F01EF9754801900120800302900094032168468C
-:20D360000173C4810474714806900594684601F0FEF9002803D00022114601F0DFFF624910
-:20D38000E12208784008400010400C30DF22104008700720487010208870FFF76FFE0020A3
-:20D3A00007B030BD70B5584C614D203CE088A84201D1082070BDE178002914D05149012359
-:20D3C00008223431A9DF0028F4D12A460C21E088A7DF5849884204D0082802D0891C88420E
-:20D3E000E8D1002070BD00231A461946A9DF70BD10B50A46044603211046FFF7CFFC0246AE
-:20D400000321204600F00AFD002803D00022114601F094FF10BD30B5054687B000200090AF
-:20D4200001900290039038486A46203800791070364A0C3A1068926804906846069205900E
-:20D4400008790C2806D003221BE00022114601F075FFA5E78C68204600F049F80190201D5E
-:20D4600000F045F802902046083000F040F8039004A8FFF714F9002892D00121FFF78EFCB9
-:20D4800002460121284600F0C9FC0028DDD187E7FEB50446087982070ED08207920F042385
-:20D4A0009B1A0022154604E08E683554401CC0B2521C9A42F8D30871012000908868029048
-:20D4C0000879800801906846FFF785F900280DD00221FFF763FC02460221204600F09EFCB8
-:20D4E000002803D00022114601F028FFFEBD10B5044602F04DF80002E178000A09060843E0
-:20D5000010BD0000902D002058280020E4F703008DD20300D3CD0300446675546172670031
-:20D520005FCF0300A7D20300CD0C000005CF0300FFFF00000230000010B50C46002802D04D
-:20D540000120086010BD2168002911D01C48421A814212D03C2A0DD23C303C3101220B78B9
-:20D5600003701346491E401E521C3C2BF7D904E00E200BE03C2201F0AAFF00223C211048A9
-:20D5800001F08AFD0E49891E08800020206010BD70B5054600223C21094801F07DFD084C21
-:20D5A000A41E2188884201D00B2070BD3C220449284601F08CFF2088401C2080002070BD87
-:20D5C000823F00208307FF22DB0E9A408907090E994000280BDA0007000F08388308FA484C
-:20D5E0009B001B18D86990430843D86170478308F6489B001B1818689043084318607047AA
-:20D6000070B50124F24960040860F24940108860F04940398860F04D6C602F20FEF7B6FDAC
-:20D62000AC60EE4D00242F206C61FEF7AFFD2C7170BDF0B5E94F2821BC6841430D19396962
-:20D640004A1C09D028224A431619AB68B268934204D8D21AB26069623861F0BD0A4602E066
-:20D660000A46796A9B1B4E1C0BD028264E433719BE689E42F4D328264E433619B768FF1A1A
-:20D68000B760AB60696228214A4311194862F0BD70B5D24C2269A5681346114606E0814212
-:20D6A00007D00A46282671434919496A4E1CF6D170BD002EFCD08A420CD1282043435819EC
-:20D6C000406A2061401C05D1C34B01209860002363616071282041434819282381685A4310
-:20D6E000406A52195062421CE2D028225043401982685118816070BDF8B5B84C2569681CF9
-:20D7000035D0B748002640686169401A07023F0A19E028204543A0682A189068B84214D8D0
-:20D72000A3693F1A8619556A002B09D0116AD0699847002807D00022114601F0FFFD02E048
-:20D74000D169106A8847681CE3D1A178E078814206D1401CC0B2E070022801D10020E07079
-:20D760009E490006800D1C310E5000F0BAF9F8BDF8B50446994800270169009146785CE038
-:20D780009648F100C2688D1851E0601C07D0934A28209268604321468018446A24E0287854
-:20D7A000182141436A68401CC0B252182870A978884200D12F70894B516828209B6848434C
-:20D7C000C0181368012B34D1037E002B31D19368C360D368036113694361526902627F4A52
-:20D7E0005279002A00D0C7607C4BC2685B6996469C46D31A1A027B4B120A9A4202D20369C3
-:20D80000D21808E0724663469A1A12020369120A934202D99A1A826000E08760C76001222E
-:20D8200007610276921E42620846FFF702FF601CABD1287869788842A7D13046761EF6B202
-:20D8400000289DD1654801690098814201D00120F8BD0020F8BD644900200860486088607F
-:20D86000C860614940390860486045E7FEB50020C0435A4D02906869019068462E6900F07B
-:20D8800035F9074600F04FF90446002F08D002AA0199009800F08FF90298FFF769FF06E050
-:20D8A0000298FFF765FF002801D1002C02D0304600F0AAF900206871FEBDFFB59807002448
-:20D8C00081B01E4615460F4600280BD1002E09D0FFF796FE41490A9888610F703246002042
-:20D8E0008E6008E0072005B0F0BD28234343D4509B181C76401CB842F7DB28204743BB19C1
-:20D90000032048700F461846CB6019461830002218232E465E43D3005B181C705C709D708A
-:20D9200058603018521C032AF5DB0020C0433861BC70FC7001242D482405046003211420A9
-:20D94000FFF740FE224880380460254C0198A06003211120FFF736FE606878610020C2E71A
-:20D9600070B51E4CA568002D06D0002A06D0002804D00023247809E0082070BD072070BDBB
-:20D9800028265E43AE59002E04D05B1CA342F7DB042070BD282401265C432E516419E261BF
-:20D9A00061600360002070BD07494868C005C00D2CD010381CD50207120F083A9208920097
-:20D9C0005118C96919E0000000ED00E000E400E080E100E040130140001001406028002054
-:20D9E00000150140FFFF7F004011014080E200E08108B14A8900891809688007C00EC1400B
-:20DA00000806800F012803D0032803D0022070470020704701207047FEB50446A74817469E
-:20DA200082680D46002A0CD001788C4201D2052D01D20720FEBD2146282359435358012B7D
-:20DA400001D00820FEBD8818406801281DD00026FFF7AAFFC00099490190C9684018694684
-:20DA600000F018F9002812D0012144600160944949680830E2C091490198C9684118009877
-:20DA8000487000F02EF80020FEBD2E46E0E70420FEBDF8B5894D0446A868002809D0297844
-:20DAA0008C4201D30720F8BD282161434058012801D00820F8BDFFF777FFC600E86869465B
-:20DAC000301800F0E7F8002809D0022112C0E86831180098487000F004F80020F8BD04206B
-:20DAE000F8BD0120774900050860704710B5734900238A78CC78A24212D0521CD2B28A70D0
-:20DB0000022A00D18B708A786C4B92001C339A580260486910180002000A4861012010BDA3
-:20DB20000360002010BDF8B5644801690091457833E06248E900C0680E1834782AE01820A2
-:20DB400060437168641C0818B178E4B2A14200D100240168022902D003291BD113E0574A00
-:20DB600040682821926841438F18397E002911D0FFF78EFD002038760CE028277843C018B1
-:20DB80000276406A03E04D4900228B680869471CF3D108617078A042D1D128466D1EEDB2D0
-:20DBA0000028C6D1454801690098814201D00120F8BD0020F8BDF7B5404C0025A7682369E0
-:20DBC0001EE028215943C9198E68864202D9301A886017E0801B751900268E600E764E6946
-:20DBE0009C464B6AB646002E0AD0019E76193602360ACE6076460E6116684E626146116045
-:20DC0000591CDED12361FEBDF8B52C4801694A1C3DD028225143826889188E6828494C681F
-:20DC200047690079E11B0D022D0AED1C002815D10120254A00045060234A403A506021491D
-:20DC4000400080310860214908602149012008602F20FEF79BFA194901200871B54200D208
-:20DC60003546E81900021649000A4031086014494968001B091B0902090A0002C91C000A88
-:20DC8000814203D901200F4940040860F8BDFFF7B7FCF8BD42788378521C934200D10022C2
-:20DCA0000378934201D1002070470A6041684078182250430818704700E400E06028002090
-:20DCC0000015014000E200E04013014000E100E00010014010B50446082904D000221146F9
-:20DCE000104601F02BFB21686068884710BD1CB501910090024A0821684601F09DFA1CBD53
-:20DD0000D5DC03000A48026803210A4302600948804709480047FEE7FEE7FEE7FEE7FEE797
-:20DD2000FEE7000005480649064A074B70470000240500404DDD0300C1C003009830002007
-:20DD4000983C00209834002098340020F8B500F035F82B4E002804D02A4870602A49F01300
-:20DD600088612A480124018CC9B201290DD1818C09070AD1018D0906090F042905D1808D56
-:20DD80000006000F01D1224884600027B461214D6F60A8058460686800280ED1C820FEF790
-:20DDA00005FA1D487F1C8742F5D30020B06101208007846068680028FCD0F8BD1348018CB5
-:20DDC000C9B2012917D1818C090714D1018D09060A0F03D1828D1206120F0ED0090F0129C2
-:20DDE00003D1828D1206120F07D0032903D1808D0006000F01D0002070470120704700008E
-:20DE000000050040DFFF07C0006C0040C00F00F000060040000100408813000030B585B071
-:20DE2000002822D00388FE4CA34220D0FD4B1B78002B1CD0FB4B10255B1C1D7059700024C0
-:20DE400001259A70032269460A820094019402940394028A0A808D708C8004A902910393E7
-:20DE600000886946A6DF05B030BD0E20FBE70820F9E7F0B58BB0044602276846077300268B
-:20DE800009968784C68408A80A900D46A18A208809AAA5DF002804D0E16A00291AD08847BE
-:20DEA00018E06846008CC007C00F13D068460682208803A9A8DF002813D1A97E28461B30BA
-:20DEC00001220B0001F055FC09430F1B202224263E284300FF20FE3069460882208803A94D
-:20DEE000A8DF0BB0F0BD00960AE0062219E069460A71029022E0204690470020F1E700920D
-:20DF00002B8B022BF3D2F0E700971DE003201AE0042018E0052016E0298B032905D20322BE
-:20DF200008212046FFF77AFFDBE741780278080210436946888003D006200090A26ADAE784
-:20DF40000720FAE7092000906946A26AD3E70322E7E730B585B00D46040038D0002D36D0EC
-:20DF60006868002833D00020C043AF4B20800FCB049301AB07C3AD4869460880891C01A888
-:20DF800063DF002822D1221D69460120A0DF00281CD168468078A071204600F0CEF8002886
-:20DFA00014D1204600F055F900280FD12946204600F002F9002809D16868A062A868002804
-:20DFC00000D0E06297490120087000204BE70E2049E73EB5002828D0002926D0826A002ABE
-:20DFE00023D00A88102A21D0112A30D0502A1FD0512A1AD104460846891D0A78022A14D196
-:20E000004A88238A9A4210D1807A04280DD006280BD0052809D0891C2046FFF72AFF002860
-:20E0200003D0E16A002900D088473EBD898810E0CA8803899A42F8D1082200928A7F6B4605
-:20E040001A7120310291826A694690473EBD0021C94301803EBDF0B585B00A4605002DD00F
-:20E0600028886F4988422BD06E480078002827D06C4C1020641C2070072060700127A770F8
-:20E080000321684601820026E11C104600F04CF801466846008A0918684601820096019680
-:20E0A00002960396298A01808770868004A80394029028886946A6DF05B0F0BD0E20FBE7D3
-:20E0C0000820F9E7F0B585B00A46050028D028885349884226D053480078002822D0514C3B
-:20E0E0001120641C20700127684607820026611C104600F019F801466846008A0918684638
-:20E1000001820096019602960396298A01808770868004A80394029028886946A6DFCBE782
-:20E120000E20C9E70820C7E70870020A4A70020C8A70000EC8700420704730B58FB0054655
-:20E140001C21684601F022FA694608780421084369460870002401940394049405940694E6
-:20E16000A87908A9887031486946801C0884601C00070794000F0C77103048778A7FF920B4
-:20E180000240921CE7200240012002438A77142109A801F0FBF908A8099007A80A906946D3
-:20E1A0008C851420CC8508860D942B46A888083309AAA2DF0FB030BDF0B58FB00F4605465A
-:20E1C0001C21684601F0E2F968460178022631430170002401940394049405940694A97917
-:20E1E00008A8817011496846091D0184601C0107090F103168460794017700200146684618
-:20E200004177817FF9200140891CE72001400120014368468177142109A801F0B7F907E086
-:20E22000FFFF000088280020FCF703003015000008A8099007A80A9068468685C4850686B5
-:20E240000D972B46A888203309AA6946A2DF0FB0F0BD30B58FB005461C21684601F096F9FD
-:20E2600069460878082108431022104369460870002401940394049405940694A87908A962
-:20E280008870144869460884601C00070794000F0C7710304877887FF9210840801CF72123
-:20E2A000084010430121084369468877142109A801F06CF908A8099007A80A9069468C851A
-:20E2C0001720CC8508860D942B46A888103309AAA2DF6FE731150000FFB583B0074600207F
-:20E2E0000C9C8646267805463AE07868A90041180A88684682804988C1800022694601A8F7
-:20E3000065DF002810D1684601780598814226D17046002801D0002200E002222078891824
-:20E3200041181F2902D90C2007B0F0BD7146002908D1401CC0B2411C069B049A21701A54AF
-:20E3400001208646217806980A18694601A865DF0028E9D1694620780978401820706D1CC0
-:20E360003888A842C1DC7046002804D020780699801B401E88550020D6E7F8B51546069C10
-:20E380001E46074602220094FFF7A6FF002806D133461022294638460094FFF79DFFF8BD07
-:20E3A000F7B582B000260546167000681446002805D02846039900F0CAF8060008D168794D
-:20E3C00000281ED02078039F001D1F2802D90C2005B0F0BD684679DF0028F9D1217803226A
-:20E3E000481C20707A5421781922481C20707A542078C1196846008800F0A4F821784018A0
-:20E400002070A8790223002810D02078039A411C2170135420780399471C012227700A54E5
-:20E420002078AA79471C039927700A54A868002815D00021415620788C460246C01C03992E
-:20E440001F28C4D8501C20708B5422780A23501C20708B5420786246431C23700A54A8899B
-:20E46000002809D028460094062202210C30039BFFF783FF0600ABD1A88A002809D02846D9
-:20E480000094072203211430039BFFF776FF06009ED1A88B002809D0284600941522142137
-:20E4A0001C30039BFFF769FF060091D1686A002805D02246039900F07FF8060088D1A86A01
-:20E4C000002805D02246039900F0B5F8060084D13020405D002806D022462846039900F0F6
-:20E4E000DCF80600C7D1304672E770B50C4692B000216A46117007251171002809D0817927
-:20E5000049070CD502A9FFF74BFF002808D102AE00E00026002C0ED0A079002802D028469D
-:20E5200012B070BD01AA0AA92046FFF739FF0028F6D10AAA00E0002268460379017830463C
-:20E5400072DFEDE70870000A487002207047F8B514780746A01C15460E461F2803D83879BF
-:20E56000801C1F2801D90C20F8BD1D20001B80B26946864608803019801C7DDF0028F3D143
-:20E580003868022805D168460088704501D8092107E038790821002801D0704501D96846F6
-:20E5A0000088421C3255641CE2B2B1542978801C081828700020F8BDF8B50D461178064636
-:20E5C000881D14461F2801D90C20F8BD33880720062BFAD31927FF01BB4202D94D4A9342D6
-:20E5E000F3D17288062AF0D3BA4202D9494FBA42EBD1484FBB4203D0BA4201D09342E4D87E
-:20E60000481C052220706A5420781222411C21702A54207841193088FFF794FF21784018C5
-:20E62000C0B2207041197088FFF78CFF2178401820700020F8BD70B5054600790E46801CD6
-:20E640001446C0B21178821C8A181F2A01D90C2070BD0A46491C401C2170B0542078FF224A
-:20E66000411C21703254207881192888FFF76AFF21784018C0B22070AA88002A09D0A968AC
-:20E68000002908D0801900F022FF2078297940182070002070BD072070BDF7B582B0029894
-:20E6A0001446C06A0F46002832D0029800252030009028E00298C16A0C2068430E18217855
-:20E6C00030794A1CC01C2270785421781622481C20707A542078C1193088FFF733FF217873
-:20E6E0004018C0B22070B288002A09D0B16800290ED0C01900F0EBFE207831794018207087
-:20E700006D1C0098EDB2007CA842D3D800205FE607205DE6FFFF000038B56749674A48883D
-:20E7200090420FD04A78664C521CD2B24A70237B934208D3083175DF002803D0A1690029FF
-:20E7400000D0884738BD00254D70217C002907D03B2176DF002803D0A169002900D0884728
-:20E7600061690029EED068460095884738BD70B5054601461C225248FDF75AFD4E4C002647
-:20E7800026702968002907D00822A01800F09FFE204608307ADF02E0474808307BDF0028C1
-:20E7A00008D1401E608044486670464A0021001DFFF7D6F870BD10B53F484068FFF769F9D5
-:20E7C00010BDF8B53C48103000F069F800263A4D3B4C002806D06169002919D001200090EB
-:20E7E000684614E02878002804D0616900290FD00096F5E7687800280CD0A16800226868B8
-:20E80000FFF70AF9002803D0A169002900D088472E70F8BD6168F1E7F8B5294C028800276B
-:20E82000254DE689102A18D029464968112A21D0122A2DD0502A0FD1801D0288B2420BD1FF
-:20E84000028B022A08D1C27E837E10021843C007C00F13D0FFF7B5FFF8BD81886980014667
-:20E86000154808221631103000F031FE6F70002EF0D0F8BD0020C04368806F700846FFF7BB
-:20E8800008F90028F5D0A1690029F2D08847F8BD811D09480822103000F019FEDAE7418827
-:20E8A000054808300288914204D34088814201D8012070470020704790280020FFFF0000B6
-:20E8C000CC2D002019E7030031B5054C04E0401E00902046FDF77AFC00980028F7D138BDC6
-:20E8E000E703000018225043FE4A00218018017181604161012281610261C1607047FFB577
-:20E9000081B0F94C049B039A054626691A4303200092002E03D1002A0ED001222261276919
-:20E92000039A0126360792003B0000F022FF072707162940526127000222EFE770693269FC
-:20E9400092B25043326933691204920C9BB2594329DF002812D102210FE0084628DF00286A
-:20E960000CD10399002901D0032106E00499002916D12978042946D017E0216105B0F0BDAE
-:20E980007069326992B25043326993B24B4301461846039A29DF0028F0D10499002901D0F4
-:20E9A0000421EAE72978042920D00521E5E773693069366980B2434368681B189B18B6B2C7
-:20E9C0004E43301880181946049A29DF0028E9D0D4E7306980B24843696880188A08696902
-:20E9E00029DF0028CAD1009900290CD00621C4E77069316989B24843316989B200F0D9FD08
-:20EA000028DF0028BAD10721B7E7F8B5B54918230A780F205A435418241DB3492278266970
-:20EA2000CF68022A1BD001252D07042A2AD0052A5BD1286981B2304600F0BBFD0146A36877
-:20EA400028699A1980B24843101A820860681818861928694B1C80B25843801B34E0B8023C
-:20EA600062686169121A0918A3683018181801239B029A4202D2920829DF31E0FF220132BA
-:20EA800029DF2DE0E268974914205043F4314018001D0BC8B04203D160685943814218D02E
-:20EAA000022A16D0286981B2304600F082FD0146286980B24843301A820828694B1C80B208
-:20EAC000584363689B19C01A83082046FFF717FF06E0286981B2304600F06BFDC01928DFED
-:20EAE000002802D17F4901228A70F8BDF8B57D4C069E65780A2D1DD027787D19EDB20A2D5B
-:20EB000001D30A3DEDB218277D432D192871AA6103C9EE60AB6069612861A1780020002978
-:20EB200004D1FFF772FF112800D100206178491C6170F8BD0420F8BD38B5024669481823B1
-:20EB400001785943081803690179022B0AD014246343644CF434E4588368009383691030F7
-:20EB6000A04738BD604B14331C68F5E7F8B55D4B9978012914D100255B499D700A69082A77
-:20EB800005D002280FD003280AD10D2006E0022807D00D7000F025FA002801D0FFF7CCFF37
-:20EBA000F8BD0D61F6E74F48182403784E496343CC681818641C001DCC600378022B05D11F
-:20EBC0004668A102B14201D3012700E00027052B01D1072A03D00021042B02D003E00121C1
-:20EBE000FAE7072A03D00026042B02D007E00126FAE74068A302834201D3002A1AD0002000
-:20EC0000314301433943C5D0374E28463561FFF793FF344C2078FFF765FEF5606078401E1E
-:20EC200060702078401CC0B220700A28B2D30A382070AFE70120E3E770B500252A4C2948D3
-:20EC4000E56025610570457085702E463046FFF749FE761C0A2EF9D3012212076560516952
-:20EC600028461269491E92B25143E560A1601D49F4310D608D600D61CD601B4914310D6090
-:20EC8000888001212170206170BDF8B5164A044610780E46002830D0002C30D0002E2ED058
-:20ECA000206800282BD0012000076768016989B28F4228D8102F26D3A168002923D09568E2
-:20ECC000794343694A19006980B243439A421AD801200007006980B2814212D901200007E1
-:20ECE000006903E0E82D0020A828002080B2394600F05FFC002906D103E00820F8BD0E20B9
-:20ED0000F8BDB80701D00720F8BDBD49486801281CD00F461421BB4A21C641438E18756092
-:20ED2000236853506168B160A168F160A268616800235143012212075B1C14699BB2A4B214
-:20ED40008C4205D21469A4B2091B02E00420F8BD00211469A4B265191469A4B28C42EBD985
-:20ED6000BD60401C336178600020F8BDF8B50446A3481E46007815460F46002807D0002F3D
-:20ED800007D0002C05D02068002817D103E00820F8BD0E20F8BD9B48016800290ED0C268E3
-:20EDA000816840684A4310186268904206D9002D04D0A94202D3A819884201D90720F8BD90
-:20EDC000384600F008F9002811D0304600F003F900280CD0606800F0FEF8002807D02B4637
-:20EDE0003A46214602200096FFF780FEF8BD1020F8BDFFB5824881B000781F4616460D462B
-:20EE0000002808D0002D08D00198002805D02868002817D103E00820B0E50E20AEE5794C91
-:20EE2000206800280ED0E168A0686268414389186A68914206D9002E04D0B04202D3F119AD
-:20EE4000814201D9072099E5019800F0C4F800281BD0384600F0BFF8002816D0686800F025
-:20EE6000BAF8002811D068683246C119019800F02EFB00962868142148432458002203215B
-:20EE80002846019BA047002078E5102076E5F8B505465B480F460078002805D0002D05D012
-:20EEA0002868002821D103E00820F8BD0E20F8BD544C00262068002817D0A168E0684843CC
-:20EEC00061684118686881420FD900F084F800280DD0296814225143091968684A68896834
-:20EEE000801A00F066FB002903D00720F8BD1020F8BD3B460022294604200096FFF7F6FDB5
-:20EF0000F8BD3F4A1278002A0DD000280DD000290BD00268002A08D0394A14321368002B3E
-:20EF200005D004207047082070470E20704702230B600068106000207047F8B504463048AF
-:20EF40001E46007817460D46002807D0002D07D0002C05D0206802281BD103E00820F8BDC3
-:20EF60000E20F8BD264814300068002811D0084600F031F800280ED0304600F02CF800286C
-:20EF800009D03B462A46214602200096FFF7AEFDF8BD0720F8BD1020F8BD08B5184A1278C8
-:20EFA000002A05D0002805D00268022A11D103E0082008BD0E2008BD114A14321268002AD5
-:20EFC00007D00B460022014604200092FFF78EFD08BD072008BD800701D000207047012068
-:20EFE0007047084910B5F43949780020002906D0FFF70BFD002802D0112800D1002010BD48
-:20F00000A8280020DC2E002070B500250C290ED304464318008941000919581A0A38C2B2BD
-:20F020001748022A027002D30A318B4201D2092070BD144800F04BFA134914480A8882422E
-:20F0400002D02388934217D14988814202D06088884211D10D4A0323521E20891B03A842DE
-:20F060000AD9690009194989914203D09E896D1CB142F4D1002070BD0B2070BD00207047C6
-:20F08000C4280020F02E002080100010FFFF000010B5FDF7ABF810BD10B50446002A02D054
-:20F0A0001088002210E00A48FBE7030A00020343A05C584003061B0F43401803584083B2EB
-:20F0C0001806C00C5840521C8A42EED310BD0000FFFF00004B48002101704C484A4A026039
-:20F0E0008160C160016108224161426081610846704710B500291DD000220A60434A5368A8
-:20F10000002B1BD0202817D85B1E5360D0682423401CD060106914684343E3180B60012366
-:20F1200083409169401C19434007400F91611061002010BD0E2010BD0C2010BD042010BD8F
-:20F14000F0B5324A0646916800292BD057691020791A4907490F14680B4624254D436519D6
-:20F16000B54206D1012495698C4065400020956104E0491C4907490F8F42EED1491C4E07DC
-:20F18000760F956901210C469C402B4623420AD19368002B07D05B1E936053685B1C53609D
-:20F1A0003346F0E70420F0BD184A2423117C1268491E4907490F594320315050002070470B
-:20F1C00070B500281AD0002918D0104AD368002B16D05B1ED360936824265B1C936053692A
-:20F1E00015681C467343EE1820330660E858641C08606007400F5061002070BD0E2070BD84
-:20F20000042070BDC5280020FC2E00201C30002030B5CB0008339DB293070024002B01D0E6
-:20F22000072030BD3B4B9A605219DA605C701C7058809980002030BDF7B5364C0E466088D5
-:20F24000814237D8344F00F069F822786078A188884201DA401C00E00020C0B2904202D155
-:20F2600000F062F824E065786078884201DA401C00E00020607000F057F8BD4218D0A0688C
-:20F28000EF000299C151009900290CD0002E0AD0608832464543E068281800F018F9A068B3
-:20F2A0003818868002E00021381881800020FEBD0420FEBD0920FEBD0EB504E068468188A8
-:20F2C000029A0098904702AA01A9684600F003F80028F3D00EBD70B50E4B05241D785E786C
-:20F2E000AE4215D01D781C789E88B44201DA641C00E000241C705C88DE686C43A41904600F
-:20F300009B68E800C418A4880C80185800241060204670BDCC280020FFFF000072B606484F
-:20F320000168491C0160704703490868401E086000D162B670470000DC280020BFF34F8F11
-:20F3400003490248C860BFF34F8FFEE70400FA0500ED00E010B5002904D000221146104619
-:20F36000FFF7ECFF00F010F810BD10B50021024A0846FFF761FF10BD55F3030010B50846E6
-:20F380001146FCF771FF10BDF8B5384C2078002837D02069002807D00026E068002805D0FB
-:20F3A0000025002E04D013E00126F6E70125F8E7684651DF052806D0002806D000221146D2
-:20F3C000FFF7BCFF04E0012602E0216900988847002D12D1608869460880A06861DF0528FA
-:20F3E00006D0002806D000221146FFF7A7FF04E0012502E0E168A0688847002ED8D0002D15
-:20F40000CFD0F8BD70B5002901D08C0701D0072070BD164C0125A16062801549636010DF46
-:20F420000028F5D1257016202EDF70BD002803D00E49C860002070470E207047002803D0A8
-:20F440000A490861002070470E20704710B507484068002807D08047002803D0002211463E
-:20F46000FFF76CFF10BDFFF78FFF10BDE02800207DF30300034610B50B439B070FD1042A66
-:20F480000DD308C810C9121FA342F8D018BA21BA884201D9012010BD0020C04310BD002AAC
-:20F4A00003D0D30703D0521C07E0002010BD03780C78401C491C1B1B07D103780C78401C61
-:20F4C000491C1B1B01D1921EF1D1184610BDF8B5042A2CD3830712D00B78491C0370401C25
-:20F4E000521E83070BD00B78491C0370401C521E830704D00B78491C0370401C521E8B07F9
-:20F500009B0F05D0C91ADF002023DE1B08C90AE0FCF78EFEF8BD1D4608C9FD401C46B440B8
-:20F520002C4310C0121F042AF5D2F308C91A521EF0D40B78491C0370401C521EEAD40B78EC
-:20F54000491C0370401C521EE4D409780170F8BD01E004C0091F0429FBD28B0701D50280F7
-:20F56000801CC90700D00270704700290BD0C30702D00270401C491E022904D3830702D5EE
-:20F580000280801C891EE3E70022EEE70022DFE70378C2781946437812061B0219438378A2
-:20F5A000C0781B04194311430902090A000608437047002203098B422CD3030A8B4211D366
-:20F5C00000239C464EE003460B433CD4002243088B4231D303098B421CD3030A8B4201D39D
-:20F5E00094463FE0C3098B4201D3CB01C01A524183098B4201D38B01C01A524143098B422D
-:20F6000001D34B01C01A524103098B4201D30B01C01A5241C3088B4201D3CB00C01A524193
-:20F6200083088B4201D38B00C01A524143088B4201D34B00C01A5241411A00D201465241FB
-:20F64000104670475DE0CA0F00D04942031000D34042534000229C4603098B422DD3030A47
-:20F660008B4212D3FC22890112BA030A8B420CD3890192118B4208D3890192118B4204D305
-:20F6800089013AD0921100E08909C3098B4201D3CB01C01A524183098B4201D38B01C01A88
-:20F6A000524143098B4201D34B01C01A524103098B4201D30B01C01A5241C3088B4201D37F
-:20F6C000CB00C01A524183088B4201D38B00C01A5241D9D243088B4201D34B00C01A52417F
-:20F6E000411A00D20146634652415B10104601D34042002B00D54942704763465B1000D31A
-:20F70000404201B50020C046C04602BD704770477047754600F022F8AE460500694653469B
-:20F72000C008C000854618B020B5FEF7FBFA60BC00274908B6460026C0C5C0C5C0C5C0C525
-:20F74000C0C5C0C5C0C5C0C5403D49008D4670470446C046C0462046FCF7FFFC004870479C
-:20F760003830002001491820ABBEFEE726000200704730B47446641E2578641CAB4200D256
-:20F780001D46635D5B00E31830BC184702000000000000000000000000000000040000009F
-:20F7A000000000000000000000000000000000000000000035C4030000000000000000004D
-:20F7C000020000000000000000000000000000000000000000000000030000000000000024
-:20F7E0000000000005000000000000000000000000000000000000000000000023D1BCEA6A
-:20F800005F782315DEEF1212000000002CF8030000280020F400000004C1030020F90300A1
-:20F82000F4280020A413000020C103000000000000000000000000000000000000000000F1
-:20F840000000000000000000000000000000000000000000000000000000000000000000A8
-:20F8600000000000000000000000FFFF000000003200000000000000000000000000000058
-:20F88000000000000000000000000000000000000000000000000000000000000000000068
-:20F8A000000000000000000000000000000000000024F40000000000000000000000000030
-:20F8C000000000000000000000000000000000000000000000000000000000000000000028
-:20F8E000000000000000000000000000000000000000000000000000000000000000000008
-:20F900000000000000000000000000000000000000000000000000000000000000000000E7
-:20FC00000100000000000000FE0000000000000000000000000000000000000000000000E5
-:020000041000EA
-:0410140000C0030015
-:040000050003C0C173
-:00000001FF
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 bootloader/softdevice_nrf51822_licence_agreement.txt
--- a/bootloader/softdevice_nrf51822_licence_agreement.txt	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * S110/S120/S130 License Agreement
- *
- * Copyright (c) 2015, Nordic Semiconductor ASA, All rights reserved.
- *
- * Redistribution. Redistribution and use in binary form, without modification,
- * are permitted provided that the following conditions are met:
- *
- * • Redistributions must reproduce the above copyright notice and the following
- *   disclaimer in the documentation and/or other materials provided with the
- *   distribution.
- * • Neither the name of the copyright holder nor the names of its contributors
- *   may be used to endorse or promote products derived from this software
- *   without specific prior written permission.
- * • No reverse engineering, decompilation, or disassembly of this software is
- *   permitted.
- *
- * DISCLAIMER.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * /
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 module.json
--- a/module.json	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-{
-  "name": "ble-nrf51822",
-  "version": "2.7.1",
-  "description": "Nordic stack and drivers for the mbed BLE API.",
-  "keywords": [
-    "Bluetooth",
-    "BLE",
-    "mbed",
-    "mbed-official"
-  ],
-  "author": "Rohit Grover",
-  "repository": {
-    "url": "git@github.com:ARMmbed/ble-nRF51822.git",
-    "type": "git"
-  },
-  "homepage": "https://developer.mbed.org/teams/Nordic-Semiconductor/",
-  "licenses": [
-    {
-      "url": "https://spdx.org/licenses/Apache-2.0",
-      "type": "Apache-2.0"
-    },
-    {
-      "type": "LicenseRef-softdevice_nrf51822_licence_agreement.txt"
-    }
-  ],
-  "dependencies": {
-    "ble": "^2.6.0",
-    "nrf51-sdk": "^2.4.0"
-  },
-  "extraIncludes": [
-    "source/btle",
-    "source/btle/custom",
-    "source/common"
-  ],
-  "targetDependencies": {}
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 nrf51-sdk.lib
--- a/nrf51-sdk.lib	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-https://developer.mbed.org/teams/Nordic-Semiconductor/code/nrf51-sdk/#4a80ff6428ab
diff -r f7faad332abc -r c90ae1400bf2 softdevice_nrf51822_licence_agreement.txt
--- a/softdevice_nrf51822_licence_agreement.txt	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * S110/S120/S130 License Agreement
- *
- * Copyright (c) 2015, Nordic Semiconductor ASA, All rights reserved.
- *
- * Redistribution. Redistribution and use in binary form, without modification,
- * are permitted provided that the following conditions are met:
- *
- * • Redistributions must reproduce the above copyright notice and the following
- *   disclaimer in the documentation and/or other materials provided with the
- *   distribution.
- * • Neither the name of the copyright holder nor the names of its contributors
- *   may be used to endorse or promote products derived from this software
- *   without specific prior written permission.
- * • No reverse engineering, decompilation, or disassembly of this software is
- *   permitted.
- *
- * DISCLAIMER.
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * /
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle.cpp
--- a/source/btle/btle.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,250 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "common/common.h"
-#include "nordic_common.h"
-
-#include "btle.h"
-
-#include "ble_flash.h"
-#include "ble_conn_params.h"
-
-#include "btle_gap.h"
-#include "btle_advertising.h"
-#include "custom/custom_helper.h"
-
-#include "ble/GapEvents.h"
-#include "nRF5xn.h"
-
-extern "C" {
-#include "pstorage.h"
-#include "device_manager.h"
-#include "softdevice_handler.h"
-#include "ble_stack_handler_types.h"
-}
-
-#include "ble_hci.h"
-#include "btle_discovery.h"
-
-#include "nRF5xGattClient.h"
-#include "nRF5xServiceDiscovery.h"
-#include "nRF5xCharacteristicDescriptorDiscoverer.h"
-
-extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name);
-void            app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name);
-
-static void btle_handler(ble_evt_t *p_ble_evt);
-
-static void sys_evt_dispatch(uint32_t sys_evt)
-{
-    pstorage_sys_event_handler(sys_evt);
-}
-
-/**
- * This function is called in interrupt context to handle BLE events; i.e. pull
- * system and user events out of the pending events-queue of the BLE stack. The
- * BLE stack signals the availability of events by the triggering the SWI2
- * interrupt, which forwards the handling to this function.
- *
- * The event processing loop is implemented in intern_softdevice_events_execute().
- *
- * In mbed OS, a callback for intern_softdevice_events_execute() is posted
- * to the scheduler, which then executes in thread mode. In mbed-classic,
- * event processing happens right-away in interrupt context (which is more
- * risk-prone). In either case, the logic of event processing is identical.
- */
-static uint32_t eventHandler()
-{
-#ifdef YOTTA_CFG_MBED_OS
-    minar::Scheduler::postCallback(intern_softdevice_events_execute);
-#else
-    intern_softdevice_events_execute();
-#endif
-
-    return NRF_SUCCESS;
-}
-
-error_t btle_init(void)
-{
-    nrf_clock_lfclksrc_t clockSource;
-    if (NRF_CLOCK->LFCLKSRC & (CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos)) {
-        clockSource = NRF_CLOCK_LFCLKSRC_XTAL_20_PPM;
-    } else {
-        clockSource = NRF_CLOCK_LFCLKSRC_RC_250_PPM_4000MS_CALIBRATION;
-    }
-    SOFTDEVICE_HANDLER_INIT(clockSource, eventHandler);
-
-    // Enable BLE stack
-    /**
-     * Using this call, the application can select whether to include the
-     * Service Changed characteristic in the GATT Server. The default in all
-     * previous releases has been to include the Service Changed characteristic,
-     * but this affects how GATT clients behave. Specifically, it requires
-     * clients to subscribe to this attribute and not to cache attribute handles
-     * between connections unless the devices are bonded. If the application
-     * does not need to change the structure of the GATT server attributes at
-     * runtime this adds unnecessary complexity to the interaction with peer
-     * clients. If the SoftDevice is enabled with the Service Changed
-     * Characteristics turned off, then clients are allowed to cache attribute
-     * handles making applications simpler on both sides.
-     */
-    static const bool IS_SRVC_CHANGED_CHARACT_PRESENT = true;
-    ble_enable_params_t enableParams = {
-        .gatts_enable_params = {
-            .service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT
-        }
-    };
-    if (sd_ble_enable(&enableParams) != NRF_SUCCESS) {
-        return ERROR_INVALID_PARAM;
-    }
-
-    ble_gap_addr_t addr;
-    if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) {
-        return ERROR_INVALID_PARAM;
-    }
-    if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) {
-        return ERROR_INVALID_PARAM;
-    }
-
-    ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler));
-    ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch));
-
-    return btle_gap_init();
-}
-
-static void btle_handler(ble_evt_t *p_ble_evt)
-{
-    /* Library service handlers */
-#if SDK_CONN_PARAMS_MODULE_ENABLE
-    ble_conn_params_on_ble_evt(p_ble_evt);
-#endif
-
-    dm_ble_evt_handler(p_ble_evt);
-
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-    bleGattcEventHandler(p_ble_evt);
-#endif
-
-    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
-    nRF5xGap             &gap             = (nRF5xGap &) ble.getGap();
-    nRF5xGattServer      &gattServer      = (nRF5xGattServer &) ble.getGattServer();
-    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
-
-    /* Custom event handler */
-    switch (p_ble_evt->header.evt_id) {
-        case BLE_GAP_EVT_CONNECTED: {
-            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
-#if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110)
-            /* Only peripheral role is supported by S110 */
-            Gap::Role_t role = Gap::PERIPHERAL;
-#else
-            Gap::Role_t role = static_cast<Gap::Role_t>(p_ble_evt->evt.gap_evt.params.connected.role);
-#endif
-            gap.setConnectionHandle(handle);
-            const Gap::ConnectionParams_t *params = reinterpret_cast<Gap::ConnectionParams_t *>(&(p_ble_evt->evt.gap_evt.params.connected.conn_params));
-            const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr;
-            const ble_gap_addr_t *own  = &p_ble_evt->evt.gap_evt.params.connected.own_addr;
-            gap.processConnectionEvent(handle,
-                                                           role,
-                                                           static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr,
-                                                           static_cast<BLEProtocol::AddressType_t>(own->addr_type),  own->addr,
-                                                           params);
-            break;
-        }
-
-        case BLE_GAP_EVT_DISCONNECTED: {
-            Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle;
-            // Since we are not in a connection and have not started advertising,
-            // store bonds
-            gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID);
-
-            Gap::DisconnectionReason_t reason;
-            switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) {
-                case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION:
-                    reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION;
-                    break;
-                case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION:
-                    reason = Gap::REMOTE_USER_TERMINATED_CONNECTION;
-                    break;
-                case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE:
-                    reason = Gap::CONN_INTERVAL_UNACCEPTABLE;
-                    break;
-                default:
-                    /* Please refer to the underlying transport library for an
-                     * interpretion of this reason's value. */
-                    reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason);
-                    break;
-            }
-
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-            // Close all pending discoveries for this connection
-            nRF5xGattClient& gattClient = ble.getGattClient();
-            gattClient.characteristicDescriptorDiscoverer().terminate(handle, BLE_ERROR_INVALID_STATE);
-            gattClient.discovery().terminate(handle);
-#endif
-
-            gap.processDisconnectionEvent(handle, reason);
-            break;
-        }
-
-        case BLE_GAP_EVT_PASSKEY_DISPLAY:
-            securityManager.processPasskeyDisplayEvent(p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->evt.gap_evt.params.passkey_display.passkey);
-            break;
-
-        case BLE_GAP_EVT_TIMEOUT:
-            gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src));
-            break;
-
-        case BLE_GATTC_EVT_TIMEOUT:
-        case BLE_GATTS_EVT_TIMEOUT:
-            // Disconnect on GATT Server and Client timeout events.
-            // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle,
-            // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION));
-            break;
-
-        case BLE_GAP_EVT_ADV_REPORT: {
-            const ble_gap_evt_adv_report_t *advReport = &p_ble_evt->evt.gap_evt.params.adv_report;
-            gap.processAdvertisementReport(advReport->peer_addr.addr,
-                                           advReport->rssi,
-                                           advReport->scan_rsp,
-                                           static_cast<GapAdvertisingParams::AdvertisingType_t>(advReport->type),
-                                           advReport->dlen,
-                                           advReport->data);
-            break;
-        }
-
-        default:
-            break;
-    }
-
-    gattServer.hwCallback(p_ble_evt);
-}
-
-/*! @brief      Callback when an error occurs inside the SoftDevice */
-void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name)
-{
-    ASSERT(false, (void) 0);
-}
-
-/*!
-    @brief      Handler for general errors above the SoftDevice layer.
-                Typically we can' recover from this so we do a reset.
-*/
-void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name)
-{
-    ASSERT_STATUS_RET_VOID( error_code );
-    NVIC_SystemReset();
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle.h
--- a/source/btle/btle.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BTLE_H_
-#define _BTLE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "common/common.h"
-
-#include "ble_srv_common.h"
-#include "nrf_ble.h"
-
-error_t     btle_init(void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // ifndef _BTLE_H_
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_advertising.cpp
--- a/source/btle/btle_advertising.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "common/common.h"
-
-#include "ble_advdata.h"
-#include "btle.h"
-
-/**************************************************************************/
-/*!
-    @brief      Starts the advertising process
-
-    @returns
-*/
-/**************************************************************************/
-error_t btle_advertising_start(void)
-{
-    ble_gap_adv_params_t adv_para = {0};
-
-    /* Set the default advertising parameters */
-    adv_para.type        = BLE_GAP_ADV_TYPE_ADV_IND;
-    adv_para.p_peer_addr = NULL; /* Undirected advertising */
-    adv_para.fp          = BLE_GAP_ADV_FP_ANY;
-    adv_para.p_whitelist = NULL;
-    adv_para.interval    = (CFG_GAP_ADV_INTERVAL_MS * 8) / 5; /* Advertising
-                                                               * interval in
-                                                               * units of 0.625
-                                                               * ms */
-    adv_para.timeout     = CFG_GAP_ADV_TIMEOUT_S;
-
-    ASSERT_STATUS( sd_ble_gap_adv_start(&adv_para));
-
-    return ERROR_NONE;
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_advertising.h
--- a/source/btle/btle_advertising.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BTLE_ADVERTISING_H_
-#define _BTLE_ADVERTISING_H_
-
-#include "common/common.h"
-
-error_t btle_advertising_start(void);
-
-#endif // ifndef _BTLE_ADVERTISING_H_
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_discovery.cpp
--- a/source/btle/btle_discovery.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,128 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xServiceDiscovery.h"
-#include "nRF5xCharacteristicDescriptorDiscoverer.h"
-#include "nRF5xGattClient.h"
-#include "nRF5xn.h"
-
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-void bleGattcEventHandler(const ble_evt_t *p_ble_evt)
-{
-    nRF5xn                &ble         = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
-    nRF5xGap              &gap         = (nRF5xGap &) ble.getGap();
-    nRF5xGattClient       &gattClient  = (nRF5xGattClient &) ble.getGattClient();
-    nRF5xServiceDiscovery &sdSingleton = gattClient.discovery();
-    nRF5xCharacteristicDescriptorDiscoverer &characteristicDescriptorDiscoverer =
-        gattClient.characteristicDescriptorDiscoverer();
-
-    switch (p_ble_evt->header.evt_id) {
-        case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
-            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
-                case BLE_GATT_STATUS_SUCCESS:
-                    sdSingleton.setupDiscoveredServices(&p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp);
-                    break;
-
-                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
-                default:
-                    sdSingleton.terminate();
-                    break;
-            }
-            break;
-
-        case BLE_GATTC_EVT_CHAR_DISC_RSP:
-            switch (p_ble_evt->evt.gattc_evt.gatt_status) {
-                case BLE_GATT_STATUS_SUCCESS:
-                    sdSingleton.setupDiscoveredCharacteristics(&p_ble_evt->evt.gattc_evt.params.char_disc_rsp);
-                    break;
-
-                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
-                default:
-                    sdSingleton.terminateCharacteristicDiscovery(BLE_ERROR_NONE);
-                    break;
-            }
-            break;
-
-        case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP:
-            if (sdSingleton.isActive()) {
-                sdSingleton.processDiscoverUUIDResponse(&p_ble_evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp);
-            }
-            break;
-
-        case BLE_GATTC_EVT_READ_RSP: {
-                GattReadCallbackParams response = {
-                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
-                    .handle     = p_ble_evt->evt.gattc_evt.params.read_rsp.handle,
-                    .offset     = p_ble_evt->evt.gattc_evt.params.read_rsp.offset,
-                    .len        = p_ble_evt->evt.gattc_evt.params.read_rsp.len,
-                    .data       = p_ble_evt->evt.gattc_evt.params.read_rsp.data,
-                };
-                gattClient.processReadResponse(&response);
-            }
-            break;
-
-        case BLE_GATTC_EVT_WRITE_RSP: {
-                GattWriteCallbackParams response = {
-                    .connHandle = p_ble_evt->evt.gattc_evt.conn_handle,
-                    .handle     = p_ble_evt->evt.gattc_evt.params.write_rsp.handle,
-                    .writeOp    = (GattWriteCallbackParams::WriteOp_t)(p_ble_evt->evt.gattc_evt.params.write_rsp.write_op),
-                    .offset     = p_ble_evt->evt.gattc_evt.params.write_rsp.offset,
-                    .len        = p_ble_evt->evt.gattc_evt.params.write_rsp.len,
-                    .data       = p_ble_evt->evt.gattc_evt.params.write_rsp.data,
-                };
-                gattClient.processWriteResponse(&response);
-            }
-            break;
-
-        case BLE_GATTC_EVT_HVX: {
-                GattHVXCallbackParams params;
-                params.connHandle = p_ble_evt->evt.gattc_evt.conn_handle;
-                params.handle     = p_ble_evt->evt.gattc_evt.params.hvx.handle;
-                params.type       = static_cast<HVXType_t>(p_ble_evt->evt.gattc_evt.params.hvx.type);
-                params.len        = p_ble_evt->evt.gattc_evt.params.hvx.len;
-                params.data       = p_ble_evt->evt.gattc_evt.params.hvx.data;
-
-                gattClient.processHVXEvent(&params);
-            }
-            break;
-
-        case BLE_GATTC_EVT_DESC_DISC_RSP: {
-            uint16_t conn_handle = p_ble_evt->evt.gattc_evt.conn_handle;
-            uint16_t status = p_ble_evt->evt.gattc_evt.gatt_status;
-            const ble_gattc_evt_desc_disc_rsp_t& discovered_descriptors = p_ble_evt->evt.gattc_evt.params.desc_disc_rsp;
-
-            switch(status) {
-                case BLE_GATT_STATUS_SUCCESS:
-                    characteristicDescriptorDiscoverer.process(
-                        conn_handle,
-                        discovered_descriptors
-                    );
-                    break;
-                case BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND:
-                    // end of discovery
-                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_NONE);
-                    break;
-                default:
-                    characteristicDescriptorDiscoverer.terminate(conn_handle, BLE_ERROR_UNSPECIFIED);
-                    break;
-            }
-        }   break;
-    }
-
-    sdSingleton.progressCharacteristicDiscovery();
-    sdSingleton.progressServiceDiscovery();
-}
-#endif
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_discovery.h
--- a/source/btle/btle_discovery.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,22 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BTLE_DISCOVERY_H_
-#define _BTLE_DISCOVERY_H_
-
-void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
-
-#endif /*_BTLE_DISCOVERY_H_*/
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_gap.cpp
--- a/source/btle/btle_gap.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,99 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "common/common.h"
-
-#include "ble_gap.h"
-#include "ble_conn_params.h"
-
-static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) ATTR_ALWAYS_INLINE ATTR_CONST;
-#if SDK_CONN_PARAMS_MODULE_ENABLE
-static void   error_callback(uint32_t nrf_error);
-#endif // SDK_CONN_PARAMS_MODULE_ENABLE
-
-/**************************************************************************/
-/*!
-    @brief      Initialise GAP in the underlying SoftDevice
-
-    @returns
-*/
-/**************************************************************************/
-error_t btle_gap_init(void)
-{
-    ble_gap_conn_params_t gap_conn_params = {0};
-
-    gap_conn_params.min_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MIN_INTERVAL_MS);  // in 1.25ms units
-    gap_conn_params.max_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MAX_INTERVAL_MS);  // in 1.25ms unit
-    gap_conn_params.slave_latency     = CFG_GAP_CONNECTION_SLAVE_LATENCY;
-    gap_conn_params.conn_sup_timeout  = CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS / 10; // in 10ms unit
-
-    ble_gap_conn_sec_mode_t sec_mode;
-    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
-
-    ASSERT_STATUS( sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *) CFG_GAP_LOCAL_NAME, strlen(CFG_GAP_LOCAL_NAME)));
-    ASSERT_STATUS( sd_ble_gap_appearance_set(CFG_GAP_APPEARANCE));
-    ASSERT_STATUS( sd_ble_gap_ppcp_set(&gap_conn_params));
-    ASSERT_STATUS( sd_ble_gap_tx_power_set(CFG_BLE_TX_POWER_LEVEL));
-
-    /**
-     * Call to conn_params_init() is not necessary; and so is disabled by default.
-     * This API should be exposed to the user to be invoked when necessary.
-     */
-#if SDK_CONN_PARAMS_MODULE_ENABLE
-    /* Connection Parameters */
-    enum {
-        FIRST_UPDATE_DELAY = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
-        NEXT_UPDATE_DELAY  = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER),
-        MAX_UPDATE_COUNT   = 3
-    };
-
-    ble_conn_params_init_t cp_init = {0};
-
-    cp_init.p_conn_params                  = NULL;
-    cp_init.first_conn_params_update_delay = FIRST_UPDATE_DELAY;
-    cp_init.next_conn_params_update_delay  = NEXT_UPDATE_DELAY;
-    cp_init.max_conn_params_update_count   = MAX_UPDATE_COUNT;
-    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
-    cp_init.disconnect_on_fail             = true;
-    cp_init.evt_handler                    = NULL;
-    cp_init.error_handler                  = error_callback;
-
-    ASSERT_STATUS ( ble_conn_params_init(&cp_init));
-#endif // SDK_CONN_PARAMS_MODULE_ENABLE
-
-    return ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief      Converts msecs to an integer representing 1.25ms units
-
-    @param[in]  ms
-                The number of milliseconds to conver to 1.25ms units
-
-    @returns    The number of 1.25ms units in the supplied number of ms
-*/
-/**************************************************************************/
-static inline uint32_t msec_to_1_25msec(uint32_t interval_ms)
-{
-    return (interval_ms * 4) / 5;
-}
-
-#if SDK_CONN_PARAMS_MODULE_ENABLE
-static void error_callback(uint32_t nrf_error)
-{
-    ASSERT_STATUS_RET_VOID( nrf_error );
-}
-#endif // SDK_CONN_PARAMS_MODULE_ENABLE
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_gap.h
--- a/source/btle/btle_gap.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BTLE_GAP_H_
-#define _BTLE_GAP_H_
-
-#include "common/common.h"
-
-error_t btle_gap_init(void);
-
-#endif // ifndef _BTLE_GAP_H_
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_security.cpp
--- a/source/btle/btle_security.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,316 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "btle.h"
-
-#include "nRF5xn.h"
-
-extern "C" {
-#include "pstorage.h"
-#include "device_manager.h"
-#include "id_manager.h"
-}
-
-#include "btle_security.h"
-
-static dm_application_instance_t applicationInstance;
-static bool                      initialized = false;
-static ret_code_t dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result);
-
-// default security parameters
-static ble_gap_sec_params_t securityParameters = {
-    .bond          = true,         /**< Perform bonding. */
-    .mitm          = true,         /**< Man In The Middle protection required. */
-    .io_caps       = SecurityManager::IO_CAPS_NONE, /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */
-    .oob           = 0,            /**< Out Of Band data available. */
-    .min_key_size  = 16,           /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */
-    .max_key_size  = 16,           /**< Maximum encryption key size in octets between min_key_size and 16. */
-    .kdist_periph  = {
-      .enc  = 1,                   /**< Long Term Key and Master Identification. */
-      .id   = 1,                   /**< Identity Resolving Key and Identity Address Information. */
-      .sign = 1,                   /**< Connection Signature Resolving Key. */
-    },                             /**< Key distribution bitmap: keys that the peripheral device will distribute. */
-};
-
-bool
-btle_hasInitializedSecurity(void)
-{
-    return initialized;
-}
-
-ble_error_t
-btle_initializeSecurity(bool                                      enableBonding,
-                        bool                                      requireMITM,
-                        SecurityManager::SecurityIOCapabilities_t iocaps,
-                        const SecurityManager::Passkey_t          passkey)
-{
-    /* guard against multiple initializations */
-    if (initialized) {
-        return BLE_ERROR_NONE;
-    }
-
-    if (pstorage_init() != NRF_SUCCESS) {
-        return BLE_ERROR_UNSPECIFIED;
-    }
-
-    ret_code_t rc;
-    if (passkey) {
-        ble_opt_t opts;
-        opts.gap_opt.passkey.p_passkey = const_cast<uint8_t *>(passkey);
-        if ((rc = sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opts)) != NRF_SUCCESS) {
-            switch (rc) {
-                case BLE_ERROR_INVALID_CONN_HANDLE:
-                case NRF_ERROR_INVALID_ADDR:
-                case NRF_ERROR_INVALID_PARAM:
-                default:
-                    return BLE_ERROR_INVALID_PARAM;
-                case NRF_ERROR_INVALID_STATE:
-                    return BLE_ERROR_INVALID_STATE;
-                case NRF_ERROR_BUSY:
-                    return BLE_STACK_BUSY;
-            }
-        }
-    }
-
-    dm_init_param_t dm_init_param = {
-        .clear_persistent_data = false /* Set to true in case the module should clear all persistent data. */
-    };
-    if (dm_init(&dm_init_param) != NRF_SUCCESS) {
-        return BLE_ERROR_UNSPECIFIED;
-    }
-
-    // update default security parameters with function call parameters
-    securityParameters.bond = enableBonding;
-    securityParameters.mitm = requireMITM;
-    securityParameters.io_caps = iocaps;
-
-    const dm_application_param_t dm_param = {
-        .evt_handler  = dm_handler,
-        .service_type = DM_PROTOCOL_CNTXT_GATT_CLI_ID,
-        .sec_param    = securityParameters
-    };
-
-    if ((rc = dm_register(&applicationInstance, &dm_param)) != NRF_SUCCESS) {
-        switch (rc) {
-            case NRF_ERROR_INVALID_STATE:
-                return BLE_ERROR_INVALID_STATE;
-            case NRF_ERROR_NO_MEM:
-                return BLE_ERROR_NO_MEM;
-            default:
-                return BLE_ERROR_UNSPECIFIED;
-        }
-    }
-
-    initialized = true;
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t
-btle_purgeAllBondingState(void)
-{
-    ret_code_t rc;
-    if ((rc = dm_device_delete_all(&applicationInstance)) == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    }
-
-    switch (rc) {
-        case NRF_ERROR_INVALID_STATE:
-            return BLE_ERROR_INVALID_STATE;
-        case NRF_ERROR_NO_MEM:
-            return BLE_ERROR_NO_MEM;
-        default:
-            return BLE_ERROR_UNSPECIFIED;
-    }
-}
-
-ble_error_t
-btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP)
-{
-    ret_code_t rc;
-    dm_handle_t dmHandle = {
-        .appl_id = applicationInstance,
-    };
-    if ((rc = dm_handle_get(connectionHandle, &dmHandle)) != NRF_SUCCESS) {
-        if (rc == NRF_ERROR_NOT_FOUND) {
-            return BLE_ERROR_INVALID_PARAM;
-        } else {
-            return BLE_ERROR_UNSPECIFIED;
-        }
-    }
-
-    if ((rc = dm_security_status_req(&dmHandle, reinterpret_cast<dm_security_status_t *>(securityStatusP))) != NRF_SUCCESS) {
-        switch (rc) {
-            case NRF_ERROR_INVALID_STATE:
-                return BLE_ERROR_INVALID_STATE;
-            case NRF_ERROR_NO_MEM:
-                return BLE_ERROR_NO_MEM;
-            default:
-                return BLE_ERROR_UNSPECIFIED;
-        }
-    }
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t
-btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode)
-{
-    // use default and updated parameters as starting point
-    // and modify structure based on security mode.
-    ble_gap_sec_params_t params = securityParameters;
-
-    switch (securityMode) {
-        case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK:
-            /**< Require no protection, open link. */
-            securityParameters.bond = false;
-            securityParameters.mitm = false;
-            break;
-
-        case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM:
-            /**< Require encryption, but no MITM protection. */
-            securityParameters.bond = true;
-            securityParameters.mitm = false;
-            break;
-
-        // not yet implemented security modes
-        case SecurityManager::SECURITY_MODE_NO_ACCESS:
-        case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM:
-            /**< Require encryption and MITM protection. */
-        case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM:
-            /**< Require signing or encryption, but no MITM protection. */
-        case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM:
-            /**< Require signing or encryption, and MITM protection. */
-        default:
-            return BLE_ERROR_NOT_IMPLEMENTED;
-    }
-
-    // update security settings for given connection
-    uint32_t result = sd_ble_gap_authenticate(connectionHandle, &params);
-
-    if (result == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_UNSPECIFIED;
-    }
-}
-
-ret_code_t
-dm_handler(dm_handle_t const *p_handle, dm_event_t const *p_event, ret_code_t event_result)
-{
-    nRF5xn               &ble             = nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
-    nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager();
-
-    switch (p_event->event_id) {
-        case DM_EVT_SECURITY_SETUP: /* started */ {
-            const ble_gap_sec_params_t *peerParams = &p_event->event_param.p_gap_param->params.sec_params_request.peer_params;
-            securityManager.processSecuritySetupInitiatedEvent(p_event->event_param.p_gap_param->conn_handle,
-                                                                                   peerParams->bond,
-                                                                                   peerParams->mitm,
-                                                                                   (SecurityManager::SecurityIOCapabilities_t)peerParams->io_caps);
-            break;
-        }
-        case DM_EVT_SECURITY_SETUP_COMPLETE:
-            securityManager.
-                processSecuritySetupCompletedEvent(p_event->event_param.p_gap_param->conn_handle,
-                                                   (SecurityManager::SecurityCompletionStatus_t)(p_event->event_param.p_gap_param->params.auth_status.auth_status));
-            break;
-        case DM_EVT_LINK_SECURED: {
-            unsigned securityMode                    = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.sm;
-            unsigned level                           = p_event->event_param.p_gap_param->params.conn_sec_update.conn_sec.sec_mode.lv;
-            SecurityManager::SecurityMode_t resolvedSecurityMode = SecurityManager::SECURITY_MODE_NO_ACCESS;
-            switch (securityMode) {
-                case 1:
-                    switch (level) {
-                        case 1:
-                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK;
-                            break;
-                        case 2:
-                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM;
-                            break;
-                        case 3:
-                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM;
-                            break;
-                    }
-                    break;
-                case 2:
-                    switch (level) {
-                        case 1:
-                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_NO_MITM;
-                            break;
-                        case 2:
-                            resolvedSecurityMode = SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM;
-                            break;
-                    }
-                    break;
-            }
-
-            securityManager.processLinkSecuredEvent(p_event->event_param.p_gap_param->conn_handle, resolvedSecurityMode);
-            break;
-        }
-        case DM_EVT_DEVICE_CONTEXT_STORED:
-            securityManager.processSecurityContextStoredEvent(p_event->event_param.p_gap_param->conn_handle);
-            break;
-        default:
-            break;
-    }
-
-    return NRF_SUCCESS;
-}
-
-ble_error_t
-btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist)
-{
-    if (!btle_hasInitializedSecurity()) {
-        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
-    }
-    ret_code_t err = dm_whitelist_create(&applicationInstance, p_whitelist);
-    if (err == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else if (err == NRF_ERROR_NULL) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    } else {
-        return BLE_ERROR_INVALID_STATE;
-    }
-}
-
-
-bool
-btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk)
-{
-    /*
-     * Use a helper function from the Nordic SDK to test whether the BLE
-     * address can be generated using the IRK.
-     */
-    return im_address_resolve(p_addr, p_irk);
-}
-
-void
-btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address)
-{
-    /* Set type to resolvable */
-    address.addr_type = BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE;
-
-    /*
-     * Assign a random number to the most significant 3 bytes
-     * of the address.
-     */
-    address.addr[BLE_GAP_ADDR_LEN - 3] = 0x8E;
-    address.addr[BLE_GAP_ADDR_LEN - 2] = 0x4F;
-    address.addr[BLE_GAP_ADDR_LEN - 1] = 0x7C;
-
-    /* Calculate the hash and store it in the top half of the address */
-    ah(irk.irk, &address.addr[BLE_GAP_ADDR_LEN - 3], address.addr);
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/btle_security.h
--- a/source/btle/btle_security.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,128 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BTLE_SECURITY_H_
-#define _BTLE_SECURITY_H_
-
-#include "ble/Gap.h"
-#include "ble/SecurityManager.h"
-
-/**
- * Function to test whether the SecurityManager has been initialized.
- * Possible by a call to @ref btle_initializeSecurity().
- *
- * @return True if the SecurityManager was previously initialized, false
- *         otherwise.
- */
-bool btle_hasInitializedSecurity(void);
-
-/**
- * Enable Nordic's Device Manager, which brings in functionality from the
- * stack's Security Manager. The Security Manager implements the actual
- * cryptographic algorithms and protocol exchanges that allow two devices to
- * securely exchange data and privately detect each other.
- *
- * @param[in]  enableBonding Allow for bonding.
- * @param[in]  requireMITM   Require protection for man-in-the-middle attacks.
- * @param[in]  iocaps        To specify IO capabilities of this peripheral,
- *                           such as availability of a display or keyboard to
- *                           support out-of-band exchanges of security data.
- * @param[in]  passkey       To specify a static passkey.
- *
- * @return BLE_ERROR_NONE on success.
- */
-ble_error_t btle_initializeSecurity(bool                                      enableBonding = true,
-                                    bool                                      requireMITM   = true,
-                                    SecurityManager::SecurityIOCapabilities_t iocaps        = SecurityManager::IO_CAPS_NONE,
-                                    const SecurityManager::Passkey_t          passkey       = NULL);
-
-/**
- * Get the security status of a link.
- *
- * @param[in]  connectionHandle
- *               Handle to identify the connection.
- * @param[out] securityStatusP
- *               security status.
- *
- * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
- */
-ble_error_t btle_getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP);
-
-/**
- * Set the security mode on a connection. Useful for elevating the security mode
- * once certain conditions are met, e.g., a particular service is found.
- *
- * @param[in]  connectionHandle
- *               Handle to identify the connection.
- * @param[in]  securityMode
- *               security mode.
- *
- * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
- */
-ble_error_t btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::SecurityMode_t securityMode);
-
-/**
- * Function for deleting all peer device context and all related bonding
- * information from the database.
- *
- * @retval BLE_ERROR_NONE             On success, else an error code indicating reason for failure.
- * @retval BLE_ERROR_INVALID_STATE    If the API is called without module initialization and/or
- *                                    application registration.
- */
-ble_error_t btle_purgeAllBondingState(void);
-
-/**
- * Query the SoftDevice bond table to extract a whitelist containing the BLE
- * addresses and IRKs of bonded devices.
- *
- * @param[in/out]  p_whitelist
- *                  (on input) p_whitelist->addr_count and
- *                  p_whitelist->irk_count specify the maximum number of
- *                  addresses and IRKs added to the whitelist structure.
- *                  (on output) *p_whitelist is a whitelist containing the
- *                  addresses and IRKs of the bonded devices.
- *
- * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure.
- */
-ble_error_t btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist);
-
-/**
- * Function to test whether a BLE address is generated using an IRK.
- *
- * @param[in]   p_addr
- *                  Pointer to a BLE address.
- * @param[in]   p_irk
- *                  Pointer to an IRK.
- *
- * @return True if p_addr can be generated using p_irk, false otherwise.
- */
-bool btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk);
-
-/**
- * Function to generate a private resolvable BLE address.
- *
- * @param[out]  p_addr
- *                  The output address.
- * @param[in]   p_irk
- *                  A reference to a IRK.
- *
- * @note This function does not generate a secure address since the prand number in the
- *       resolvable address is not truly random. Therefore, the output of this function
- *       is only meant to be used by the application internally but never exported.
- */
-void btle_generateResolvableAddress(const ble_gap_irk_t &irk, ble_gap_addr_t &address);
-
-#endif /* _BTLE_SECURITY_H_ */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/custom/custom_helper.cpp
--- a/source/btle/custom/custom_helper.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,361 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "custom_helper.h"
-
-/*
- * The current version of the soft-device doesn't handle duplicate 128-bit UUIDs
- * very  well. It is therefore necessary to filter away duplicates before
- * passing long UUIDs to sd_ble_uuid_vs_add(). The following types and data
- * structures involved in maintaining a local cache of 128-bit UUIDs.
- */
-typedef struct {
-    UUID::LongUUIDBytes_t uuid;
-    uint8_t         type;
-} converted_uuid_table_entry_t;
-static const unsigned UUID_TABLE_MAX_ENTRIES = 4; /* This is the maximum number of 128-bit UUIDs with distinct bases that
-                                                   * we expect to be in use; increase this limit if needed. */
-static unsigned uuidTableEntries = 0; /* current usage of the table */
-converted_uuid_table_entry_t convertedUUIDTable[UUID_TABLE_MAX_ENTRIES];
-
-/**
- * lookup the cache of previously converted 128-bit UUIDs to find a type value.
- * @param  uuid          base 128-bit UUID
- * @param  recoveredType the type field of the 3-byte nRF's uuid.
- * @return               true if a match is found.
- */
-static bool
-lookupConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t *recoveredType)
-{
-    unsigned i;
-    for (i = 0; i < uuidTableEntries; i++) {
-        unsigned byteIndex;
-        for (byteIndex = 0; byteIndex < UUID::LENGTH_OF_LONG_UUID; byteIndex++) {
-            /* Skip bytes 2 and 3, because they contain the shortUUID (16-bit) version of the
-             * long UUID; and we're comparing against the remainder. */
-            if ((byteIndex == 2) || (byteIndex == 3)) {
-                continue;
-            }
-
-            if (convertedUUIDTable[i].uuid[byteIndex] != uuid[byteIndex]) {
-                break;
-            }
-        }
-
-        if (byteIndex == UUID::LENGTH_OF_LONG_UUID) {
-            *recoveredType = convertedUUIDTable[i].type;
-            return true;
-        }
-    }
-
-    return false;
-}
-
-static void
-addToConvertedUUIDTable(const UUID::LongUUIDBytes_t uuid, uint8_t type)
-{
-    if (uuidTableEntries == UUID_TABLE_MAX_ENTRIES) {
-        return; /* recovery needed; or at least the user should be warned about this fact.*/
-    }
-
-    memcpy(convertedUUIDTable[uuidTableEntries].uuid, uuid, UUID::LENGTH_OF_LONG_UUID);
-    convertedUUIDTable[uuidTableEntries].uuid[2] = 0;
-    convertedUUIDTable[uuidTableEntries].uuid[3] = 0;
-    convertedUUIDTable[uuidTableEntries].type    = type;
-    uuidTableEntries++;
-}
-
-/**
- * The nRF transport has its own 3-byte representation of a UUID. If the user-
- * specified UUID is 128-bits wide, then the UUID base needs to be added to the
- * soft-device and converted to a 3-byte handle before being used further. This
- * function is responsible for this translation of user-specified UUIDs into
- * nRF's representation.
- *
- * @param[in]  uuid
- *                 user-specified UUID
- * @return nRF
- *              3-byte UUID (containing a type and 16-bit UUID) representation
- *              to be used with SVC calls.
- */
-ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid)
-{
-    ble_uuid_t nordicUUID;
-    nordicUUID.uuid = uuid.getShortUUID();
-    nordicUUID.type = BLE_UUID_TYPE_UNKNOWN; /* to be set below */
-
-    if (uuid.shortOrLong() == UUID::UUID_TYPE_SHORT) {
-        nordicUUID.type = BLE_UUID_TYPE_BLE;
-    } else {
-        if (!lookupConvertedUUIDTable(uuid.getBaseUUID(), &nordicUUID.type)) {
-            nordicUUID.type = custom_add_uuid_base(uuid.getBaseUUID());
-            addToConvertedUUIDTable(uuid.getBaseUUID(), nordicUUID.type);
-        }
-    }
-
-    return nordicUUID;
-}
-
-/**************************************************************************/
-/*!
-    @brief      Adds the base UUID to the custom service. All UUIDs used
-                by this service are based on this 128-bit UUID.
-
-    @note       This UUID needs to be added to the SoftDevice stack before
-                adding the service's primary service via
-                'sd_ble_gatts_service_add'
-
-    @param[in]  p_uuid_base   A pointer to the 128-bit UUID array (8*16)
-
-    @returns    The UUID type.
-                A return value of 0 should be considered an error.
-
-    @retval     0x00    BLE_UUID_TYPE_UNKNOWN
-    @retval     0x01    BLE_UUID_TYPE_BLE
-    @retval     0x02    BLE_UUID_TYPE_VENDOR_BEGIN
-
-    @section EXAMPLE
-    @code
-
-    // Take note that bytes 2/3 are blank since these are used to identify
-    // the primary service and individual characteristics
-    #define CFG_CUSTOM_UUID_BASE  "\x6E\x40\x00\x00\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E"
-
-    uint8_t uuid_type = custom_add_uuid_base(CFG_CUSTOM_UUID_BASE);
-    ASSERT(uuid_type > 0, ERROR_NOT_FOUND);
-
-    // We can now safely add the primary service and any characteristics
-    // for our custom service ...
-
-    @endcode
-*/
-/**************************************************************************/
-uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base)
-{
-    ble_uuid128_t base_uuid;
-    uint8_t       uuid_type = 0;
-
-    for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
-        base_uuid.uuid128[i] = p_uuid_base[i];
-    }
-
-    ASSERT_INT( ERROR_NONE, sd_ble_uuid_vs_add( &base_uuid, &uuid_type ), 0);
-
-    return uuid_type;
-}
-
-/**************************************************************************/
-/*!
-
-*/
-/**************************************************************************/
-error_t custom_decode_uuid_base(uint8_t const *const p_uuid_base,
-                                ble_uuid_t          *p_uuid)
-{
-    UUID::LongUUIDBytes_t uuid_base_le;
-
-    for (uint8_t i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
-        uuid_base_le[i] = p_uuid_base[i];
-    }
-
-    ASSERT_STATUS( sd_ble_uuid_decode(UUID::LENGTH_OF_LONG_UUID, uuid_base_le, p_uuid));
-
-    return ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief      Adds a new characteristic to the custom service, assigning
-                properties, a UUID add-on value, etc.
-
-    @param[in]  service_handle
-    @param[in]  p_uuid            The 16-bit value to add to the base UUID
-                                  for this characteristic (normally >1
-                                  since 1 is typically used by the primary
-                                  service).
-    @param[in]  char_props        The characteristic properties, as
-                                  defined by ble_gatt_char_props_t
-    @param[in]  max_length        The maximum length of this characeristic
-    @param[in]  has_variable_len  Whether the characteristic data has
-                                  variable length.
-    @param[out] p_char_handle
-
-    @returns
-    @retval     ERROR_NONE        Everything executed normally
-*/
-/**************************************************************************/
-error_t custom_add_in_characteristic(uint16_t                  service_handle,
-                                     ble_uuid_t               *p_uuid,
-                                     uint8_t                   properties,
-                                     SecurityManager::SecurityMode_t       requiredSecurity,
-                                     uint8_t                  *p_data,
-                                     uint16_t                  length,
-                                     uint16_t                  max_length,
-                                     bool                      has_variable_len,
-                                     const uint8_t            *userDescriptionDescriptorValuePtr,
-                                     uint16_t                  userDescriptionDescriptorValueLen,
-                                     bool                      readAuthorization,
-                                     bool                      writeAuthorization,
-                                     ble_gatts_char_handles_t *p_char_handle)
-{
-    /* Characteristic metadata */
-    ble_gatts_attr_md_t   cccd_md;
-    ble_gatt_char_props_t char_props;
-
-    memcpy(&char_props, &properties, 1);
-
-    if (char_props.notify || char_props.indicate) {
-        /* Notification requires cccd */
-        memclr_( &cccd_md, sizeof(ble_gatts_attr_md_t));
-        cccd_md.vloc = BLE_GATTS_VLOC_STACK;
-        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
-        BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
-    }
-
-    ble_gatts_char_md_t char_md = {0};
-
-    char_md.char_props = char_props;
-    char_md.p_cccd_md  =
-        (char_props.notify || char_props.indicate) ? &cccd_md : NULL;
-    if ((userDescriptionDescriptorValueLen > 0) && (userDescriptionDescriptorValuePtr != NULL)) {
-        char_md.p_char_user_desc        = const_cast<uint8_t *>(userDescriptionDescriptorValuePtr);
-        char_md.char_user_desc_max_size = userDescriptionDescriptorValueLen;
-        char_md.char_user_desc_size     = userDescriptionDescriptorValueLen;
-    }
-
-    /* Attribute declaration */
-    ble_gatts_attr_md_t attr_md = {0};
-
-    attr_md.rd_auth = readAuthorization;
-    attr_md.wr_auth = writeAuthorization;
-
-    attr_md.vloc = BLE_GATTS_VLOC_STACK;
-    /* Always set variable size */
-    attr_md.vlen = has_variable_len;
-
-    if (char_props.read || char_props.notify || char_props.indicate) {
-        switch (requiredSecurity) {
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
-                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.read_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.read_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.read_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.read_perm);
-                break;
-            default:
-                break;
-        };
-    }
-
-    if (char_props.write || char_props.write_wo_resp) {
-        switch (requiredSecurity) {
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK :
-                BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_NO_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.write_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(&attr_md.write_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_SIGNED_NO_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(&attr_md.write_perm);
-                break;
-            case SecurityManager::SECURITY_MODE_SIGNED_WITH_MITM :
-                BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(&attr_md.write_perm);
-                break;
-            default:
-                break;
-        };
-    }
-
-    ble_gatts_attr_t attr_char_value = {0};
-
-    attr_char_value.p_uuid    = p_uuid;
-    attr_char_value.p_attr_md = &attr_md;
-    attr_char_value.init_len  = length;
-    attr_char_value.max_len   = max_length;
-    attr_char_value.p_value   = p_data;
-
-    ASSERT_STATUS ( sd_ble_gatts_characteristic_add(service_handle,
-                                                    &char_md,
-                                                    &attr_char_value,
-                                                    p_char_handle));
-
-    return ERROR_NONE;
-}
-
-
-
-/**************************************************************************/
-/*!
-    @brief      Adds a new descriptor to the custom service, assigning
-                value, a UUID add-on value, etc.
-
-    @param[in]  char_handle
-    @param[in]  p_uuid            The 16-bit value to add to the base UUID
-                                  for this descriptor (normally >1
-                                  since 1 is typically used by the primary
-                                  service).
-    @param[in]  max_length        The maximum length of this descriptor
-    @param[in]  has_variable_len  Whether the characteristic data has
-                                  variable length.
-
-    @returns
-    @retval     ERROR_NONE        Everything executed normally
-*/
-/**************************************************************************/
-error_t custom_add_in_descriptor(uint16_t    char_handle,
-                                 ble_uuid_t *p_uuid,
-                                 uint8_t    *p_data,
-                                 uint16_t    length,
-                                 uint16_t    max_length,
-                                 bool        has_variable_len,
-                                 uint16_t   *p_desc_handle)
-{
-    /* Descriptor metadata */
-    ble_gatts_attr_md_t   desc_md = {0};
-
-    desc_md.vloc = BLE_GATTS_VLOC_STACK;
-    /* Always set variable size */
-    desc_md.vlen = has_variable_len;
-
-    /* Make it readable and writable */
-    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.read_perm);
-    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&desc_md.write_perm);
-
-    ble_gatts_attr_t attr_desc = {0};
-
-    attr_desc.p_uuid    = p_uuid;
-    attr_desc.p_attr_md = &desc_md;
-    attr_desc.init_len  = length;
-    attr_desc.max_len   = max_length;
-    attr_desc.p_value   = p_data;
-
-    ASSERT_STATUS ( sd_ble_gatts_descriptor_add(char_handle,
-                                                &attr_desc,
-                                                p_desc_handle));
-
-    return ERROR_NONE;
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/btle/custom/custom_helper.h
--- a/source/btle/custom/custom_helper.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _CUSTOM_HELPER_H_
-#define _CUSTOM_HELPER_H_
-
-#include "common/common.h"
-#include "nrf_ble.h"
-#include "ble/UUID.h"
-#include "ble/GattCharacteristic.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-uint8_t custom_add_uuid_base(uint8_t const *const p_uuid_base);
-error_t custom_decode_uuid(uint8_t const *const p_uuid_base,
-                           ble_uuid_t          *p_uuid);
-ble_uuid_t custom_convert_to_nordic_uuid(const UUID &uuid);
-
-error_t custom_add_in_characteristic(uint16_t                  service_handle,
-                                     ble_uuid_t               *p_uuid,
-                                     uint8_t                   properties,
-                                     SecurityManager::SecurityMode_t requiredSecurity,
-                                     uint8_t                  *p_data,
-                                     uint16_t                  length,
-                                     uint16_t                  max_length,
-                                     bool                      has_variable_len,
-                                     const uint8_t            *userDescriptionDescriptorValuePtr,
-                                     uint16_t                  userDescriptionDescriptorValueLen,
-                                     bool                      readAuthorization,
-                                     bool                      writeAuthorization,
-                                     ble_gatts_char_handles_t *p_char_handle);
-
-error_t custom_add_in_descriptor(uint16_t                      char_handle,
-                                     ble_uuid_t               *p_uuid,
-                                     uint8_t                  *p_data,
-                                     uint16_t                  length,
-                                     uint16_t                  max_length,
-                                     bool                      has_variable_len,
-                                     uint16_t                 *p_desc_handle);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // ifndef _CUSTOM_HELPER_H_
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/ansi_escape.h
--- a/source/common/ansi_escape.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,103 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     ansi_esc_code.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, hathach (tinyusb.org)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-    This file is part of the tinyusb stack.
-*/
-/**************************************************************************/
-
-/** \file
- *  \brief TBD
- *
- *  \note TBD
- */
-
-/** \ingroup TBD
- *  \defgroup TBD
- *  \brief TBD
- *
- *  @{
- */
-
-#ifndef _ANSI_ESC_CODE_H_
-#define _ANSI_ESC_CODE_H_
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CSI_CODE(seq)   "\33[" seq
-#define CSI_SGR(x)      CSI_CODE(#x) "m"
-
-//------------- Cursor movement -------------//
-#define ANSI_CURSOR_UP(n)        CSI_CODE(#n "A")
-#define ANSI_CURSOR_DOWN(n)      CSI_CODE(#n "B")
-#define ANSI_CURSOR_FORWARD(n)   CSI_CODE(#n "C")
-#define ANSI_CURSOR_BACKWARD(n)  CSI_CODE(#n "D")
-#define ANSI_CURSOR_LINE_DOWN(n) CSI_CODE(#n "E")
-#define ANSI_CURSOR_LINE_UP(n)   CSI_CODE(#n "F")
-#define ANSI_CURSOR_POSITION(n, m) CSI_CODE(#n ";" #m "H")
-
-#define ANSI_ERASE_SCREEN(n)     CSI_CODE(#n "J")
-#define ANSI_ERASE_LINE(n)       CSI_CODE(#n "K")
-
-/** text color */
-#define ANSI_TEXT_BLACK          CSI_SGR(30)
-#define ANSI_TEXT_RED            CSI_SGR(31)
-#define ANSI_TEXT_GREEN          CSI_SGR(32)
-#define ANSI_TEXT_YELLOW         CSI_SGR(33)
-#define ANSI_TEXT_BLUE           CSI_SGR(34)
-#define ANSI_TEXT_MAGENTA        CSI_SGR(35)
-#define ANSI_TEXT_CYAN           CSI_SGR(36)
-#define ANSI_TEXT_WHITE          CSI_SGR(37)
-#define ANSI_TEXT_DEFAULT        CSI_SGR(39)
-
-/** background color */
-#define ANSI_BG_BLACK            CSI_SGR(40)
-#define ANSI_BG_RED              CSI_SGR(41)
-#define ANSI_BG_GREEN            CSI_SGR(42)
-#define ANSI_BG_YELLOW           CSI_SGR(43)
-#define ANSI_BG_BLUE             CSI_SGR(44)
-#define ANSI_BG_MAGENTA          CSI_SGR(45)
-#define ANSI_BG_CYAN             CSI_SGR(46)
-#define ANSI_BG_WHITE            CSI_SGR(47)
-#define ANSI_BG_DEFAULT          CSI_SGR(49)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _TUSB_ANSI_ESC_CODE_H_ */
-
-/** @} */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/assertion.h
--- a/source/common/assertion.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,198 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     assertion.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, K. Townsend (microBuilder.eu)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**************************************************************************/
-
-/** \file
- *  \brief TBD
- *
- *  \note TBD
- */
-
-/** \ingroup TBD
- *  \defgroup TBD
- *  \brief TBD
- *
- *  @{
- */
-
-#ifndef _ASSERTION_H_
-#define _ASSERTION_H_
-
-#include "projectconfig.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-static inline void debugger_breakpoint(void) ATTR_ALWAYS_INLINE;
-static inline void debugger_breakpoint(void)
-{
-#ifndef _TEST_
-  __asm("BKPT #0\n");
-#endif
-}
-
-//--------------------------------------------------------------------+
-// Compile-time Assert
-//--------------------------------------------------------------------+
-#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
-  #define _ASSERT_COUNTER __COUNTER__
-#else
-  #define _ASSERT_COUNTER __LINE__
-#endif
-
-#define ASSERT_STATIC(const_expr, message) enum { XSTRING_CONCAT_(static_assert_, _ASSERT_COUNTER) = 1/(!!(const_expr)) }
-
-//--------------------------------------------------------------------+
-// Assert Helper
-//--------------------------------------------------------------------+
-//#ifndef _TEST_
-//  #define ASSERT_MESSAGE(format, ...) _PRINTF("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
-//#else
-//  #define ASSERT_MESSAGE(format, ...) _PRINTF("%d:note: Assert " format "\n", __LINE__, __VA_ARGS__)
-//#endif
-
-#if CFG_DEBUG == 3
-  #define ASSERT_MESSAGE(format, ...) debugger_breakpoint()
-#elif CFG_DEBUG == 2
-  #define ASSERT_MESSAGE(format, ...) printf("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__)
-#else
-  #define ASSERT_MESSAGE(format, ...)
-#endif
-
-#define ASSERT_ERROR_HANDLER(x, para)  \
-    return (x)
-
-#define ASSERT_DEFINE_WITH_HANDLER(error_handler, handler_para, setup_statement, condition, error, format, ...) \
-  do{\
-    setup_statement;\
-	  if (!(condition)) {\
-	    ASSERT_MESSAGE(format, __VA_ARGS__);\
-	    error_handler(error, handler_para);\
-	  }\
-	}while(0)
-
-#define ASSERT_DEFINE(...) ASSERT_DEFINE_WITH_HANDLER(ASSERT_ERROR_HANDLER, NULL, __VA_ARGS__)
-
-//--------------------------------------------------------------------+
-// error_t Status Assert TODO use ASSERT_DEFINE
-//--------------------------------------------------------------------+
-#define ASSERT_STATUS_MESSAGE(sts, message) \
-    ASSERT_DEFINE(error_t status = (error_t)(sts),\
-                  ERROR_NONE == status, status, "%s: %s", ErrorStr[status], message)
-
-#define ASSERT_STATUS(sts) \
-    ASSERT_DEFINE(error_t status = (error_t)(sts),\
-                  ERROR_NONE == status, status, "error = %d", status)
-
-#define ASSERT_STATUS_RET_VOID(sts) \
-    ASSERT_DEFINE(error_t status = (error_t)(sts),\
-                  ERROR_NONE == status, (void) 0, "error = %d", status)
-
-//--------------------------------------------------------------------+
-// Logical Assert
-//--------------------------------------------------------------------+
-#define ASSERT(...)                      ASSERT_TRUE(__VA_ARGS__)
-#define ASSERT_TRUE(condition  , error)  ASSERT_DEFINE( , (condition), error, "%s", "evaluated to false")
-#define ASSERT_FALSE(condition , error)  ASSERT_DEFINE( ,!(condition), error, "%s", "evaluated to true")
-
-//--------------------------------------------------------------------+
-// Pointer Assert
-//--------------------------------------------------------------------+
-#define ASSERT_PTR(...)                    ASSERT_PTR_NOT_NULL(__VA_ARGS__)
-#define ASSERT_PTR_NOT_NULL(pointer, error) ASSERT_DEFINE( , NULL != (pointer), error, "%s", "pointer is NULL")
-#define ASSERT_PTR_NULL(pointer, error)    ASSERT_DEFINE( , NULL == (pointer), error, "%s", "pointer is not NULL")
-
-//--------------------------------------------------------------------+
-// Integral Assert
-//--------------------------------------------------------------------+
-#define ASSERT_XXX_EQUAL(type_format, expected, actual, error) \
-    ASSERT_DEFINE(\
-                  uint32_t exp = (expected); uint32_t act = (actual),\
-                  exp==act,\
-                  error,\
-                  "expected " type_format ", actual " type_format, exp, act)
-
-#define ASSERT_XXX_WITHIN(type_format, lower, upper, actual, error) \
-    ASSERT_DEFINE(\
-                  uint32_t low = (lower); uint32_t up = (upper); uint32_t act = (actual),\
-                  (low <= act) && (act <= up),\
-                  error,\
-                  "expected within " type_format " - " type_format ", actual " type_format, low, up, act)
-
-//--------------------------------------------------------------------+
-// Integer Assert
-//--------------------------------------------------------------------+
-#define ASSERT_INT(...)        ASSERT_INT_EQUAL(__VA_ARGS__)
-#define ASSERT_INT_EQUAL(...)  ASSERT_XXX_EQUAL("%d", __VA_ARGS__)
-#define ASSERT_INT_WITHIN(...) ASSERT_XXX_WITHIN("%d", __VA_ARGS__)
-
-//--------------------------------------------------------------------+
-// Hex Assert
-//--------------------------------------------------------------------+
-#define ASSERT_HEX(...)        ASSERT_HEX_EQUAL(__VA_ARGS__)
-#define ASSERT_HEX_EQUAL(...)  ASSERT_XXX_EQUAL("0x%x", __VA_ARGS__)
-#define ASSERT_HEX_WITHIN(...) ASSERT_XXX_WITHIN("0x%x", __VA_ARGS__)
-
-//--------------------------------------------------------------------+
-// Bin Assert
-//--------------------------------------------------------------------+
-#define BIN8_PRINTF_PATTERN "%d%d%d%d%d%d%d%d"
-#define BIN8_PRINTF_CONVERT(byte)  \
-  ((byte) & 0x80 ? 1 : 0), \
-  ((byte) & 0x40 ? 1 : 0), \
-  ((byte) & 0x20 ? 1 : 0), \
-  ((byte) & 0x10 ? 1 : 0), \
-  ((byte) & 0x08 ? 1 : 0), \
-  ((byte) & 0x04 ? 1 : 0), \
-  ((byte) & 0x02 ? 1 : 0), \
-  ((byte) & 0x01 ? 1 : 0)
-
-#define ASSERT_BIN8(...)        ASSERT_BIN8_EQUAL(__VA_ARGS__)
-#define ASSERT_BIN8_EQUAL(expected, actual, error)\
-    ASSERT_DEFINE(\
-                  uint8_t exp = (expected); uint8_t act = (actual),\
-                  exp==act,\
-                  error,\
-                  "expected " BIN8_PRINTF_PATTERN ", actual " BIN8_PRINTF_PATTERN, BIN8_PRINTF_CONVERT(exp), BIN8_PRINTF_CONVERT(act) )
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _ASSERTION_H_ */
-
-/** @} */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/binary.h
--- a/source/common/binary.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     binary.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, K. Townsend (microBuilder.eu)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**************************************************************************/
-
-/** \ingroup TBD
- *  \defgroup TBD
- *  \brief TBD
- *
- *  @{
- */
-
-#ifndef _BINARY_H_
-#define _BINARY_H_
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-/// n-th Bit
-#define BIT(n) (1 << (n))
-
-/// set n-th bit of x to 1
-#define BIT_SET(x, n) ( (x) | BIT(n) )
-
-/// clear n-th bit of x
-#define BIT_CLR(x, n) ( (x) & (~BIT(n)) )
-
-/// test n-th bit of x
-#define BIT_TEST(x, n) ( (x) & BIT(n) )
-
-#if defined(__GNUC__) && !defined(__CC_ARM) // keil does not support binary format
-
-#define BIN8(x)               ((uint8_t)  (0b##x))
-#define BIN16(b1, b2)         ((uint16_t) (0b##b1##b2))
-#define BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
-
-#else
-
-//  internal macro of B8, B16, B32
-#define _B8__(x) (((x&0x0000000FUL)?1:0) \
-                +((x&0x000000F0UL)?2:0) \
-                +((x&0x00000F00UL)?4:0) \
-                +((x&0x0000F000UL)?8:0) \
-                +((x&0x000F0000UL)?16:0) \
-                +((x&0x00F00000UL)?32:0) \
-                +((x&0x0F000000UL)?64:0) \
-                +((x&0xF0000000UL)?128:0))
-
-#define BIN8(d) ((uint8_t) _B8__(0x##d##UL))
-#define BIN16(dmsb,dlsb) (((uint16_t)BIN8(dmsb)<<8) + BIN8(dlsb))
-#define BIN32(dmsb,db2,db3,dlsb) \
-            (((uint32_t)BIN8(dmsb)<<24) \
-            + ((uint32_t)BIN8(db2)<<16) \
-            + ((uint32_t)BIN8(db3)<<8) \
-            + BIN8(dlsb))
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _BINARY_H_ */
-
-/** @} */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/ble_error.h
--- a/source/common/ble_error.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,151 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     ble_error.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, K. Townsend (microBuilder.eu)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**************************************************************************/
-
-/** \file
- *  \brief Error Header
- *
- *  \note TBD
- */
-
-/** \ingroup Group_Common
- *  \defgroup Group_Error Error Codes
- *  @{
- */
-
-#ifndef _BLE_ERROR_H_
-#define _BLE_ERROR_H_
-
-#include "projectconfig.h"
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-typedef enum 
-{
-  /*=======================================================================
-    NORDIC GLOBAL ERRORS                                   0x0000 .. 0x00FF
-    -----------------------------------------------------------------------
-    Errors mapped from nrf_error.h
-    -----------------------------------------------------------------------*/
-    ERROR_NONE                                    = 0x0000 , ///< Successful command
-    ERROR_SVC_HANDLER_MISSING                     = 0x0001 , ///< SVC handler is missing
-    ERROR_SOFTDEVICE_NOT_ENABLED                  = 0x0002 , ///< SoftDevice has not been enabled
-    ERROR_INTERNAL                                = 0x0003 , ///< Internal Error
-    ERROR_NO_MEM                                  = 0x0004 , ///< No Memory for operation
-    ERROR_NOT_FOUND                               = 0x0005 , ///< Not found
-    ERROR_NOT_SUPPORTED                           = 0x0006 , ///< Not supported
-    ERROR_INVALID_PARAM                           = 0x0007 , ///< Invalid Parameter
-    ERROR_INVALID_STATE                           = 0x0008 , ///< Invalid state, operation disallowed in this state
-    ERROR_INVALID_LENGTH                          = 0x0009 , ///< Invalid Length
-    ERROR_INVALID_FLAGS                           = 0x000A , ///< Invalid Flags
-    ERROR_INVALID_DATA                            = 0x000B , ///< Invalid Data
-    ERROR_DATA_SIZE                               = 0x000C , ///< Data size exceeds limit
-    ERROR_TIMEOUT                                 = 0x000D , ///< Operation timed out
-    ERROR_NULL                                    = 0x000E , ///< Null Pointer
-    ERROR_FORBIDDEN                               = 0x000F , ///< Forbidden Operation
-    ERROR_INVALID_ADDR                            = 0x0010 , ///< Bad Memory Address
-    ERROR_BUSY                                    = 0x0011 , ///< Busy
-  /*=======================================================================*/
-
-  ERROR_INVALIDPARAMETER                        = 0x0100 , /**< An invalid parameter value was provided */
-  ERROR_I2C_XFER_FAILED                         = 0x0101 , /**< an failed attempt to make I2C transfer */
-
-  /*=======================================================================
-    SIMPLE BINARY PROTOCOL ERRORS                          0x0120 .. 0x013F
-    -----------------------------------------------------------------------
-    Errors relating to the simple binary protocol (/src//protocol)
-    -----------------------------------------------------------------------*/
-    ERROR_PROT_INVALIDMSGTYPE                   = 0x121,  /**< Unexpected msg type encountered */
-    ERROR_PROT_INVALIDCOMMANDID                 = 0x122,  /**< Unknown or out of range command ID */
-    ERROR_PROT_INVALIDPAYLOAD                   = 0x123,  /**< Message payload has a problem (invalid len, etc.) */
-  /*=======================================================================*/
-
-  //------------- based on Nordic SDM nrf_error_sdm.h -------------//
-  ERROR_SDM_LFCLK_SOURCE_UNKNOWN                = 0x1000 , ///< Unknown lfclk source
-  ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION   = 0x1001 , ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts)
-  ERROR_SDM_INCORRECT_CLENR0                    = 0x1002 , ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing)
-
-  //------------- based on Nordic SOC nrf_error_soc.h -------------//
-  /* Mutex Errors */
-  ERROR_SOC_MUTEX_ALREADY_TAKEN                 = 0x2000 ,  ///< Mutex already taken
-
-  /* NVIC errors */
-  ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE        = 0x2001 ,  ///< NVIC interrupt not available
-  ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED = 0x2002 ,  ///< NVIC interrupt priority not allowed
-  ERROR_SOC_NVIC_SHOULD_NOT_RETURN              = 0x2003 ,  ///< NVIC should not return
-
-  /* Power errors */
-  ERROR_SOC_POWER_MODE_UNKNOWN                  = 0x2004 ,  ///< Power mode unknown
-  ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN         = 0x2005 ,  ///< Power POF threshold unknown
-  ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN         = 0x2006 ,  ///< Power off should not return
-
-  /* Rand errors */
-  ERROR_SOC_RAND_NOT_ENOUGH_VALUES              = 0x2007 ,  ///< RAND not enough values
-
-  /* PPI errors */
-  ERROR_SOC_PPI_INVALID_CHANNEL                 = 0x2008 ,  ///< Invalid PPI Channel
-  ERROR_SOC_PPI_INVALID_GROUP                   = 0x2009 ,  ///< Invalid PPI Group
-
-  //------------- based on Nordic STK (ble) ble_err.h -------------//
-  ERROR_BLE_INVALID_CONN_HANDLE                 = 0x3001 , /**< Invalid connection handle. */
-  ERROR_BLE_INVALID_ATTR_HANDLE                 = 0x3002 , /**< Invalid attribute handle. */
-  ERROR_BLE_NO_TX_BUFFERS                       = 0x3003 , /**< Buffer capacity exceeded. */
-
-  // L2CAP
-  ERROR_BLE_L2CAP_CID_IN_USE                    = 0x3100 , /**< CID already in use. */
-
-  // GAP
-  ERROR_BLE_GAP_UUID_LIST_MISMATCH              = 0x3200 , /**< UUID list does not contain an integral number of UUIDs. */
-  ERROR_BLE_GAP_DISCOVERABLE_WITH_WHITELIST     = 0x3201 , /**< Use of Whitelist not permitted with discoverable advertising. */
-  ERROR_BLE_GAP_INVALID_BLE_ADDR                = 0x3202 , /**< The upper two bits of the address do not correspond to the specified address type. */
-
-  // GATTC
-  ERROR_BLE_GATTC_PROC_NOT_PERMITTED            = 0x3300 ,
-
-  // GATTS
-  ERROR_BLEGATTS_INVALID_ATTR_TYPE              = 0x3400 , /**< Invalid attribute type. */
-  ERROR_BLEGATTS_SYS_ATTR_MISSING               = 0x3401 , /**< System Attributes missing. */
-
-}error_t;
-
-#ifdef __cplusplus
- }
-#endif
-
-#endif /* _BLE_ERROR_H_ */
-
- /**  @} */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/common.h
--- a/source/common/common.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,236 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     common.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, K. Townsend (microBuilder.eu)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**************************************************************************/
-
-/** \defgroup Group_Common Common Files
- * @{
- *
- *  \defgroup Group_CommonH common.h
- *
- *  @{
- */
-
-#ifndef _COMMON_H_
-#define _COMMON_H_
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-//--------------------------------------------------------------------+
-// INCLUDES
-//--------------------------------------------------------------------+
-
-//------------- Standard Header -------------//
-#include <stdint.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <string.h>
-#include <stdio.h>
-
-//------------- General Header -------------//
-#include "projectconfig.h"
-#include "compiler.h"
-#include "assertion.h"
-#include "binary.h"
-#include "ble_error.h"
-
-//------------- MCU header -------------//
-//#include "nrf.h"
-
-//--------------------------------------------------------------------+
-// TYPEDEFS
-//--------------------------------------------------------------------+
-typedef unsigned char byte_t;
-typedef float  float32_t;
-typedef double float64_t;
-
-//--------------------------------------------------------------------+
-// MACROS
-//--------------------------------------------------------------------+
-#define STRING_(x)  #x                             // stringify without expand
-#define XSTRING_(x) STRING_(x)                     // expand then stringify
-#define STRING_CONCAT_(a, b) a##b                  // concat without expand
-#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) // expand then concat
-
-#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
-#define U16_LOW_U8(u16)  ((uint8_t) ((u16)       & 0x00ff))
-#define U16_TO_U8S_BE(u16)  U16_HIGH_U8(u16), U16_LOW_U8(u16)
-#define U16_TO_U8S_LE(u16)  U16_LOW_U8(u16), U16_HIGH_U8(u16)
-
-#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB
-#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff))
-#define U32_B3_U8(u32) ((uint8_t) (((u32) >>  8) & 0x000000ff))
-#define U32_B4_U8(u32) ((uint8_t) ((u32)        & 0x000000ff)) // LSB
-
-#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32)
-#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32)
-
-//--------------------------------------------------------------------+
-// INLINE FUNCTION
-//--------------------------------------------------------------------+
-#define memclr_(buffer, size)  memset(buffer, 0, size)
-
-//------------- Conversion -------------//
-/// form an uint32_t from 4 x uint8_t
-static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4)
-{
-  return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
-}
-
-static inline uint8_t u16_high_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
-static inline uint8_t u16_high_u8(uint16_t u16)
-{
-  return (uint8_t) ((u16 >> 8) & 0x00ff);
-}
-
-static inline uint8_t u16_low_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE;
-static inline uint8_t u16_low_u8(uint16_t u16)
-{
-  return (uint8_t) (u16 & 0x00ff);
-}
-
-//------------- Min -------------//
-static inline uint8_t min8_of(uint8_t x, uint8_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint8_t min8_of(uint8_t x, uint8_t y)
-{
-  return (x < y) ? x : y;
-}
-
-static inline uint16_t min16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint16_t min16_of(uint16_t x, uint16_t y)
-{
-  return (x < y) ? x : y;
-}
-
-static inline uint32_t min32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t min32_of(uint32_t x, uint32_t y)
-{
-  return (x < y) ? x : y;
-}
-
-//------------- Max -------------//
-static inline uint32_t max32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t max32_of(uint32_t x, uint32_t y)
-{
-  return (x > y) ? x : y;
-}
-
-//------------- Align -------------//
-static inline uint32_t align32 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t align32 (uint32_t value)
-{
-	return (value & 0xFFFFFFE0UL);
-}
-
-static inline uint32_t align16 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t align16 (uint32_t value)
-{
-	return (value & 0xFFFFFFF0UL);
-}
-
-static inline uint32_t align_n (uint32_t alignment, uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t align_n (uint32_t alignment, uint32_t value)
-{
-	return value & (~(alignment-1));
-}
-
-static inline uint32_t align4k (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t align4k (uint32_t value)
-{
-	return (value & 0xFFFFF000UL);
-}
-
-static inline uint32_t offset4k(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint32_t offset4k(uint32_t value)
-{
-	return (value & 0xFFFUL);
-}
-
-//------------- Mathematics -------------//
-/// inclusive range checking
-static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper)
-{
-  return (lower <= value) && (value <= upper);
-}
-
-/// exclusive range checking
-static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper)
-{
-  return (lower < value) && (value < upper);
-}
-
-static inline uint8_t log2_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint8_t log2_of(uint32_t value)
-{
-  uint8_t result = 0; // log2 of a value is its MSB's position
-
-  while (value >>= 1)
-  {
-    result++;
-  }
-  return result;
-}
-
-// return the number of set bits in value
-static inline uint8_t cardinality_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST;
-static inline uint8_t cardinality_of(uint32_t value)
-{
-  // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only
-  // the high bit set, then it will only go once through the loop
-  // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie)
-  // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method
-  // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and
-  // published in 1964 in a book edited by Beckenbach.)"
-  uint8_t count;
-  for (count = 0; value; count++)
-  {
-    value &= value - 1; // clear the least significant bit set
-  }
-
-  return count;
-}
-
-#ifdef __cplusplus
- }
-#endif
-
-#endif /* _COMMON_H_ */
-
-/**  @} */
-/**  @} */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/common/compiler.h
--- a/source/common/compiler.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,152 +0,0 @@
-/**************************************************************************/
-/*!
-    @file     compiler.h
-    @author   hathach (tinyusb.org)
-
-    @section LICENSE
-
-    Software License Agreement (BSD License)
-
-    Copyright (c) 2013, K. Townsend (microBuilder.eu)
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without
-    modification, are permitted provided that the following conditions are met:
-    1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
-    2. Redistributions in binary form must reproduce the above copyright
-    notice, this list of conditions and the following disclaimer in the
-    documentation and/or other materials provided with the distribution.
-    3. Neither the name of the copyright holders nor the
-    names of its contributors may be used to endorse or promote products
-    derived from this software without specific prior written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
-    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-    INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND
-    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-    INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS
-    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**************************************************************************/
-
-/** \file
- *  \brief GCC Header
- */
-
-/** \ingroup Group_Compiler
- *  \defgroup Group_GCC GNU GCC
- *  @{
- */
-
-#ifndef _COMPILER_GCC_H_
-#define _COMPILER_GCC_H_
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#include "projectconfig.h"
-
-//#ifndef __GNUC__
-//  #define ATTR_ALWAYS_INLINE
-//  #define ATTR_CONST
-//#else
-
-#ifdef _TEST_
-  #define ATTR_ALWAYS_INLINE
-  #define STATIC_
-  #define INLINE_
-#else
-  #define STATIC_ static
-  #define INLINE_ inline
-
-  #if CFG_DEBUG == 3
-    #define ATTR_ALWAYS_INLINE  // no inline for debug = 3
-  #endif
-#endif
-
-#define ALIGN_OF(x)                __alignof__(x)
-
-/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section
-#define ATTR_SECTION(section)      __attribute__ ((#section))
-
-/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking
-#define ATTR_ERROR(Message)        __attribute__ ((error(Message)))
-
-/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking
-#define ATTR_WARNING(Message)      __attribute__ ((warning(Message)))
-
-/**
- *  \defgroup Group_VariableAttr Variable Attributes
- *  @{
- */
-
-/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes
-#define ATTR_ALIGNED(Bytes)        __attribute__ ((aligned(Bytes)))
-
-/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute
-#define ATTR_PACKED                __attribute__ ((packed))
-
-#define ATTR_PREPACKED
-
-#define ATTR_PACKED_STRUCT(x)    x __attribute__ ((packed))
-/** @} */
-
-/**
- *  \defgroup Group_FuncAttr Function Attributes
- *  @{
- */
-
-#ifndef ATTR_ALWAYS_INLINE
-/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified
-#define ATTR_ALWAYS_INLINE         __attribute__ ((always_inline))
-#endif
-
-/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null
-#define ATTR_NON_NULL              __attribute__ ((nonull))
-
-/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure
-#define ATTR_PURE                  __attribute__ ((pure))
-
-/// Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
-/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void
-#define ATTR_CONST                 __attribute__ ((const))
-
-/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses
-#define ATTR_DEPRECATED            __attribute__ ((deprecated))
-
-/// Same as the deprecated attribute with optional message in the warning
-#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess)))
-
-/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code
-#define ATTR_WEAK                  __attribute__ ((weak))
-
-/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified
-#define ATTR_ALIAS(func)           __attribute__ ((alias(#func)))
-
-/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static
-#define ATTR_WEAKREF(func)         __attribute__ ((weakref(#func)))
-
-/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug
-#define ATTR_WARN_UNUSED_RESULT    __attribute__ ((warn_unused_result))
-
-/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.
-#define ATTR_USED                  __attribute__ ((used))
-
-/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function.
-#define ATTR_UNUSED                __attribute__ ((unused))
-
-/** @} */
-
-#ifdef __cplusplus
- }
-#endif
-
-#endif /* _COMPILER_GCC_H_ */
-
-/// @}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xCharacteristicDescriptorDiscoverer.cpp
--- a/source/nRF5xCharacteristicDescriptorDiscoverer.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,235 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2015 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "nRF5xCharacteristicDescriptorDiscoverer.h"
-#include "ble_err.h"
-#include "ble/DiscoveredCharacteristicDescriptor.h"
-
-nRF5xCharacteristicDescriptorDiscoverer::nRF5xCharacteristicDescriptorDiscoverer() :
-    discoveryRunning() {
-    // nothing to do
-}
-
-nRF5xCharacteristicDescriptorDiscoverer::~nRF5xCharacteristicDescriptorDiscoverer() {
-    // nothing to do
-}
-
-ble_error_t nRF5xCharacteristicDescriptorDiscoverer::launch(
-    const DiscoveredCharacteristic& characteristic,
-    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
-    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
-) {
-    Gap::Handle_t connHandle = characteristic.getConnectionHandle();
-    // it is ok to deduce that the start handle for descriptors is after
-    // the characteristic declaration and the characteristic value declaration
-    // see BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] (3.3)
-    Gap::Handle_t descriptorStartHandle = characteristic.getDeclHandle() + 2;
-    Gap::Handle_t descriptorEndHandle = characteristic.getLastHandle();
-
-    // check if there is any descriptor to discover
-    if (descriptorEndHandle < descriptorStartHandle) {
-        CharacteristicDescriptorDiscovery::TerminationCallbackParams_t termParams = {
-            characteristic,
-            BLE_ERROR_NONE
-        };
-        terminationCallback.call(&termParams);
-        return BLE_ERROR_NONE;
-    }
-
-    // check if we can run this discovery
-    if (isConnectionInUse(connHandle)) {
-        return BLE_STACK_BUSY;
-    }
-
-    // get a new discovery slot, if none are available, just return
-    Discovery* discovery = getAvailableDiscoverySlot();
-    if(discovery == NULL) {
-        return BLE_STACK_BUSY;
-    }
-
-    // try to launch the discovery
-    ble_error_t err = gattc_descriptors_discover(connHandle, descriptorStartHandle, descriptorEndHandle);
-    if(!err) {
-        // commit the new discovery to its slot
-        *discovery = Discovery(characteristic, discoveryCallback, terminationCallback);
-    }
-
-    return err;
-}
-
-bool nRF5xCharacteristicDescriptorDiscoverer::isActive(const DiscoveredCharacteristic& characteristic) const {
-    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
-        if(discoveryRunning[i].getCharacteristic() == characteristic) {
-            return true;
-        }
-    }
-    return false;
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::requestTerminate(const DiscoveredCharacteristic& characteristic) {
-    Discovery* discovery = findRunningDiscovery(characteristic);
-    if(discovery) {
-        // call terminate anyway
-        terminate(discovery, BLE_ERROR_NONE);
-    }
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors) {
-    Discovery* discovery = findRunningDiscovery(connectionHandle);
-    // the discovery has been removed
-    if(!discovery) {
-        return;
-    }
-
-    for (uint16_t i = 0; i < descriptors.count; ++i) {
-        discovery->process(
-            descriptors.descs[i].handle, UUID(descriptors.descs[i].uuid.uuid)
-        );
-    }
-
-    // prepare the next discovery request (if needed)
-    uint16_t startHandle = descriptors.descs[descriptors.count - 1].handle + 1;
-    uint16_t endHandle = discovery->getCharacteristic().getLastHandle();
-
-    if(startHandle > endHandle) {
-        terminate(discovery, BLE_ERROR_NONE);
-        return;
-    }
-
-    ble_error_t err = gattc_descriptors_discover(connectionHandle, startHandle, endHandle);
-    if(err) {
-        terminate(discovery, err);
-        return;
-    }
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::terminate(uint16_t handle, ble_error_t err) {
-    Discovery* discovery = findRunningDiscovery(handle);
-    // the discovery has already been terminated
-    if(!discovery) {
-        return;
-    }
-
-    terminate(discovery, err);
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::terminate(Discovery* discovery, ble_error_t err) {
-    // temporary copy, user code can try to launch a new discovery in the onTerminate
-    // callback. So, this discovery should not appear in such case.
-    Discovery tmp = *discovery;
-    *discovery = Discovery();
-    tmp.terminate(err);
-}
-
-nRF5xCharacteristicDescriptorDiscoverer::Discovery*
-nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(const DiscoveredCharacteristic& characteristic) {
-    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
-        if((discoveryRunning[i].getCharacteristic() == characteristic) &&
-           (discoveryRunning[i].isEmpty() == false)) {
-            return &discoveryRunning[i];
-        }
-    }
-    return NULL;
-}
-
-nRF5xCharacteristicDescriptorDiscoverer::Discovery*
-nRF5xCharacteristicDescriptorDiscoverer::findRunningDiscovery(uint16_t handle) {
-    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
-        if((discoveryRunning[i].getCharacteristic().getConnectionHandle() == handle) &&
-           (discoveryRunning[i].isEmpty() == false)) {
-            return &discoveryRunning[i];
-        }
-    }
-    return NULL;
-}
-
-nRF5xCharacteristicDescriptorDiscoverer::Discovery*
-nRF5xCharacteristicDescriptorDiscoverer::getAvailableDiscoverySlot() {
-    for(size_t i = 0; i < MAXIMUM_CONCURRENT_CONNECTIONS_COUNT; ++i) {
-        if(discoveryRunning[i].isEmpty()) {
-            return &discoveryRunning[i];
-        }
-    }
-    return NULL;
-}
-
-bool nRF5xCharacteristicDescriptorDiscoverer::isConnectionInUse(uint16_t connHandle) {
-     return findRunningDiscovery(connHandle) != NULL;
-}
-
-ble_error_t nRF5xCharacteristicDescriptorDiscoverer::gattc_descriptors_discover(
-    uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle) {
-
-    ble_gattc_handle_range_t discoveryRange = {
-        start_handle,
-        end_handle
-    };
-    uint32_t err = sd_ble_gattc_descriptors_discover(connection_handle, &discoveryRange);
-
-    switch(err) {
-        case NRF_SUCCESS:
-            return BLE_ERROR_NONE;
-        case BLE_ERROR_INVALID_CONN_HANDLE:
-            return BLE_ERROR_INVALID_PARAM;
-        case NRF_ERROR_INVALID_ADDR:
-            return BLE_ERROR_PARAM_OUT_OF_RANGE;
-        case NRF_ERROR_BUSY:
-            return BLE_STACK_BUSY;
-        default:
-            return BLE_ERROR_UNSPECIFIED;
-    }
-}
-
-// implementation of nRF5xCharacteristicDescriptorDiscoverer::Discovery
-
-nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery() :
-    characteristic(), onDiscovery(), onTerminate() {
-}
-
-nRF5xCharacteristicDescriptorDiscoverer::Discovery::Discovery(
-    const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb) :
-    characteristic(c), onDiscovery(dCb), onTerminate(tCb) {
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::Discovery::process(
-    GattAttribute::Handle_t handle, const UUID& uuid) {
-    CharacteristicDescriptorDiscovery::DiscoveryCallbackParams_t params = {
-        characteristic,
-        DiscoveredCharacteristicDescriptor(
-            characteristic.getGattClient(),
-            characteristic.getConnectionHandle(),
-            handle,
-            uuid
-        )
-    };
-    onDiscovery.call(&params);
-}
-
-void nRF5xCharacteristicDescriptorDiscoverer::Discovery::terminate(ble_error_t err) {
-    CharacteristicDescriptorDiscovery::TerminationCallbackParams_t params = {
-        characteristic,
-        err
-    };
-
-    onTerminate.call(&params);
-}
-
-bool nRF5xCharacteristicDescriptorDiscoverer::Discovery::isEmpty() const {
-    return *this == Discovery();
-}
-
-const DiscoveredCharacteristic& nRF5xCharacteristicDescriptorDiscoverer::Discovery::getCharacteristic() const {
-    return characteristic;
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xCharacteristicDescriptorDiscoverer.h
--- a/source/nRF5xCharacteristicDescriptorDiscoverer.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,214 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2015 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
-#define __NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__
-
-#include "ble/Gap.h"
-#include "ble/DiscoveredCharacteristic.h"
-#include "ble/CharacteristicDescriptorDiscovery.h"
-#include "ble/GattClient.h"
-#include "ble_gattc.h"
-
-/**
- * @brief Manage the discovery of Characteristic descriptors
- * @details is a bridge between BLE API and Nordic stack regarding Characteristic
- * Descriptor discovery. The BLE API can launch, monitor and ask for termination
- * of a discovery. The Nordic stack will provide new descriptors and indicate when
- * the discovery is done.
- */
-class nRF5xCharacteristicDescriptorDiscoverer
-{
-    typedef CharacteristicDescriptorDiscovery::DiscoveryCallback_t DiscoveryCallback_t;
-    typedef CharacteristicDescriptorDiscovery::TerminationCallback_t TerminationCallback_t;
-
-public:
-    /**
-     * @brief Construct a new characteristic descriptor discoverer.
-     */
-    nRF5xCharacteristicDescriptorDiscoverer();
-
-    /**
-     * @brief Destroy a characteristic descriptor discoverer.
-     */
-    ~nRF5xCharacteristicDescriptorDiscoverer();
-
-    /**
-     * Launch a new characteristic descriptor discovery for a given DiscoveredCharacteristic.
-     * @param characteristic The characteristic owning the descriptors to discover.
-     * @param discoveryCallback The callback called when a descriptor is discovered.
-     * @param terminationCallback The callback called when the discovery process end.
-     * @return BLE_ERROR_NONE if characteristic descriptor discovery is launched successfully;
-     *         else an appropriate error.
-     * @note: this will be called by BLE API side.
-     */
-    ble_error_t launch(
-        const DiscoveredCharacteristic& characteristic,
-        const DiscoveryCallback_t& discoveryCallback,
-        const TerminationCallback_t& terminationCallback
-    );
-
-    /**
-     * @brief indicate if a characteristic descriptor discovery is active for a
-     * given DiscoveredCharacteristic.
-     * @param characteristic The characteristic for whom the descriptor might be
-     * currently discovered.
-     * @return true if descriptors of characteristic are discovered, false otherwise.
-     * @note: this will be called by BLE API side.
-     */
-    bool isActive(const DiscoveredCharacteristic& characteristic) const;
-
-    /**
-     * @brief request the termination of characteristic descriptor discovery
-     * for a give DiscoveredCharacteristic
-     * @param characteristic The characteristic for whom the descriptor discovery
-     * should be stopped.
-     * @note: this will be called by BLE API side.
-     */
-    void requestTerminate(const DiscoveredCharacteristic& characteristic);
-
-    /**
-     * @brief process descriptors discovered from the Nordic stack.
-     * @param connectionHandle The connection handle upon which descriptors has been
-     * discovered.
-     * @param descriptors Discovered descriptors.
-     * @note This will be called by the Nordic stack.
-     */
-    void process(uint16_t connectionHandle, const ble_gattc_evt_desc_disc_rsp_t& descriptors);
-
-    /**
-     * @brief Called by the Nordic stack when the discovery is over.
-     * @param The connection handle upon which the discovery process is done.
-     * @param err An error if the termination is due to an error.
-     */
-    void terminate(uint16_t connectionHandle, ble_error_t err);
-
-private:
-    // protection against copy construction and assignment
-    nRF5xCharacteristicDescriptorDiscoverer(const nRF5xCharacteristicDescriptorDiscoverer&);
-    nRF5xCharacteristicDescriptorDiscoverer& operator=(const nRF5xCharacteristicDescriptorDiscoverer&);
-
-    /**
-     * @brief Discovery process, it store the DiscoveredCharacteristic, the
-     * discovery callback and the termination callback.
-     */
-    class Discovery {
-    public:
-        /**
-         * @brief Construct an empty discovery, such can be considerate as a not running discovery.
-         * @note #isEmpty function will return true
-         */
-        Discovery();
-
-        /**
-         * @brief Construct a valid discovery process.
-         *
-         * @param c the characteristic from whom descriptors will be discovered.
-         * @param dCb The discovery callback called each time a descriptor is discovered.
-         * @param tCb The termination callback called when the discovery terminate.
-         *
-         * @note #isEmpty function will return false
-         */
-        Discovery(const DiscoveredCharacteristic& c, const DiscoveryCallback_t& dCb, const TerminationCallback_t& tCb);
-
-        /**
-         * @brief Process the discovery of a descriptor.
-         *
-         * @param handle The attribute handle of the descriptor found
-         * @param uuid The UUID of the descriptor found.
-         */
-        void process(GattAttribute::Handle_t handle, const UUID& uuid);
-
-        /**
-         * @brief Terminate the discovery process.
-         *
-         * @param err Error associate with the termination
-         * @note after this call #isEmpty function will return true.
-         */
-        void terminate(ble_error_t err);
-
-        /**
-         * @brief check if the discovery process is empty or not. Empty discovery are
-         * not running.
-         *
-         * @detail Discovery are empty after:
-         *     - a default construction
-         *     - a copy construction form a default constructed
-         *     - an assignment from a default constructed Discovery
-         * @return true if the Discovery is empty and false otherwise.
-         */
-        bool isEmpty() const;
-
-        /**
-         * @brief return the characteristic from whom descriptors are discovered.
-         * @return the characteristic from whom descriptors are discovered.
-         */
-        const DiscoveredCharacteristic& getCharacteristic() const;
-
-        /**
-         * @brief equal to operator, test if two discovery process are equal
-         *
-         * @param lhs left hand side of the expression
-         * @param rhs right hand side of the expression
-         * @return true if lhs == rhs
-         */
-        friend bool operator==(const Discovery& lhs, const Discovery& rhs) {
-            return lhs.characteristic == rhs.characteristic &&
-                   lhs.onDiscovery == rhs.onDiscovery &&
-                   lhs.onTerminate == rhs.onTerminate;
-        }
-
-        /**
-         * @brief not equal to operator, test if two discovery process are not equal
-         *
-         * @param lhs left hand side of the expression
-         * @param rhs right hand side of the expression
-         * @return true if lhs != rhs
-         */
-        friend bool operator!=(const Discovery& lhs, const Discovery& rhs) {
-            return !(lhs == rhs);
-        }
-
-    private:
-        DiscoveredCharacteristic characteristic;
-        DiscoveryCallback_t onDiscovery;
-        TerminationCallback_t onTerminate;
-    };
-
-    // find a running discovery process
-    Discovery* findRunningDiscovery(const DiscoveredCharacteristic& characteristic);
-    Discovery* findRunningDiscovery(uint16_t handle);
-
-    // Called to terminate a discovery is over.
-    void terminate(Discovery* discovery, ble_error_t err);
-
-    // get one slot for a discovery process
-    Discovery* getAvailableDiscoverySlot();
-
-    // indicate if a connection is already running a discovery
-    bool isConnectionInUse(uint16_t connHandle);
-
-    // low level start of a discovery
-    static ble_error_t gattc_descriptors_discover(uint16_t connection_handle, uint16_t start_handle, uint16_t end_handle);
-
-    // count of concurrent connections which can run a descriptor discovery process
-    static const size_t MAXIMUM_CONCURRENT_CONNECTIONS_COUNT = 3;
-
-    // array of running discoveries
-    Discovery discoveryRunning[MAXIMUM_CONCURRENT_CONNECTIONS_COUNT];
-};
-
-#endif /*__NRF_CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__*/
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xDiscoveredCharacteristic.cpp
--- a/source/nRF5xDiscoveredCharacteristic.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xDiscoveredCharacteristic.h"
-#include "nRF5xGattClient.h"
-#include "ble_gatt.h"
-
-void
-nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
-                                     Gap::Handle_t            connectionHandleIn,
-                                     ble_gatt_char_props_t    propsIn,
-                                     GattAttribute::Handle_t  declHandleIn,
-                                     GattAttribute::Handle_t  valueHandleIn)
-{
-    gattc       = gattcIn;
-    connHandle  = connectionHandleIn;
-    declHandle  = declHandleIn;
-    valueHandle = valueHandleIn;
-
-    props._broadcast       = propsIn.broadcast;
-    props._read            = propsIn.read;
-    props._writeWoResp     = propsIn.write_wo_resp;
-    props._write           = propsIn.write;
-    props._notify          = propsIn.notify;
-    props._indicate        = propsIn.indicate;
-    props._authSignedWrite = propsIn.auth_signed_wr;
-}
-
-void
-nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient         *gattcIn,
-                                      Gap::Handle_t            connectionHandleIn,
-                                     UUID::ShortUUIDBytes_t   uuidIn,
-                                     ble_gatt_char_props_t    propsIn,
-                                     GattAttribute::Handle_t  declHandleIn,
-                                     GattAttribute::Handle_t  valueHandleIn)
-{
-    gattc       = gattcIn;
-    connHandle  = connectionHandleIn;
-    uuid        = uuidIn;
-    declHandle  = declHandleIn;
-    valueHandle = valueHandleIn;
-
-    props._broadcast       = propsIn.broadcast;
-    props._read            = propsIn.read;
-    props._writeWoResp     = propsIn.write_wo_resp;
-    props._write           = propsIn.write;
-    props._notify          = propsIn.notify;
-    props._indicate        = propsIn.indicate;
-    props._authSignedWrite = propsIn.auth_signed_wr;
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xDiscoveredCharacteristic.h
--- a/source/nRF5xDiscoveredCharacteristic.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF_DISCOVERED_CHARACTERISTIC_H__
-#define __NRF_DISCOVERED_CHARACTERISTIC_H__
-
-#include "ble/DiscoveredCharacteristic.h"
-#include "ble_gatt.h"
-
-class nRF5xGattClient; /* forward declaration */
-
-class nRF5xDiscoveredCharacteristic : public DiscoveredCharacteristic {
-public:
-    void setup(nRF5xGattClient         *gattcIn,
-               Gap::Handle_t            connectionHandleIn,
-               ble_gatt_char_props_t    propsIn,
-               GattAttribute::Handle_t  declHandleIn,
-               GattAttribute::Handle_t  valueHandleIn);
-
-    void setup(nRF5xGattClient         *gattcIn,
-               Gap::Handle_t            connectionHandleIn,
-               UUID::ShortUUIDBytes_t   uuidIn,
-               ble_gatt_char_props_t    propsIn,
-               GattAttribute::Handle_t  declHandleIn,
-               GattAttribute::Handle_t  valueHandleIn);
-
-    void setLastHandle(GattAttribute::Handle_t last) {
-      lastHandle = last;
-    }
-};
-
-#endif /* __NRF_DISCOVERED_CHARACTERISTIC_H__ */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGap.cpp
--- a/source/nRF5xGap.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,933 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xn.h"
-#ifdef YOTTA_CFG_MBED_OS
-    #include "mbed-drivers/mbed.h"
-#else
-    #include "mbed.h"
-#endif
-#include "ble/BLE.h"
-
-#include "common/common.h"
-#include "ble_advdata.h"
-#include "ble_hci.h"
-
-void radioNotificationStaticCallback(bool param) {
-    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
-    gap.processRadioNotificationEvent(param);
-}
-
-/**************************************************************************/
-/*!
-    @brief  Sets the advertising parameters and payload for the device
-
-    @param[in]  params
-                Basic advertising details, including the advertising
-                delay, timeout and how the device should be advertised
-    @params[in] advData
-                The primary advertising data payload
-    @params[in] scanResponse
-                The optional Scan Response payload if the advertising
-                type is set to \ref GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED
-                in \ref GapAdveritinngParams
-
-    @returns    \ref ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @retval     BLE_ERROR_BUFFER_OVERFLOW
-                The proposed action would cause a buffer overflow.  All
-                advertising payloads must be <= 31 bytes, for example.
-
-    @retval     BLE_ERROR_NOT_IMPLEMENTED
-                A feature was requested that is not yet supported in the
-                nRF51 firmware or hardware.
-
-    @retval     BLE_ERROR_PARAM_OUT_OF_RANGE
-                One of the proposed values is outside the valid range.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse)
-{
-    /* Make sure we don't exceed the advertising payload length */
-    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) {
-        return BLE_ERROR_BUFFER_OVERFLOW;
-    }
-
-    /* Make sure we have a payload! */
-    if (advData.getPayloadLen() == 0) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    /* Check the scan response payload limits */
-    //if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED))
-    //{
-    //    /* Check if we're within the upper limit */
-    //    if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD)
-    //    {
-    //        return BLE_ERROR_BUFFER_OVERFLOW;
-    //    }
-    //    /* Make sure we have a payload! */
-    //    if (advData.getPayloadLen() == 0)
-    //    {
-    //        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    //    }
-    //}
-
-    /* Send advertising data! */
-    ASSERT(ERROR_NONE ==
-           sd_ble_gap_adv_data_set(advData.getPayload(),
-                                   advData.getPayloadLen(),
-                                   scanResponse.getPayload(),
-                                   scanResponse.getPayloadLen()),
-           BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    /* Make sure the GAP Service appearance value is aligned with the
-     *appearance from GapAdvertisingData */
-    ASSERT(ERROR_NONE == sd_ble_gap_appearance_set(advData.getAppearance()),
-           BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    /* ToDo: Perform some checks on the payload, for example the Scan Response can't */
-    /* contains a flags AD type, etc. */
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Starts the BLE HW, initialising any services that were
-            added before this function was called.
-
-    @note   All services must be added before calling this function!
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams &params)
-{
-    /* Make sure we support the advertising type */
-    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) {
-        /* ToDo: This requires a propery security implementation, etc. */
-        return BLE_ERROR_NOT_IMPLEMENTED;
-    }
-
-    /* Check interval range */
-    if (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED) {
-        /* Min delay is slightly longer for unconnectable devices */
-        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) ||
-            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
-            return BLE_ERROR_PARAM_OUT_OF_RANGE;
-        }
-    } else {
-        if ((params.getIntervalInADVUnits() < GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MIN) ||
-            (params.getIntervalInADVUnits() > GapAdvertisingParams::GAP_ADV_PARAMS_INTERVAL_MAX)) {
-            return BLE_ERROR_PARAM_OUT_OF_RANGE;
-        }
-    }
-
-    /* Check timeout is zero for Connectable Directed */
-    if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) && (params.getTimeout() != 0)) {
-        /* Timeout must be 0 with this type, although we'll never get here */
-        /* since this isn't implemented yet anyway */
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    /* Check timeout for other advertising types */
-    if ((params.getAdvertisingType() != GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) &&
-        (params.getTimeout() > GapAdvertisingParams::GAP_ADV_PARAMS_TIMEOUT_MAX)) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    /* Allocate the stack's whitelist statically */
-    ble_gap_whitelist_t  whitelist;
-    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
-    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
-    /* Initialize the whitelist */
-    whitelist.pp_addrs   = whitelistAddressPtrs;
-    whitelist.pp_irks    = whitelistIrkPtrs;
-    whitelist.addr_count = 0;
-    whitelist.irk_count  = 0;
-
-    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
-    if (advertisingPolicyMode != Gap::ADV_POLICY_IGNORE_WHITELIST) {
-        ble_error_t error = generateStackWhitelist(whitelist);
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-
-    /* Start Advertising */
-    ble_gap_adv_params_t adv_para = {0};
-
-    adv_para.type        = params.getAdvertisingType();
-    adv_para.p_peer_addr = NULL;                           // Undirected advertisement
-    adv_para.fp          = advertisingPolicyMode;
-    adv_para.p_whitelist = &whitelist;
-    adv_para.interval    = params.getIntervalInADVUnits(); // advertising interval (in units of 0.625 ms)
-    adv_para.timeout     = params.getTimeout();
-
-    ASSERT(ERROR_NONE == sd_ble_gap_adv_start(&adv_para), BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    return BLE_ERROR_NONE;
-}
-
-/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-ble_error_t nRF5xGap::startRadioScan(const GapScanningParams &scanningParams)
-{
-    /* Allocate the stack's whitelist statically */
-    ble_gap_whitelist_t  whitelist;
-    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
-    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
-    /* Initialize the whitelist */
-    whitelist.pp_addrs   = whitelistAddressPtrs;
-    whitelist.pp_irks    = whitelistIrkPtrs;
-    whitelist.addr_count = 0;
-    whitelist.irk_count  = 0;
-
-    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
-    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
-        ble_error_t error = generateStackWhitelist(whitelist);
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-
-    ble_gap_scan_params_t scanParams = {
-        .active      = scanningParams.getActiveScanning(), /**< If 1, perform active scanning (scan requests). */
-        .selective   = scanningPolicyMode,    /**< If 1, ignore unknown devices (non whitelisted). */
-        .p_whitelist = &whitelist, /**< Pointer to whitelist, NULL if none is given. */
-        .interval    = scanningParams.getInterval(),  /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        .window      = scanningParams.getWindow(),    /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        .timeout     = scanningParams.getTimeout(),   /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
-    };
-
-    if (sd_ble_gap_scan_start(&scanParams) != NRF_SUCCESS) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::stopScan(void) {
-    if (sd_ble_gap_scan_stop() == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    }
-
-    return BLE_STACK_BUSY;
-}
-#endif
-
-/**************************************************************************/
-/*!
-    @brief  Stops the BLE HW and disconnects from any devices
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::stopAdvertising(void)
-{
-    /* Stop Advertising */
-    ASSERT(ERROR_NONE == sd_ble_gap_adv_stop(), BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    state.advertising = 0;
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::connect(const Address_t             peerAddr,
-                              BLEProtocol::AddressType_t  peerAddrType,
-                              const ConnectionParams_t   *connectionParams,
-                              const GapScanningParams    *scanParamsIn)
-{
-    ble_gap_addr_t addr;
-    addr.addr_type = peerAddrType;
-    memcpy(addr.addr, peerAddr, Gap::ADDR_LEN);
-
-    ble_gap_conn_params_t connParams;
-    if (connectionParams != NULL) {
-        connParams.min_conn_interval = connectionParams->minConnectionInterval;
-        connParams.max_conn_interval = connectionParams->maxConnectionInterval;
-        connParams.slave_latency     = connectionParams->slaveLatency;
-        connParams.conn_sup_timeout  = connectionParams->connectionSupervisionTimeout;
-    } else {
-        connParams.min_conn_interval = 50;
-        connParams.max_conn_interval = 100;
-        connParams.slave_latency     = 0;
-        connParams.conn_sup_timeout  = 600;
-    }
-
-    /* Allocate the stack's whitelist statically */
-    ble_gap_whitelist_t  whitelist;
-    ble_gap_addr_t      *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE];
-    ble_gap_irk_t       *whitelistIrkPtrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
-    /* Initialize the whitelist */
-    whitelist.pp_addrs   = whitelistAddressPtrs;
-    whitelist.pp_irks    = whitelistIrkPtrs;
-    whitelist.addr_count = 0;
-    whitelist.irk_count  = 0;
-
-    /* Add missing IRKs to whitelist from the bond table held by the SoftDevice */
-    if (scanningPolicyMode != Gap::SCAN_POLICY_IGNORE_WHITELIST) {
-        ble_error_t error = generateStackWhitelist(whitelist);
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-
-    ble_gap_scan_params_t scanParams;
-    scanParams.selective   = scanningPolicyMode;    /**< If 1, ignore unknown devices (non whitelisted). */
-    scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */
-    if (scanParamsIn != NULL) {
-        scanParams.active      = scanParamsIn->getActiveScanning();   /**< If 1, perform active scanning (scan requests). */
-        scanParams.interval    = scanParamsIn->getInterval();         /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        scanParams.window      = scanParamsIn->getWindow();           /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        scanParams.timeout     = scanParamsIn->getTimeout();          /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
-    } else {
-        scanParams.active      = _scanningParams.getActiveScanning(); /**< If 1, perform active scanning (scan requests). */
-        scanParams.interval    = _scanningParams.getInterval();       /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        scanParams.window      = _scanningParams.getWindow();         /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */
-        scanParams.timeout     = _scanningParams.getTimeout();        /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */
-    }
-
-    uint32_t rc = sd_ble_gap_connect(&addr, &scanParams, &connParams);
-    if (rc == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    }
-    switch (rc) {
-        case NRF_ERROR_INVALID_ADDR:
-            return BLE_ERROR_INVALID_PARAM;
-        case NRF_ERROR_INVALID_PARAM:
-            return BLE_ERROR_INVALID_PARAM;
-        case NRF_ERROR_INVALID_STATE:
-            return BLE_ERROR_INVALID_STATE;
-        case BLE_ERROR_GAP_INVALID_BLE_ADDR:
-            return BLE_ERROR_INVALID_PARAM;
-        case NRF_ERROR_NO_MEM:
-            return BLE_ERROR_NO_MEM;
-        case NRF_ERROR_BUSY:
-            return BLE_STACK_BUSY;
-        default:
-        case BLE_ERROR_GAP_WHITELIST_IN_USE:
-            return BLE_ERROR_UNSPECIFIED;
-    }
-}
-
-ble_error_t nRF5xGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason)
-{
-    uint8_t code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
-    switch (reason) {
-        case REMOTE_USER_TERMINATED_CONNECTION:
-            code = BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION;
-            break;
-        case CONN_INTERVAL_UNACCEPTABLE:
-            code = BLE_HCI_CONN_INTERVAL_UNACCEPTABLE;
-            break;
-        default:
-            break;
-    }
-
-    /* Disconnect if we are connected to a central device */
-    ASSERT_INT(ERROR_NONE, sd_ble_gap_disconnect(connectionHandle, code), BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    return BLE_ERROR_NONE;
-}
-
-/*!
-    @brief  Disconnects if we are connected to a central device
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-*/
-ble_error_t nRF5xGap::disconnect(DisconnectionReason_t reason)
-{
-    return disconnect(m_connectionHandle, reason);
-}
-
-ble_error_t nRF5xGap::getPreferredConnectionParams(ConnectionParams_t *params)
-{
-    ASSERT_INT(NRF_SUCCESS,
-        sd_ble_gap_ppcp_get(reinterpret_cast<ble_gap_conn_params_t *>(params)),
-        BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::setPreferredConnectionParams(const ConnectionParams_t *params)
-{
-    ASSERT_INT(NRF_SUCCESS,
-        sd_ble_gap_ppcp_set(reinterpret_cast<const ble_gap_conn_params_t *>(params)),
-        BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::updateConnectionParams(Handle_t handle, const ConnectionParams_t *newParams)
-{
-    uint32_t rc;
-
-    rc = sd_ble_gap_conn_param_update(handle, reinterpret_cast<ble_gap_conn_params_t *>(const_cast<ConnectionParams_t*>(newParams)));
-    if (rc == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-}
-
-/**************************************************************************/
-/*!
-    @brief  Clear nRF5xGap's state.
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::reset(void)
-{
-    /* Clear all state that is from the parent, including private members */
-    if (Gap::reset() != BLE_ERROR_NONE) {
-        return BLE_ERROR_INVALID_STATE;
-    }
-
-    /* Clear derived class members */
-    m_connectionHandle = BLE_CONN_HANDLE_INVALID;
-
-    /* Set the whitelist policy filter modes to IGNORE_WHITELIST */
-    advertisingPolicyMode = Gap::ADV_POLICY_IGNORE_WHITELIST;
-    scanningPolicyMode    = Gap::SCAN_POLICY_IGNORE_WHITELIST;
-
-    /* Clear the internal whitelist */
-    whitelistAddressesSize = 0;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Sets the 16-bit connection handle
-*/
-/**************************************************************************/
-void nRF5xGap::setConnectionHandle(uint16_t con_handle)
-{
-    m_connectionHandle = con_handle;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Gets the 16-bit connection handle
-*/
-/**************************************************************************/
-uint16_t nRF5xGap::getConnectionHandle(void)
-{
-    return m_connectionHandle;
-}
-
-/**************************************************************************/
-/*!
-    @brief      Sets the BLE device address
-
-    @returns    ble_error_t
-
-    @section EXAMPLE
-
-    @code
-
-    uint8_t device_address[6] = { 0xca, 0xfe, 0xf0, 0xf0, 0xf0, 0xf0 };
-    nrf.getGap().setAddress(Gap::BLEProtocol::AddressType::RANDOM_STATIC, device_address);
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address)
-{
-    uint8_t cycle_mode;
-    ble_gap_addr_t dev_addr;
-
-    /* When using Public or Static addresses, the cycle mode must be None.
-       When using Random Private addresses, the cycle mode must be Auto.
-       In auto mode, the given address is ignored.
-    */
-    if ((type == BLEProtocol::AddressType::PUBLIC) || (type == BLEProtocol::AddressType::RANDOM_STATIC))
-    {
-        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_NONE;
-        memcpy(dev_addr.addr, address, ADDR_LEN);
-    }
-    else if ((type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) || (type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE))
-    {
-        cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_AUTO;
-        // address is ignored when in auto mode
-    }
-    else
-    {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    dev_addr.addr_type = type;
-    ASSERT_INT(ERROR_NONE, sd_ble_gap_address_set(cycle_mode, &dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::getAddress(AddressType_t *typeP, Address_t address)
-{
-    ble_gap_addr_t dev_addr;
-    if (sd_ble_gap_address_get(&dev_addr) != NRF_SUCCESS) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    if (typeP != NULL) {
-        *typeP = static_cast<AddressType_t>(dev_addr.addr_type);
-    }
-    if (address != NULL) {
-        memcpy(address, dev_addr.addr, ADDR_LEN);
-    }
-    return BLE_ERROR_NONE;
-}
-
-ble_error_t nRF5xGap::setDeviceName(const uint8_t *deviceName)
-{
-    ble_gap_conn_sec_mode_t sec_mode;
-    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed
-
-    if (sd_ble_gap_device_name_set(&sec_mode, deviceName, strlen((const char *)deviceName)) == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-}
-
-ble_error_t nRF5xGap::getDeviceName(uint8_t *deviceName, unsigned *lengthP)
-{
-    if (sd_ble_gap_device_name_get(deviceName, (uint16_t *)lengthP) == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-}
-
-ble_error_t nRF5xGap::setAppearance(GapAdvertisingData::Appearance appearance)
-{
-    if (sd_ble_gap_appearance_set(appearance) == NRF_SUCCESS) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-}
-
-ble_error_t nRF5xGap::getAppearance(GapAdvertisingData::Appearance *appearanceP)
-{
-    if ((sd_ble_gap_appearance_get(reinterpret_cast<uint16_t *>(appearanceP)) == NRF_SUCCESS)) {
-        return BLE_ERROR_NONE;
-    } else {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-}
-
-/* (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
-ble_error_t nRF5xGap::setTxPower(int8_t txPower)
-{
-    unsigned rc;
-    if ((rc = sd_ble_gap_tx_power_set(txPower)) != NRF_SUCCESS) {
-        switch (rc) {
-            case NRF_ERROR_BUSY:
-                return BLE_STACK_BUSY;
-            case NRF_ERROR_INVALID_PARAM:
-            default:
-                return BLE_ERROR_PARAM_OUT_OF_RANGE;
-        }
-    }
-
-    return BLE_ERROR_NONE;
-}
-
-void nRF5xGap::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP)
-{
-    static const int8_t permittedTxValues[] = {
-        -40, -30, -20, -16, -12, -8, -4, 0, 4
-    };
-
-    *valueArrayPP = permittedTxValues;
-    *countP = sizeof(permittedTxValues) / sizeof(int8_t);
-}
-
-/**************************************************************************/
-/*!
-    @brief  Get the capacity of the internal whitelist maintained by this
-            implementation.
-
-    @returns    The capacity of the internal whitelist.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-uint8_t nRF5xGap::getMaxWhitelistSize(void) const
-{
-    return YOTTA_CFG_WHITELIST_MAX_SIZE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Get a copy of the implementation's internal whitelist.
-
-    @param[out] whitelistOut
-                A \ref Gap::Whitelist_t structure containing a copy of the
-                addresses in the implemenetation's internal whitelist.
-
-    @returns    \ref ble_errror_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::getWhitelist(Gap::Whitelist_t &whitelistOut) const
-{
-    uint8_t i;
-    for (i = 0; i < whitelistAddressesSize && i < whitelistOut.capacity; ++i) {
-        memcpy(&whitelistOut.addresses[i], &whitelistAddresses[i], sizeof(BLEProtocol::Address_t));
-    }
-    whitelistOut.size = i;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Set the whitelist that will be used in the next call to
-            startAdvertising().
-
-    @param[in]  whitelistIn
-                A reference to a \ref Gap::Whitelist_t structure
-                representing a whitelist containing all the white listed
-                BLE addresses.
-
-    @returns    \ref ble_errror_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly.
-
-                BLE_ERROR_INVALID_PARAM
-                The supplied whitelist contains a private non-resolvable
-                address
-
-                BLE_ERROR_PARAM_OUT_OF_RANGE
-                The size of the supplied whitelist exceeds the maximum
-                capacity of the implementation's internal whitelist.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setWhitelist(const Gap::Whitelist_t &whitelistIn)
-{
-    if (whitelistIn.size > getMaxWhitelistSize()) {
-        return BLE_ERROR_PARAM_OUT_OF_RANGE;
-    }
-
-    /* Test for invalid parameters before we change the internal state */
-    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
-        if (whitelistIn.addresses[i].type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE) {
-            /* This is not allowed because it is completely meaningless */
-            return BLE_ERROR_INVALID_PARAM;
-        }
-    }
-
-    whitelistAddressesSize = 0;
-    for (uint8_t i = 0; i < whitelistIn.size; ++i) {
-        memcpy(&whitelistAddresses[whitelistAddressesSize], &whitelistIn.addresses[i], sizeof(BLEProtocol::Address_t));
-        whitelistAddressesSize++;
-    }
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Set the advertising policy filter mode that will be used in
-            the next call to startAdvertising().
-
-    @returns    \ref ble_errror_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly.
-
-                BLE_ERROR_NOT_IMPLEMENTED
-                This feature is currently note implemented.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setAdvertisingPolicyMode(Gap::AdvertisingPolicyMode_t mode)
-{
-    advertisingPolicyMode = mode;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Set the scanning policy filter mode that will be used in
-            the next call to startAdvertising().
-
-    @returns    \ref ble_errror_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly.
-
-                BLE_ERROR_NOT_IMPLEMENTED
-                This feature is currently note implemented.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setScanningPolicyMode(Gap::ScanningPolicyMode_t mode)
-{
-    scanningPolicyMode = mode;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Set the initiator policy filter mode that will be used in
-            the next call to startAdvertising()
-
-    @returns    \ref ble_errror_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly.
-
-                BLE_ERROR_NOT_IMPLEMENTED
-                This feature is currently note implemented.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::setInitiatorPolicyMode(Gap::InitiatorPolicyMode_t mode)
-{
-    return BLE_ERROR_NOT_IMPLEMENTED;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Get the current advertising policy filter mode.
-
-    @returns    The advertising policy filter mode.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-Gap::AdvertisingPolicyMode_t nRF5xGap::getAdvertisingPolicyMode(void) const
-{
-    return advertisingPolicyMode;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Get the current scanning policy filter mode.
-
-    @returns    The scanning policy filter mode.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-Gap::ScanningPolicyMode_t nRF5xGap::getScanningPolicyMode(void) const
-{
-    return scanningPolicyMode;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Get the current initiator policy filter mode.
-
-    @returns    The initiator policy filter mode.
-
-    @note   Currently initiator filtering using the whitelist is not
-            implemented in this module.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-Gap::InitiatorPolicyMode_t nRF5xGap::getInitiatorPolicyMode(void) const
-{
-    return Gap::INIT_POLICY_IGNORE_WHITELIST;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Helper function used to populate the ble_gap_whitelist_t that
-            will be used by the SoftDevice for filtering requests.
-
-    @returns    \ref ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @retval     BLE_ERROR_INVALID_STATE
-                The internal stack was not initialized correctly.
-
-    @note  Both the SecurityManager and Gap must initialize correctly for
-           this function to succeed.
-
-    @note  This function is needed because for the BLE API the whitelist
-           is just a collection of keys, but for the stack it also includes
-           the IRK table.
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGap::generateStackWhitelist(ble_gap_whitelist_t &whitelist)
-{
-    ble_gap_whitelist_t  whitelistFromBondTable;
-    ble_gap_addr_t      *addressPtr[1];
-    ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
-
-    nRF5xSecurityManager& securityManager = (nRF5xSecurityManager&) nRF5xn::Instance(0).getSecurityManager();
-
-    if (securityManager.hasInitialized()) {
-        /* We do not care about the addresses, set the count to 0 */
-        whitelistFromBondTable.addr_count = 0;
-        /* The Nordic SDK will return a failure if we set pp_addr to NULL */
-        whitelistFromBondTable.pp_addrs   = addressPtr;
-        /* We want all the IRKs we can get because we do not know which ones match the addresses */
-        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
-        whitelistFromBondTable.pp_irks    = irkPtr;
-
-        /* Use the security manager to get the IRKs from the bond table */
-        ble_error_t error = securityManager.createWhitelistFromBondTable(whitelistFromBondTable);
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    } else  {
-        /**
-         * If there is no security manager then we cannot access the bond table,
-         * so disable IRK matching
-         */
-        whitelistFromBondTable.addr_count = 0;
-        whitelistFromBondTable.irk_count  = 0;
-    }
-
-    /**
-     * For every private resolvable address in the local whitelist check if
-     * there is an IRK for said address in the bond table and add it to the
-     * local IRK list.
-     */
-    whitelist.irk_count  = 0;
-    whitelist.addr_count = 0;
-    for (uint8_t i = 0; i < whitelistAddressesSize; ++i) {
-        if (whitelistAddresses[i].addr_type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) {
-            /* Test if there is a matching IRK for this private resolvable address */
-            for (uint8_t j = 0; j < whitelistFromBondTable.irk_count; ++j) {
-                if (securityManager.matchAddressAndIrk(&whitelistAddresses[i], whitelistFromBondTable.pp_irks[j])) {
-                    /* Found the corresponding IRK, add it to our local whitelist */
-                    whitelist.pp_irks[whitelist.irk_count] = whitelistFromBondTable.pp_irks[j];
-                    whitelist.irk_count++;
-                    /* Make sure we do not look at this IRK again */
-                    if (j != whitelistFromBondTable.irk_count - 1) {
-                        /**
-                         * This is not the last IRK, so replace the pointer
-                         * with the last pointer in the array
-                         */
-                        whitelistFromBondTable.pp_irks[j] =
-                            whitelistFromBondTable.pp_irks[whitelistFromBondTable.irk_count - 1];
-                    }
-                    /**
-                     * If the IRK is the last pointer in the array simply
-                     * decrement the total IRK count
-                     */
-                    whitelistFromBondTable.irk_count--;
-                    break;
-                }
-            }
-        } else {
-            /* Include the address into the whitelist */
-            whitelist.pp_addrs[whitelist.addr_count] = &whitelistAddresses[i];
-            whitelist.addr_count++;
-        }
-    }
-
-    return BLE_ERROR_NONE;
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGap.h
--- a/source/nRF5xGap.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,246 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF5x_GAP_H__
-#define __NRF5x_GAP_H__
-
-#ifdef YOTTA_CFG_MBED_OS
-    #include "mbed-drivers/mbed.h"
-#else
-    #include "mbed.h"
-#endif
-#ifndef YOTTA_CFG_WHITELIST_MAX_SIZE
-    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
-#elif YOTTA_CFG_WHITELIST_MAX_SIZE > BLE_GAP_WHITELIST_ADDR_MAX_COUNT
-    #undef YOTTA_CFG_WHITELIST_MAX_SIZE
-    #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT
-#endif
-#ifndef YOTTA_CFG_IRK_TABLE_MAX_SIZE
-    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
-#elif YOTTA_CFG_IRK_TABLE_MAX_SIZE > BLE_GAP_WHITELIST_IRK_MAX_COUNT
-    #undef YOTTA_CFG_IRK_TABLE_MAX_SIZE
-    #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT
-#endif
-#include "ble/blecommon.h"
-#include "nrf_ble.h"
-#include "ble/GapAdvertisingParams.h"
-#include "ble/GapAdvertisingData.h"
-#include "ble/Gap.h"
-#include "ble/GapScanningParams.h"
-
-#include "nrf_soc.h"
-
-extern "C" {
-#include "ble_radio_notification.h"
-}
-
-#include "btle_security.h"
-
-void radioNotificationStaticCallback(bool param);
-
-/**************************************************************************/
-/*!
-    \brief
-
-*/
-/**************************************************************************/
-class nRF5xGap : public Gap
-{
-public:
-    /* Functions that must be implemented from Gap */
-    virtual ble_error_t setAddress(AddressType_t  type,  const Address_t address);
-    virtual ble_error_t getAddress(AddressType_t *typeP, Address_t address);
-    virtual ble_error_t setAdvertisingData(const GapAdvertisingData &, const GapAdvertisingData &);
-
-    virtual uint16_t    getMinAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MIN);}
-    virtual uint16_t    getMinNonConnectableAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_NONCON_INTERVAL_MIN);}
-    virtual uint16_t    getMaxAdvertisingInterval(void) const {return GapAdvertisingParams::ADVERTISEMENT_DURATION_UNITS_TO_MS(BLE_GAP_ADV_INTERVAL_MAX);}
-
-    virtual ble_error_t startAdvertising(const GapAdvertisingParams &);
-    virtual ble_error_t stopAdvertising(void);
-    virtual ble_error_t connect(const Address_t, BLEProtocol::AddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams);
-    virtual ble_error_t disconnect(Handle_t connectionHandle, DisconnectionReason_t reason);
-    virtual ble_error_t disconnect(DisconnectionReason_t reason);
-
-    virtual ble_error_t setDeviceName(const uint8_t *deviceName);
-    virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP);
-    virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance);
-    virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP);
-
-    virtual ble_error_t setTxPower(int8_t txPower);
-    virtual void        getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP);
-
-    void     setConnectionHandle(uint16_t con_handle);
-    uint16_t getConnectionHandle(void);
-
-    virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params);
-    virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params);
-    virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params);
-
-    virtual ble_error_t reset(void);
-
-    /*
-     * The following functions are part of the whitelisting experimental API.
-     * Therefore, this functionality can change in the near future.
-     */
-    virtual uint8_t getMaxWhitelistSize(void) const;
-    virtual ble_error_t getWhitelist(Gap::Whitelist_t &whitelistOut) const;
-    virtual ble_error_t setWhitelist(const Gap::Whitelist_t &whitelistIn);
-
-    virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode);
-    virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode);
-    virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode);
-    virtual Gap::AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const;
-    virtual Gap::ScanningPolicyMode_t getScanningPolicyMode(void) const;
-    virtual Gap::InitiatorPolicyMode_t getInitiatorPolicyMode(void) const;
-
-    virtual ble_error_t initRadioNotification(void) {
-        if (ble_radio_notification_init(NRF_APP_PRIORITY_HIGH, NRF_RADIO_NOTIFICATION_DISTANCE_800US, radioNotificationStaticCallback) == NRF_SUCCESS) {
-            return BLE_ERROR_NONE;
-        }
-
-        return BLE_ERROR_UNSPECIFIED;
-    }
-
-/* Observer role is not supported by S110, return BLE_ERROR_NOT_IMPLEMENTED */
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-    virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams);
-    virtual ble_error_t stopScan(void);
-#endif
-
-private:
-    /*
-     * Whitelisting API related structures and helper functions.
-     */
-
-    /* Policy modes set by the user. By default these are set to ignore the whitelist */
-    Gap::AdvertisingPolicyMode_t advertisingPolicyMode;
-    Gap::ScanningPolicyMode_t    scanningPolicyMode;
-
-    /* Internal representation of a whitelist */
-    uint8_t         whitelistAddressesSize;
-    ble_gap_addr_t  whitelistAddresses[YOTTA_CFG_WHITELIST_MAX_SIZE];
-
-    /*
-     * An internal function used to populate the ble_gap_whitelist_t that will be used by
-     * the SoftDevice for filtering requests. This function is needed because for the BLE
-     * API the whitelist is just a collection of keys, but for the stack it also includes
-     * the IRK table.
-     */
-    ble_error_t generateStackWhitelist(ble_gap_whitelist_t &whitelist);
-
-private:
-    bool    radioNotificationCallbackParam; /* parameter to be passed into the Timeout-generated radio notification callback. */
-    Timeout radioNotificationTimeout;
-
-    /*
-     * A helper function to post radio notification callbacks with low interrupt priority.
-     */
-    void postRadioNotificationCallback(void) {
-#ifdef YOTTA_CFG_MBED_OS
-        /*
-         * In mbed OS, all user-facing BLE events (interrupts) are posted to the
-         * MINAR scheduler to be executed as callbacks in thread mode. MINAR guards
-         * its critical sections from interrupts by acquiring CriticalSectionLock,
-         * which results in a call to sd_nvic_critical_region_enter(). Thus, it is
-         * safe to invoke MINAR APIs from interrupt context as long as those
-         * interrupts are blocked by sd_nvic_critical_region_enter().
-         *
-         * Radio notifications are a special case for the above. The Radio
-         * Notification IRQ is handled at a very high priority--higher than the
-         * level blocked by sd_nvic_critical_region_enter(). Thus Radio Notification
-         * events can preempt MINAR's critical sections. Using MINAR APIs (such as
-         * posting an event) directly in processRadioNotification() may result in a
-         * race condition ending in a hard-fault.
-         *
-         * The solution is to *not* call MINAR APIs directly from the Radio
-         * Notification handling; i.e. to do the bulk of RadioNotification
-         * processing at a reduced priority which respects MINAR's critical
-         * sections. Unfortunately, on a cortex-M0, there is no clean way to demote
-         * priority for the currently executing interrupt--we wouldn't want to
-         * demote the radio notification handling anyway because it is sensitive to
-         * timing, and the system expects to finish this handling very quickly. The
-         * workaround is to employ a Timeout to trigger
-         * postRadioNotificationCallback() after a very short delay (~0 us) and post
-         * the MINAR callback that context.
-         *
-         * !!!WARNING!!! Radio notifications are very time critical events. The
-         * current solution is expected to work under the assumption that
-         * postRadioNotificationCalback() will be executed BEFORE the next radio
-         * notification event is generated.
-         */
-        minar::Scheduler::postCallback(
-            mbed::util::FunctionPointer1<void, bool>(&radioNotificationCallback, &FunctionPointerWithContext<bool>::call).bind(radioNotificationCallbackParam)
-        );
-#else
-        /*
-         * In mbed classic, all user-facing BLE events execute callbacks in interrupt
-         * mode. Radio Notifications are a special case because its IRQ is handled at
-         * a very high priority. Thus Radio Notification events can preempt other
-         * operations that require interaction with the SoftDevice such as advertising
-         * payload updates and changing the Gap state. Therefore, executing a Radio
-         * Notification callback directly from processRadioNotification() may result
-         * in a race condition ending in a hard-fault.
-         *
-         * The solution is to *not* execute the Radio Notification callback directly
-         * from the Radio Notification handling; i.e. to do the bulk of the
-         * Radio Notification processing at a reduced priority. Unfortunately, on a
-         * cortex-M0, there is no clean way to demote priority for the currently
-         * executing interrupt--we wouldn't want to demote the radio notification
-         * handling anyway because it is sensitive to timing, and the system expects
-         * to finish this handling very quickly. The workaround is to employ a Timeout
-         * to trigger postRadioNotificationCallback() after a very short delay (~0 us)
-         * and execute the callback in that context.
-         *
-         * !!!WARNING!!! Radio notifications are very time critical events. The
-         * current solution is expected to work under the assumption that
-         * postRadioNotificationCalback() will be executed BEFORE the next radio
-         * notification event is generated.
-         */
-        radioNotificationCallback.call(radioNotificationCallbackParam);
-#endif /* #ifdef YOTTA_CFG_MBED_OS */
-    }
-
-    /**
-     * A helper function to process radio-notification events; to be called internally.
-     * @param param [description]
-     */
-    void processRadioNotificationEvent(bool param) {
-        radioNotificationCallbackParam = param;
-        radioNotificationTimeout.attach_us(this, &nRF5xGap::postRadioNotificationCallback, 0);
-    }
-    friend void radioNotificationStaticCallback(bool param); /* allow invocations of processRadioNotificationEvent() */
-
-private:
-    uint16_t m_connectionHandle;
-
-    /*
-     * Allow instantiation from nRF5xn when required.
-     */
-    friend class nRF5xn;
-
-    nRF5xGap() :
-        advertisingPolicyMode(Gap::ADV_POLICY_IGNORE_WHITELIST),
-        scanningPolicyMode(Gap::SCAN_POLICY_IGNORE_WHITELIST),
-        whitelistAddressesSize(0) {
-        m_connectionHandle = BLE_CONN_HANDLE_INVALID;
-    }
-
-    nRF5xGap(nRF5xGap const &);
-    void operator=(nRF5xGap const &);
-};
-
-#endif // ifndef __NRF5x_GAP_H__
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGattClient.cpp
--- a/source/nRF5xGattClient.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xGattClient.h"
-
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-ble_error_t
-nRF5xGattClient::launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
-                                        ServiceDiscovery::ServiceCallback_t         sc,
-                                        ServiceDiscovery::CharacteristicCallback_t  cc,
-                                        const UUID                                 &matchingServiceUUIDIn,
-                                        const UUID                                 &matchingCharacteristicUUIDIn)
-{
-    return _discovery.launch(connectionHandle, sc, cc, matchingServiceUUIDIn, matchingCharacteristicUUIDIn);
-}
-
-ble_error_t nRF5xGattClient::discoverCharacteristicDescriptors(
-    const DiscoveredCharacteristic& characteristic,
-    const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
-    const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback)
-{
-    return _characteristicDescriptorDiscoverer.launch(
-        characteristic, 
-        discoveryCallback, 
-        terminationCallback
-    );
-}
-
-bool nRF5xGattClient::isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const {
-    return _characteristicDescriptorDiscoverer.isActive(characteristic);   
-}
-
-void nRF5xGattClient::terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic) { 
-    return _characteristicDescriptorDiscoverer.requestTerminate(characteristic);
-}
-
-#endif
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGattClient.h
--- a/source/nRF5xGattClient.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,218 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF51822_GATT_CLIENT_H__
-#define __NRF51822_GATT_CLIENT_H__
-
-#include "ble/GattClient.h"
-#include "nRF5xServiceDiscovery.h"
-#include "nRF5xCharacteristicDescriptorDiscoverer.h"
-
-class nRF5xGattClient : public GattClient
-{
-public:
-    /**
-     * When using S110, all Gatt client features will return
-     * BLE_ERROR_NOT_IMPLEMENTED
-     */
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-
-    /**
-     * Launch service discovery. Once launched, service discovery will remain
-     * active with callbacks being issued back into the application for matching
-     * services/characteristics. isActive() can be used to determine status; and
-     * a termination callback (if setup) will be invoked at the end. Service
-     * discovery can be terminated prematurely if needed using terminate().
-     *
-     * @param  connectionHandle
-     *           Handle for the connection with the peer.
-     * @param  sc
-     *           This is the application callback for matching service. Taken as
-     *           NULL by default. Note: service discovery may still be active
-     *           when this callback is issued; calling asynchronous BLE-stack
-     *           APIs from within this application callback might cause the
-     *           stack to abort service discovery. If this becomes an issue, it
-     *           may be better to make local copy of the discoveredService and
-     *           wait for service discovery to terminate before operating on the
-     *           service.
-     * @param  cc
-     *           This is the application callback for matching characteristic.
-     *           Taken as NULL by default. Note: service discovery may still be
-     *           active when this callback is issued; calling asynchronous
-     *           BLE-stack APIs from within this application callback might cause
-     *           the stack to abort service discovery. If this becomes an issue,
-     *           it may be better to make local copy of the discoveredCharacteristic
-     *           and wait for service discovery to terminate before operating on the
-     *           characteristic.
-     * @param  matchingServiceUUID
-     *           UUID based filter for specifying a service in which the application is
-     *           interested. By default it is set as the wildcard UUID_UNKNOWN,
-     *           in which case it matches all services. If characteristic-UUID
-     *           filter (below) is set to the wildcard value, then a service
-     *           callback will be invoked for the matching service (or for every
-     *           service if the service filter is a wildcard).
-     * @param  matchingCharacteristicUUIDIn
-     *           UUID based filter for specifying characteristic in which the application
-     *           is interested. By default it is set as the wildcard UUID_UKNOWN
-     *           to match against any characteristic. If both service-UUID
-     *           filter and characteristic-UUID filter are used with non- wildcard
-     *           values, then only a single characteristic callback is
-     *           invoked for the matching characteristic.
-     *
-     * @Note     Using wildcard values for both service-UUID and characteristic-
-     *           UUID will result in complete service discovery--callbacks being
-     *           called for every service and characteristic.
-     *
-     * @return
-     *           BLE_ERROR_NONE if service discovery is launched successfully; else an appropriate error.
-     */
-    virtual ble_error_t launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
-                                               ServiceDiscovery::ServiceCallback_t         sc = NULL,
-                                               ServiceDiscovery::CharacteristicCallback_t  cc = NULL,
-                                               const UUID                                 &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN),
-                                               const UUID                                 &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN));
-
-    virtual void onServiceDiscoveryTermination(ServiceDiscovery::TerminationCallback_t callback) {
-        _discovery.onTermination(callback);
-    }
-
-    /**
-     * Is service-discovery currently active?
-     */
-    virtual bool isServiceDiscoveryActive(void) const {
-        return _discovery.isActive();
-    }
-
-    /**
-     * Terminate an ongoing service-discovery. This should result in an
-     * invocation of the TerminationCallback if service-discovery is active.
-     */
-    virtual void terminateServiceDiscovery(void) {
-        _discovery.terminate();
-    }
-
-    /**
-     * @brief Implementation of GattClient::discoverCharacteristicDescriptors
-     * @see GattClient::discoverCharacteristicDescriptors
-     */
-    virtual ble_error_t discoverCharacteristicDescriptors(
-        const DiscoveredCharacteristic& characteristic,
-        const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback,
-        const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback
-    );
-
-    /**
-     * @brief Implementation of GattClient::isCharacteristicDiscoveryActive
-     * @see GattClient::isCharacteristicDiscoveryActive
-     */
-    virtual bool isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const;
-
-    /**
-     * @brief Implementation of GattClient::terminateCharacteristicDiscovery
-     * @see GattClient::terminateCharacteristicDiscovery
-     */
-    virtual void terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic);
-
-    virtual ble_error_t read(Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset) const {
-        uint32_t rc = sd_ble_gattc_read(connHandle, attributeHandle, offset);
-        if (rc == NRF_SUCCESS) {
-            return BLE_ERROR_NONE;
-        }
-        switch (rc) {
-            case NRF_ERROR_BUSY:
-                return BLE_STACK_BUSY;
-            case BLE_ERROR_INVALID_CONN_HANDLE:
-            case NRF_ERROR_INVALID_STATE:
-            case NRF_ERROR_INVALID_ADDR:
-            default:
-                return BLE_ERROR_INVALID_STATE;
-        }
-    }
-
-    virtual ble_error_t write(GattClient::WriteOp_t cmd, Gap::Handle_t connHandle, GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value) const {
-        ble_gattc_write_params_t writeParams;
-        writeParams.write_op = cmd;
-        writeParams.flags    = 0; /* this is inconsequential */
-        writeParams.handle   = attributeHandle;
-        writeParams.offset   = 0;
-        writeParams.len      = length;
-        writeParams.p_value  = const_cast<uint8_t *>(value);
-
-        uint32_t rc = sd_ble_gattc_write(connHandle, &writeParams);
-        if (rc == NRF_SUCCESS) {
-            return BLE_ERROR_NONE;
-        }
-        switch (rc) {
-            case NRF_ERROR_BUSY:
-                return BLE_STACK_BUSY;
-            case BLE_ERROR_NO_TX_BUFFERS:
-                return BLE_ERROR_NO_MEM;
-            case BLE_ERROR_INVALID_CONN_HANDLE:
-            case NRF_ERROR_INVALID_STATE:
-            case NRF_ERROR_INVALID_ADDR:
-            default:
-                return BLE_ERROR_INVALID_STATE;
-        }
-    }
-
-    /**
-     * @brief  Clear nRF5xGattClient's state.
-     *
-     * @return
-     *           BLE_ERROR_NONE if successful.
-     */
-    virtual ble_error_t reset(void) {
-        /* Clear all state that is from the parent, including private members */
-        if (GattClient::reset() != BLE_ERROR_NONE) {
-            return BLE_ERROR_INVALID_STATE;
-        }
-
-        /* Clear derived class members */
-        _discovery.reset();
-
-        return BLE_ERROR_NONE;
-    }
-
-public:
-    /*
-     * Allow instantiation from nRF5xn when required.
-     */
-    friend class nRF5xn;
-
-    nRF5xGattClient() : _discovery(this) {
-        /* empty */
-    }
-
-    nRF5xServiceDiscovery& discovery() {
-        return _discovery;
-    }
-
-    nRF5xCharacteristicDescriptorDiscoverer& characteristicDescriptorDiscoverer() {
-        return _characteristicDescriptorDiscoverer;
-    }
-
-private:
-    nRF5xGattClient(const nRF5xGattClient &);
-    const nRF5xGattClient& operator=(const nRF5xGattClient &);
-
-private:
-    nRF5xServiceDiscovery _discovery;
-    nRF5xCharacteristicDescriptorDiscoverer _characteristicDescriptorDiscoverer;
-
-#endif // if !S110
-};
-
-#endif // ifndef __NRF51822_GATT_CLIENT_H__
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGattServer.cpp
--- a/source/nRF5xGattServer.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,532 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xGattServer.h"
-#ifdef YOTTA_CFG_MBED_OS
-    #include "mbed-drivers/mbed.h"
-#else
-    #include "mbed.h"
-#endif
-
-#include "common/common.h"
-#include "btle/custom/custom_helper.h"
-
-#include "nRF5xn.h"
-
-/**************************************************************************/
-/*!
-    @brief  Adds a new service to the GATT table on the peripheral
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @section EXAMPLE
-
-    @code
-
-    @endcode
-*/
-/**************************************************************************/
-ble_error_t nRF5xGattServer::addService(GattService &service)
-{
-    /* ToDo: Make sure this service UUID doesn't already exist (?) */
-    /* ToDo: Basic validation */
-
-    /* Add the service to the nRF51 */
-    ble_uuid_t nordicUUID;
-    nordicUUID = custom_convert_to_nordic_uuid(service.getUUID());
-
-    uint16_t serviceHandle;
-    ASSERT( ERROR_NONE ==
-            sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
-                                     &nordicUUID,
-                                     &serviceHandle),
-            BLE_ERROR_PARAM_OUT_OF_RANGE );
-    service.setHandle(serviceHandle);
-
-    /* Add characteristics to the service */
-    for (uint8_t i = 0; i < service.getCharacteristicCount(); i++) {
-        if (characteristicCount >= BLE_TOTAL_CHARACTERISTICS) {
-            return BLE_ERROR_NO_MEM;
-        }
-        GattCharacteristic *p_char = service.getCharacteristic(i);
-
-        /* Skip any incompletely defined, read-only characteristics. */
-        if ((p_char->getValueAttribute().getValuePtr() == NULL) &&
-            (p_char->getValueAttribute().getLength() == 0) &&
-            (p_char->getProperties() == GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ)) {
-            continue;
-        }
-
-        nordicUUID = custom_convert_to_nordic_uuid(p_char->getValueAttribute().getUUID());
-
-        /* The user-description descriptor is a special case which needs to be
-         * handled at the time of adding the characteristic. The following block
-         * is meant to discover its presence. */
-        const uint8_t *userDescriptionDescriptorValuePtr = NULL;
-        uint16_t userDescriptionDescriptorValueLen = 0;
-        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
-            GattAttribute *p_desc = p_char->getDescriptor(j);
-            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
-                userDescriptionDescriptorValuePtr = p_desc->getValuePtr();
-                userDescriptionDescriptorValueLen = p_desc->getLength();
-            }
-        }
-
-        ASSERT ( ERROR_NONE ==
-                 custom_add_in_characteristic(BLE_GATT_HANDLE_INVALID,
-                                              &nordicUUID,
-                                              p_char->getProperties(),
-                                              p_char->getRequiredSecurity(),
-                                              p_char->getValueAttribute().getValuePtr(),
-                                              p_char->getValueAttribute().getLength(),
-                                              p_char->getValueAttribute().getMaxLength(),
-                                              p_char->getValueAttribute().hasVariableLength(),
-                                              userDescriptionDescriptorValuePtr,
-                                              userDescriptionDescriptorValueLen,
-                                              p_char->isReadAuthorizationEnabled(),
-                                              p_char->isWriteAuthorizationEnabled(),
-                                              &nrfCharacteristicHandles[characteristicCount]),
-                 BLE_ERROR_PARAM_OUT_OF_RANGE );
-
-        /* Update the characteristic handle */
-        p_characteristics[characteristicCount] = p_char;
-        p_char->getValueAttribute().setHandle(nrfCharacteristicHandles[characteristicCount].value_handle);
-        characteristicCount++;
-
-        /* Add optional descriptors if any */
-        for (uint8_t j = 0; j < p_char->getDescriptorCount(); j++) {
-            if (descriptorCount >= BLE_TOTAL_DESCRIPTORS) {
-                return BLE_ERROR_NO_MEM;
-            }
-
-            GattAttribute *p_desc = p_char->getDescriptor(j);
-            /* skip the user-description-descriptor here; this has already been handled when adding the characteristic (above). */
-            if (p_desc->getUUID() == BLE_UUID_DESCRIPTOR_CHAR_USER_DESC) {
-                continue;
-            }
-
-            nordicUUID = custom_convert_to_nordic_uuid(p_desc->getUUID());
-
-            ASSERT(ERROR_NONE ==
-                   custom_add_in_descriptor(BLE_GATT_HANDLE_INVALID,
-                                            &nordicUUID,
-                                            p_desc->getValuePtr(),
-                                            p_desc->getLength(),
-                                            p_desc->getMaxLength(),
-                                            p_desc->hasVariableLength(),
-                                            &nrfDescriptorHandles[descriptorCount]),
-                BLE_ERROR_PARAM_OUT_OF_RANGE);
-
-            p_descriptors[descriptorCount] = p_desc;
-            p_desc->setHandle(nrfDescriptorHandles[descriptorCount]);
-            descriptorCount++;
-        }
-    }
-
-    serviceCount++;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Reads the value of a characteristic, based on the service
-            and characteristic index fields
-
-    @param[in]  attributeHandle
-                The handle of the GattCharacteristic to read from
-    @param[in]  buffer
-                Buffer to hold the the characteristic's value
-                (raw byte array in LSB format)
-    @param[in/out] len
-                input:  Length in bytes to be read.
-                output: Total length of attribute value upon successful return.
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-*/
-/**************************************************************************/
-ble_error_t nRF5xGattServer::read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
-{
-    return read(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, lengthP);
-}
-
-ble_error_t nRF5xGattServer::read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP)
-{
-    ble_gatts_value_t value = {
-        .len     = *lengthP,
-        .offset  = 0,
-        .p_value = buffer,
-    };
-
-    ASSERT( ERROR_NONE ==
-            sd_ble_gatts_value_get(connectionHandle, attributeHandle, &value),
-            BLE_ERROR_PARAM_OUT_OF_RANGE);
-    *lengthP = value.len;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Updates the value of a characteristic, based on the service
-            and characteristic index fields
-
-    @param[in]  charHandle
-                The handle of the GattCharacteristic to write to
-    @param[in]  buffer
-                Data to use when updating the characteristic's value
-                (raw byte array in LSB format)
-    @param[in]  len
-                The number of bytes in buffer
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-*/
-/**************************************************************************/
-ble_error_t nRF5xGattServer::write(GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
-{
-    return write(BLE_CONN_HANDLE_INVALID, attributeHandle, buffer, len, localOnly);
-}
-
-ble_error_t nRF5xGattServer::write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t buffer[], uint16_t len, bool localOnly)
-{
-    ble_error_t returnValue = BLE_ERROR_NONE;
-
-    ble_gatts_value_t value = {
-        .len     = len,
-        .offset  = 0,
-        .p_value = const_cast<uint8_t *>(buffer),
-    };
-
-    if (localOnly) {
-        /* Only update locally regardless of notify/indicate */
-        ASSERT_INT( ERROR_NONE,
-                    sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
-                    BLE_ERROR_PARAM_OUT_OF_RANGE );
-        return BLE_ERROR_NONE;
-    }
-
-    int characteristicIndex = resolveValueHandleToCharIndex(attributeHandle);
-    if ((characteristicIndex != -1) &&
-        (p_characteristics[characteristicIndex]->getProperties() & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
-        /* HVX update for the characteristic value */
-        ble_gatts_hvx_params_t hvx_params;
-
-        hvx_params.handle = attributeHandle;
-        hvx_params.type   =
-            (p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) ? BLE_GATT_HVX_NOTIFICATION : BLE_GATT_HVX_INDICATION;
-        hvx_params.offset = 0;
-        hvx_params.p_data = const_cast<uint8_t *>(buffer);
-        hvx_params.p_len  = &len;
-
-        if (connectionHandle == BLE_CONN_HANDLE_INVALID) { /* use the default connection handle if the caller hasn't specified a valid connectionHandle. */
-            nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
-            connectionHandle = gap.getConnectionHandle();
-        }
-        error_t error = (error_t) sd_ble_gatts_hvx(connectionHandle, &hvx_params);
-        if (error != ERROR_NONE) {
-            switch (error) {
-                case ERROR_BLE_NO_TX_BUFFERS: /*  Notifications consume application buffers. The return value can be used for resending notifications. */
-                case ERROR_BUSY:
-                    returnValue = BLE_STACK_BUSY;
-                    break;
-
-                case ERROR_INVALID_STATE:
-                case ERROR_BLEGATTS_SYS_ATTR_MISSING:
-                    returnValue = BLE_ERROR_INVALID_STATE;
-                    break;
-
-                default :
-                    ASSERT_INT( ERROR_NONE,
-                                sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value),
-                                BLE_ERROR_PARAM_OUT_OF_RANGE );
-
-                    /* Notifications consume application buffers. The return value can
-                     * be used for resending notifications. */
-                    returnValue = BLE_STACK_BUSY;
-                    break;
-            }
-        }
-    } else {
-        uint32_t err = sd_ble_gatts_value_set(connectionHandle, attributeHandle, &value);
-        switch(err) {
-            case NRF_SUCCESS:
-                returnValue = BLE_ERROR_NONE;
-                break;
-            case NRF_ERROR_INVALID_ADDR:
-            case NRF_ERROR_INVALID_PARAM:
-                returnValue = BLE_ERROR_INVALID_PARAM;
-                break;
-            case NRF_ERROR_NOT_FOUND:
-            case NRF_ERROR_DATA_SIZE:
-            case BLE_ERROR_INVALID_CONN_HANDLE:
-            case BLE_ERROR_GATTS_INVALID_ATTR_TYPE:
-                returnValue = BLE_ERROR_PARAM_OUT_OF_RANGE;
-                break;
-            case NRF_ERROR_FORBIDDEN:
-                returnValue = BLE_ERROR_OPERATION_NOT_PERMITTED;
-                break;
-            default:
-                returnValue = BLE_ERROR_UNSPECIFIED;
-                break;
-        }
-    }
-
-    return returnValue;
-}
-
-ble_error_t nRF5xGattServer::areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP)
-{
-    /* Forward the call with the default connection handle. */
-    nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap();
-    return areUpdatesEnabled(gap.getConnectionHandle(), characteristic, enabledP);
-}
-
-ble_error_t nRF5xGattServer::areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP)
-{
-    int characteristicIndex = resolveValueHandleToCharIndex(characteristic.getValueHandle());
-    if (characteristicIndex == -1) {
-        return BLE_ERROR_INVALID_PARAM;
-    }
-
-    /* Read the cccd value from the GATT server. */
-    GattAttribute::Handle_t cccdHandle = nrfCharacteristicHandles[characteristicIndex].cccd_handle;
-    uint16_t cccdValue;
-    uint16_t length = sizeof(cccdValue);
-    ble_error_t rc = read(connectionHandle, cccdHandle, reinterpret_cast<uint8_t *>(&cccdValue), &length);
-    if (rc != BLE_ERROR_NONE) {
-        return rc;
-    }
-    if (length != sizeof(cccdValue)) {
-        return BLE_ERROR_INVALID_STATE;
-    }
-
-    /* Check for NOTFICATION or INDICATION in CCCD. */
-    if ((cccdValue & BLE_GATT_HVX_NOTIFICATION) || (cccdValue & BLE_GATT_HVX_INDICATION)) {
-        *enabledP = true;
-    }
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Clear nRF5xGattServer's state.
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-*/
-/**************************************************************************/
-ble_error_t nRF5xGattServer::reset(void)
-{
-    /* Clear all state that is from the parent, including private members */
-    if (GattServer::reset() != BLE_ERROR_NONE) {
-        return BLE_ERROR_INVALID_STATE;
-    }
-
-    /* Clear derived class members */
-    memset(p_characteristics,        0, sizeof(p_characteristics));
-    memset(p_descriptors,            0, sizeof(p_descriptors));
-    memset(nrfCharacteristicHandles, 0, sizeof(ble_gatts_char_handles_t));
-    memset(nrfDescriptorHandles,     0, sizeof(nrfDescriptorHandles));
-    descriptorCount = 0;
-
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Callback handler for events getting pushed up from the SD
-*/
-/**************************************************************************/
-void nRF5xGattServer::hwCallback(ble_evt_t *p_ble_evt)
-{
-    GattAttribute::Handle_t        handle_value;
-    GattServerEvents::gattEvent_t  eventType;
-    const ble_gatts_evt_t         *gattsEventP = &p_ble_evt->evt.gatts_evt;
-
-    switch (p_ble_evt->header.evt_id) {
-        case BLE_GATTS_EVT_WRITE: {
-                /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */
-
-                /* 1.) Handle CCCD changes */
-                handle_value = gattsEventP->params.write.handle;
-                int characteristicIndex = resolveCCCDHandleToCharIndex(handle_value);
-                if ((characteristicIndex != -1) &&
-                    (p_characteristics[characteristicIndex]->getProperties() &
-                        (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY))) {
-
-                    uint16_t cccd_value = (gattsEventP->params.write.data[1] << 8) | gattsEventP->params.write.data[0]; /* Little Endian but M0 may be mis-aligned */
-
-                    if (((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION)) ||
-                        ((p_characteristics[characteristicIndex]->getProperties() & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) {
-                        eventType = GattServerEvents::GATT_EVENT_UPDATES_ENABLED;
-                    } else {
-                        eventType = GattServerEvents::GATT_EVENT_UPDATES_DISABLED;
-                    }
-
-                    handleEvent(eventType, p_characteristics[characteristicIndex]->getValueHandle());
-                    return;
-                }
-
-                /* 2.) Changes to the characteristic value will be handled with other events below */
-                eventType = GattServerEvents::GATT_EVENT_DATA_WRITTEN;
-            }
-            break;
-
-        case BLE_GATTS_EVT_HVC:
-            /* Indication confirmation received */
-            eventType    = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED;
-            handle_value = gattsEventP->params.hvc.handle;
-            break;
-
-        case BLE_EVT_TX_COMPLETE: {
-            handleDataSentEvent(p_ble_evt->evt.common_evt.params.tx_complete.count);
-            return;
-        }
-
-        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
-            sd_ble_gatts_sys_attr_set(gattsEventP->conn_handle, NULL, 0, 0);
-            return;
-
-        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
-            switch (gattsEventP->params.authorize_request.type) {
-                case BLE_GATTS_AUTHORIZE_TYPE_READ:
-                    eventType    = GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ;
-                    handle_value = gattsEventP->params.authorize_request.request.read.handle;
-                    break;
-                case BLE_GATTS_AUTHORIZE_TYPE_WRITE:
-                    eventType    = GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ;
-                    handle_value = gattsEventP->params.authorize_request.request.write.handle;
-                    break;
-                default:
-                    return;
-            }
-            break;
-
-        default:
-            return;
-    }
-
-    int characteristicIndex = resolveValueHandleToCharIndex(handle_value);
-    if (characteristicIndex == -1) {
-        return;
-    }
-
-    /* Find index (charHandle) in the pool */
-    switch (eventType) {
-        case GattServerEvents::GATT_EVENT_DATA_WRITTEN: {
-            GattWriteCallbackParams cbParams = {
-                .connHandle = gattsEventP->conn_handle,
-                .handle     = handle_value,
-                .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.write.op),
-                .offset     = gattsEventP->params.write.offset,
-                .len        = gattsEventP->params.write.len,
-                .data       = gattsEventP->params.write.data
-            };
-            handleDataWrittenEvent(&cbParams);
-            break;
-        }
-        case GattServerEvents::GATT_EVENT_WRITE_AUTHORIZATION_REQ: {
-            GattWriteAuthCallbackParams cbParams = {
-                .connHandle = gattsEventP->conn_handle,
-                .handle     = handle_value,
-                .offset     = gattsEventP->params.authorize_request.request.write.offset,
-                .len        = gattsEventP->params.authorize_request.request.write.len,
-                .data       = gattsEventP->params.authorize_request.request.write.data,
-                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
-                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
-                                                                   * request is to proceed. */
-            };
-            ble_gatts_rw_authorize_reply_params_t reply = {
-                .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE,
-                .params = {
-                    .write = {
-                        .gatt_status = p_characteristics[characteristicIndex]->authorizeWrite(&cbParams)
-                    }
-                }
-            };
-            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
-
-            /*
-             * If write-authorization is enabled for a characteristic,
-             * AUTHORIZATION_REQ event (if replied with true) is *not*
-             * followed by another DATA_WRITTEN event; so we still need
-             * to invoke handleDataWritten(), much the same as we would
-             * have done if write-authorization had not been enabled.
-             */
-            if (reply.params.write.gatt_status == BLE_GATT_STATUS_SUCCESS) {
-                GattWriteCallbackParams cbParams = {
-                    .connHandle = gattsEventP->conn_handle,
-                    .handle     = handle_value,
-                    .writeOp    = static_cast<GattWriteCallbackParams::WriteOp_t>(gattsEventP->params.authorize_request.request.write.op),
-                    .offset     = gattsEventP->params.authorize_request.request.write.offset,
-                    .len        = gattsEventP->params.authorize_request.request.write.len,
-                    .data       = gattsEventP->params.authorize_request.request.write.data,
-                };
-                handleDataWrittenEvent(&cbParams);
-            }
-            break;
-        }
-        case GattServerEvents::GATT_EVENT_READ_AUTHORIZATION_REQ: {
-            GattReadAuthCallbackParams cbParams = {
-                .connHandle         = gattsEventP->conn_handle,
-                .handle             = handle_value,
-                .offset             = gattsEventP->params.authorize_request.request.read.offset,
-                .len                = 0,
-                .data               = NULL,
-                .authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS /* the callback handler must leave this member
-                                                                   * set to AUTH_CALLBACK_REPLY_SUCCESS if the client
-                                                                   * request is to proceed. */
-            };
-
-            ble_gatts_rw_authorize_reply_params_t reply = {
-                .type = BLE_GATTS_AUTHORIZE_TYPE_READ,
-                .params = {
-                    .read = {
-                        .gatt_status = p_characteristics[characteristicIndex]->authorizeRead(&cbParams)
-                    }
-                }
-            };
-
-            if (cbParams.authorizationReply == BLE_GATT_STATUS_SUCCESS) {
-                if (cbParams.data != NULL) {
-                    reply.params.read.update = 1;
-                    reply.params.read.offset = cbParams.offset;
-                    reply.params.read.len    = cbParams.len;
-                    reply.params.read.p_data = cbParams.data;
-                }
-            }
-
-            sd_ble_gatts_rw_authorize_reply(gattsEventP->conn_handle, &reply);
-            break;
-        }
-
-        default:
-            handleEvent(eventType, handle_value);
-            break;
-    }
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xGattServer.h
--- a/source/nRF5xGattServer.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,103 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF51822_GATT_SERVER_H__
-#define __NRF51822_GATT_SERVER_H__
-
-#include <stddef.h>
-
-#include "ble/blecommon.h"
-#include "nrf_ble.h" /* nordic ble */
-#include "ble/Gap.h"
-#include "ble/GattServer.h"
-
-class nRF5xGattServer : public GattServer
-{
-public:
-    /* Functions that must be implemented from GattServer */
-    virtual ble_error_t addService(GattService &);
-    virtual ble_error_t read(GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
-    virtual ble_error_t read(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP);
-    virtual ble_error_t write(GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
-    virtual ble_error_t write(Gap::Handle_t connectionHandle, GattAttribute::Handle_t, const uint8_t[], uint16_t, bool localOnly = false);
-    virtual ble_error_t areUpdatesEnabled(const GattCharacteristic &characteristic, bool *enabledP);
-    virtual ble_error_t areUpdatesEnabled(Gap::Handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP);
-    virtual ble_error_t reset(void);
-
-    /* nRF51 Functions */
-    void eventCallback(void);
-    void hwCallback(ble_evt_t *p_ble_evt);
-
-
-private:
-    const static unsigned BLE_TOTAL_CHARACTERISTICS = 20;
-    const static unsigned BLE_TOTAL_DESCRIPTORS     = 8;
-
-private:
-    /**
-     * resolve a value attribute to its owning characteristic.
-     * @param  valueHandle the value handle to be resolved.
-     * @return             characteristic index if a resolution is found, else -1.
-     */
-    int resolveValueHandleToCharIndex(GattAttribute::Handle_t valueHandle) const {
-        unsigned charIndex;
-        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
-            if (nrfCharacteristicHandles[charIndex].value_handle == valueHandle) {
-                return charIndex;
-            }
-        }
-
-        return -1;
-    }
-
-    /**
-     * resolve a CCCD attribute handle to its owning characteristic.
-     * @param  cccdHandle the CCCD handle to be resolved.
-     * @return             characteristic index if a resolution is found, else -1.
-     */
-    int resolveCCCDHandleToCharIndex(GattAttribute::Handle_t cccdHandle) const {
-        unsigned charIndex;
-        for (charIndex = 0; charIndex < characteristicCount; charIndex++) {
-            if (nrfCharacteristicHandles[charIndex].cccd_handle == cccdHandle) {
-                return charIndex;
-            }
-        }
-
-        return -1;
-    }
-
-private:
-    GattCharacteristic       *p_characteristics[BLE_TOTAL_CHARACTERISTICS];
-    ble_gatts_char_handles_t  nrfCharacteristicHandles[BLE_TOTAL_CHARACTERISTICS];
-    GattAttribute            *p_descriptors[BLE_TOTAL_DESCRIPTORS];
-    uint8_t                   descriptorCount;
-    uint16_t                  nrfDescriptorHandles[BLE_TOTAL_DESCRIPTORS];
-
-    /*
-     * Allow instantiation from nRF5xn when required.
-     */
-    friend class nRF5xn;
-
-    nRF5xGattServer() : GattServer(), p_characteristics(), nrfCharacteristicHandles(), p_descriptors(), descriptorCount(0), nrfDescriptorHandles() {
-        /* empty */
-    }
-
-private:
-    nRF5xGattServer(const nRF5xGattServer &);
-    const nRF5xGattServer& operator=(const nRF5xGattServer &);
-};
-
-#endif // ifndef __NRF51822_GATT_SERVER_H__
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xSecurityManager.h
--- a/source/nRF5xSecurityManager.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,174 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF51822_SECURITY_MANAGER_H__
-#define __NRF51822_SECURITY_MANAGER_H__
-
-#include <stddef.h>
-
-#include "nRF5xGap.h"
-#include "ble/SecurityManager.h"
-#include "btle_security.h"
-
-class nRF5xSecurityManager : public SecurityManager
-{
-public:
-    /* Functions that must be implemented from SecurityManager */
-    virtual ble_error_t init(bool                     enableBonding,
-                             bool                     requireMITM,
-                             SecurityIOCapabilities_t iocaps,
-                             const Passkey_t          passkey) {
-        return btle_initializeSecurity(enableBonding, requireMITM, iocaps, passkey);
-    }
-
-    virtual ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, LinkSecurityStatus_t *securityStatusP) {
-        return btle_getLinkSecurity(connectionHandle, securityStatusP);
-    }
-
-    virtual ble_error_t setLinkSecurity(Gap::Handle_t connectionHandle, SecurityMode_t securityMode) {
-        return btle_setLinkSecurity(connectionHandle, securityMode);
-    }
-
-    virtual ble_error_t purgeAllBondingState(void) {
-        return btle_purgeAllBondingState();
-    }
-
-    /**
-     * @brief  Returns a list of addresses from peers in the stacks bond table.
-     *
-     * @param[in/out]   addresses
-     *                  (on input) @ref Gap::Whitelist_t structure where at
-     *                  most addresses.capacity addresses from bonded peers will
-     *                  be stored.
-     *                  (on output) A copy of the addresses from bonded peers.
-     *
-     * @return
-     *           BLE_ERROR_NONE if successful.
-     */
-    virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const {
-        uint8_t i;
-
-        ble_gap_whitelist_t  whitelistFromBondTable;
-        ble_gap_addr_t      *addressPtr[YOTTA_CFG_WHITELIST_MAX_SIZE];
-        ble_gap_irk_t       *irkPtr[YOTTA_CFG_IRK_TABLE_MAX_SIZE];
-
-        /* Initialize the structure so that we get as many addreses as the whitelist can hold */
-        whitelistFromBondTable.addr_count = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
-        whitelistFromBondTable.pp_addrs   = addressPtr;
-        whitelistFromBondTable.irk_count  = YOTTA_CFG_IRK_TABLE_MAX_SIZE;
-        whitelistFromBondTable.pp_irks    = irkPtr;
-
-        ble_error_t error = createWhitelistFromBondTable(whitelistFromBondTable);
-        if (error != BLE_ERROR_NONE) {
-            addresses.size = 0;
-            return error;
-        }
-
-        /* Put all the addresses in the structure */
-        for (i = 0; i < whitelistFromBondTable.addr_count; ++i) {
-            if (i >= addresses.capacity) {
-                /* Ran out of space in the output Gap::Whitelist_t */
-                addresses.size = i;
-                return BLE_ERROR_NONE;
-            }
-            memcpy(&addresses.addresses[i], whitelistFromBondTable.pp_addrs[i], sizeof(BLEProtocol::Address_t));
-        }
-
-        /* Update the current address count */
-        addresses.size = i;
-
-        /* The assumption here is that the underlying implementation of
-         * createWhitelistFromBondTable()  will not return the private resolvable
-         * addresses (which is the case in the SoftDevice). Rather it returns the
-         * IRKs, so we need to generate the private resolvable address by ourselves.
-         */
-        for (i = 0; i < whitelistFromBondTable.irk_count; ++i) {
-            if (i + addresses.size >= addresses.capacity) {
-                /* Ran out of space in the output Gap::Whitelist_t */
-                addresses.size += i;
-                return BLE_ERROR_NONE;
-            }
-            btle_generateResolvableAddress(
-                *whitelistFromBondTable.pp_irks[i],
-                (ble_gap_addr_t &) addresses.addresses[i + addresses.size]
-            );
-        }
-
-        /* Update the current address count */
-        addresses.size += i;
-
-        return BLE_ERROR_NONE;
-    }
-
-    /**
-     * @brief  Clear nRF5xSecurityManager's state.
-     *
-     * @return
-     *           BLE_ERROR_NONE if successful.
-     */
-    virtual ble_error_t reset(void)
-    {
-        if (SecurityManager::reset() != BLE_ERROR_NONE) {
-            return BLE_ERROR_INVALID_STATE;
-        }
-
-        return BLE_ERROR_NONE;
-    }
-
-    bool hasInitialized(void) const {
-        return btle_hasInitializedSecurity();
-    }
-
-public:
-    /*
-     * Allow instantiation from nRF5xn when required.
-     */
-    friend class nRF5xn;
-
-    nRF5xSecurityManager() {
-        /* empty */
-    }
-
-private:
-    nRF5xSecurityManager(const nRF5xSecurityManager &);
-    const nRF5xSecurityManager& operator=(const nRF5xSecurityManager &);
-
-    /*
-     * Expose an interface that allows us to query the SoftDevice bond table
-     * and extract a whitelist.
-     */
-    ble_error_t createWhitelistFromBondTable(ble_gap_whitelist_t &whitelistFromBondTable) const {
-        return btle_createWhitelistFromBondTable(&whitelistFromBondTable);
-    }
-
-    /*
-     * Given a BLE address and a IRK this function check whether the address
-     * can be generated from the IRK. To do so, this function uses the hash
-     * function and algorithm described in the Bluetooth low Energy
-     * Specification. Internally, Nordic SDK functions are used.
-     */
-    bool matchAddressAndIrk(ble_gap_addr_t *address, ble_gap_irk_t *irk) const {
-        return btle_matchAddressAndIrk(address, irk);
-    }
-
-    /*
-     * Give nRF5xGap access to createWhitelistFromBondTable() and
-     * matchAddressAndIrk()
-     */
-    friend class nRF5xGap;
-};
-
-#endif // ifndef __NRF51822_SECURITY_MANAGER_H__
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xServiceDiscovery.cpp
--- a/source/nRF5xServiceDiscovery.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,310 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nRF5xServiceDiscovery.h"
-
-ble_error_t
-nRF5xServiceDiscovery::launchCharacteristicDiscovery(Gap::Handle_t connectionHandle,
-                                                     Gap::Handle_t startHandle,
-                                                     Gap::Handle_t endHandle)
-{
-    characteristicDiscoveryStarted(connectionHandle);
-
-    ble_gattc_handle_range_t handleRange = {
-        .start_handle = startHandle,
-        .end_handle   = endHandle
-    };
-    uint32_t rc = sd_ble_gattc_characteristics_discover(connectionHandle, &handleRange);
-    ble_error_t err = BLE_ERROR_NONE;
-
-    switch (rc) {
-        case NRF_SUCCESS:
-            err = BLE_ERROR_NONE;
-            break;
-        case BLE_ERROR_INVALID_CONN_HANDLE:
-        case NRF_ERROR_INVALID_ADDR:
-            err = BLE_ERROR_INVALID_PARAM;
-            break;
-        case NRF_ERROR_BUSY:
-            err = BLE_STACK_BUSY;
-            break;
-        case NRF_ERROR_INVALID_STATE:
-            err = BLE_ERROR_INVALID_STATE;
-            break;
-        default:
-            err = BLE_ERROR_UNSPECIFIED;
-            break;
-    }
-
-    if (err) {
-        terminateCharacteristicDiscovery(err);
-    }
-    return err;
-}
-
-void
-nRF5xServiceDiscovery::setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response)
-{
-    serviceIndex = 0;
-    numServices  = response->count;
-
-    /* Account for the limitation on the number of discovered services we can handle at a time. */
-    if (numServices > BLE_DB_DISCOVERY_MAX_SRV) {
-        numServices = BLE_DB_DISCOVERY_MAX_SRV;
-    }
-
-    serviceUUIDDiscoveryQueue.reset();
-    for (unsigned serviceIndex = 0; serviceIndex < numServices; serviceIndex++) {
-        if (response->services[serviceIndex].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
-            serviceUUIDDiscoveryQueue.enqueue(serviceIndex);
-            services[serviceIndex].setup(response->services[serviceIndex].handle_range.start_handle,
-                                         response->services[serviceIndex].handle_range.end_handle);
-        } else {
-            services[serviceIndex].setup(response->services[serviceIndex].uuid.uuid,
-                                         response->services[serviceIndex].handle_range.start_handle,
-                                         response->services[serviceIndex].handle_range.end_handle);
-        }
-    }
-
-    /* Trigger discovery of service UUID if necessary. */
-    if (serviceUUIDDiscoveryQueue.getCount()) {
-        serviceUUIDDiscoveryQueue.triggerFirst();
-    }
-}
-
-void
-nRF5xServiceDiscovery::setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response)
-{
-    numCharacteristics  = response->count;
-
-    /* Account for the limitation on the number of discovered characteristics we can handle at a time. */
-    if (numCharacteristics > BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV) {
-        numCharacteristics = BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV;
-    }
-
-    charUUIDDiscoveryQueue.reset();
-    for (unsigned charIndex = 0; charIndex < numCharacteristics; charIndex++) {
-        if (response->chars[charIndex].uuid.type == BLE_UUID_TYPE_UNKNOWN) {
-            charUUIDDiscoveryQueue.enqueue(charIndex);
-            characteristics[charIndex].setup(gattc,
-                                             connHandle,
-                                             response->chars[charIndex].char_props,
-                                             response->chars[charIndex].handle_decl,
-                                             response->chars[charIndex].handle_value);
-        } else {
-            characteristics[charIndex].setup(gattc,
-                                             connHandle,
-                                             response->chars[charIndex].uuid.uuid,
-                                             response->chars[charIndex].char_props,
-                                             response->chars[charIndex].handle_decl,
-                                             response->chars[charIndex].handle_value);
-        }
-    }
-
-    /* Trigger discovery of char UUID if necessary. */
-    if (charUUIDDiscoveryQueue.getCount()) {
-        charUUIDDiscoveryQueue.triggerFirst();
-    }
-}
-
-void
-nRF5xServiceDiscovery::progressCharacteristicDiscovery(void)
-{
-    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
-        return;
-    }
-
-    if ((discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) && (numCharacteristics > 0)) {
-        discoveredCharacteristic.setLastHandle(characteristics[0].getDeclHandle() - 1);
-
-        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
-            ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
-             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
-            if (characteristicCallback) {
-                characteristicCallback(&discoveredCharacteristic);
-            }
-        }
-    }
-
-    for (uint8_t i = 0; i < numCharacteristics; ++i) {
-        if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
-            return;
-        }
-
-        if (i == (numCharacteristics - 1)) {
-            discoveredCharacteristic = characteristics[i];
-            break;
-        } else {
-            characteristics[i].setLastHandle(characteristics[i + 1].getDeclHandle() - 1);
-        }
-
-        if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
-            ((matchingCharacteristicUUID == characteristics[i].getUUID()) &&
-             (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
-            if (characteristicCallback) {
-                characteristicCallback(&characteristics[i]);
-            }
-        }
-    }
-
-    if (state != CHARACTERISTIC_DISCOVERY_ACTIVE) {
-        return;
-    }
-
-    Gap::Handle_t startHandle = (numCharacteristics > 0) ? characteristics[numCharacteristics - 1].getValueHandle() + 1 : SRV_DISC_END_HANDLE;
-    Gap::Handle_t endHandle   = services[serviceIndex].getEndHandle();
-    resetDiscoveredCharacteristics(); /* Note: resetDiscoveredCharacteristics() must come after fetching start and end Handles. */
-
-    if (startHandle < endHandle) {
-        ble_gattc_handle_range_t handleRange = {
-            .start_handle = startHandle,
-            .end_handle   = endHandle
-        };
-        if (sd_ble_gattc_characteristics_discover(connHandle, &handleRange) != NRF_SUCCESS) {
-            terminateCharacteristicDiscovery(BLE_ERROR_UNSPECIFIED);
-        }
-    } else {
-        terminateCharacteristicDiscovery(BLE_ERROR_NONE);
-    }
-}
-
-void
-nRF5xServiceDiscovery::progressServiceDiscovery(void)
-{
-    /* Iterate through the previously discovered services cached in services[]. */
-    while ((state == SERVICE_DISCOVERY_ACTIVE) && (serviceIndex < numServices)) {
-        if ((matchingServiceUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
-            (matchingServiceUUID == services[serviceIndex].getUUID())) {
-
-            if (serviceCallback && (matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN))) {
-                serviceCallback(&services[serviceIndex]);
-            }
-
-            if ((state == SERVICE_DISCOVERY_ACTIVE) && characteristicCallback) {
-                launchCharacteristicDiscovery(connHandle, services[serviceIndex].getStartHandle(), services[serviceIndex].getEndHandle());
-            } else {
-                serviceIndex++;
-            }
-        } else {
-            serviceIndex++;
-        }
-    }
-
-    /* Relaunch discovery of new services beyond the last entry cached in services[]. */
-    if ((state == SERVICE_DISCOVERY_ACTIVE) && (numServices > 0) && (serviceIndex > 0)) {
-        /* Determine the ending handle of the last cached service. */
-        Gap::Handle_t endHandle = services[serviceIndex - 1].getEndHandle();
-        resetDiscoveredServices(); /* Note: resetDiscoveredServices() must come after fetching endHandle. */
-
-        if (endHandle == SRV_DISC_END_HANDLE) {
-            terminateServiceDiscovery();
-        } else {
-            if (sd_ble_gattc_primary_services_discover(connHandle, endHandle, NULL) != NRF_SUCCESS) {
-                terminateServiceDiscovery();
-            }
-        }
-    }
-}
-
-void
-nRF5xServiceDiscovery::ServiceUUIDDiscoveryQueue::triggerFirst(void)
-{
-    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
-        parentDiscoveryObject->state = DISCOVER_SERVICE_UUIDS;
-
-        unsigned serviceIndex = getFirst();
-        ble_uuid_t uuid = {
-            .uuid = BLE_UUID_SERVICE_PRIMARY,
-            .type = BLE_UUID_TYPE_BLE,
-        };
-        ble_gattc_handle_range_t handleRange = {
-            .start_handle = parentDiscoveryObject->services[serviceIndex].getStartHandle(),
-            .end_handle   = parentDiscoveryObject->services[serviceIndex].getEndHandle(),
-        };
-        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
-            return;
-        }
-
-        /* Skip this service if we fail to launch a read for its service-declaration
-         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
-        dequeue();
-    }
-
-    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
-    if (parentDiscoveryObject->state == DISCOVER_SERVICE_UUIDS) {
-        parentDiscoveryObject->state = SERVICE_DISCOVERY_ACTIVE;
-    }
-}
-
-void
-nRF5xServiceDiscovery::CharUUIDDiscoveryQueue::triggerFirst(void)
-{
-    while (numIndices) { /* loop until a call to char_value_by_uuid_read() succeeds or we run out of pending indices. */
-        parentDiscoveryObject->state = DISCOVER_CHARACTERISTIC_UUIDS;
-
-        unsigned charIndex = getFirst();
-        ble_uuid_t uuid = {
-            .uuid = BLE_UUID_CHARACTERISTIC,
-            .type = BLE_UUID_TYPE_BLE,
-        };
-        ble_gattc_handle_range_t handleRange = { };
-        handleRange.start_handle = parentDiscoveryObject->characteristics[charIndex].getDeclHandle();
-        handleRange.end_handle   = parentDiscoveryObject->characteristics[charIndex].getDeclHandle() + 1;
-        if (sd_ble_gattc_char_value_by_uuid_read(parentDiscoveryObject->connHandle, &uuid, &handleRange) == NRF_SUCCESS) {
-            return;
-        }
-
-        /* Skip this service if we fail to launch a read for its service-declaration
-         * attribute. Its UUID will remain INVALID, and it may not match any filters. */
-        dequeue();
-    }
-
-    /* Switch back to service discovery upon exhausting the service-indices pending UUID discovery. */
-    if (parentDiscoveryObject->state == DISCOVER_CHARACTERISTIC_UUIDS) {
-        parentDiscoveryObject->state = CHARACTERISTIC_DISCOVERY_ACTIVE;
-    }
-}
-
-void
-nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response)
-{
-    if (state == DISCOVER_SERVICE_UUIDS) {
-        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID)) {
-            UUID::LongUUIDBytes_t uuid;
-            memcpy(uuid, response->handle_value[0].p_value, UUID::LENGTH_OF_LONG_UUID);
-
-            unsigned serviceIndex = serviceUUIDDiscoveryQueue.dequeue();
-            services[serviceIndex].setupLongUUID(uuid, UUID::LSB);
-
-            serviceUUIDDiscoveryQueue.triggerFirst();
-        } else {
-            serviceUUIDDiscoveryQueue.dequeue();
-        }
-    } else if (state == DISCOVER_CHARACTERISTIC_UUIDS) {
-        if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID + 1 /* props */ + 2 /* value handle */)) {
-            UUID::LongUUIDBytes_t uuid;
-
-            memcpy(uuid, &(response->handle_value[0].p_value[3]), UUID::LENGTH_OF_LONG_UUID);
-
-            unsigned charIndex = charUUIDDiscoveryQueue.dequeue();
-            characteristics[charIndex].setupLongUUID(uuid, UUID::LSB);
-
-            charUUIDDiscoveryQueue.triggerFirst();
-        } else {
-            charUUIDDiscoveryQueue.dequeue();
-        }
-    }
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xServiceDiscovery.h
--- a/source/nRF5xServiceDiscovery.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,366 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF_SERVICE_DISCOVERY_H__
-#define __NRF_SERVICE_DISCOVERY_H__
-
-#include "ble/ServiceDiscovery.h"
-#include "ble/DiscoveredService.h"
-#include "nRF5xDiscoveredCharacteristic.h"
-
-#include "nrf_ble.h"
-#include "ble_gattc.h"
-
-class nRF5xGattClient; /* forward declaration */
-
-class nRF5xServiceDiscovery : public ServiceDiscovery
-{
-public:
-    static const uint16_t SRV_DISC_START_HANDLE             = 0x0001; /**< The start handle value used during service discovery. */
-    static const uint16_t SRV_DISC_END_HANDLE               = 0xFFFF; /**< The end handle value used during service discovery. */
-
-public:
-    static const unsigned BLE_DB_DISCOVERY_MAX_SRV          = 4;      /**< Maximum number of services we can retain information for after a single discovery. */
-    static const unsigned BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV = 4;      /**< Maximum number of characteristics per service we can retain information for. */
-
-public:
-    nRF5xServiceDiscovery(nRF5xGattClient *gattcIn) :
-        gattc(gattcIn),
-        serviceIndex(0),
-        numServices(0),
-        numCharacteristics(0),
-        state(INACTIVE),
-        services(),
-        characteristics(),
-        serviceUUIDDiscoveryQueue(this),
-        charUUIDDiscoveryQueue(this),
-        onTerminationCallback(NULL) {
-        /* empty */
-    }
-
-    virtual ble_error_t launch(Gap::Handle_t                               connectionHandle,
-                               ServiceDiscovery::ServiceCallback_t         sc,
-                               ServiceDiscovery::CharacteristicCallback_t  cc,
-                               const UUID                                 &matchingServiceUUIDIn,
-                               const UUID                                 &matchingCharacteristicUUIDIn)
-    {
-        if (isActive()) {
-            return BLE_ERROR_INVALID_STATE;
-        }
-
-        serviceCallback            = sc;
-        characteristicCallback     = cc;
-        matchingServiceUUID        = matchingServiceUUIDIn;
-        matchingCharacteristicUUID = matchingCharacteristicUUIDIn;
-
-        serviceDiscoveryStarted(connectionHandle);
-
-        uint32_t rc;
-        if ((rc = sd_ble_gattc_primary_services_discover(connectionHandle, SRV_DISC_START_HANDLE, NULL)) != NRF_SUCCESS) {
-            terminate();
-            switch (rc) {
-                case NRF_ERROR_INVALID_PARAM:
-                case BLE_ERROR_INVALID_CONN_HANDLE:
-                    return BLE_ERROR_INVALID_PARAM;
-                case NRF_ERROR_BUSY:
-                    return BLE_STACK_BUSY;
-                default:
-                case NRF_ERROR_INVALID_STATE:
-                    return BLE_ERROR_INVALID_STATE;
-            }
-        }
-
-        return BLE_ERROR_NONE;
-    }
-
-    virtual bool isActive(void) const {
-        return state != INACTIVE;
-    }
-
-    virtual void terminate(void) {
-        terminateServiceDiscovery();
-    }
-
-    void terminate(Gap::Handle_t connectionHandle) {
-        if(connHandle == connectionHandle) {
-            terminate();
-        }
-    }
-
-    virtual void onTermination(ServiceDiscovery::TerminationCallback_t callback) {
-        onTerminationCallback = callback;
-    }
-
-    /**
-     * @brief  Clear nRF5xServiceDiscovery's state.
-     *
-     * @return
-     *           BLE_ERROR_NONE if successful.
-     */
-    virtual ble_error_t reset(void) {
-        /* Clear all state that is from the parent, including private members */
-        if (ServiceDiscovery::reset() != BLE_ERROR_NONE) {
-            return BLE_ERROR_INVALID_STATE;
-        }
-
-        /* Clear derived class members */
-        serviceIndex = 0;
-        numServices = 0;
-        numCharacteristics = 0;
-
-        state = INACTIVE;
-
-        serviceUUIDDiscoveryQueue.reset();
-        charUUIDDiscoveryQueue.reset();
-
-        onTerminationCallback = NULL;
-
-        return BLE_ERROR_NONE;
-    }
-
-private:
-    ble_error_t launchCharacteristicDiscovery(Gap::Handle_t connectionHandle, Gap::Handle_t startHandle, Gap::Handle_t endHandle);
-
-private:
-    void setupDiscoveredServices(const ble_gattc_evt_prim_srvc_disc_rsp_t *response);
-    void setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response);
-
-    void triggerServiceUUIDDiscovery(void);
-    void processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response);
-    void removeFirstServiceNeedingUUIDDiscovery(void);
-
-    void terminateServiceDiscovery(void) {
-        discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
-
-        bool wasActive = isActive();
-        state = INACTIVE;
-
-        if (wasActive && onTerminationCallback) {
-            onTerminationCallback(connHandle);
-        }
-    }
-
-    void terminateCharacteristicDiscovery(ble_error_t err) {
-        if (state == CHARACTERISTIC_DISCOVERY_ACTIVE) {
-            if(discoveredCharacteristic != nRF5xDiscoveredCharacteristic()) {
-               if(err == BLE_ERROR_NONE) {
-                    // fullfill the last characteristic
-                    discoveredCharacteristic.setLastHandle(services[serviceIndex].getEndHandle());
-
-                    if ((matchingCharacteristicUUID == UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) ||
-                        ((matchingCharacteristicUUID == discoveredCharacteristic.getUUID()) &&
-                         (matchingServiceUUID != UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)))) {
-                        if (characteristicCallback) {
-                            characteristicCallback(&discoveredCharacteristic);
-                        }
-                    }
-               }
-               discoveredCharacteristic = nRF5xDiscoveredCharacteristic();
-            }
-
-            state = SERVICE_DISCOVERY_ACTIVE;
-        }
-        serviceIndex++; /* Progress service index to keep discovery alive. */
-    }
-
-private:
-    void resetDiscoveredServices(void) {
-        numServices  = 0;
-        serviceIndex = 0;
-    }
-
-    void resetDiscoveredCharacteristics(void) {
-        numCharacteristics  = 0;
-    }
-
-private:
-    void serviceDiscoveryStarted(Gap::Handle_t connectionHandle) {
-        connHandle = connectionHandle;
-        resetDiscoveredServices();
-        state = SERVICE_DISCOVERY_ACTIVE;
-    }
-
-private:
-    void characteristicDiscoveryStarted(Gap::Handle_t connectionHandle) {
-        connHandle = connectionHandle;
-        resetDiscoveredCharacteristics();
-        state = CHARACTERISTIC_DISCOVERY_ACTIVE;
-    }
-
-private:
-    /**
-     * A datatype to contain service-indices for which long UUIDs need to be
-     * discovered using read_val_by_uuid().
-     */
-    class ServiceUUIDDiscoveryQueue {
-    public:
-        ServiceUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
-            numIndices(0),
-            serviceIndices(),
-            parentDiscoveryObject(parent) {
-            /* empty */
-        }
-
-    public:
-        void reset(void) {
-            numIndices = 0;
-            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
-                serviceIndices[i] = INVALID_INDEX;
-            }
-        }
-        void enqueue(int serviceIndex) {
-            serviceIndices[numIndices++] = serviceIndex;
-        }
-        int dequeue(void) {
-            if (numIndices == 0) {
-                return INVALID_INDEX;
-            }
-
-            unsigned valueToReturn = serviceIndices[0];
-            numIndices--;
-            for (unsigned i = 0; i < numIndices; i++) {
-                serviceIndices[i] = serviceIndices[i + 1];
-            }
-
-            return valueToReturn;
-        }
-        unsigned getFirst(void) const {
-            return serviceIndices[0];
-        }
-        size_t getCount(void) const {
-            return numIndices;
-        }
-
-        /**
-         * Trigger UUID discovery for the first of the enqueued ServiceIndices.
-         */
-        void triggerFirst(void);
-
-    private:
-        static const int INVALID_INDEX = -1;
-
-    private:
-        size_t numIndices;
-        int    serviceIndices[BLE_DB_DISCOVERY_MAX_SRV];
-
-        nRF5xServiceDiscovery *parentDiscoveryObject;
-    };
-    friend class ServiceUUIDDiscoveryQueue;
-
-    /**
-     * A datatype to contain characteristic-indices for which long UUIDs need to
-     * be discovered using read_val_by_uuid().
-     */
-    class CharUUIDDiscoveryQueue {
-    public:
-        CharUUIDDiscoveryQueue(nRF5xServiceDiscovery *parent) :
-            numIndices(0),
-            charIndices(),
-            parentDiscoveryObject(parent) {
-            /* empty */
-        }
-
-    public:
-        void reset(void) {
-            numIndices = 0;
-            for (unsigned i = 0; i < BLE_DB_DISCOVERY_MAX_SRV; i++) {
-                charIndices[i] = INVALID_INDEX;
-            }
-        }
-        void enqueue(int serviceIndex) {
-            charIndices[numIndices++] = serviceIndex;
-        }
-        int dequeue(void) {
-            if (numIndices == 0) {
-                return INVALID_INDEX;
-            }
-
-            unsigned valueToReturn = charIndices[0];
-            numIndices--;
-            for (unsigned i = 0; i < numIndices; i++) {
-                charIndices[i] = charIndices[i + 1];
-            }
-
-            return valueToReturn;
-        }
-        unsigned getFirst(void) const {
-            return charIndices[0];
-        }
-        size_t getCount(void) const {
-            return numIndices;
-        }
-
-        /**
-         * Trigger UUID discovery for the first of the enqueued charIndices.
-         */
-        void triggerFirst(void);
-
-    private:
-        static const int INVALID_INDEX = -1;
-
-    private:
-        size_t numIndices;
-        int    charIndices[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
-
-        nRF5xServiceDiscovery *parentDiscoveryObject;
-    };
-    friend class CharUUIDDiscoveryQueue;
-
-private:
-    friend void bleGattcEventHandler(const ble_evt_t *p_ble_evt);
-    void progressCharacteristicDiscovery(void);
-    void progressServiceDiscovery(void);
-
-private:
-    nRF5xGattClient *gattc;
-
-private:
-    uint8_t  serviceIndex;        /**< Index of the current service being discovered. This is intended for internal use during service discovery.*/
-    uint8_t  numServices;         /**< Number of services at the peers GATT database.*/
-    uint8_t  numCharacteristics;  /**< Number of characteristics within the service.*/
-
-    enum State_t {
-        INACTIVE,
-        SERVICE_DISCOVERY_ACTIVE,
-        CHARACTERISTIC_DISCOVERY_ACTIVE,
-        DISCOVER_SERVICE_UUIDS,
-        DISCOVER_CHARACTERISTIC_UUIDS,
-    } state;
-
-    DiscoveredService           services[BLE_DB_DISCOVERY_MAX_SRV];  /**< Information related to the current service being discovered.
-                                                                      *  This is intended for internal use during service discovery. */
-    nRF5xDiscoveredCharacteristic characteristics[BLE_DB_DISCOVERY_MAX_CHAR_PER_SRV];
-
-    ServiceUUIDDiscoveryQueue   serviceUUIDDiscoveryQueue;
-    CharUUIDDiscoveryQueue      charUUIDDiscoveryQueue;
-
-    TerminationCallback_t       onTerminationCallback;
-
-    /*
-     * The currently discovered characteristic. Discovery of a characteristic
-     * is a two phase process.
-     * First, declaration handle is fetched, it provide the UUID, the value handle and
-     * the properties of a characteristic.
-     * Second, the next declaration handle is fetched, with its declaration handle, it is
-     * possible to compute the last handle of the discovered characteristic and fill the
-     * missing part of the object.
-     * If there is no remaining characteristic to discover, the last handle of the
-     * discovered characteristic will be set to the last handle of its enclosing service.
-     */
-    nRF5xDiscoveredCharacteristic discoveredCharacteristic;
-};
-
-#endif /*__NRF_SERVICE_DISCOVERY_H__*/
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xn.cpp
--- a/source/nRF5xn.cpp	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,209 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifdef YOTTA_CFG_MBED_OS
-    #include "mbed-drivers/mbed.h"
-#else
-    #include "mbed.h"
-#endif
-#include "nRF5xn.h"
-#include "ble/blecommon.h"
-#include "nrf_soc.h"
-
-#include "btle/btle.h"
-#include "nrf_delay.h"
-
-extern "C" {
-#include "softdevice_handler.h"
-}
-
-/**
- * The singleton which represents the nRF51822 transport for the BLE.
- */
-static nRF5xn deviceInstance;
-
-/**
- * BLE-API requires an implementation of the following function in order to
- * obtain its transport handle.
- */
-BLEInstanceBase *
-createBLEInstance(void)
-{
-    return &nRF5xn::Instance(BLE::DEFAULT_INSTANCE);
-}
-
-nRF5xn& nRF5xn::Instance(BLE::InstanceID_t instanceId)
-{
-    return deviceInstance;
-}
-
-nRF5xn::nRF5xn(void) :
-    initialized(false),
-    instanceID(BLE::DEFAULT_INSTANCE),
-    gapInstance(),
-    gattServerInstance(NULL),
-    gattClientInstance(NULL),
-    securityManagerInstance(NULL)
-{
-}
-
-nRF5xn::~nRF5xn(void)
-{
-}
-
-const char *nRF5xn::getVersion(void)
-{
-    if (!initialized) {
-        return "INITIALIZATION_INCOMPLETE";
-    }
-
-    static char versionString[32];
-    static bool versionFetched = false;
-
-    if (!versionFetched) {
-        ble_version_t version;
-        if ((sd_ble_version_get(&version) == NRF_SUCCESS) && (version.company_id == 0x0059)) {
-            switch (version.version_number) {
-                case 0x07:
-                case 0x08:
-                    snprintf(versionString, sizeof(versionString), "Nordic BLE4.1 ver:%u fw:%04x", version.version_number, version.subversion_number);
-                    break;
-                default:
-                    snprintf(versionString, sizeof(versionString), "Nordic (spec unknown) ver:%u fw:%04x", version.version_number, version.subversion_number);
-                    break;
-            }
-            versionFetched = true;
-        } else {
-            strncpy(versionString, "unknown", sizeof(versionString));
-        }
-    }
-
-    return versionString;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Initialize the BLE stack.
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE if everything executed properly and
-                BLE_ERROR_ALREADY_INITIALIZED if the stack has already
-                been initialized (possibly through a call to nRF5xn::init()).
-                BLE_ERROR_INTERNAL_STACK_FAILURE is returned if initialization
-                of the internal stack (SoftDevice) failed.
-
-*/
-/**************************************************************************/
-ble_error_t nRF5xn::init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback)
-{
-    if (initialized) {
-        BLE::InitializationCompleteCallbackContext context = {
-            BLE::Instance(instanceID),
-            BLE_ERROR_ALREADY_INITIALIZED
-        };
-        callback.call(&context);
-        return BLE_ERROR_ALREADY_INITIALIZED;
-    }
-
-    instanceID   = instanceID;
-
-    /* ToDo: Clear memory contents, reset the SD, etc. */
-    if (btle_init() != ERROR_NONE) {
-        return BLE_ERROR_INTERNAL_STACK_FAILURE;
-    }
-
-    initialized = true;
-    BLE::InitializationCompleteCallbackContext context = {
-        BLE::Instance(instanceID),
-        BLE_ERROR_NONE
-    };
-    callback.call(&context);
-    return BLE_ERROR_NONE;
-}
-
-/**************************************************************************/
-/*!
-    @brief  Purge the BLE stack of GATT and GAP state.
-
-    @returns    ble_error_t
-
-    @retval     BLE_ERROR_NONE
-                Everything executed properly
-
-    @note  When using S110, GattClient::shutdown() will not be called
-           since Gatt client features are not supported.
-*/
-/**************************************************************************/
-ble_error_t nRF5xn::shutdown(void)
-{
-    if (!initialized) {
-        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
-    }
-
-    /*
-     * Shutdown the SoftDevice first. This is because we need to disable all
-     * interrupts. Otherwise if we clear the BLE API and glue code first there
-     * will be many NULL references and no config information which could lead
-     * to errors if the shutdown process is interrupted.
-     */
-    if (softdevice_handler_sd_disable() != NRF_SUCCESS) {
-        return BLE_STACK_BUSY;
-    }
-
-
-    /* Shutdown the BLE API and nRF51 glue code */
-    ble_error_t error;
-
-    if (gattServerInstance != NULL) {
-        error = gattServerInstance->reset();
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-
-    if (securityManagerInstance != NULL) {
-        error = securityManagerInstance->reset();
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-
-    /* S110 does not support BLE client features, nothing to reset. */
-#if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110)
-    if (gattClientInstance != NULL) {
-        error = gattClientInstance->reset();
-        if (error != BLE_ERROR_NONE) {
-            return error;
-        }
-    }
-#endif
-
-    /* Gap instance is always present */
-    error = gapInstance.reset();
-    if (error != BLE_ERROR_NONE) {
-        return error;
-    }
-
-    initialized = false;
-    return BLE_ERROR_NONE;
-}
-
-void
-nRF5xn::waitForEvent(void)
-{
-    sd_app_evt_wait();
-}
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/nRF5xn.h
--- a/source/nRF5xn.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,182 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __NRF51822_H__
-#define __NRF51822_H__
-
-#include "ble/BLE.h"
-#include "ble/blecommon.h"
-#include "ble/BLEInstanceBase.h"
-
-#include "nRF5xGap.h"
-#include "nRF5xGattServer.h"
-#include "nRF5xGattClient.h"
-#include "nRF5xSecurityManager.h"
-
-#include "btle.h"
-
-class nRF5xn : public BLEInstanceBase
-{
-public:
-    nRF5xn(void);
-    virtual ~nRF5xn(void);
-
-    virtual ble_error_t init(BLE::InstanceID_t instanceID, FunctionPointerWithContext<BLE::InitializationCompleteCallbackContext *> callback);
-    virtual bool        hasInitialized(void) const {
-        return initialized;
-    }
-    virtual ble_error_t shutdown(void);
-    virtual const char *getVersion(void);
-
-    /**
-     * Accessors to GAP. This function checks whether gapInstance points to an
-     * object. If if does not, then the gapInstance is updated to
-     * &_getInstance before returning.
-     *
-     * @return  A reference to GattServer.
-     *
-     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
-     *        always needed in a BLE application. Therefore it is allocated
-     *        statically.
-     */
-    virtual Gap &getGap() {
-        return gapInstance;
-    };
-
-    /**
-     * Accessors to GATT Server. This function checks whether a GattServer
-     * object was previously instantiated. If such object does not exist, then
-     * it is created before returning.
-     *
-     * @return  A reference to GattServer.
-     */
-    virtual GattServer &getGattServer() {
-        if (gattServerInstance == NULL) {
-            gattServerInstance = new nRF5xGattServer();
-        }
-        return *gattServerInstance;
-    };
-
-    /**
-     * Accessors to GATT Client. This function checks whether a GattClient
-     * object was previously instantiated. If such object does not exist, then
-     * it is created before returning.
-     *
-     * @return  A reference to GattClient.
-     */
-    virtual nRF5xGattClient &getGattClient() {
-        if (gattClientInstance == NULL) {
-            gattClientInstance = new nRF5xGattClient();
-        }
-        return *gattClientInstance;
-    }
-
-    /**
-     * Accessors to Security Manager. This function checks whether a SecurityManager
-     * object was previously instantiated. If such object does not exist, then
-     * it is created before returning.
-     *
-     * @return  A reference to GattServer.
-     */
-    virtual nRF5xSecurityManager &getSecurityManager() {
-        if (securityManagerInstance == NULL) {
-            securityManagerInstance = new nRF5xSecurityManager();
-        }
-        return *securityManagerInstance;
-    }
-
-    /**
-     * Accessors to GAP. This function checks whether gapInstance points to an
-     * object. If if does not, then the gapInstance is updated to
-     * &_getInstance before returning.
-     *
-     * @return  A const reference to GattServer.
-     *
-     * @note  Unlike the GattClient, GattServer and SecurityManager, Gap is
-     *        always needed in a BLE application. Therefore it is allocated
-     *        statically.
-     *
-     * @note  The accessor is able to modify the object's state because the
-     *        internal pointer has been declared mutable.
-     */
-    virtual const nRF5xGap &getGap() const  {
-        return gapInstance;
-    };
-
-    /**
-     * Accessors to GATT Server. This function checks whether a GattServer
-     * object was previously instantiated. If such object does not exist, then
-     * it is created before returning.
-     *
-     * @return  A const reference to GattServer.
-     *
-     * @note  The accessor is able to modify the object's state because the
-     *        internal pointer has been declared mutable.
-     */
-    virtual const nRF5xGattServer &getGattServer() const {
-        if (gattServerInstance == NULL) {
-            gattServerInstance = new nRF5xGattServer();
-        }
-        return *gattServerInstance;
-    };
-
-    /**
-     * Accessors to Security Manager. This function checks whether a SecurityManager
-     * object was previously instantiated. If such object does not exist, then
-     * it is created before returning.
-     *
-     * @return  A const reference to GattServer.
-     *
-     * @note  The accessor is able to modify the object's state because the
-     *        internal pointer has been declared mutable.
-     */
-    virtual const nRF5xSecurityManager &getSecurityManager() const {
-        if (securityManagerInstance == NULL) {
-            securityManagerInstance = new nRF5xSecurityManager();
-        }
-        return *securityManagerInstance;
-    }
-
-    virtual void waitForEvent(void);
-
-public:
-    static nRF5xn& Instance(BLE::InstanceID_t instanceId);
-
-private:
-    bool              initialized;
-    BLE::InstanceID_t instanceID;
-
-private:
-    mutable nRF5xGap gapInstance; /**< Gap instance whose reference is returned from a call to
-                                   * getGap(). Unlike the GattClient, GattServer and
-                                   * SecurityManager, Gap is always needed in a BLE application. */
-
-private:
-    mutable nRF5xGattServer      *gattServerInstance;      /**< Pointer to the GattServer object instance.
-                                                            *   If NULL, then GattServer has not been initialized.
-                                                            *   The pointer has been declared as 'mutable' so that
-                                                            *   it can be assigned inside a 'const' function. */
-    mutable nRF5xGattClient      *gattClientInstance;      /**< Pointer to the GattClient object instance.
-                                                            *   If NULL, then GattClient has not been initialized.
-                                                            *   The pointer has been declared as 'mutable' so that
-                                                            *   it can be assigned inside a 'const' function. */
-    mutable nRF5xSecurityManager *securityManagerInstance; /**< Pointer to the SecurityManager object instance.
-                                                            *   If NULL, then SecurityManager has not been initialized.
-                                                            *   The pointer has been declared as 'mutable' so that
-                                                            *   it can be assigned inside a 'const' function. */
-};
-
-#endif
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/projectconfig.h
--- a/source/projectconfig.h	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,136 +0,0 @@
-/* mbed Microcontroller Library
- * Copyright (c) 2006-2013 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _PROJECTCONFIG_H_
-#define _PROJECTCONFIG_H_
-
-#include "ble/GapAdvertisingData.h"
-
-/*=========================================================================
-    MCU & BOARD SELCTION
-
-    CFG_BOARD is one of the value defined in board.h
-    -----------------------------------------------------------------------*/
-    #define CFG_BOARD                                  BOARD_PCA10001
-    #define CFG_MCU_STRING                             "nRF51822"
-/*=========================================================================*/
-
-
-/*=========================================================================
-    CODE BASE VERSION SETTINGS
-
-    Please do not modify this version number.  To set a version number
-    for your project or firmware, change the values in your 'boards/'
-    config file.
-    -----------------------------------------------------------------------*/
-    #define CFG_CODEBASE_VERSION_MAJOR                 0
-    #define CFG_CODEBASE_VERSION_MINOR                 1
-    #define CFG_CODEBASE_VERSION_REVISION              0
-/*=========================================================================*/
-
-
-/*=========================================================================
-    FIRMWARE VERSION SETTINGS
-    -----------------------------------------------------------------------*/
-    #define CFG_FIRMWARE_VERSION_MAJOR                 0
-    #define CFG_FIRMWARE_VERSION_MINOR                 0
-    #define CFG_FIRMWARE_VERSION_REVISION              0
-/*=========================================================================*/
-
-
-/*=========================================================================
-    DEBUG LEVEL
-    -----------------------------------------------------------------------
-
-    CFG_DEBUG                 Level 3: Full debug output, any failed assert
-                                       will produce a breakpoint for the
-                                       debugger
-                              Level 2: ATTR_ALWAYS_INLINE is null, ASSERT
-                                       has text
-                              Level 1: ATTR_ALWAYS_INLINE is an attribute,
-                                       ASSERT has no text
-                              Level 0: No debug information generated
-
-    -----------------------------------------------------------------------*/
-    #define CFG_DEBUG                                  (1)
-
-    #if (CFG_DEBUG > 3) || (CFG_DEBUG < 0)
-      #error "CFG_DEBUG must be a value between 0 (no debug) and 3"
-    #endif
-/*=========================================================================*/
-
-
-/*=========================================================================
-    GENERAL NRF51 PERIPHERAL SETTINGS
-    -----------------------------------------------------------------------
-
-    CFG_SCHEDULER_ENABLE      Set this to 'true' or 'false' depending on
-                              if you use the event scheduler or not
-
-    -----------------------------------------------------------------------*/
-    #define CFG_SCHEDULER_ENABLE                       false
-
-    /*------------------------------- GPIOTE ------------------------------*/
-    #define CFG_GPIOTE_MAX_USERS                       1                        /**< Maximum number of users of the GPIOTE handler. */
-
-    /*-------------------------------- TIMER ------------------------------*/
-    #define CFG_TIMER_PRESCALER                        0                        /**< Value of the RTC1 PRESCALER register. freq = (32768/(PRESCALER+1)) */
-    #define CFG_TIMER_MAX_INSTANCE                     1                        /**< Maximum number of simultaneously created timers. */
-    #define CFG_TIMER_OPERATION_QUEUE_SIZE             2                        /**< Size of timer operation queues. */
-/*=========================================================================*/
-
-
-/*=========================================================================
-    BTLE SETTINGS
-    -----------------------------------------------------------------------*/
-
-    #define CFG_BLE_TX_POWER_LEVEL                     0                        /**< in dBm (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */
-
-    /*---------------------------- BOND MANAGER ---------------------------*/
-    #define CFG_BLE_BOND_FLASH_PAGE_BOND               (BLE_FLASH_PAGE_END-1)   /**< Flash page used for bond manager bonding information.*/
-    #define CFG_BLE_BOND_FLASH_PAGE_SYS_ATTR           (BLE_FLASH_PAGE_END-3)   /**< Flash page used for bond manager system attribute information. TODO check if we can use BLE_FLASH_PAGE_END-2*/
-    #define CFG_BLE_BOND_DELETE_BUTTON_NUM             0                        /**< Button to press to delete bond details during init */
-
-    /*------------------------------ SECURITY -----------------------------*/
-    #define CFG_BLE_SEC_PARAM_MITM                     0                        /**< Man In The Middle protection not required. */
-    #define CFG_BLE_SEC_PARAM_IO_CAPABILITIES          BLE_GAP_IO_CAPS_NONE     /**< No I/O capabilities. */
-    #define CFG_BLE_SEC_PARAM_OOB                      0                        /**< Out Of Band data not available. */
-    #define CFG_BLE_SEC_PARAM_MIN_KEY_SIZE             7                        /**< Minimum encryption key size. */
-    #define CFG_BLE_SEC_PARAM_MAX_KEY_SIZE             16
-
-    /*--------------------------------- GAP -------------------------------*/
-    #define CFG_GAP_APPEARANCE                         GapAdvertisingData::GENERIC_TAG
-    #define CFG_GAP_LOCAL_NAME                         "nRF5x"
-
-    #define CFG_GAP_CONNECTION_MIN_INTERVAL_MS           50                     /**< Minimum acceptable connection interval */
-    #define CFG_GAP_CONNECTION_MAX_INTERVAL_MS          500                     /**< Maximum acceptable connection interval */
-    #define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS  4000                     /**< Connection supervisory timeout */
-    #define CFG_GAP_CONNECTION_SLAVE_LATENCY           0                        /**< Slave Latency in number of connection events. */
-
-    #define CFG_GAP_ADV_INTERVAL_MS                    25                       /**< The advertising interval in miliseconds, should be multiply of 0.625 */
-    #define CFG_GAP_ADV_TIMEOUT_S                      180                      /**< The advertising timeout in units of seconds. */
-/*=========================================================================*/
-
-
-/*=========================================================================
-    VALIDATION
-    -----------------------------------------------------------------------*/
-    #if CFG_BLE_TX_POWER_LEVEL != -40 && CFG_BLE_TX_POWER_LEVEL != -20 && CFG_BLE_TX_POWER_LEVEL != -16 && CFG_BLE_TX_POWER_LEVEL != -12 && CFG_BLE_TX_POWER_LEVEL != -8  && CFG_BLE_TX_POWER_LEVEL != -4  && CFG_BLE_TX_POWER_LEVEL != 0   && CFG_BLE_TX_POWER_LEVEL != 4
-        #error "CFG_BLE_TX_POWER_LEVEL must be -40, -20, -16, -12, -8, -4, 0 or 4"
-    #endif
-/*=========================================================================*/
-
-#endif /* _PROJECTCONFIG_H_ */
\ No newline at end of file
diff -r f7faad332abc -r c90ae1400bf2 source/supress-warnings.cmake
--- a/source/supress-warnings.cmake	Mon Apr 11 16:15:24 2016 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,21 +0,0 @@
-# Copyright 2015 ARM Limited
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-message("suppressing warnings from ble-nrf51822")
-
-if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
-    set_target_properties(ble-nrf51822
-        PROPERTIES COMPILE_FLAGS "-Wno-sign-compare -Wno-unused-variable -Wno-unused-parameter -Wno-unused-function -Wno-missing-field-initializers"
-    )
-endif()
\ No newline at end of file