my fork

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
filartrix
Date:
Wed Apr 08 14:17:20 2015 +0000
Parent:
3:f57d754b1814
Commit message:
first

Changed in this revision

inc/ble_status.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_aci_const.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_gap_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_gatt_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_hal_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_interface.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_l2cap_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_updater_aci.h Show annotated file Show diff for this revision Revisions of this file
inc/bluenrg_utils.h Show annotated file Show diff for this revision Revisions of this file
inc/clock.h Show annotated file Show diff for this revision Revisions of this file
inc/compiler.h Show annotated file Show diff for this revision Revisions of this file
inc/connection_config.h Show annotated file Show diff for this revision Revisions of this file
inc/cube_hal.h Show annotated file Show diff for this revision Revisions of this file
inc/debug.h Show annotated file Show diff for this revision Revisions of this file
inc/gap.h Show annotated file Show diff for this revision Revisions of this file
inc/gatt_server.h Show annotated file Show diff for this revision Revisions of this file
inc/gp_timer.h Show annotated file Show diff for this revision Revisions of this file
inc/hal.h Show annotated file Show diff for this revision Revisions of this file
inc/hal_types.h Show annotated file Show diff for this revision Revisions of this file
inc/hci.h Show annotated file Show diff for this revision Revisions of this file
inc/hci_const.h Show annotated file Show diff for this revision Revisions of this file
inc/link_layer.h Show annotated file Show diff for this revision Revisions of this file
inc/list.h Show annotated file Show diff for this revision Revisions of this file
inc/osal.h Show annotated file Show diff for this revision Revisions of this file
inc/sensor_service.h Show annotated file Show diff for this revision Revisions of this file
inc/sm.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32_bluenrg_ble.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32f4xx_hal_conf.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32f4xx_nucleo.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32f4xx_nucleo_bluenrg.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32l0xx_hal_conf.h Show annotated file Show diff for this revision Revisions of this file
inc/stm32xx_it.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show diff for this revision Revisions of this file
mbed.lib Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_IFR.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_gap_aci.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_gatt_aci.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_hal_aci.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_interface.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_l2cap_aci.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_updater_aci.c Show annotated file Show diff for this revision Revisions of this file
src/bluenrg_utils.c Show annotated file Show diff for this revision Revisions of this file
src/clock.c Show annotated file Show diff for this revision Revisions of this file
src/cube_hal_f4.c Show annotated file Show diff for this revision Revisions of this file
src/gp_timer.c Show annotated file Show diff for this revision Revisions of this file
src/hci.c Show annotated file Show diff for this revision Revisions of this file
src/list.c Show annotated file Show diff for this revision Revisions of this file
src/osal.c Show annotated file Show diff for this revision Revisions of this file
src/sensor_service.c Show annotated file Show diff for this revision Revisions of this file
src/stm32_bluenrg_ble.c Show annotated file Show diff for this revision Revisions of this file
src/stm32f4xx_nucleo.c Show annotated file Show diff for this revision Revisions of this file
src/stm32xx_it.c Show annotated file Show diff for this revision Revisions of this file
diff -r f57d754b1814 -r 987b201ec4b1 inc/ble_status.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/ble_status.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,114 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : ble_status.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file with BLE Stack status codes.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+#ifndef __BLE_STATUS_H__
+#define __BLE_STATUS_H__
+
+#include <hal_types.h>
+
+
+/** @defgroup ble_status Bluetooth Status/Error Codes
+ * @{
+ */
+ 
+typedef uint8_t tBleStatus; 
+
+/* Error Codes as specified by the specification 
+ * according to the spec the error codes range
+ * from 0x00 to 0x3F 
+ */
+#define ERR_CMD_SUCCESS         	                (0x00)
+#define BLE_STATUS_SUCCESS            		        (0x00)
+#define ERR_UNKNOWN_HCI_COMMAND                         (0x01)
+#define ERR_UNKNOWN_CONN_IDENTIFIER	                (0x02)
+
+#define ERR_AUTH_FAILURE                            (0x05)
+#define ERR_PIN_OR_KEY_MISSING                      (0x06)
+#define ERR_MEM_CAPACITY_EXCEEDED                   (0x07)
+#define ERR_CONNECTION_TIMEOUT                      (0x08)
+
+#define ERR_COMMAND_DISALLOWED				        (0x0C)
+
+#define ERR_UNSUPPORTED_FEATURE				        (0x11)
+#define ERR_INVALID_HCI_CMD_PARAMS                  (0x12)
+#define ERR_RMT_USR_TERM_CONN                       (0x13)
+#define ERR_RMT_DEV_TERM_CONN_LOW_RESRCES           (0x14)
+#define ERR_RMT_DEV_TERM_CONN_POWER_OFF             (0x15)
+#define ERR_LOCAL_HOST_TERM_CONN                    (0x16)
+
+#define ERR_UNSUPP_RMT_FEATURE                      (0x1A)
+
+#define ERR_INVALID_LMP_PARAM                       (0x1E)
+#define ERR_UNSPECIFIED_ERROR                       (0x1F)
+
+#define ERR_LL_RESP_TIMEOUT                         (0x22)
+#define ERR_LMP_PDU_NOT_ALLOWED                     (0x24)
+
+#define ERR_INSTANT_PASSED                          (0x28)
+
+#define ERR_PAIR_UNIT_KEY_NOT_SUPP                  (0x29)
+#define ERR_CONTROLLER_BUSY                         (0x3A)
+
+#define ERR_DIRECTED_ADV_TIMEOUT                    (0x3C)
+
+#define ERR_CONN_END_WITH_MIC_FAILURE               (0x3D)
+
+#define ERR_CONN_FAILED_TO_ESTABLISH                (0x3E)
+
+
+#define BLE_STATUS_FAILED             		(0x41)
+#define BLE_STATUS_INVALID_PARAMS     		(0x42)
+#define BLE_STATUS_BUSY               		(0x43)
+#define BLE_STATUS_INVALID_LEN_PDU    		(0x44)
+#define BLE_STATUS_PENDING            		(0x45)
+#define BLE_STATUS_NOT_ALLOWED        		(0x46)
+#define BLE_STATUS_ERROR              		(0x47)
+
+#define FLASH_READ_FAILED 					(0x49)
+#define FLASH_WRITE_FAILED 					(0x4A)
+#define FLASH_ERASE_FAILED 					(0x4B)
+
+#define BLE_STATUS_INVALID_CID         		(0x50)
+
+#define TIMER_NOT_VALID_LAYER				(0x54)
+#define TIMER_INSUFFICIENT_RESOURCES		(0x55)
+ 
+#define BLE_STATUS_CSRK_NOT_FOUND			(0x5A)
+#define BLE_STATUS_IRK_NOT_FOUND			(0x5B)
+#define BLE_STATUS_DEV_NOT_FOUND_IN_DB		(0x5C)
+#define BLE_STATUS_SEC_DB_FULL				(0x5D)
+#define BLE_STATUS_DEV_NOT_BONDED           (0x5E)
+ 
+#define BLE_STATUS_INVALID_HANDLE           (0x60)
+#define BLE_STATUS_INVALID_PARAMETER        (0x61)
+#define BLE_STATUS_OUT_OF_HANDLE            (0x62)
+#define BLE_STATUS_INVALID_OPERATION        (0x63)
+#define BLE_STATUS_INSUFFICIENT_RESOURCES   (0x64)
+#define BLE_INSUFFICIENT_ENC_KEYSIZE		(0x65)
+#define BLE_STATUS_CHARAC_ALREADY_EXISTS    (0x66)
+
+ /*
+  * Library Error Codes
+  */
+#define BLE_STATUS_TIMEOUT                     (0xFF)
+#define BLE_STATUS_PROFILE_ALREADY_INITIALIZED (0xF0)
+#define BLE_STATUS_NULL_PARAM                  (0xF1) 
+
+/**
+ * @}
+ */
+ 
+
+#endif /* __BLE_STATUS_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,28 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_hci.h
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file that includes commands and events for BlueNRG
+*                      FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_ACI_H__
+#define __BLUENRG_ACI_H__
+
+#include "bluenrg_aci_const.h"
+#include "bluenrg_gap_aci.h"
+#include "bluenrg_gatt_aci.h"
+#include "bluenrg_l2cap_aci.h"
+#include "bluenrg_hal_aci.h"
+#include "bluenrg_updater_aci.h"
+
+#endif /* __BLUENRG_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_aci_const.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_aci_const.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,467 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_aci_const.h
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with ACI definitions for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_ACI_CONST_H_
+#define __BLUENRG_ACI_CONST_H_
+
+#include "compiler.h"
+#include "link_layer.h"
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+
+#define OCF_HAL_WRITE_CONFIG_DATA   0x000C
+
+#define OCF_HAL_SET_TX_POWER_LEVEL          0x000F
+typedef __packed struct _hal_set_tx_power_level_cp{
+	uint8_t	en_high_power;
+    uint8_t pa_level;
+} PACKED hal_set_tx_power_level_cp;
+#define HAL_SET_TX_POWER_LEVEL_CP_SIZE 2
+
+#define OCF_HAL_DEVICE_STANDBY          0x0013
+
+#define OCF_HAL_TONE_START                  0x0015
+typedef __packed struct _hal_tone_start_cp{
+	uint8_t	rf_channel;
+} PACKED hal_tone_start_cp;
+#define HAL_TONE_START_CP_SIZE 1
+
+#define OCF_HAL_TONE_STOP                   0x0016
+
+#define OCF_UPDATER_START                   0x0020
+#define OCF_UPDATER_REBOOT                  0x0021
+
+#define OCF_GET_UPDATER_VERSION                 0x0022
+typedef __packed struct _get_updater_version_rp{
+    uint8_t		    status;
+	uint8_t		    version;
+} PACKED get_updater_version_rp;
+#define GET_UPDATER_VERSION_RP_SIZE 2
+
+#define OCF_GET_UPDATER_BUFSIZE             0x0023
+typedef __packed struct _get_updater_bufsize_rp{
+    uint8_t		    status;
+	uint8_t		    buffer_size;
+} PACKED get_updater_bufsize_rp;
+#define GET_UPDATER_BUFSIZE_RP_SIZE 2
+
+#define OCF_UPDATER_ERASE_BLUE_FLAG         0x0024
+
+#define OCF_UPDATER_RESET_BLUE_FLAG         0x0025
+
+#define OCF_UPDATER_ERASE_SECTOR            0x0026
+typedef __packed struct _updater_erase_sector_cp{
+	uint32_t	address;
+} PACKED updater_erase_sector_cp;
+#define UPDATER_ERASE_SECTOR_CP_SIZE 4
+
+#define OCF_UPDATER_PROG_DATA_BLOCK         0x0027
+/* Variable length parameters */
+
+#define OCF_UPDATER_READ_DATA_BLOCK         0x0028
+typedef __packed struct _updater_read_data_block_cp{
+	uint32_t	address;
+    uint16_t    data_len;
+} PACKED updater_read_data_block_cp;
+#define UPDATER_READ_DATA_BLOCK_CP_SIZE 6
+typedef __packed struct _updater_read_data_block_rp{
+    uint8_t		    status;
+	uint8_t		    data[0];
+} PACKED updater_read_data_block_rp;
+#define GET_UPDATER_BUFSIZE_RP_SIZE 2
+
+#define OCF_UPDATER_CALC_CRC                0x0029
+typedef __packed struct _updater_calc_crc_cp{
+	uint32_t	address;
+    uint8_t    num_sectors;
+} PACKED updater_calc_crc_cp;
+#define UPDATER_CALC_CRC_CP_SIZE 5
+typedef __packed struct _updater_calc_crc_rp{
+    uint8_t		    status;
+	uint32_t		crc;
+} PACKED updater_calc_crc_rp;
+#define UPDATER_CALC_CRC_RP_SIZE 5
+
+#define OCF_UPDATER_HW_VERSION              0x002A
+typedef __packed struct _updater_hw_version_rp{
+    uint8_t		    status;
+	uint8_t		    version;
+} PACKED updater_hw_version_rp;
+#define UPDATER_HW_VERSION_RP_SIZE 2
+
+#define OCF_GAP_SET_NON_DISCOVERABLE	    0x0081
+
+#define OCF_GAP_SET_LIMITED_DISCOVERABLE	0x0082
+
+#define OCF_GAP_SET_DISCOVERABLE	        0x0083
+
+#define OCF_GAP_SET_DIRECT_CONNECTABLE      0x0084
+typedef __packed struct _gap_set_direct_conectable_cp{
+    uint8_t		own_bdaddr_type;
+	uint8_t		direct_bdaddr_type;
+    tBDAddr		direct_bdaddr;
+} PACKED gap_set_direct_conectable_cp;
+#define GAP_SET_DIRECT_CONNECTABLE_CP_SIZE 8
+
+#define OCF_GAP_SET_IO_CAPABILITY      0x0085
+typedef __packed struct _gap_set_io_capability_cp{
+    uint8_t		io_capability;
+} PACKED gap_set_io_capability_cp;
+#define GAP_SET_IO_CAPABILITY_CP_SIZE 1
+
+#define OCF_GAP_SET_AUTH_REQUIREMENT      0x0086
+typedef __packed struct _gap_set_auth_requirement_cp{
+    uint8_t	mitm_mode;
+    uint8_t     oob_enable;
+    uint8_t     oob_data[16];
+    uint8_t     min_encryption_key_size;
+    uint8_t     max_encryption_key_size;
+    uint8_t     use_fixed_pin;
+    uint32_t    fixed_pin;
+    uint8_t     bonding_mode;
+} PACKED gap_set_auth_requirement_cp;
+#define GAP_SET_AUTH_REQUIREMENT_CP_SIZE 26
+
+#define OCF_GAP_SET_AUTHOR_REQUIREMENT      0x0087
+typedef __packed struct _gap_set_author_requirement_cp{
+  uint16_t      conn_handle;
+  uint8_t       authorization_enable;
+} PACKED gap_set_author_requirement_cp;
+#define GAP_SET_AUTHOR_REQUIREMENT_CP_SIZE 3
+
+#define OCF_GAP_PASSKEY_RESPONSE      0x0088
+typedef __packed struct _gap_passkey_response_cp{
+  uint16_t conn_handle;
+  uint32_t passkey;
+} PACKED gap_passkey_response_cp;
+#define GAP_PASSKEY_RESPONSE_CP_SIZE 6
+
+#define OCF_GAP_AUTHORIZATION_RESPONSE      0x0089
+typedef __packed struct _gap_authorization_response_cp{
+  uint16_t conn_handle;
+  uint8_t  authorize;
+} PACKED gap_authorization_response_cp;
+#define GAP_AUTHORIZATION_RESPONSE_CP_SIZE 3
+
+#define OCF_GAP_INIT		        0x008A
+typedef __packed struct _gap_init_cp{
+	uint8_t	role;
+} PACKED gap_init_cp;
+#define GAP_INIT_CP_SIZE 1
+typedef __packed struct _gap_init_rp{
+    uint8_t		    status;
+	uint16_t		service_handle;
+    uint16_t		dev_name_char_handle;
+    uint16_t		appearance_char_handle;
+} PACKED gap_init_rp;
+#define GAP_INIT_RP_SIZE 7
+
+#define OCF_GAP_SET_NON_CONNECTABLE      0x008B
+typedef __packed struct _gap_set_non_connectable_cp{
+    uint8_t	advertising_event_type;
+} PACKED gap_set_non_connectable_cp;
+#define GAP_SET_NON_CONNECTABLE_CP_SIZE 1
+
+#define OCF_GAP_SET_UNDIRECTED_CONNECTABLE      0x008C
+typedef __packed struct _gap_set_undirected_connectable_cp{
+    uint8_t	adv_filter_policy;
+    uint8_t	own_addr_type;
+} PACKED gap_set_undirected_connectable_cp;
+#define GAP_SET_UNDIRECTED_CONNECTABLE_CP_SIZE 2
+
+#define OCF_GAP_SLAVE_SECURITY_REQUEST      0x008D
+typedef __packed struct _gap_slave_security_request_cp{
+  uint16_t conn_handle;
+  uint8_t  bonding;
+  uint8_t  mitm_protection;
+} PACKED gap_slave_security_request_cp;
+#define GAP_SLAVE_SECURITY_REQUEST_CP_SIZE 4
+
+#define OCF_GAP_UPDATE_ADV_DATA      0x008E
+
+#define OCF_GAP_DELETE_AD_TYPE      0x008F
+typedef __packed struct _gap_delete_ad_type_cp{
+    uint8_t	ad_type;
+} PACKED gap_delete_ad_type_cp;
+#define GAP_DELETE_AD_TYPE_CP_SIZE 1
+
+#define OCF_GAP_GET_SECURITY_LEVEL      0x0090
+typedef __packed struct _gap_get_security_level_rp{
+    uint8_t		    status;
+	uint8_t		    mitm_protection;
+    uint8_t		    bonding;
+    uint8_t		    oob_data;
+    uint8_t         passkey_required;
+} PACKED gap_get_security_level_rp;
+#define GAP_GET_SECURITY_LEVEL_RP_SIZE 5
+
+#define OCF_GAP_SET_EVT_MASK      0x0091
+typedef __packed struct _gap_set_evt_mask_cp{
+    uint16_t	evt_mask;
+} PACKED gap_set_evt_mask_cp;
+#define GAP_SET_EVT_MASK_CP_SIZE 2
+
+#define OCF_GAP_CONFIGURE_WHITELIST   0x0092
+
+#define OCF_GAP_TERMINATE      0x0093
+typedef __packed struct _gap_terminate_cp{
+  uint16_t handle;
+  uint8_t  reason;
+} PACKED gap_terminate_cp;
+#define GAP_TERMINATE_CP_SIZE 3
+
+#define OCF_GAP_CLEAR_SECURITY_DB   0x0094
+
+#define OCF_GAP_ALLOW_REBOND_DB     0x0095
+
+#define OCF_GAP_START_LIMITED_DISCOVERY_PROC   0x0096
+typedef __packed struct _gap_start_limited_discovery_proc_cp{
+  uint16_t scanInterval;
+  uint16_t scanWindow;
+  uint8_t  own_address_type;
+  uint8_t  filterDuplicates;
+} PACKED gap_start_limited_discovery_proc_cp;
+#define GAP_START_LIMITED_DISCOVERY_PROC_CP_SIZE 6
+
+#define OCF_GAP_START_GENERAL_DISCOVERY_PROC   0x0097
+typedef __packed struct _gap_start_general_discovery_proc_cp{
+  uint16_t scanInterval;
+  uint16_t scanWindow;
+  uint8_t  own_address_type;
+  uint8_t  filterDuplicates;
+} PACKED gap_start_general_discovery_proc_cp;
+#define GAP_START_GENERAL_DISCOVERY_PROC_CP_SIZE 6
+
+#define OCF_GAP_START_AUTO_CONN_ESTABLISHMENT  0x0099
+
+#define OCF_GAP_CREATE_CONNECTION      0x009C
+typedef __packed struct _gap_create_connection_cp{
+  uint16_t scanInterval;
+  uint16_t scanWindow;
+  uint8_t peer_bdaddr_type;
+  tBDAddr peer_bdaddr;
+  uint8_t own_bdaddr_type;
+  uint16_t conn_min_interval;
+  uint16_t conn_max_interval;
+  uint16_t conn_latency;
+  uint16_t supervision_timeout;
+  uint16_t min_conn_length;
+  uint16_t max_conn_length;
+} PACKED gap_create_connection_cp;
+#define GAP_CREATE_CONNECTION_CP_SIZE 24
+
+#define OCF_GAP_TERMINATE_GAP_PROCEDURE      0x009D
+
+#define OCF_GAP_SEND_PAIRING_REQUEST      0x009F
+typedef __packed struct _gap_send_pairing_request_cp{
+  uint16_t conn_handle;
+  uint8_t force_rebond;
+} PACKED gap_send_pairing_request_cp;
+#define GAP_SEND_PAIRING_REQUEST_CP_SIZE 3
+
+#define OCF_GATT_INIT		        0x0101
+
+#define OCF_GATT_ADD_SERV		    0x0102
+typedef __packed struct _gatt_add_serv_rp{
+    uint8_t		    status;
+	uint16_t		handle;
+} PACKED gatt_add_serv_rp;
+#define GATT_ADD_SERV_RP_SIZE 3
+
+#define OCF_GATT_INCLUDE_SERV		0x0103
+typedef __packed struct _gatt_include_serv_rp{
+	uint8_t		    status;
+    uint16_t		handle;    
+} PACKED gatt_include_serv_rp;
+#define GATT_INCLUDE_SERV_RP_SIZE 3
+
+#define OCF_GATT_ADD_CHAR		    0x0104
+typedef __packed struct _gatt_add_char_rp{
+    uint8_t		    status;
+	uint16_t		handle;
+} PACKED gatt_add_char_rp;
+#define GATT_ADD_CHAR_RP_SIZE 3
+
+#define OCF_GATT_ADD_CHAR_DESC	    0x0105
+typedef __packed struct _gatt_add_char_desc_rp{
+    uint8_t		    status;
+	uint16_t		handle;
+} PACKED gatt_add_char_desc_rp;
+#define GATT_ADD_CHAR_DESC_RP_SIZE 3
+
+#define OCF_GATT_UPD_CHAR_VAL		0x0106
+
+#define OCF_GATT_DEL_CHAR   		0x0107
+typedef __packed struct _gatt_del_char_cp{
+	uint16_t	service_handle;
+	uint16_t	char_handle;
+} PACKED gatt_del_char_cp;
+#define GATT_DEL_CHAR_CP_SIZE 4
+
+#define OCF_GATT_DEL_SERV   		0x0108
+typedef __packed struct _gatt_del_serv_cp{
+	uint16_t	service_handle;
+} PACKED gatt_del_serv_cp;
+#define GATT_DEL_SERV_CP_SIZE 2
+
+#define OCF_GATT_DEL_INC_SERV   	0x0109
+typedef __packed struct _gatt_del_inc_serv_cp{
+	uint16_t	service_handle;
+    uint16_t	inc_serv_handle;
+} PACKED gatt_del_inc_serv_cp;
+#define GATT_DEL_INC_SERV_CP_SIZE 4
+
+#define OCF_GATT_SET_EVT_MASK      0x010A
+typedef __packed struct _gatt_set_evt_mask_cp{
+    uint32_t	evt_mask;
+} PACKED gatt_set_evt_mask_cp;
+#define GATT_SET_EVT_MASK_CP_SIZE 4
+
+#define OCF_GATT_EXCHANGE_CONFIG      0x010B
+typedef __packed struct _gatt_exchange_config_cp{
+    uint16_t	conn_handle;
+} PACKED gatt_exchange_config_cp;
+#define GATT_EXCHANGE_CONFIG_CP_SIZE 2
+
+#define OCF_GATT_FIND_INFO_REQ      0x010C
+typedef __packed struct _gatt_find_info_req_cp{
+    uint16_t	conn_handle;
+    uint16_t	start_handle;
+    uint16_t	end_handle;
+} PACKED gatt_find_info_req_cp;
+#define GATT_GATT_FIND_INFO_REQ_CP_SIZE 6
+
+#define OCF_GATT_DISC_ALL_PRIM_SERVICES 0X0112
+typedef __packed struct _gatt_disc_all_prim_serivces_cp{
+  uint16_t conn_handle;
+} PACKED gatt_disc_all_prim_services_cp;
+#define GATT_DISC_ALL_PRIM_SERVICES_CP_SIZE 2
+
+#define OCF_GATT_FIND_INCLUDED_SERVICES 0X0114
+typedef __packed struct _gatt_disc_find_included_services_cp{
+  uint16_t conn_handle;
+  uint16_t start_handle;
+  uint16_t end_handle;
+} PACKED gatt_find_included_services_cp;
+#define GATT_FIND_INCLUDED_SERVICES_CP_SIZE 6
+
+#define OCF_GATT_DISC_ALL_CHARAC_OF_SERV 0X0115
+typedef __packed struct _gatt_disc_all_charac_of_serv_cp{
+  uint16_t conn_handle;
+  uint16_t start_attr_handle;
+  uint16_t end_attr_handle;
+} PACKED gatt_disc_all_charac_of_serv_cp;
+#define GATT_DISC_ALL_CHARAC_OF_SERV_CP_SIZE 6
+
+#define OCF_GATT_DISC_CHARAC_BY_UUID 0X0116
+
+#define OCF_GATT_DISC_ALL_CHARAC_DESCRIPTORS 0X0117
+typedef __packed struct _gatt_disc_all_charac_descriptors_cp{
+  uint16_t conn_handle;
+  uint16_t char_val_handle;
+  uint16_t char_end_handle;
+} PACKED gatt_disc_all_charac_descriptors_cp;
+#define GATT_DISC_ALL_CHARAC_DESCRIPTORS_CP_SIZE 6
+
+#define OCF_GATT_READ_CHARAC_VAL   0x0118
+typedef __packed struct _gatt_read_charac_val_cp{
+  uint16_t conn_handle;
+  uint16_t attr_handle;
+} PACKED gatt_read_charac_val_cp;
+#define GATT_READ_CHARAC_VAL_CP_SIZE 4
+
+#define OCF_GATT_READ_LONG_CHARAC_VAL   0x011A
+typedef __packed struct _gatt_read_long_charac_val_cp{
+  uint16_t conn_handle;
+  uint16_t attr_handle;
+  uint16_t val_offset;
+} PACKED gatt_read_long_charac_val_cp;
+#define GATT_READ_LONG_CHARAC_VAL_CP_SIZE 6
+
+#define OCF_GATT_WRITE_CHAR_VALUE   0x011C
+#define OCF_GATT_WRITE_CHAR_DESCRIPTOR      0x0121
+
+#define OCF_GATT_READ_CHAR_DESCRIPTOR       0x0122
+
+#define OCF_GATT_WRITE_WITHOUT_RESPONSE     0x0123
+
+#define OCF_GATT_SIGNED_WRITE_WITHOUT_RESPONSE     0x0124
+
+#define OCF_GATT_CONFIRM_INDICATION                0x0125
+typedef __packed struct _gatt_confirm_indication_cp{
+	uint16_t	conn_handle;
+} PACKED gatt_confirm_indication_cp;
+#define GATT_CONFIRM_INDICATION_CP_SIZE 2
+
+#define OCF_GATT_WRITE_RESPONSE                    0x0126
+
+#define OCF_GATT_ALLOW_READ		    0x0127
+typedef __packed struct _gatt_allow_read_cp{
+	uint16_t	conn_handle;
+} PACKED gatt_allow_read_cp;
+#define GATT_ALLOW_READ_CP_SIZE 2
+
+#define OCF_GATT_SET_DESC_VAL		0x0129
+
+#define OCF_GATT_READ_HANDLE_VALUE      0x012A
+typedef __packed struct _gatt_read_handle_val_cp{
+	uint16_t	attr_handle;
+} PACKED gatt_read_handle_val_cp;
+#define GATT_READ_HANDLE_VALUE_CP_SIZE 2
+
+#define OCF_L2CAP_CONN_PARAM_UPDATE_REQ  0x0181
+typedef __packed struct _l2cap_conn_param_update_req_cp{
+  uint16_t conn_handle;
+  uint16_t interval_min;
+  uint16_t interval_max;
+  uint16_t slave_latency;
+  uint16_t timeout_multiplier;
+} PACKED l2cap_conn_param_update_req_cp;
+#define L2CAP_CONN_PARAM_UPDATE_REQ_CP_SIZE 10
+
+#define OCF_L2CAP_CONN_PARAM_UPDATE_RESP  0x0182
+typedef __packed struct _l2cap_conn_param_update_resp_cp{
+  uint16_t conn_handle;
+  uint16_t interval_min;
+  uint16_t interval_max;
+  uint16_t slave_latency;
+  uint16_t timeout_multiplier;
+  uint8_t id;
+  uint8_t accept;
+} PACKED l2cap_conn_param_update_resp_cp;
+#define L2CAP_CONN_PARAM_UPDATE_RESP_CP_SIZE 12
+
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
+/**
+ * @defgroup BlueNRG_Events BlueNRG events (vendor specific)
+ * @{
+ */
+
+/**
+ * Vendor specific event for BlueNRG.
+ */
+typedef __packed struct _evt_blue_aci{
+  uint16_t ecode; /**< One of the BlueNRG event codes. */
+  uint8_t  data[0];
+} PACKED evt_blue_aci;
+
+
+/**
+ * @}
+ */
+
+#endif /* __BLUENRG_ACI_CONST_H_ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_gap_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_gap_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,771 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_gap_aci.h
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with GAP commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_GAP_ACI_H__
+#define __BLUENRG_GAP_ACI_H__
+
+#include <sm.h>
+
+/**
+ *@defgroup GAP_Functions GAP functions
+ *@brief API for GAP layer.
+ *@{
+ */
+
+/**
+  * @brief  Initialize the GAP layer.
+  * @note   Register the GAP service with the GATT. If the role is peripheral,
+  *         all the standard GAP characteristic will be also added:
+  *         @li Device Name
+  *         @li Appearance
+  *         @li Peripheral Privacy Flag
+  *         @li Reconnection Address
+  *         @li Peripheral Preferred Connection Parameters
+  *         @code
+
+              tBleStatus ret;
+              uint16_t service_handle, dev_name_char_handle, appearance_char_handle;
+
+              ret = aci_gap_init(1, &service_handle, &dev_name_char_handle, &appearance_char_handle);
+              if(ret){
+                PRINTF("GAP_Init failed.\n");
+                reboot();    
+              }  
+              const char *name = "BlueNRG";  
+              ret = aci_gatt_update_char_value(service_handle, dev_name_char_handle, 0, strlen(name), (uint8_t *)name);        
+              if(ret){
+                PRINTF("aci_gatt_update_char_value failed.\n");
+              }  
+  *         @endcode
+  * @param       role     One of the allowed roles: PERIPHERAL or CENTRAL.
+  * @param[out]  service_handle  Handle of the GAP service.
+  * @param[out]  dev_name_char_handle  Device Name Characteristic handle
+  * @param[out]  appearance_char_handle Appearance Characteristic handle
+  * @retval tBleStatus Value indicating success or error code.
+  */
+tBleStatus aci_gap_init(uint8_t role,
+                 uint16_t* service_handle,
+                 uint16_t* dev_name_char_handle,
+                 uint16_t* appearance_char_handle);
+
+/**
+  * @brief   Set the Device in non-discoverable mode.
+  * @note    This command will disable the LL advertising.
+  * @retval  tBleStatus Value indicating success or error code.
+  */
+tBleStatus aci_gap_set_non_discoverable(void);
+
+/**
+ * @brief  Put the device in limited discoverable mode
+ *         (as defined in GAP specification volume 3, section 9.2.3).
+ * @note    The device will be discoverable for TGAP (lim_adv_timeout) = 180 seconds.
+ *          The advertising can be disabled at any time by issuing
+ *          aci_gap_set_non_discoverable() command.
+ *          The AdvIntervMin and AdvIntervMax parameters are optional. If both
+ *          are set to 0, the GAP will use default values (250 ms and 500 ms respectively).
+ *          Host can set the Local Name, a Service UUID list and the Slave Connection
+ *          Minimum and Maximum. If provided, these data will be inserted into the
+ *          advertising packet payload as AD data. These parameters are optional
+ *          in this command. These values can be also set using aci_gap_update_adv_data()
+ *          separately.
+ *          The total size of data in advertising packet cannot exceed 31 bytes.
+ *          With this command, the BLE Stack will also add automatically the following
+ *          standard AD types:
+ *          @li AD Flags
+ *          @li TX Power Level
+ *
+ *          When advertising timeout happens (i.e. limited discovery period has elapsed), controller generates
+ *          @ref EVT_BLUE_GAP_LIMITED_DISCOVERABLE event.
+ *
+ *          Example:
+ * @code
+ *
+ *              #define  ADV_INTERVAL_MIN_MS  100
+ *              #define  ADV_INTERVAL_MAX_MS  200
+ *
+ *              tBleStatus ret;
+ *
+ *              const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME,'B','l','u','e','N','R','G'};
+ *              const uint8_t serviceUUIDList[] = {AD_TYPE_16_BIT_SERV_UUID,0x34,0x12};
+ *
+ *              ret = aci_gap_set_limited_discoverable(ADV_IND, (ADV_INTERVAL_MIN_MS*1000)/0.625,
+ *                                                     (ADV_INTERVAL_MAX_MS*1000)/0.625,
+ *                                                     RANDOM_ADDR, NO_WHITE_LIST_USE,
+ *                                                    sizeof(local_name), local_name,
+ *                                                     sizeof(serviceUUIDList), serviceUUIDList,
+ *                                                     0, 0);
+ * @endcode
+ *
+ * @param       AdvType     One of the advertising types:
+ *               @arg @ref ADV_IND Connectable undirected advertising
+ *               @arg @ref ADV_SCAN_IND Scannable undirected advertising
+ *               @arg @ref ADV_NONCONN_IND Non connectable undirected advertising
+ * @param       AdvIntervMin     Minimum advertising interval
+ * @param       AdvIntervMax     Maximum advertising interval
+ * @param       OwnAddrType     Type of our address used during advertising
+ *                              (@ref PUBLIC_ADDR,@ref RANDOM_ADDR).
+ * @param       AdvFilterPolicy  Filter policy:
+ *                               @arg NO_WHITE_LIST_USE
+ *                               @arg WHITE_LIST_FOR_ONLY_SCAN
+ *                               @arg WHITE_LIST_FOR_ONLY_CONN
+ *                               @arg WHITE_LIST_FOR_ALL
+ * @param  LocalNameLen  Length of LocalName array.
+ * @param  LocalName  Array containing the Local Name AD data. First byte is the AD type:
+ *                       @ref AD_TYPE_SHORTENED_LOCAL_NAME or @ref AD_TYPE_COMPLETE_LOCAL_NAME.
+ * @param  ServiceUUIDLen Length of ServiceUUIDList array.
+ * @param  ServiceUUIDList  This is the list of the UUIDs AD Types as defined in Volume 3,
+ *  							Section 11.1.1 of GAP Specification. First byte is the AD Type.
+ *  							@arg @ref AD_TYPE_16_BIT_SERV_UUID
+ *  							@arg @ref AD_TYPE_16_BIT_SERV_UUID_CMPLT_LIST
+ *  							@arg @ref AD_TYPE_128_BIT_SERV_UUID
+ *  							@arg @ref AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST
+ * @param  SlaveConnIntervMin Slave connection interval minimum value suggested by Peripheral.
+ * 							 If SlaveConnIntervMin and SlaveConnIntervMax are not 0x0000,
+ * 							 Slave Connection Interval Range AD structure will be added in advertising
+ * 							 data.
+ * 							 Connection interval is defined in the following manner:
+ * 							 connIntervalmin = Slave_Conn_Interval_Min x 1.25ms
+ * 							 Slave_Conn_Interval_Min range: 0x0006 to 0x0C80
+ * 							 Value of 0xFFFF indicates no specific minimum.
+ * @param  SlaveConnIntervMax Slave connection interval maximum value suggested by Peripheral.
+ * 							 If SlaveConnIntervMin and SlaveConnIntervMax are not 0x0000,
+ * 							 Slave Connection Interval Range AD structure will be added in advertising
+ * 							 data.
+ * 							 ConnIntervalmax = Slave_Conn_Interval_Max x 1.25ms
+ * 							 Slave_Conn_Interval_Max range: 0x0006 to 0x0C80
+ * 							 Slave_ Conn_Interval_Max shall be equal to or greater than the Slave_Conn_Interval_Min.
+ * 							 Value of 0xFFFF indicates no specific maximum.
+ *
+ * @retval tBleStatus Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_limited_discoverable(uint8_t AdvType, uint16_t AdvIntervMin, uint16_t AdvIntervMax,
+					    uint8_t OwnAddrType, uint8_t AdvFilterPolicy, uint8_t LocalNameLen,
+					    const char *LocalName, uint8_t ServiceUUIDLen, uint8_t* ServiceUUIDList,
+					    uint16_t SlaveConnIntervMin, uint16_t SlaveConnIntervMax);
+/**
+ * @brief Put the Device in general discoverable mode (as defined in GAP specification volume 3, section 9.2.4).
+ * @note  The device will be discoverable until the Host issue Bluehci_Gap_Set_Non_Discoverable command.
+ * 		  The Adv_Interval_Min and Adv_Interval_Max parameters are optional. If both are set to 0, the GAP uses
+ * 		  the default values for advertising intervals (1.28 s and 2.56 s respectively).
+ * 		  Host can set the Local Name, a Service UUID list and the Slave Connection Interval Range. If provided,
+ * 		  these data will be inserted into the advertising packet payload as AD data. These parameters are optional
+ * 		  in this command. These values can be also set using aci_gap_update_adv_data() separately.
+ * 		  The total size of data in advertising packet cannot exceed 31 bytes.
+ * 		  With this command, the BLE Stack will also add automatically the following standard AD types:
+ * 		  @li AD Flags
+ * 		  @li TX Power Level
+ *
+ * 		  Usage example:
+ *
+ * 		  @code
+ *
+ *              #define  ADV_INTERVAL_MIN_MS  800
+ *              #define  ADV_INTERVAL_MAX_MS  900
+ *              #define  CONN_INTERVAL_MIN_MS 100
+ *              #define  CONN_INTERVAL_MAX_MS 300
+ *
+ *              tBleStatus ret;
+ *
+ *              const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME,'B','l','u','e','N','R','G'};
+ *              const uint8_t serviceUUIDList[] = {AD_TYPE_16_BIT_SERV_UUID,0x34,0x12};
+ *
+ *              ret = aci_gap_set_discoverable(ADV_IND, (ADV_INTERVAL_MIN_MS*1000)/0.625,
+ *                                                     (ADV_INTERVAL_MAX_MS*1000)/0.625,
+ *                                                     RANDOM_ADDR, NO_WHITE_LIST_USE,
+ *                                                     sizeof(local_name), local_name,
+ *                                                     0, NULL,
+ *                                                     (CONN_INTERVAL_MIN_MS*1000)/1250,
+ *                                                     (CONN_INTERVAL_MAX_MS*1000)/1250);
+ * 			@endcode
+ *
+ * @param AdvType One of the advertising types:
+ *                @arg @ref ADV_IND Connectable undirected advertising
+ *                @arg @ref ADV_SCAN_IND Scannable undirected advertising
+ *                @arg @ref ADV_NONCONN_IND Non connectable undirected advertising
+ * @param       AdvIntervMin     Minimum advertising interval
+ * @param       AdvIntervMax     Maximum advertising interval
+ * @param       OwnAddrType     Type of our address used during advertising
+ *                              (@ref PUBLIC_ADDR,@ref RANDOM_ADDR).
+ * @param       AdvFilterPolicy  Filter policy:
+ *                               @arg @ref NO_WHITE_LIST_USE
+ *                               @arg @ref WHITE_LIST_FOR_ONLY_SCAN
+ *                               @arg @ref WHITE_LIST_FOR_ONLY_CONN
+ *                               @arg @ref WHITE_LIST_FOR_ALL
+ * @param  LocalNameLen  Length of LocalName array.
+ * @param  LocalName  Array containing the Local Name AD data. First byte is the AD type:
+ *                       @ref AD_TYPE_SHORTENED_LOCAL_NAME or @ref AD_TYPE_COMPLETE_LOCAL_NAME.
+ * @param  ServiceUUIDLen Length of ServiceUUIDList array.
+ * @param  ServiceUUIDList  This is the list of the UUIDs AD Types as defined in Volume 3,
+ *  							Section 11.1.1 of GAP Specification. First byte is the AD Type.
+ *  							@arg @ref AD_TYPE_16_BIT_SERV_UUID
+ *  							@arg @ref AD_TYPE_16_BIT_SERV_UUID_CMPLT_LIST
+ *  							@arg @ref AD_TYPE_128_BIT_SERV_UUID
+ *  							@arg @ref AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST
+ * @param  SlaveConnIntervMin Slave connection interval minimum value suggested by Peripheral.
+ * 							 If SlaveConnIntervMin and SlaveConnIntervMax are not 0x0000,
+ * 							 Slave Connection Interval Range AD structure will be added in advertising
+ * 							 data.
+ * 							 Connection interval is defined in the following manner:
+ * 							 connIntervalmin = Slave_Conn_Interval_Min x 1.25ms
+ * 							 Slave_Conn_Interval_Min range: 0x0006 to 0x0C80
+ * 							 Value of 0xFFFF indicates no specific minimum.
+ * @param  SlaveConnIntervMax Slave connection interval maximum value suggested by Peripheral.
+ * 							 If SlaveConnIntervMin and SlaveConnIntervMax are not 0x0000,
+ * 							 Slave Connection Interval Range AD structure will be added in advertising
+ * 							 data.
+ * 							 ConnIntervalmax = Slave_Conn_Interval_Max x 1.25ms
+ * 							 Slave_Conn_Interval_Max range: 0x0006 to 0x0C80
+ * 							 Slave_ Conn_Interval_Max shall be equal to or greater than the Slave_Conn_Interval_Min.
+ * 							 Value of 0xFFFF indicates no specific maximum.
+ *
+ * @retval tBleStatus Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_discoverable(uint8_t AdvType, uint16_t AdvIntervMin, uint16_t AdvIntervMax,
+                             uint8_t OwnAddrType, uint8_t AdvFilterPolicy, uint8_t LocalNameLen,
+                             const char *LocalName, uint8_t ServiceUUIDLen, uint8_t* ServiceUUIDList,
+                             uint16_t SlaveConnIntervMin, uint16_t SlaveConnIntervMax);
+
+/**
+ * @brief Set the Device in direct connectable mode (as defined in GAP specification Volume 3, Section 9.3.3).
+ * @note  If the privacy is enabled, the reconnection address is used for advertising, otherwise the address
+ * 		  of the type specified in OwnAddrType is used. The device will be in directed connectable mode only
+ * 		  for 1.28 seconds. If no connection is established within this duration, the device enters non
+ * 		  discoverable mode and advertising will have to be again enabled explicitly.
+ * 		  The controller generates a @ref EVT_LE_CONN_COMPLETE event with the status set to @ref HCI_DIRECTED_ADV_TIMEOUT
+ * 		  if the connection was not established and 0x00 if the connection was successfully established.
+ *
+ * 		  Usage example:
+ * 		  @code
+ *
+ * 		  tBleStatus ret;
+ *
+ * 		  const uint8_t central_address = {0x43,0x27,0x84,0xE1,0x80,0x02};
+ * 		  ret = aci_gap_set_direct_connectable(PUBLIC_ADDR, PUBLIC_ADDR, central_address);
+ * 		  @endcode
+ *
+ *
+ *
+ * @param OwnAddrType  Type of our address used during advertising (@ref PUBLIC_ADDR,@ref RANDOM_ADDR).
+ * @param InitiatorAddrType Type of peer address (@ref PUBLIC_ADDR,@ref RANDOM_ADDR).
+ * @param InitiatorAddr     Initiator's address (Little Endian).
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_direct_connectable(uint8_t OwnAddrType, uint8_t InitiatorAddrType, const uint8_t *InitiatorAddr);
+
+/**
+ * @brief Set the IO capabilities of the device.
+ * @note This command has to be given only when the device is not in a connected state.
+ * @param io_capability One of the allowed codes for IO Capability:
+ * 		  @arg @ref IO_CAP_DISPLAY_ONLY
+ * 		  @arg @ref IO_CAP_DISPLAY_YES_NO
+ * 		  @arg @ref IO_CAP_KEYBOARD_ONLY
+ * 		  @arg @ref IO_CAP_NO_INPUT_NO_OUTPUT
+ * 		  @arg @ref IO_CAP_KEYBOARD_DISPLAY
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_io_capabilitiy(uint8_t io_capability);
+
+/**
+ * @brief Set the authentication requirements for the device.
+ * @note  If the oob_enable is set to 0, oob_data will be ignored.
+ *        This command has to be given only when the device is not in a connected state.
+ * @param mitm_mode MITM mode:
+ * 					@arg @ref MITM_PROTECTION_NOT_REQUIRED
+ * 					@arg @ref MITM_PROTECTION_REQUIRED
+ * @param oob_enable If OOB data are present or not:
+ * 					 @arg @ref OOB_AUTH_DATA_ABSENT
+ * 					 @arg @ref OOB_AUTH_DATA_PRESENT
+ * @param oob_data   Out-Of-Band data
+ * @param min_encryption_key_size Minimum size of the encryption key to be used during the pairing process
+ * @param max_encryption_key_size Maximum size of the encryption key to be used during the pairing process
+ * @param use_fixed_pin If application wants to use a fixed pin or not:
+ * 						@arg @ref USE_FIXED_PIN_FOR_PAIRING
+ * 						@arg @ref DONOT_USE_FIXED_PIN_FOR_PAIRING
+ * 						If a fixed pin is not used, it has to be provided by the application with
+ * 						aci_gap_pass_key_response() after @ref EVT_BLUE_GAP_PASS_KEY_REQUEST event.
+ * @param fixed_pin If use_fixed_pin is USE_FIXED_PIN_FOR_PAIRING, this is the value of the pin that will
+ * 					be used during pairing if MIMT protection is enabled. Any value between 0 to 999999 is
+ * 					accepted.
+ * @param bonding_mode One of the bonding modes:
+ * 					   @arg @ref BONDING
+ * 					   @arg @ref NO_BONDING
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_auth_requirement(uint8_t mitm_mode,
+                                        uint8_t oob_enable,
+                                        uint8_t oob_data[16],
+                                        uint8_t min_encryption_key_size,
+                                        uint8_t max_encryption_key_size,
+                                        uint8_t use_fixed_pin,
+                                        uint32_t fixed_pin,
+                                        uint8_t bonding_mode);
+ /**
+  * @brief Set the authorization requirements of the device.
+  * @note This command has to be given only when the device is not in a connected state.
+  * @param conn_handle Handle of the connection in case BlueNRG is configured as a master (otherwise it can be also 0).
+  * @param authorization_enable @arg @ref AUTHORIZATION_NOT_REQUIRED : Authorization not required
+  * 							@arg @ref AUTHORIZATION_REQUIRED : Authorization required. This enables
+  * 							the authorization requirement in the device and when a remote device
+  * 							tries to connect to GATT server, @ref EVT_BLUE_GAP_AUTHORIZATION_REQUEST event
+  * 							will be sent to the Host.
+  *
+  * @return Value indicating success or error code.
+  */
+tBleStatus aci_gap_set_author_requirement(uint16_t conn_handle, uint8_t authorization_enable);
+
+/**
+ * @brief Provide the pass key that will be used during pairing.
+ * @note This command should be sent by the Host in response to @ref EVT_BLUE_GAP_PASS_KEY_REQUEST event.
+ * @param conn_handle Connection handle
+ * @param passkey	  Pass key that will be used during the pairing process. Must be a number between
+ * 					  0 and 999999.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_pass_key_response(uint16_t conn_handle, uint32_t passkey);
+
+/**
+ * @brief Authorize a device to access attributes.
+ * @note Application should send this command after it has received a @ref EVT_BLUE_GAP_AUTHORIZATION_REQUEST.
+ *
+ * @param conn_handle Connection handle
+ * @param authorize   @arg @ref CONNECTION_AUTHORIZED : Authorize (accept connection)
+ * 					  @arg @ref CONNECTION_REJECTED : Reject (reject connection)
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_authorization_response(uint16_t conn_handle, uint8_t authorize);
+
+/**
+ * @brief Put the device into non-connectable mode.
+ * @param adv_type One of the allowed advertising types:
+ *                 @arg @ref ADV_SCAN_IND : Scannable undirected advertising
+ *                 @arg @ref ADV_NONCONN_IND : Non-connectable undirected advertising
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_non_connectable(uint8_t adv_type);
+
+/**
+ * @brief Put the device into undirected connectable mode.
+ * @note  If privacy is enabled in the device, a resolvable private address is generated and used
+ *        as the advertiser's address. If not, the address of the type specified in own_addr_type
+ *        is used for advertising.
+ * @param own_addr_type Type of our address used during advertising:
+ * 			@arg @ref PUBLIC_ADDR.
+ * 			@arg @ref RANDOM_ADDR.
+ * @param adv_filter_policy  Filter policy:
+ *                         @arg @ref NO_WHITE_LIST_USE
+ *                         @arg @ref WHITE_LIST_FOR_ALL
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_set_undirected_connectable(uint8_t own_addr_type, uint8_t adv_filter_policy);
+
+/**
+ * @brief Send a slave security request to the master.
+ * @note This command has to be issued to notify the master of the security requirements of the slave.
+ * 		 The master may encrypt the link, initiate the pairing procedure, or reject the request.
+ * @param conn_handle Connection handle
+ * @param bonding	   One of the bonding modes:
+ * 					   @arg @ref BONDING
+ * 					   @arg @ref NO_BONDING
+ * @param mitm_protection  If MITM protection is required or not:
+ * 						   @arg @ref MITM_PROTECTION_NOT_REQUIRED
+ * 					       @arg @ref MITM_PROTECTION_REQUIRED
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_slave_security_request(uint16_t conn_handle, uint8_t bonding, uint8_t mitm_protection);
+
+/**
+ * @brief Update advertising data.
+ * @note This command can be used to update the advertising data for a particular AD type.
+ *       If the AD type specified does not exist, then it is added to the advertising data.
+ *       If the overall advertising data length is more than 31 octets after the update, then
+ *       the command is rejected and the old data is retained.
+ * @param AdvLen Length of AdvData array
+ * @param AdvData Advertisement Data,  formatted as specified in Bluetooth specification
+ *        (Volume 3, Part C, 11), including data length. It can contain more than one AD type.
+ *        Example
+ * @code
+ *  tBleStatus ret;
+ *  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME,'B','l','u','e','N','R','G'};
+ *  const uint8_t serviceUUIDList[] = {AD_TYPE_16_BIT_SERV_UUID,0x34,0x12};
+ *  const uint8_t manuf_data[] = {4, AD_TYPE_MANUFACTURER_SPECIFIC_DATA, 0x05, 0x02, 0x01};
+ *
+ *  ret = aci_gap_set_discoverable(ADV_IND, 0, 0, RANDOM_ADDR, NO_WHITE_LIST_USE,
+ *                                 8, local_name, 3, serviceUUIDList, 0, 0);
+ *  ret = aci_gap_update_adv_data(5, manuf_data);
+ * @endcode
+ *
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_update_adv_data(uint8_t AdvLen, uint8_t *AdvData);
+
+/**
+ * @brief Add addresses of bonded devices into the controller's whitelist.
+ * @note  The command will return an error if there are no devices in the database or if it was unable
+ * 		  to add the device into the whitelist.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_configure_whitelist(void);
+
+/**
+ * @brief Terminate a connection.
+ * @note  A @ref EVT_DISCONN_COMPLETE event will be generated when the link is disconnected.
+ * @param conn_handle Connection handle
+ * @param reason  Reason for requesting disconnection. The error code can be any of ones as specified
+ * 				  for the disconnected command in the HCI specification (See @ref HCI_Error_codes).
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_terminate(uint16_t conn_handle, uint8_t reason);
+
+/**
+ * @brief Clear the security database.
+ * @note  All the devices in the security database will be removed.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_clear_security_database(void);
+
+/**
+ * @brief Allows the security manager to complete the pairing procedure and re-bond with the master.
+ * @note This command can be issued by the application if a @ref EVT_BLUE_GAP_BOND_LOST event is generated.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_allow_rebond(void);
+
+/**
+ * @brief Start the limited discovery procedure.
+ * @note  The controller is commanded to start active scanning. When this procedure is started,
+ *        only the devices in limited discoverable mode are returned to the upper layers.
+ *        The procedure is terminated when either the upper layers issue a command to terminate the
+ *        procedure by issuing the command aci_gap_terminate_gap_procedure() with the procedure code
+ *        set to @ref GAP_LIMITED_DISCOVERY_PROC or a timeout happens. When the procedure is terminated
+ *        due to any of the above  reasons, @ref EVT_BLUE_GAP_PROCEDURE_COMPLETE event is returned with
+ *        the procedure code set to @ref GAP_LIMITED_DISCOVERY_PROC.
+ *        The device found when the procedure is ongoing is returned to the upper layers through the
+ *        event @ref EVT_BLUE_GAP_DEVICE_FOUND.
+ * @param scanInterval Time interval from when the Controller started its last LE scan until it begins
+ * 					   the subsequent LE scan. The scan interval should be a number in the range
+ * 					   0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					   For a number N, Time = N x 0.625 msec.
+ * @param scanWindow Amount of time for the duration of the LE scan. Scan_Window shall be less than
+ * 					 or equal to Scan_Interval. The scan window should be a number in the range
+ * 					 0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					 For a number N, Time = N x 0.625 msec.
+ * @param own_address_type Type of our address used during advertising (@ref PUBLIC_ADDR, @ref RANDOM_ADDR).
+ * @param filterDuplicates Duplicate filtering enabled or not.
+ * 						   @arg 0x00: Do not filter the duplicates
+ * 						   @arg 0x01: Filter duplicates
+ *
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_start_limited_discovery_proc(uint16_t scanInterval, uint16_t scanWindow,
+						uint8_t own_address_type, uint8_t filterDuplicates);
+
+/**
+ * @brief Start the general discovery procedure.
+ * @note  The controller is commanded to start active scanning. The procedure is terminated when
+ * 		  either the upper layers issue a command to terminate the procedure by issuing the command
+ * 		  aci_gap_terminate_gap_procedure() with the procedure code set to GAP_GENERAL_DISCOVERY_PROC
+ * 		  or a timeout happens. When the procedure is terminated due to any of the above reasons,
+ * 		  @ref EVT_BLUE_GAP_PROCEDURE_COMPLETE event is returned with the procedure code set to
+ * 		  @ref GAP_GENERAL_DISCOVERY_PROC. The device found when the procedure is ongoing is returned to
+ * 		  the upper layers through the event @ref EVT_BLUE_GAP_DEVICE_FOUND.
+ * @param scanInterval Time interval from when the Controller started its last LE scan until it begins
+ * 					   the subsequent LE scan. The scan interval should be a number in the range
+ * 					   0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					   For a number N, Time = N x 0.625 msec.
+ * @param scanWindow Amount of time for the duration of the LE scan. Scan_Window shall be less than
+ * 					 or equal to Scan_Interval. The scan window should be a number in the range
+ * 					 0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					 For a number N, Time = N x 0.625 msec.
+ * @param own_address_type Type of our address used during advertising (@ref PUBLIC_ADDR, @ref RANDOM_ADDR).
+ * @param filterDuplicates Duplicate filtering enabled or not.
+ * 						   @arg 0x00: Do not filter the duplicates
+ * 						   @arg 0x01: Filter duplicates
+ *
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_start_general_discovery_proc(uint16_t scanInterval, uint16_t scanWindow,
+						uint8_t own_address_type, uint8_t filterDuplicates);
+
+/**
+ * @brief Start the auto connection establishment procedure.
+ * @note The devices specified are added to the white list of the controller and a LE_Create_Connection
+ * 		 call will be made to the controller by GAP with the initiator filter policy set to
+ * 		 “use whitelist to determine which advertiser to connect to”. When a command is issued to
+ * 		 terminate the procedure by upper layer, a LE_Create_Connection_Cancel call will be made to the
+ * 		 controller by GAP.
+ * 		 The procedure is terminated when either a connection is successfully established with one of
+ * 		 the specified devices in the white list or the procedure is explicitly terminated by issuing
+ * 		 the command aci_gap_terminate_gap_procedure() with the procedure code set to
+ * 		 @ref GAP_AUTO_CONNECTION_ESTABLISHMENT_PROC. A @ref EVT_BLUE_GAP_PROCEDURE_COMPLETE event is returned with
+ * 		 the procedure code set to @ref GAP_AUTO_CONNECTION_ESTABLISHMENT_PROC.
+ * @param scanInterval Time interval from when the Controller started its last LE scan until it begins
+ * 					   the subsequent LE scan. The scan interval should be a number in the range
+ * 					   0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					   For a number N, Time = N x 0.625 msec.
+ * @param scanWindow Amount of time for the duration of the LE scan. Scan_Window shall be less than
+ * 					 or equal to Scan_Interval. The scan window should be a number in the range
+ * 					 0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					 For a number N, Time = N x 0.625 msec.
+ * @param own_bdaddr_type Type of our address used during advertising (PUBLIC_ADDR,RANDOM_ADDR).
+ * @param conn_min_interval Minimum value for the connection event interval. This shall be less than or
+ * 							equal to Conn_Interval_Max.\n
+ * 							Range: 0x0006 to 0x0C80\n
+ * 							Time = N x 1.25 msec\n
+ * 							Time Range: 7.5 msec to 4 seconds
+ * @param conn_max_interval Maximum value for the connection event interval. This shall be greater than or
+ * 							equal to Conn_Interval_Min.\n
+ * 							Range: 0x0006 to 0x0C80\n
+ * 							Time = N x 1.25 msec\n
+ * 							Time Range: 7.5 msec to 4 seconds
+ * @param conn_latency Slave latency for the connection in number of connection events.\n
+ * 						 Range: 0x0000 to 0x01F4
+ * @param supervision_timeout Supervision timeout for the LE Link.\n
+ * 							  Range: 0x000A to 0x0C80\n
+ * 							  Time = N x 10 msec\n
+ * 							  Time Range: 100 msec to 32 seconds
+ * @param min_conn_length Minimum length of connection needed for the LE connection.\n
+ * 						  Range: 0x0000 - 0xFFFF\n
+ * 						  Time = N x 0.625 msec.
+ * @param max_conn_length Maximum length of connection needed for the LE connection.\n
+ * 						  Range: 0x0000 - 0xFFFF\n
+ * 						  Time = N x 0.625 msec.
+ * @param num_whitelist_entries Number of devices that have to be added to the whitelist.
+ * @param addr_array addr_array will contain the addresses that have to be added into the whitelist. The
+ * 					 format of the addr_array should be: address type followed by address.
+ * 					 Example:
+ * 					 @code
+ * 					 uint8_t addr_array[] = {PUBLIC_ADDR,0x01,0x00,0x00,0xe1,0x80,0x02,
+ * 					 	PUBLIC_ADDR,0x02,0x00,0x00,0xe1,0x80,0x02}
+ * 					 @endcode
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_start_auto_conn_establishment(uint16_t scanInterval, uint16_t scanWindow,
+						 uint8_t own_bdaddr_type, uint16_t conn_min_interval,	
+						 uint16_t conn_max_interval, uint16_t conn_latency,	
+						 uint16_t supervision_timeout, uint16_t min_conn_length, 
+						 uint16_t max_conn_length, uint8_t num_whitelist_entries,
+						 uint8_t *addr_array);
+
+/**
+ * @brief Start the direct connection establishment procedure.
+ * @note  A LE_Create_Connection call will be made to the controller by GAP with the initiator filter
+ * 		  policy set to “ignore whitelist and process connectable advertising packets only for the
+ * 		  specified device”. The procedure can be terminated explicitly by the upper layer by issuing
+ * 		  the command aci_gap_terminate_gap_procedure(). When a command is issued to terminate the
+ * 		  procedure by upper layer, a LE_Create_Connection_Cancel call will be made to the controller
+ * 		  by GAP.
+ * 		  On termination of the procedure, a @ref EVT_LE_CONN_COMPLETE event is returned. The procedure can
+ * 		  be explicitly terminated by the upper layer by issuing the command
+ * 		  aci_gap_terminate_gap_procedure() with the procedure_code set to @ref GAP_DIRECT_CONNECTION_ESTABLISHMENT_PROC.
+ * @param scanInterval Time interval from when the Controller started its last LE scan until it begins
+ * 					   the subsequent LE scan. The scan interval should be a number in the range
+ * 					   0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					   For a number N, Time = N x 0.625 msec.
+ * @param scanWindow Amount of time for the duration of the LE scan. Scan_Window shall be less than
+ * 					 or equal to Scan_Interval. The scan window should be a number in the range
+ * 					 0x0004 to 0x4000. This corresponds to a time range 2.5 msec to 10240 msec.
+ * 					 For a number N, Time = N x 0.625 msec.
+ * @param peer_bdaddr_type Type of the peer address (@ref PUBLIC_ADDR, @ref RANDOM_ADDR).
+ * @param peer_bdaddr Address of the peer device with which a connection has to be established.
+ * @param own_bdaddr_type Type of our address used during advertising (PUBLIC_ADDR,RANDOM_ADDR).
+ * @param conn_min_interval Minimum value for the connection event interval. This shall be less than or
+ * 							equal to Conn_Interval_Max.\n
+ * 							Range: 0x0006 to 0x0C80\n
+ * 							Time = N x 1.25 msec\n
+ * 							Time Range: 7.5 msec to 4 seconds
+ * @param conn_max_interval Maximum value for the connection event interval. This shall be greater than or
+ * 							equal to Conn_Interval_Min.\n
+ * 							Range: 0x0006 to 0x0C80\n
+ * 							Time = N x 1.25 msec\n
+ * 							Time Range: 7.5 msec to 4 seconds
+ * @param conn_latency Slave latency for the connection in number of connection events.\n
+ * 						 Range: 0x0000 to 0x01F4
+ * @param supervision_timeout Supervision timeout for the LE Link.\n
+ * 							  Range: 0x000A to 0x0C80\n
+ * 							  Time = N x 10 msec\n
+ * 							  Time Range: 100 msec to 32 seconds
+ * @param min_conn_length Minimum length of connection needed for the LE connection.\n
+ * 						  Range: 0x0000 - 0xFFFF\n
+ * 						  Time = N x 0.625 msec.
+ * @param max_conn_length Maximum length of connection needed for the LE connection.\n
+ * 						  Range: 0x0000 - 0xFFFF\n
+ * 						  Time = N x 0.625 msec.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_create_connection(uint16_t scanInterval, uint16_t scanWindow,
+				     uint8_t peer_bdaddr_type, tBDAddr peer_bdaddr,	
+				     uint8_t own_bdaddr_type, uint16_t conn_min_interval,	
+				     uint16_t conn_max_interval, uint16_t conn_latency,	
+				     uint16_t supervision_timeout, uint16_t min_conn_length, 
+				     uint16_t max_conn_length);
+
+/**
+ * @brief Terminate the specified GATT procedure. @ref EVT_BLUE_GAP_PROCEDURE_COMPLETE event is
+ *  	  returned with the procedure code set to the corresponding procedure.
+ * @param procedure_code One of the procedure codes (gap_procedure_codes).
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_terminate_gap_procedure(uint8_t procedure_code);
+
+/**
+ * @brief Send the SM pairing request to start a pairing process.
+ *        The authentication requirements and IO capabilities should be set
+ *        before issuing this command using the Bluehci_Set_IO_Capabilities
+ *        and Bluehci_Set_Authentication_Requirements commands.
+ *
+ * @param conn_handle Handle of the connection for which the pairing request has
+ *                    to be sent.
+ *
+ * @param force_rebond 0x00: Pairing request is sent only if the device has not
+ *                           previously bonded
+ *                     0x01: Pairing request will be sent even if the device was
+ *                           previously bonded
+ *
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gap_send_pairing_request(uint16_t conn_handle, uint8_t force_rebond);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup GAP_Events GAP events
+ * @{
+ */
+
+/**
+ * This event is generated by the controller when the limited discoverable
+ *  mode ends due to timeout (180 seconds)
+ */
+#define EVT_BLUE_GAP_LIMITED_DISCOVERABLE     (0x0400)
+
+
+/**
+ * This event is generated when the pairing process has completed successfully
+ * or a pairing procedure timeout has occurred or the pairing has failed.
+ * This is to notify the application that we have paired with a remote device
+ * so that it can take further actions or to notify that a timeout has occurred
+ *  so that the upper layer can decide to disconnect the link. See @ref evt_gap_pairing_cmplt.
+ */
+#define EVT_BLUE_GAP_PAIRING_CMPLT                (0x0401)
+typedef __packed struct _evt_gap_pairing_cmplt{
+  uint16_t conn_handle; /**< Connection handle on which the pairing procedure completed */
+  /**
+   * 0x00: Pairing Success. Pairing with a remote device was successful\n
+   * 0x01: Pairing Timeout. The SMP timeout has elapsed and no further SMP commands will be processed until reconnection\n
+   * 0x02: Pairing Failed. The pairing failed with the remote device.
+   */
+  uint8_t  status;
+} PACKED evt_gap_pairing_cmplt;
+
+
+/**
+ * This event is generated by the Security manager to the application when a pass key is required for pairing.
+ * When this event is received, the application has to respond with the aci_gap_pass_key_response() command.
+ */
+#define EVT_BLUE_GAP_PASS_KEY_REQUEST             (0x0402)
+typedef __packed struct _evt_gap_pass_key_req{
+  uint16_t conn_handle; /**< Connection handle for which the passkey has been requested. */
+} PACKED evt_gap_pass_key_req;
+
+
+/**
+ * This event is generated by the Security manager to the application when the application
+ * has set that authorization is required for reading/writing of attributes. This event will
+ * be generated as soon as the pairing is complete. When this event is received,
+ * aci_gap_authorization_response() command should be used by the application.
+ */
+#define EVT_BLUE_GAP_AUTHORIZATION_REQUEST        (0x0403)
+typedef __packed struct _evt_gap_author_req{
+  uint16_t conn_handle; /**< Connection handle for which authorization has been requested. */
+} PACKED evt_gap_author_req;
+
+/**
+ * This event is generated when the slave security request is successfully sent to the master.
+ */
+#define EVT_BLUE_GAP_SLAVE_SECURITY_INITIATED     (0X0404)
+
+/**
+ * This event is generated when a pairing request is issued in response to a slave security
+ * request from a master which has previously bonded with the slave. When this event is received,
+ * the upper layer has to issue the command aci_gap_allow_rebond() in order to allow the slave
+ * to continue the pairing process with the master.
+ */
+#define EVT_BLUE_GAP_BOND_LOST                    (0X0405)
+
+/**
+ * The event is given by the GAP layer to the upper layers when a device is discovered during scanning
+ * as a consequence of one of the GAP procedures started by the upper layers. See @ref evt_gap_device_found.
+ */
+#define EVT_BLUE_GAP_DEVICE_FOUND                 (0x0406)
+#ifndef BLUENRG_FW_6_4
+typedef __packed struct _evt_gap_device_found{
+  uint8_t peer_address_type; /**< Type of the peer address (@ref PUBLIC_ADDR, @ref RANDOM_ADDR). */
+  uint8_t peer_address[6];   /**< Address of the peer device found during scanning. */
+} PACKED evt_gap_device_found;
+#else
+typedef __packed struct _evt_gap_device_found{
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+  	uint8_t		evt_type;
+	uint8_t		bdaddr_type;  /**< Type of the peer address (@ref PUBLIC_ADDR, @ref RANDOM_ADDR). */
+	tBDAddr	    bdaddr;       /**< Address of the peer device found during scanning. */
+	uint8_t		length;       /**< Lenght of advertising or scan response data. */
+	uint8_t		data_RSSI[VARIABLE_SIZE]; /**< Advertising or scan response data + RSSI. RSSI is last octect (signed integer). */
+} PACKED evt_gap_device_found;
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+#endif
+
+/**
+ * This event is sent by the GAP to the upper layers when a procedure previously started has been terminated
+ * by the upper layer or has completed for any other reason. See @ref evt_gap_procedure_complete.
+ */
+#define EVT_BLUE_GAP_PROCEDURE_COMPLETE           (0x0407)
+typedef __packed struct _evt_gap_procedure_complete{
+  uint8_t procedure_code; /**< Terminated procedure. See @ref gap_procedure_codes. */
+  /**
+   * @ref BLE_STATUS_SUCCESS, @ref BLE_STATUS_FAILED or @ref ERR_AUTH_FAILURE (procedure failed
+   * due to authentication requirements).
+   */
+  uint8_t status;
+  /**
+   * Procedure specific data.\n
+   * @li For Name Discovery Procedure:\n
+   * the name of the peer device if the procedure completed successfully.
+   * @li For General Connection Establishment Procedure:\n
+   * The reconnection address written to the peripheral device if the peripheral is privacy enabled
+   */
+  uint8_t data[VARIABLE_SIZE];
+} PACKED evt_gap_procedure_complete;
+
+/**
+ * This event is raised when the reconnection address is generated during the general connection
+ * establishment procedure. The same address is set to the peer device also as a part of the general
+ * connection establishment procedure. In order to make use of the reconnection address the next time
+ * while connecting to the bonded peripheral, the application needs to use this reconnection address
+ * as its own address as well as the peer address to which it wants to connect.
+ */
+#define EVT_BLUE_GAP_RECONNECTION_ADDRESS           (0x0408)
+typedef __packed struct _evt_gap_reconnection_addr{
+  uint8_t reconnection_address[6];
+} PACKED evt_gap_reconnection_addr;
+
+/**
+ * @}
+ */
+
+
+#endif /* __BLUENRG_GAP_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_gatt_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_gatt_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,755 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_gatt_aci.h
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with GATT commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_GATT_ACI_H__
+#define __BLUENRG_GATT_ACI_H__
+
+#include "gatt_server.h"
+
+/**
+ *@defgroup GATT_Functions GATT functions
+ *@brief API for GATT layer.
+ *@{
+ */
+
+/**
+  * @brief  Initialize the GATT layer for server and client roles.
+  * @note   It adds also the GATT service with Service Changed Characteristic.
+ *           Until this command is issued the GATT channel will not process any commands
+  *          even if the connection is opened. This command has to be given
+  *          before using any of the GAP features.
+  * @return Value indicating success or error code.
+  */
+tBleStatus aci_gatt_init(void);
+
+/**
+ * @brief Add a service to the GATT Server. When a service is created in the server, the Host needs
+ *        to reserve the handle ranges for this service using max_attr_records parameter. This
+ *        parameter specifies the maximum number of attribute records that can be added to this
+ *        service (including the service attribute, include attribute, characteristic attribute,
+ *        characteristic value attribute and characteristic descriptor attribute). Handle of the
+ *        created service is returned.
+ * @param service_uuid_type Type of service UUID (16-bit or 128-bit). See @ref UUID_Types.
+ * @param[in] service_uuid 16-bit or 128-bit UUID based on the UUID Type field
+ * @param service_type Primary or secondary service. See @ref Service_type.
+ * @param max_attr_records Maximum number of attribute records that can be added to this service
+ * @param[out] serviceHandle Handle of the Service. When this service is added to the service,
+ * 							 a handle is allocated by the server to this service. Server also
+ * 							 allocates a range of handles for this service from serviceHandle to
+ * 							 <serviceHandle + max_attr_records>.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_add_serv(uint8_t service_uuid_type,
+			     const uint8_t* service_uuid,
+			     uint8_t service_type,
+			     uint8_t max_attr_records,
+			     uint16_t *serviceHandle);
+
+/**
+ * @brief Include a service given by included_start_handle and included_end_handle to another service
+ * 		  given by service_handle. Attribute server creates an INCLUDE definition attribute and return
+ * 		  the handle of this attribute in included_handle.
+ * @param service_handle Handle of the service to which another service has to be included
+ * @param included_start_handle Start Handle of the service which has to be included in service
+ * @param included_end_handle End Handle of the service which has to be included in service
+ * @param included_uuid_type Type of UUID for included service (16-bit or 128-bit). See @ref UUID_Types.
+ * @param[in] included_uuid 16-bit or 128-bit UUID.
+ * @param[out] included_handle Handle of the include declaration.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_include_service(uint16_t service_handle, uint16_t included_start_handle,
+				    uint16_t included_end_handle, uint8_t included_uuid_type,
+				    const uint8_t* included_uuid, uint16_t *included_handle);
+
+/**
+ * @brief Add a characteristic to a service.
+ * @param serviceHandle Handle of the service to which the characteristic has to be added.
+ * @param charUuidType Type of characteristic UUID (16-bit or 128-bit). See @ref UUID_Types.
+ *         @arg @ref UUID_TYPE_16
+ *         @arg @ref UUID_TYPE_128
+ * @param charUuid 16-bit or 128-bit UUID.
+ * @param charValueLen Maximum length of the characteristic value.
+ * @param charProperties Bitwise OR values of Characteristic Properties (defined in Volume 3,
+ *        Section 3.3.3.1 of Bluetooth Specification 4.0). See @ref Char_properties.
+ * @param secPermissions Security permissions for the added characteristic. See @ref Security_permissions.
+ * 			@arg ATTR_PERMISSION_NONE
+ * 			@arg ATTR_PERMISSION_AUTHEN_READ
+ * 			@arg ATTR_PERMISSION_AUTHOR_READ
+ * 			@arg ATTR_PERMISSION_ENCRY_READ
+ * 			@arg ATTR_PERMISSION_AUTHEN_WRITE
+ * 			@arg ATTR_PERMISSION_AUTHOR_WRITE
+ * 			@arg ATTR_PERMISSION_ENCRY_WRITE
+ * @param gattEvtMask Bit mask that enables events that will be sent to the application by the GATT server
+ * 					  on certain ATT requests. See @ref Gatt_Event_Mask.
+ * 		   @arg GATT_DONT_NOTIFY_EVENTS
+ * 		   @arg GATT_NOTIFY_ATTRIBUTE_WRITE
+ * 		   @arg GATT_NOTIFY_WRITE_REQ_AND_WAIT_FOR_APPL_RESP
+ * 		   @arg GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP
+ * @param encryKeySize The minimum encryption key size requirement for this attribute. Valid Range: 7 to 16.
+ * @param isVariable If the attribute has a variable length value field (1) or not (0).
+ * @param charHandle Handle of the Characteristic that has been added. It is the handle of the characteristic declaration.
+ * 		  The attribute that holds the characteristic value is allocated at the next handle, followed by the Client
+ * 		  Characteristic Configuration descriptor if the characteristic has @ref CHAR_PROP_NOTIFY or @ref CHAR_PROP_INDICATE
+ * 		  properties.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_add_char(uint16_t serviceHandle,
+			     uint8_t charUuidType,
+			     const uint8_t* charUuid, 
+			     uint8_t charValueLen, 
+			     uint8_t charProperties,
+			     uint8_t secPermissions,
+			     uint8_t gattEvtMask,
+			     uint8_t encryKeySize,
+			     uint8_t isVariable,
+			     uint16_t* charHandle);
+
+/**
+ * Add a characteristic descriptor to a service.
+ * @param serviceHandle Handle of the service to which the characteristic belongs
+ * @param charHandle Handle of the characteristic to which description has to be added.
+ * @param descUuidType 16-bit or 128-bit UUID. See @ref UUID_Types.
+ *         @arg @ref UUID_TYPE_16
+ *         @arg @ref UUID_TYPE_128
+ * @param[in] uuid UUID of the Characteristic descriptor. It can be one of the UUID assigned by Bluetooth SIG
+ * 		(Well_known_UUIDs) or a user-defined one.
+ * @param descValueMaxLen The maximum length of the descriptor value
+ * @param descValueLen Current Length of the characteristic descriptor value
+ * @param[in] descValue Value of the characteristic description
+ * @param secPermissions Security permissions for the added descriptor. See @ref Security_permissions.
+ * 			@arg ATTR_PERMISSION_NONE
+ * 			@arg ATTR_PERMISSION_AUTHEN_READ
+ * 			@arg ATTR_PERMISSION_AUTHOR_READ
+ * 			@arg ATTR_PERMISSION_ENCRY_READ
+ * 			@arg ATTR_PERMISSION_AUTHEN_WRITE
+ * 			@arg ATTR_PERMISSION_AUTHOR_WRITE
+ * 			@arg ATTR_PERMISSION_ENCRY_WRITE
+ * @param accPermissions Access permissions for the added descriptor. See @ref Access_permissions.
+ * 			@arg ATTR_NO_ACCESS
+ * 			@arg ATTR_ACCESS_READ_ONLY
+ * 			@arg ATTR_ACCESS_WRITE_REQ_ONLY
+ * 			@arg ATTR_ACCESS_READ_WRITE
+ * 			@arg ATTR_ACCESS_WRITE_WITHOUT_RESPONSE
+ * 			@arg ATTR_ACCESS_SIGNED_WRITE_ALLOWED
+ * @param gattEvtMask Bit mask that enables events that will be sent to the application by the GATT server
+ * 					  on certain ATT requests. See @ref Gatt_Event_Mask.
+ * @param encryKeySize The minimum encryption key size requirement for this attribute. Valid Range: 7 to 16.
+ * @param isVariable If the attribute has a variable length value field (1) or not (0).
+ * @param[out] descHandle Handle of the Characteristic Descriptor.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_add_char_desc(uint16_t serviceHandle,
+                                  uint16_t charHandle,
+                                  uint8_t descUuidType,
+                                  const uint8_t* uuid, 
+                                  uint8_t descValueMaxLen,
+                                  uint8_t descValueLen,
+                                  const void* descValue, 
+                                  uint8_t secPermissions,
+                                  uint8_t accPermissions,
+                                  uint8_t gattEvtMask,
+                                  uint8_t encryKeySize,
+                                  uint8_t isVariable,
+                                  uint16_t* descHandle);
+
+/**
+ * @brief Update a characteristic value in a service.
+ * @note If notifications (or indications) are enabled on that characteristic, a notification (or indication)
+ *   	 will be sent to the client after sending this command to the BlueNRG. The command is queued into the
+ *   	 BlueNRG command queue. If the buffer is full, because previous commands could not be still processed,
+ *   	 the function will return @ref BLE_STATUS_INSUFFICIENT_RESOURCES. This will happen if notifications (or
+ *   	 indications) are enabled and the application calls aci_gatt_update_char_value() at an higher rate
+ *   	 than what is allowed by the link. Throughput on BLE link depends on connection interval and
+ *   	 connection length parameters (decided by the master, see aci_l2cap_connection_parameter_update_request()
+ *   	 for more info on how to suggest new connection parameters from a slave). If the application does not
+ *   	 want to lose notifications because BlueNRG buffer becomes full, it has to retry again till the function
+ *   	 returns @ref BLE_STATUS_SUCCESS or any other error code.\n
+ *   	 Example:\n
+ *   	 Here if BlueNRG buffer become full because BlueNRG was not able to send packets for a while, some
+ *   	 notifications will be lost.
+ *   	 @code
+ *   	 tBleStatus Free_Fall_Notify(void)
+ *		 {
+ *		 	uint8_t val;
+ * 			tBleStatus ret;
+ *
+ *			val = 0x01;
+ *			ret = aci_gatt_update_char_value(accServHandle, freeFallCharHandle, 0, 1, &val);
+ *
+ *			if (ret != BLE_STATUS_SUCCESS){
+ *			  PRINTF("Error while updating ACC characteristic.\n") ;
+ *			  return BLE_STATUS_ERROR ;
+ *			}
+ *		    return BLE_STATUS_SUCCESS;
+ *		 }
+ *		 @endcode
+ *		 Here if BlueNRG buffer become full, the application try again to send the notification.
+ *		 @code
+ *       struct timer t;
+ *       Timer_Set(&t, CLOCK_SECOND*10);
+ *       while(aci_gatt_update_char_value(chatServHandle,TXCharHandle,0,len,array_val)==BLE_STATUS_INSUFFICIENT_RESOURCES){
+ *         // Radio is busy (buffer full).
+ *         if(Timer_Expired(&t))
+ *           break;
+ *       }
+ *       @endcode
+ *
+ * @param servHandle Handle of the service to which characteristic belongs
+ * @param charHandle Handle of the characteristic
+ * @param charValOffset The offset from which the attribute value has to be updated. If this is set to 0,
+ * 						and the attribute value is of variable length, then the length of the attribute will
+ * 						be set to the charValueLen. If the charValOffset is set to a value greater than 0,
+ * 						then the length of the attribute will be set to the maximum length as specified for
+ * 						the attribute while adding the characteristic.
+ * @param charValueLen Length of the characteristic value in octets
+ * @param[in] charValue Characteristic value
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_update_char_value(uint16_t servHandle, 
+				      uint16_t charHandle,
+				      uint8_t charValOffset,
+				      uint8_t charValueLen,   
+				      const uint8_t *charValue);
+/**
+ * @brief Delete the specified characteristic from the service.
+ * @param servHandle Handle of the service to which characteristic belongs
+ * @param charHandle Handle of the characteristic to be deleted
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_del_char(uint16_t servHandle, uint16_t charHandle);
+
+/**
+ * @brief Delete the specified service from the GATT server database.
+ * @param servHandle Handle of the service to be deleted
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_del_service(uint16_t servHandle);
+
+/**
+ * @brief Delete the Include definition from the service.
+ * @param servHandle Handle of the service to which Include definition belongs
+ * @param includeServHandle Handle of the Included definition to be deleted
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_del_include_service(uint16_t servHandle, uint16_t includeServHandle);
+
+/**
+ * @brief Perform an ATT MTU exchange procedure.
+ * @note  When the ATT MTU exchange procedure is completed, a @ref EVT_BLUE_ATT_EXCHANGE_MTU_RESP
+ * 		  event is generated. A @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is also generated
+ * 		  to indicate the end of the procedure.
+ * @param conn_handle Connection handle for which the command is given.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_exchange_configuration(uint16_t conn_handle);
+
+/**
+ * @brief Send a @a Find @a Information @a Request.
+ * @note This command is used to obtain the mapping of attribute handles with their associated
+ * 		 types. The responses of the procedure are given through the
+ * 		 @ref EVT_BLUE_ATT_FIND_INFORMATION_RESP event. The end of the procedure is indicated by
+ * 		 a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event.
+ * @param conn_handle Connection handle for which the command is given
+ * @param start_handle Starting handle of the range of attributes to be discovered on the server
+ * @param end_handle Ending handle of the range of attributes to be discovered on the server
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_find_information_req(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle);
+
+/**
+ * @brief This command will start the GATT client procedure to discover all primary services on the server.
+ * @note  The responses of the procedure are given through the @ref EVT_BLUE_ATT_READ_BY_GROUP_TYPE_RESP event.
+ * 		  The end of the procedure is indicated by a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event.
+ * @param conn_handle Connection handle for which the command is given.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_disc_all_prim_services(uint16_t conn_handle);
+
+/**
+ * @brief Start the procedure to find all included services.
+ * @note The responses of the procedure are given through the @ref EVT_BLUE_ATT_READ_BY_TYPE_RESP event.
+ * 		 The end of the procedure is indicated by a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event.
+ * @param conn_handle Connection handle for which the command is given.
+ * @param start_handle Start handle of the service
+ * @param end_handle End handle of the service
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_find_included_services(uint16_t conn_handle, uint16_t start_handle,
+					   uint16_t end_handle);
+
+/**
+ * @brief Start the procedure to discover all the characteristics of a given service.
+ * @note When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * 		 Before procedure completion the response packets are given through @ref EVT_BLUE_ATT_READ_BY_TYPE_RESP event.
+ * @param conn_handle Connection handle for which the command is given
+ * @param start_attr_handle Start attribute handle of the service
+ * @param end_attr_handle End attribute handle of the service
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_disc_all_charac_of_serv(uint16_t conn_handle, uint16_t start_attr_handle,
+					    uint16_t end_attr_handle);
+
+/**
+ * @brief Start the procedure to discover all the characteristics specified by a UUID.
+ * @note  When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ *  	  Before procedure completion the response packets are given through @ref EVT_BLUE_ATT_READ_BY_TYPE_RESP event.
+ * @param conn_handle
+ * @param start_handle
+ * @param end_handle
+ * @param charUuidType
+ * @param charUuid
+ * @return
+ */
+tBleStatus aci_gatt_discovery_characteristic_by_uuid(uint16_t conn_handle, uint16_t start_handle,
+				                     uint16_t end_handle, uint8_t charUuidType,
+                                                     const uint8_t* charUuid);
+
+/**
+ * @brief Start the procedure to discover all characteristic descriptors on the server.
+ * @note When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * 		 Before procedure completion the response packets are given through @ref EVT_BLUE_ATT_FIND_INFORMATION_RESP event.
+ * @param conn_handle Connection handle for which the command is given.
+ * @param char_val_handle Starting handle of the characteristic
+ * @param char_end_handle End handle of the characteristic
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_disc_all_charac_descriptors(uint16_t conn_handle, uint16_t char_val_handle,
+						uint16_t char_end_handle);
+
+/**
+ * @brief Start the procedure to read the attribute value.
+ * @note  When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * 		  Before procedure completion the response packet is given through @ref EVT_BLUE_ATT_READ_RESP event.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the characteristic to be read
+ * @return Value indicating success or error code.\n
+ * 		 It can be @ref BLE_STATUS_NOT_ALLOWED in the following cases:\n
+ *		- If the exchange has already taken place\n
+ *		- If GATT is expecting response for previous request\n
+ *		- Already a request is in the queue to be sent\n
+ *		- Channel not open\n
+ *		- Already one GATT procedure is started
+ */
+tBleStatus aci_gatt_read_charac_val(uint16_t conn_handle, uint16_t attr_handle);
+
+/**
+ * @brief Start the procedure to read a long characteristic value.
+ * @note When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * 		 Before procedure completion the response packets are given through @ref EVT_BLUE_ATT_READ_BLOB_RESP event.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the characteristic to be read
+ * @param val_offset Offset from which the value needs to be read
+ * @return Value indicating success or error code.\n
+ * 		 It can be @ref BLE_STATUS_NOT_ALLOWED in the following cases:\n
+ *		- If the exchange has already taken place\n
+ *		- If GATT is expecting response for previous request\n
+ *		- Already a request is in the queue to be sent\n
+ *		- Channel not open\n
+ *		- Already one GATT procedure is started
+ */
+tBleStatus aci_gatt_read_long_charac_val(uint16_t conn_handle, uint16_t attr_handle,
+					 uint16_t val_offset);
+
+/**
+ * @brief Start the procedure to write a characteristic value.
+ * @note When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the characteristic to be written
+ * @param value_len Length of the value to be written
+ * @param[in] attr_value Value to be written
+ * @return Value indicating success or error code.\n
+ * 		 It can be @ref BLE_STATUS_NOT_ALLOWED in the following cases:\n
+ *		- If the exchange has already taken place\n
+ *		- If GATT is expecting response for previous request\n
+ *		- Already a request is in the queue to be sent\n
+ *		- Channel not open\n
+ *		- Already one GATT procedure is started
+ */
+tBleStatus aci_gatt_write_charac_value(uint16_t conn_handle, uint16_t attr_handle,
+				       uint8_t value_len, uint8_t *attr_value);
+
+/**
+ * @brief Start the procedure to write a characteristic descriptor.
+ * @note When the procedure is completed, a @ref EVT_BLUE_GATT_PROCEDURE_COMPLETE event is generated.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the attribute to be written
+ * @param value_len Length of the value to be written
+ * @param[in] attr_value Value to be written
+ * @return Value indicating success or error code.\n
+ * 		 It can be @ref BLE_STATUS_NOT_ALLOWED in the following cases:\n
+ *		- If the exchange has already taken place\n
+ *		- If GATT is expecting response for previous request\n
+ *		- Already a request is in the queue to be sent\n
+ *		- Channel not open\n
+ *		- Already one GATT procedure is started
+ */
+tBleStatus aci_gatt_write_charac_descriptor(uint16_t conn_handle, uint16_t attr_handle,
+					   uint8_t value_len, uint8_t *attr_value);
+
+/**
+ * @brief Start the procedure to write a characteristic value without waiting for any response from the server.
+ * @note No events are generated after this command is executed.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the attribute to be written
+ * @param value_len Length of the value to be written
+ * @param[in] attr_value Value to be written
+ * @return Value indicating success or error code.\n
+ * 		 It can be @ref BLE_STATUS_NOT_ALLOWED in the following cases:\n
+ *		- If the exchange has already taken place\n
+ *		- If GATT is expecting response for previous request\n
+ *		- Already a request is in the queue to be sent\n
+ *		- Channel not open\n
+ *		- Already one GATT procedure is started
+ */
+tBleStatus aci_gatt_write_without_response(uint16_t conn_handle, uint16_t attr_handle,
+					   uint8_t value_len, uint8_t *attr_value);
+
+/**
+ * @brief Confirm an indication
+ * @note  This command has to be sent when the application receives the event @ref EVT_BLUE_GATT_INDICATION.
+ * @param conn_handle Connection handle for which the command is given.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_confirm_indication(uint16_t conn_handle);
+
+/**
+ * @brief Allow or reject a write request from a client.
+ * @note This command has to be sent by the application when it receives the @ref EVT_BLUE_GATT_WRITE_PERMIT_REQ.
+ *  	 If the write is allowed, then the status and error code has to be set to 0. If the write is not allowed,
+ *  	 then the status has to be set to 1 and the error code has to be set to the error code that has to be
+ *  	 passed to the client.
+ * @param conn_handle Connection handle for which the command is given
+ * @param attr_handle Handle of the attribute that was passed in the event @ref EVT_BLUE_GATT_WRITE_PERMIT_REQ.
+ * @param write_status 0x00: The value can be written to the attribute specified by attr_handle\n
+ * 					   0x01: The value cannot be written to the attribute specified by the attr_handle.
+ * @param err_code  The error code that has to be passed to the client in case the write has to be rejected.
+ * @param att_val_len Length of the value to be written as passed in the event @ref EVT_BLUE_GATT_WRITE_PERMIT_REQ.
+ * @param att_val Value as passed in the event @ref EVT_BLUE_GATT_WRITE_PERMIT_REQ.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_write_response(uint16_t conn_handle,
+                                   uint16_t attr_handle,
+                                   uint8_t write_status,
+                                   uint8_t err_code,
+                                   uint8_t att_val_len,
+                                   uint8_t *att_val);
+
+/**
+ * @brief Allow the GATT server to send a response to a read request from a client.
+ * @note The application has to send this command when it receives the @ref EVT_BLUE_GATT_READ_PERMIT_REQ
+ * 		 or @ref EVT_BLUE_GATT_READ_MULTI_PERMIT_REQ. This command indicates to the stack that the response
+ * 		 can be sent to the client. So if the application wishes to update any of the attributes before
+ * 		 they are read by the client, it has to update the characteristic values using the aci_gatt_update_char_value
+ * 		 and then give this command. The application should perform the required operations within 30 seconds,
+ * 		 otherwise the GATT procedure will go to timeout.
+ * @param conn_handle Connection handle for which the command is given.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_allow_read(uint16_t conn_handle);
+
+/**
+ * @brief This command sets the value of the descriptor specified by charDescHandle.
+ * @param servHandle Handle of the service which contains the descriptor.
+ * @param charHandle Handle of the characteristic which contains the descriptor.
+ * @param charDescHandle Handle of the descriptor whose value has to be set.
+ * @param charDescValOffset Offset from which the descriptor value has to be updated.
+ * @param charDescValueLen Length of the descriptor value
+ * @param[in] charDescValue descriptor value
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_set_desc_value(uint16_t servHandle,
+				   uint16_t charHandle,
+				   uint16_t charDescHandle,
+				   uint16_t charDescValOffset,
+				   uint8_t charDescValueLen,
+				   const uint8_t *charDescValue);
+
+/**
+ * @brief Reads the value of the attribute handle specified from the local GATT database.
+ * @param attr_handle Handle of the attribute to read
+ * @param data_len Length of the data buffer.
+ * @param[in] data_len_out_p Length of the read attribute.
+ * @param[in] data Pointer to the buffer that will contain the read value.
+ * 				The buffer will be filled with the attribute value.
+ * 				The length will be the minimum between the provided data_len and the actual length of the
+ * 				attribute (in data_len_out_p).
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_gatt_read_handle_value(uint16_t attr_handle, uint16_t data_len, uint16_t *data_len_out_p, uint8_t *data);
+
+/**
+ * @}
+ */
+
+
+/**
+ * @defgroup GATT_Events GATT events
+ * The structures are the data field of @ref evt_blue_aci.
+ * @{
+ */
+
+/**
+ * This event is raised to the application by the GATT server when a client modifies any attribute on the server,
+ * if event is enabled (see Gatt_Event_Mask). See @ref evt_gatt_attr_modified.
+ */
+#define EVT_BLUE_GATT_ATTRIBUTE_MODIFIED          (0x0C01)
+typedef __packed struct _evt_gatt_attr_modified{
+  uint16_t conn_handle; /**< The connection handle which modified the attribute. */
+  uint16_t attr_handle; /**< Handle of the attribute that was modified. */
+  uint8_t  data_length; /**< The length of the data */
+  uint8_t  att_data[VARIABLE_SIZE]; /**< The new value (length is data_length) */
+} PACKED evt_gatt_attr_modified;
+
+/**
+ * This event is generated by the client/server to the application on a GATT timeout (30 seconds).
+ */
+#define EVT_BLUE_GATT_PROCEDURE_TIMEOUT           (0x0C02)
+typedef __packed struct _evt_gatt_procedure_timeout{
+	uint16_t conn_handle; /**< The connection handle handle on which the GATT procedure has timed out */
+} PACKED evt_gatt_procedure_timeout;
+
+/**
+ * This event is generated in response to an Exchange MTU request. See aci_gatt_exchange_configuration().
+ */
+#define EVT_BLUE_ATT_EXCHANGE_MTU_RESP		  (0x0C03)
+typedef __packed struct _evt_att_exchange_mtu_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint16_t server_rx_mtu;
+} PACKED evt_att_exchange_mtu_resp;
+
+/**
+ * This event is generated in response to a @a Find @a Information @a Request. See aci_gatt_find_information_req() and
+ * Find Information Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_FIND_INFORMATION_RESP	  (0x0C04)
+typedef __packed struct _evt_att_find_information_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  format;
+  uint8_t  handle_uuid_pair[VARIABLE_SIZE];
+} PACKED evt_att_find_information_resp;
+
+/**
+ * This event is generated in response to a @a Find @a By @a Type @a Value @a Request. See
+ * Find By Type Value Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_FIND_BY_TYPE_VAL_RESP	  (0x0C05)
+typedef __packed struct _evt_att_find_by_type_val_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  handles_info_list[VARIABLE_SIZE]; /**< Handles Information List as defined in Bluetooth Core v4.0 spec. */
+} PACKED evt_att_find_by_type_val_resp;
+
+/**
+ * This event is generated in response to a @a Read @a By @a Type @a Request. See aci_gatt_find_included_services() and
+ * aci_gatt_disc_all_charac_of_serv().
+ * For more info see Read By Type Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_READ_BY_TYPE_RESP		  (0x0C06)
+typedef __packed struct _evt_att_read_by_type_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  handle_value_pair_length;
+  uint8_t  handle_value_pair[VARIABLE_SIZE];
+} PACKED evt_att_read_by_type_resp;
+
+/**
+ * This event is generated in response to a @a Read @a Request. See aci_gatt_read_charac_val().
+ * For more info see Read Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_READ_RESP			  (0x0C07)
+typedef __packed struct _evt_att_read_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  attribute_value[VARIABLE_SIZE];
+} PACKED evt_att_read_resp;
+
+/**
+ * This event is generated in response to a @a Read @a Blob @a Request. See aci_gatt_read_long_charac_val().
+ * For more info see Read Blob Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_READ_BLOB_RESP		  (0x0C08)
+typedef __packed struct _evt_att_read_blob_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  part_attribute_value[VARIABLE_SIZE];
+} PACKED evt_att_read_blob_resp;
+
+/**
+ * This event is generated in response to a @a Read @a Multiple @a Request.
+ * For more info see Read Multiple Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_READ_MULTIPLE_RESP		  (0x0C09)
+typedef __packed struct _evt_att_read_mult_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  set_of_values[VARIABLE_SIZE];
+} PACKED evt_att_read_mult_resp;
+
+/**
+ * This event is generated in response to a @a Read @a By @a Group @a Type @a Request. See aci_gatt_disc_all_prim_services().
+ * For more info see Read By Group type Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_READ_BY_GROUP_TYPE_RESP           (0x0C0A)
+typedef __packed struct _evt_att_read_by_group_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  handle_value_pair_length;
+  uint8_t  handle_value_pair[VARIABLE_SIZE];
+} PACKED evt_att_read_by_group_resp;
+
+/**
+ * This event is generated in response to a @a Write @a Request. See aci_gatt_disc_all_prim_services().
+ * For more info see Write Response in Bluetooth Core v4.0 spec. Not used in BlueNRG FW 6.3.
+ */
+#define EVT_BLUE_ATT_WRITE_RESP			  (0x0C0B)
+
+/**
+ * This event is generated in response to a @a Prepare @a Write @a Request.
+ * For more info see Prepare Write Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_PREPARE_WRITE_RESP		  (0x0C0C)
+
+/**
+ * This event is generated in response to an @a Execute @a Write @a Request.
+ * For more info see Execute Write Response in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_ATT_EXEC_WRITE_RESP		  (0x0C0D)
+
+/**
+ * This event is generated when an indication is received from the server.
+ * For more info see Handle Value Indication in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_GATT_INDICATION		  (0x0C0E)
+typedef __packed struct _evt_gatt_indication{
+  uint16_t conn_handle;
+  uint8_t  data_length; /**< Lenght of attribute value + handle. */
+  uint16_t attr_handle;
+  uint8_t  attr_value[VARIABLE_SIZE];
+} PACKED evt_gatt_indication;
+
+/**
+ * This event is generated when a notification is received from the server.
+ * For more info see Handle Value Notification in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_GATT_NOTIFICATION		  (0x0C0F)
+typedef __packed struct _evt_gatt_notification{
+  uint16_t conn_handle;
+  uint8_t  data_length; /**< Lenght of attribute value + handle. */
+  uint16_t attr_handle;
+  uint8_t  attr_value[VARIABLE_SIZE];
+} PACKED evt_gatt_attr_notification;
+
+/**
+ * This event is generated when a GATT client procedure completes either with error or successfully. See @ref evt_gatt_procedure_complete.
+ */
+#define EVT_BLUE_GATT_PROCEDURE_COMPLETE          (0x0C10)
+typedef __packed struct _evt_gatt_procedure_complete{
+  uint16_t conn_handle; /**< The connection handle on which the GATT procedure has completed */
+  uint8_t  data_length; /**< Length of error_code field (always 1). */
+  /**
+   * Indicates whether the procedure completed with error (BLE_STATUS_FAILED) or was successful (BLE_STATUS_SUCCESS).
+   */
+  uint8_t  error_code;
+} PACKED evt_gatt_procedure_complete;
+
+/**
+ * This event is generated when an Error Response is received from the server. The error response can be given
+ * by the server at the end of one of the GATT dicovery procedures. This does not mean that the procedure ended
+ * with an error, but this error event is part of the procedure itself.
+ */
+#define EVT_BLUE_GATT_ERROR_RESP                  (0x0C11)
+typedef __packed struct _evt_gatt_error_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint8_t  req_opcode;
+  uint16_t attr_handle;
+  uint8_t  error_code;
+} PACKED evt_gatt_error_resp;
+
+/**
+ * This event can be generated during a "Discover Characteristics By UUID" procedure or a "Read using
+ * Characteristic UUID" procedure.
+ * The attribute value will be a service declaration as defined in Bluetooth Core v4.0 spec (vol.3, Part G, ch. 3.3.1),
+ * when a "Discover Characteristics By UUID" has been started. It will be the value of the Characteristic if a
+ * "Read using Characteristic UUID" has been performed.
+ */
+#define EVT_BLUE_GATT_DISC_READ_CHAR_BY_UUID_RESP (0x0C12)
+typedef __packed struct _evt_gatt_disc_read_char_by_uuid_resp{
+  uint16_t conn_handle;
+  uint8_t  event_data_length;
+  uint16_t attr_handle;
+  uint8_t  attr_value[VARIABLE_SIZE];
+} PACKED evt_gatt_disc_read_char_by_uuid_resp;
+
+/**
+ * This event is given to the application when a write request, write command or signed write command
+ * is received by the server from the client. This event will be given to the application only if the
+ * event bit for this event generation is set when the characteristic was added.
+ * When this event is received, the application has to check whether the value being requested for write
+ * is allowed to be written and respond with the command aci_gatt_write_response().
+ * If the write is rejected by the application, then the value of the attribute will not be modified.
+ * In case of a write request, an error response will be sent to the client, with the error code as specified by the application.
+ * In case of write/signed write commands, no response is sent to the client but the attribute is not modified.
+ * See @ref evt_gatt_write_permit_req.
+ */
+#define EVT_BLUE_GATT_WRITE_PERMIT_REQ            (0x0C13)
+typedef __packed struct _evt_gatt_write_permit_req{
+  uint16_t conn_handle; /**< Handle of the connection on which there was the request to write the attribute. */
+  uint16_t attr_handle; /**< The handle of the attribute for which the write request has been made by the client */
+  uint8_t  data_length; /**< Length of data field. */
+  uint8_t  data[VARIABLE_SIZE]; /**< The data that the client has requested to write */
+} PACKED evt_gatt_write_permit_req;
+
+/**
+ * This event is given to the application when a read request or read blob request is received by the server
+ * from the client. This event will be given to the application only if the event bit for this event generation
+ * is set when the characteristic was added.
+ * On receiving this event, the application can update the value of the handle if it desires and when done
+ * it has to use the aci_gatt_allow_read() command to indicate to the stack that it can send the response to the client.
+ * See @ref evt_gatt_read_permit_req.
+ *
+ */
+#define EVT_BLUE_GATT_READ_PERMIT_REQ             (0x0C14)
+typedef __packed struct _evt_gatt_read_permit_req{
+  uint16_t conn_handle; /**< Handle of the connection on which there was the request to read the attribute. */
+  uint16_t attr_handle; /**< The handle of the attribute for which the read request has been made by the client */
+  uint8_t  data_length; /**< Length of offset field. (always 1). */
+  uint8_t  offset; /**< Contains the offset from which the read has been requested */
+} PACKED evt_gatt_read_permit_req;
+
+/**
+ * This event is given to the application when a read multiple request or read by type request is received
+ * by the server from the client. This event will be given to the application only if the event bit for this
+ * event generation is set when the characteristic was added.
+ * On receiving this event, the application can update the values of the handles if it desires and when done
+ * it has to send the aci_gatt_allow_read command to indicate to the stack that it can send the response to the client.
+ * See @ref evt_gatt_read_multi_permit_req.
+ *
+ */
+#define EVT_BLUE_GATT_READ_MULTI_PERMIT_REQ       (0x0C15)
+typedef __packed struct _evt_gatt_read_multi_permit_req{
+  uint16_t conn_handle; /**< Handle of the connection on which there was the request to read the attribute. */
+  uint8_t  data_length; /**< Length of data field. */
+  uint8_t  data[VARIABLE_SIZE]; /**< The handles of the attributes that have been requested by the client for a read. */
+} PACKED evt_gatt_read_multi_permit_req;
+
+/**
+ * @}
+ */
+
+#endif /* __BLUENRG_GATT_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_hal_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_hal_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,146 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_hal_aci.h
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with HCI commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_HAL_ACI_H__
+#define __BLUENRG_HAL_ACI_H__
+
+/**
+ * @defgroup HAL_Functions HAL functions
+ * @brief API for BlueNRG HAL layer.
+ * @{
+ */
+
+/**
+ * @brief This command writes a value to a low level configure data structure.
+ * @note  It is useful to setup directly some low level parameters for the system at runtime.
+ * @param offset Offset in the data structure. The starting member in the data structure will have an offset 0.\n
+ * 				 See @ref Config_vals.
+ *
+ * @param len Length of data to be written
+ * @param[out] val Data to be written
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_hal_write_config_data(uint8_t offset, 
+                                    uint8_t len,
+                                    const uint8_t *val);
+
+/**
+ * @brief This command sets the TX power level of the BlueNRG.
+ * @note  By controlling the EN_HIGH_POWER and the PA_LEVEL, the combination of the 2 determines
+ *        the output power level (dBm).
+ *        When the system starts up or reboots, the default TX power level will be used, which is
+ *        the maximum value of 8dBm. Once this command is given, the output power will be changed
+ *        instantly, regardless if there is Bluetooth communication going on or not. For example,
+ *        for debugging purpose, the BlueNRG can be set to advertise all the time and use this
+ *        command to observe the signal strength changing. The system will keep the last received
+ *        TX power level from the command, i.e. the 2nd command overwrites the previous TX power
+ *        level. The new TX power level remains until another Set TX Power command, or the system
+ *        reboots.\n
+ * @param en_high_power Can be only 0 or 1. Set high power bit on or off. It is strongly adviced to use the
+ * 						right value, depending on the selected hardware configuration for the RF network:
+ * 						normal mode or high power mode.
+ * @param pa_level Can be from 0 to 7. Set the PA level value.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_hal_set_tx_power_level(uint8_t en_high_power, uint8_t pa_level);
+
+/**
+ * @brief Put the device in standby mode.
+ * @note Normally the BlueNRG will automatically enter sleep mode to save power. This command puts the
+ * 		 device into the Standby mode instead of the sleep mode. The difference is that, in sleep mode,
+ * 		 the device can still wake up itself with the internal timer. But in standby mode, this timer is
+ * 		 disabled. So the only possibility to wake up the device is by external signals, e.g. a HCI command
+ * 		 sent via SPI bus.
+ * 		 The command is only accepted when there is no other Bluetooth activity. Otherwise an error code
+ * 		 ERR_COMMAND_DISALLOWED will be returned.
+ *
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_hal_device_standby(void);
+
+/**
+ * @brief This command starts a carrier frequency, i.e. a tone, on a specific channel.
+ * @note  The frequency sine wave at the specific channel may be used for test purpose only.
+ * 		  The channel ID is a parameter from 0 to 39 for the 40 BLE channels, e.g. 0 for 2.402GHz, 1 for 2.404GHz etc.
+ * 		  This command shouldn't be used when normal Bluetooth activities are ongoing.
+ * 		  The tone should be stopped by aci_hal_tone_stop() command.
+ *
+ * @param rf_channel BLE Channel ID, from 0 to 39 meaning (2.402 + 2*N) GHz. Actually the tone will be emitted at the
+ * 					 channel central frequency minus 250 kHz.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_hal_tone_start(uint8_t rf_channel);
+
+/**
+ * This command is used to stop the previously started aci_hal_tone_start() command.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_hal_tone_stop(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Config_vals Offsets and lengths for configuration values.
+ * @brief Offsets and lengths for configuration values.
+ * 		  See aci_hal_write_config_data().
+ * @{
+ */
+
+/**
+ * @defgroup Config_offset Offsets for configuration values.
+ * @brief  See @ref aci_hal_write_config_data().
+ */
+#define CONFIG_DATA_PUBADDR_OFFSET          (0x00) /**< Bluetooth public address */
+#define CONFIG_DATA_DIV_OFFSET              (0x06) /**< DIV used to derive CSRK */
+#define CONFIG_DATA_ER_OFFSET               (0x08) /**< Encryption root key used to derive LTK and CSRK */
+#define CONFIG_DATA_IR_OFFSET               (0x18) /**< Identity root key used to derive LTK and CSRK */
+#define CONFIG_DATA_LL_WITHOUT_HOST         (0x2C) /**< Switch on/off Link Layer only mode. Set to 1 to disable Host.
+ 	 	 	 	 	 	 	 	 	 	 	 	 	 It can be written only if aci_hal_write_config_data() is the first command
+ 	 	 	 	 	 	 	 	 	 	 	 	 	 after reset. */
+
+/**
+ * Select the BlueNRG roles and mode configurations.\n
+ * @li Mode 1: slave or master, 1 connection, RAM1 only
+ * @li Mode 2: slave or master, 1 connection, RAM1 only
+ * @li Mode 3: master, 8 connections, RAM1 and RAM2.
+ */
+#define CONFIG_DATA_ROLE					(0x2D)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Config_len Length for configuration values.
+ * @brief  See @ref aci_hal_write_config_data().
+ */
+#define CONFIG_DATA_PUBADDR_LEN             (6)
+#define CONFIG_DATA_DIV_LEN                 (2)
+#define CONFIG_DATA_ER_LEN                  (16)
+#define CONFIG_DATA_IR_LEN                  (16)
+#define CONFIG_DATA_LL_WITHOUT_HOST_LEN     (1)
+#define CONFIG_DATA_ROLE_LEN                (1)
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+
+#endif /* __BLUENRG_HAL_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_interface.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_interface.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,54 @@
+/**
+  ******************************************************************************
+  * @file    bluenrg_interface.h
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+  
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __BLUENRG_INTERFACE_H_
+#define __BLUENRG_INTERFACE_H_
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32_bluenrg_ble.h"
+#include "hal_types.h"
+
+void Hal_Write_Serial(const void* data1, const void* data2, int32_t n_bytes1,
+                      int32_t n_bytes2);
+void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin);
+
+
+#endif //__BLUENRG_INTERFACE_H_
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_l2cap_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_l2cap_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,111 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_l2cap_aci.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with L2CAP commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_L2CAP_ACI_H__
+#define __BLUENRG_L2CAP_ACI_H__
+
+/**
+ *@defgroup L2CAP_Functions L2CAP functions
+ *@brief API for L2CAP layer.
+ *@{
+ */
+
+/**
+ * @brief Send an L2CAP Connection Parameter Update request from the slave to the master.
+ * @note  An @ref EVT_BLUE_L2CAP_CONN_UPD_RESP event will be raised when the master will respond to the request
+ * 		  (accepts or rejects).
+ * @param conn_handle Connection handle on which the connection parameter update request has to be sent.
+ * @param interval_min Defines minimum value for the connection event interval in the following manner:
+ *						connIntervalMin = interval_min x 1.25ms
+ * @param interval_max Defines maximum value for the connection event interval in the following manner:
+ * 						connIntervalMax = interval_max x 1.25ms
+ * @param slave_latency Defines the slave latency parameter (number of connection events that can be skipped).
+ * @param timeout_multiplier Defines connection timeout parameter in the following manner:
+ * 							 timeout_multiplier x 10ms.
+ * @return Value indicating success or error code.
+ */
+tBleStatus aci_l2cap_connection_parameter_update_request(uint16_t conn_handle, uint16_t interval_min,
+							 uint16_t interval_max, uint16_t slave_latency,
+							 uint16_t timeout_multiplier);
+/**
+ * @brief Accept or reject a connection update.
+ * @note  This command should be sent in response to a @ref EVT_BLUE_L2CAP_CONN_UPD_REQ event from the controller.
+ * 		  The accept parameter has to be set if the connection parameters given in the event are acceptable.
+ * @param conn_handle Handle received in @ref EVT_BLUE_L2CAP_CONN_UPD_REQ event.
+ * @param interval_min
+ * @param interval_max
+ * @param slave_latency
+ * @param timeout_multiplier
+ * @param id
+ * @param accept
+ * @return
+ */
+tBleStatus aci_l2cap_connection_parameter_update_response(uint16_t conn_handle, uint16_t interval_min,
+							 uint16_t interval_max, uint16_t slave_latency,
+							 uint16_t timeout_multiplier, uint8_t id, uint8_t accept);
+
+/**
+ * @}
+ */
+   
+/**
+ * @defgroup L2CAP_Events L2CAP events
+ * @{
+ */
+
+/**
+ * This event is generated when the master responds to the L2CAP connection update request packet.
+ * For more info see CONNECTION PARAMETER UPDATE RESPONSE in Bluetooth Core v4.0 spec.
+ */
+#define EVT_BLUE_L2CAP_CONN_UPD_RESP		  (0x0800)
+typedef __packed struct _evt_l2cap_conn_upd_resp{
+  uint16_t conn_handle;
+  uint8_t  resp_len;
+  uint8_t  code; /**< It will always be 0x13  */
+  uint8_t  identifier;
+  uint16_t l2cap_length;
+  uint16_t result;
+} PACKED evt_l2cap_conn_upd_resp;
+
+/**
+ * This event is generated when the master does not respond to the connection update request
+ * within 30 seconds.
+ */
+#define EVT_BLUE_L2CAP_PROCEDURE_TIMEOUT      (0x0801)
+
+/**
+ * The event is given by the L2CAP layer when a connection update request is received from the slave.
+ * The application has to respond by calling aci_l2cap_connection_parameter_update_response().
+ */
+#define EVT_BLUE_L2CAP_CONN_UPD_REQ		  	  (0x0802)
+typedef __packed struct _evt_l2cap_conn_upd_req{
+  uint16_t conn_handle;
+  uint8_t  resp_len;
+  uint8_t  code; /**< It will always be 0x12  */
+  uint8_t  identifier;
+  uint16_t l2cap_length;
+  uint16_t interval_min;
+  uint16_t interval_max;
+  uint16_t slave_latency;
+  uint16_t timeout_mult;
+} PACKED evt_l2cap_conn_upd_req;
+
+/**
+ * @}
+ */
+
+
+#endif /* __BLUENRG_L2CAP_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_updater_aci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_updater_aci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,68 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_updater_aci.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : Header file with updater commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __BLUENRG_UPDATER_ACI_H__
+#define __BLUENRG_UPDATER_ACI_H__
+
+#include <compiler.h>
+
+/**
+ * @defgroup Updater_Functions Updater functions
+ * @brief API for BlueNRG Updater.
+ * @{
+ */
+
+tBleStatus aci_updater_start();
+
+tBleStatus aci_updater_reboot();
+
+tBleStatus aci_get_updater_version(uint8_t *version);
+
+tBleStatus aci_get_updater_buffer_size(uint8_t *buffer_size);
+
+tBleStatus aci_erase_blue_flag();
+
+tBleStatus aci_reset_blue_flag();
+
+tBleStatus aci_updater_erase_sector(uint32_t address);
+
+tBleStatus aci_updater_program_data_block(uint32_t address, uint16_t len, const uint8_t *data);
+
+tBleStatus aci_updater_read_data_block(uint32_t address, uint16_t data_len, uint8_t *data);
+
+tBleStatus aci_updater_calc_crc(uint32_t address, uint8_t num_sectors, uint32_t *crc);
+
+tBleStatus aci_updater_hw_version(uint8_t *version);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Updater_Events Updater events
+ * @{
+ */
+/** HCI vendor specific event, raised at BlueNRG power-up or reboot. */
+#define EVT_BLUE_INITIALIZED                      (0x0001)
+typedef __packed struct _evt_blue_initialized{
+  uint8_t reason_code;
+} PACKED evt_blue_initialized;
+/**
+ * @}
+ */
+
+
+#endif /* __BLUENRG_UPDATER_ACI_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/bluenrg_utils.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/bluenrg_utils.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,194 @@
+/******************** (C) COPYRIGHT 2013 STMicroelectronics ********************
+* File Name          : bluenrg_utils.h
+* Author             : AMS - AAS, RF Application Team
+* Version            : V1.0.0
+* Date               : 21-March-2014
+* Description        : Header file for BlueNRG utility functions 
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+/**
+ * @file  bluenrg_utils.h
+ * @brief BlueNRG IFR updater & BlueNRG stack updater utility APIs description
+ *
+ * <!-- Copyright 2014 by STMicroelectronics.  All rights reserved.       *80*-->
+**/
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __BLUENRG_UTILS_H
+#define __BLUENRG_UTILS_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "hal_types.h" 
+#include "compiler.h"
+
+/* Exported types ------------------------------------------------------------*/
+typedef struct{
+  uint8_t stack_mode;
+  uint8_t day;
+  uint8_t month;
+  uint8_t year;
+  uint16_t slave_sca_ppm;
+  uint8_t master_sca;
+  uint16_t hs_startup_time; /* In system time units*/
+} IFR_config2_TypeDef;
+
+/**
+ * Structure inside IFR for configuration options. 
+ */
+typedef __packed struct{
+  uint8_t cold_ana_act_config_table[64];
+  uint8_t hot_ana_config_table[64];
+  uint8_t stack_mode;
+  uint8_t rsrvd1[3];
+  uint32_t rsrvd2[4];
+  uint32_t ls_crystal_period;
+  uint32_t ls_crystal_freq;
+  uint16_t slave_sca_ppm;
+  uint8_t master_sca;
+  uint8_t rsrvd3;
+  uint16_t hs_startup_time; /* In system time units*/
+  uint8_t crystal_par;
+  uint8_t hot_cold_ta;
+  uint8_t uid[3];
+  uint8_t rf_power;
+  uint8_t rsrvd4;
+  uint8_t year;  
+  uint8_t month;
+  uint8_t day;
+  uint32_t rsrvd5[5];
+} PACKED IFR_config_TypeDef;
+
+/* Exported constants --------------------------------------------------------*/
+extern const IFR_config_TypeDef IFR_config;
+
+/* Exported macros -----------------------------------------------------------*/
+#define FROM_US_TO_SYS_TIME(us)      ((uint16_t)(us/2.4414))
+#define FROM_SYS_TIME_TO_US(sys)     ((uint16_t)(sys*2.4414))
+
+/* Convert 2 digit BCD number to an integer */
+#define BCD_TO_INT(bcd) ((bcd & 0xF) + ((bcd & 0xF0) >> 4)*10)
+
+/* Convert 2 digit number to a BCD number */
+#define INT_TO_BCD(n) ((((uint8_t)n/10)<<4) + (uint8_t)n%10)
+
+/** 
+  * Return values 
+  */ 
+#define BLE_UTIL_SUCCESS                 0
+#define BLE_UTIL_UNSUPPORTED_VERSION     1
+#define BLE_UTIL_WRONG_IMAGE_SIZE        2
+#define BLE_UTIL_ACI_ERROR               3
+#define BLE_UTIL_CRC_ERROR               4
+#define BLE_UTIL_PARSE_ERROR             5
+#define BLE_UTIL_WRONG_VERIFY            6
+
+/* Exported functions ------------------------------------------------------- */ 
+/**
+  * @brief  Flash a new firmware using internal bootloader.
+  * @param  fw_image     Pointer to the firmware image (raw binary data,
+  *                      little-endian).
+  * @param  fw_size      Size of the firmware image. 
+  * @param  skip_bootloader_verif     If true, verification of the first sector,
+  *                                   that contains the bootloader, will not be executed.
+  * @note   this is useful when a new image with a new bootloader must be
+  *         programmed.
+  * @retval int      It returns 0 if successful, or a number not equal to 0 in
+                     case of error (ACI_ERROR, UNSUPPORTED_VERSION,
+  *                  WRONG_IMAGE_SIZE, CRC_ERROR)
+  */
+int program_device(const uint8_t *fw_image, uint32_t fw_size, uint8_t skip_bootloader_verif);
+
+/**
+  * @brief  Read raw data from IFR (3 64-bytes blocks).
+  * @param  data     Pointer to the buffer that will contain the read data.
+  *                  Its size must be 192 bytes. This data can be parsed by
+  *                  parse_IFR_data_config().
+  * @retval int      It returns 0 if successful, or a number not equal to 0 in
+                     case of error (ACI_ERROR, UNSUPPORTED_VERSION)
+  */
+int read_IFR(uint8_t data[192]);
+
+/**
+  * @brief  Verify raw data from IFR (3 64-bytes blocks).
+  * @param  ifr_data Pointer to the buffer that will contain the data to verify.
+  *                  Its size must be 192 bytes.
+  * @retval int      It returns 0 if successful, or a number not equal to 0 in
+                     case of error (ACI_ERROR, BLE_UTIL_WRONG_VERIFY)
+  */
+uint8_t verify_IFR(const IFR_config_TypeDef *ifr_data);
+
+/**
+  * @brief  Program raw data to IFR (3 64-bytes blocks).
+  * @param  ifr_image     Pointer to the buffer that will contain the data to program.
+  *                  Its size must be 192 bytes.
+  * @retval int      It returns 0 if successful
+  */
+int program_IFR(const IFR_config_TypeDef *ifr_image);
+
+/**
+  * @brief  Parse IFR raw data.
+  * @param  data     Pointer to the raw data: last 64 bytes read from IFR sector.
+  * @param  IFR_config     Data structure that will be filled with parsed data.
+  * @retval None
+  */
+void parse_IFR_data_config(const uint8_t data[64], IFR_config2_TypeDef *IFR_config);
+
+/**
+  * @brief  Check for the correctness of parsed data.
+  * @param  IFR_config     Data structure filled with parsed data.
+  * @retval int      It returns 0 if successful, or PARSE_ERROR in case data is
+  *                  not correct.
+  */
+int IFR_validate(IFR_config2_TypeDef *IFR_config);
+
+/**
+  * @brief  Modify IFR data. (Last 64-bytes block).
+  * @param  IFR_config   Structure that contains the new parameters inside the
+  *                      IFR configuration data.
+  * @note   It is highly recommended to parse the IFR configuration from
+  *         a working IFR block (this should be done with parse_IFR_data_config()).
+  *         Then it is possible to write the new parameters inside the IFR_config
+  *         structure.
+  * @param  data     Pointer to the buffer that contains the original data. It
+  *                  will be modified according to the new data in the IFR_config
+  *                  structure. Then this data must be written in the last
+  *                  64-byte block in the IFR.
+  *                  Its size must be 64 bytes.
+  * @retval None
+  */
+void change_IFR_data_config(IFR_config2_TypeDef *IFR_config, uint8_t data[64]);
+
+/**
+  * @brief  Get BlueNRG hardware and firmware version
+  * @param  hwVersion This parameter returns the Hardware Version (i.e. CUT 3.0 = 0x30, CUT 3.1 = 0x31).
+  * @param  fwVersion This parameter returns the Firmware Version in the format JJ.M.N
+  *                   where JJ = Major Version number, M = Minor Version number and N = Patch Version number.
+  * @retval Status of the call
+  */
+uint8_t getBlueNRGVersion(uint8_t *hwVersion, uint16_t *fwVersion);
+
+/**
+  * @brief  Get BlueNRG updater version
+  * @param  version This parameter returns the updater version. If the updadter version is 0x03 
+  *                 the chip has the updater old, needs to update the bootloader.
+  * @retval Status of the call
+  */
+uint8_t getBlueNRGUpdaterVersion(uint8_t *version);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /*__BLUENRG_UTILS_H */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/clock.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/clock.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,54 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : clock.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.1
+* Date               : 19-July-2012
+* Description        : Header file for clock library, that gives a simple time
+*                       reference to the BLE Stack.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __CLOCK_H__
+#define __CLOCK_H__
+
+#include <hal_types.h>
+
+/**
+ * Number of clocks in one seconds.
+ * This value must be set by each platorm implementation, basing on its needs.
+ */
+extern const uint32_t CLOCK_SECOND;
+
+typedef uint32_t tClockTime;
+
+/**
+ * This function initializes the clock library and should be called before
+ * any other Stack functions.
+ *
+ */
+void Clock_Init(void);
+
+/**
+ * This function returns the current system clock time. it is used by
+ * the host stack and has to be implemented.
+ *
+ * @return The current clock time, measured in system ticks.
+ */
+tClockTime Clock_Time(void);
+
+/**
+ * This function waits for a given number of milliseconds.
+ *
+ */
+void Clock_Wait(uint32_t i);
+
+
+#endif /* __CLOCK_H__ */
+
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/compiler.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/compiler.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,34 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : compiler.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Compiler-dependent macros.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+
+#ifdef __ICCARM__
+#define PACKED
+#else
+#ifdef __GNUC__
+#define __packed
+#define PACKED __attribute__((packed))
+#else
+#define PACKED
+#define __packed
+#endif
+#endif
+
+/* Change this define to 1 if zero-length arrays are not supported by your compiler. */
+#define VARIABLE_SIZE 0
+
+#endif /* DOXYGEN_SHOULD_SKIP_THIS */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/connection_config.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/connection_config.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,72 @@
+/**
+  ******************************************************************************
+  * @file    connection_config.h 
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   This file defines macros for configuring the BlueNRG connection.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef _CONNECTION_CONFIG_
+#define _CONNECTION_CONFIG_
+
+/* Exported macro ------------------------------------------------------------*/
+/** 
+ * @brief Connection period, arg in msec.
+ */
+#define CONN_P(x) ((int)((x)/1.25f))
+/** 
+ * @brief connection length, arg in msec.
+ */
+#define CONN_L(x) ((int)((x)/0.625f))
+
+#define SCAN_P (0x4000)
+#define SCAN_L (0x4000)
+
+//#define CONN_P1		(CONN_P(10)) 
+//#define CONN_P2		(CONN_P(10)) 
+#define CONN_P1		(CONN_P(1000)) 
+#define CONN_P2		(CONN_P(1000)) 
+
+/** 
+ * @brief Supervision timeout, arg in msec.
+ */
+//#define SUPERV_TIMEOUT (60)
+#define SUPERV_TIMEOUT (600)
+
+#define CONN_L1		(CONN_L(5)) 
+#define CONN_L2		(CONN_L(5)) 
+
+#endif /* _CONNECTION_CONFIG_ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/cube_hal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/cube_hal.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,62 @@
+/**
+  ******************************************************************************
+  * @file    cube_hal.h
+  * @author  CL
+  * @version V1.0.0
+  * @date    03-November-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef _CUBE_HAL_H_
+#define _CUBE_HAL_H_
+#define USE_STM32F4XX_NUCLEO
+/* Includes ------------------------------------------------------------------*/
+#ifdef USE_STM32F4XX_NUCLEO
+  #include "stm32f4xx_hal.h"
+  #include "stm32f4xx_nucleo.h"
+  #include "stm32f4xx_nucleo_bluenrg.h"
+  #include "stm32f4xx_hal_conf.h"
+#endif
+
+#ifdef USE_STM32L0XX_NUCLEO
+  #include "stm32l0xx_hal.h"
+  #include "stm32l0xx_nucleo.h"
+  #include "stm32l0xx_nucleo_bluenrg.h"
+  #include "stm32l0xx_hal_conf.h"
+#endif
+
+void SystemClock_Config(void);
+
+#endif //_CUBE_HAL_H_
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/debug.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/debug.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,74 @@
+/**
+  ******************************************************************************
+  * @file    debug.h 
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   This file defines print functions for debug purposes.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __DEBUG_H
+#define __DEBUG_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif 
+
+/* Includes ------------------------------------------------------------------*/
+#include <string.h>
+
+/* Exported macro ------------------------------------------------------------*/
+//#define DEBUG
+#ifdef DEBUG
+#include <stdio.h>
+#define PRINTF(...) printf(__VA_ARGS__)
+#else
+#define PRINTF(...)
+#endif
+
+/* Print the data travelling over the SPI in the .csv format for the GUI*/
+//#define PRINT_CSV_FORMAT 
+#ifdef PRINT_CSV_FORMAT
+#include <stdio.h>
+#define PRINT_CSV(...) printf(__VA_ARGS__)
+#else
+#define PRINT_CSV(...)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __DEBUG_H */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/gap.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/gap.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,141 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : gap.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file for BlueNRG's GAP layer. 
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+#ifndef __GAP_H__
+#define __GAP_H__
+
+#include <link_layer.h>
+
+/*----------------GAP UUIDs--------------------------*/
+#define GAP_SERVICE_UUID                        (0x1800)
+#define DEVICE_NAME_UUID						(0x2A00)
+#define APPEARANCE_UUID							(0x2A01)
+#define PERIPHERAL_PRIVACY_FLAG_UUID			(0x2A02)
+#define RECONNECTION_ADDR_UUID					(0x2A03)
+#define PERIPHERAL_PREFERRED_CONN_PARAMS_UUID	(0x2A04)
+
+/*----------------Characteristic value lengths--------------*/
+#define DEVICE_NAME_CHARACTERISTIC_LEN			        (8)
+#define APPEARANCE_CHARACTERISTIC_LEN			        (2)
+#define PERIPHERAL_PRIVACY_CHARACTERISTIC_LEN	        (1)
+#define RECONNECTION_ADDR_CHARACTERISTIC_LEN			(6)
+#define PERIPHERAL_PREF_CONN_PARAMS_CHARACTERISTIC_LEN	(8)
+
+/*------------- AD types for adv data and scan response data ----------------*/
+
+/* FLAGS AD type */
+#define AD_TYPE_FLAGS							(0x01)
+/* flag bits */
+#define FLAG_BIT_LE_LIMITED_DISCOVERABLE_MODE	(0x01)
+#define FLAG_BIT_LE_GENERAL_DISCOVERABLE_MODE	(0x02)
+#define FLAG_BIT_BR_EDR_NOT_SUPPORTED			(0x04)
+#define FLAG_BIT_LE_BR_EDR_CONTROLLER			(0x08)/* single device supports BR/EDR and LE controller */
+#define FLAG_BIT_LE_BR_EDR_HOST					(0x10)/* single device supports BR/EDR and LE host */
+
+/* SERVICE UUID AD types */
+#define AD_TYPE_16_BIT_SERV_UUID				(0x02)
+#define AD_TYPE_16_BIT_SERV_UUID_CMPLT_LIST		(0x03)
+#define AD_TYPE_32_BIT_SERV_UUID				(0x04)
+#define AD_TYPE_32_BIT_SERV_UUID_CMPLT_LIST		(0x05)
+#define AD_TYPE_128_BIT_SERV_UUID				(0x06)
+#define AD_TYPE_128_BIT_SERV_UUID_CMPLT_LIST	(0x07)
+
+/* LOCAL NAME AD types */
+#define AD_TYPE_SHORTENED_LOCAL_NAME			(0x08)
+#define AD_TYPE_COMPLETE_LOCAL_NAME			    (0x09)
+
+/* TX power level AD type*/
+#define AD_TYPE_TX_POWER_LEVEL					(0x0A)
+
+/* security manager TK value AD type */
+#define AD_TYPE_SEC_MGR_TK_VALUE				(0x10)
+
+/* security manager OOB flags */
+#define AD_TYPE_SEC_MGR_OOB_FLAGS				(0x11)
+
+/* slave connection interval AD type */
+#define AD_TYPE_SLAVE_CONN_INTERVAL				(0x12)
+
+/* service solicitation UUID list Ad types*/
+#define AD_TYPE_SERV_SOLICIT_16_BIT_UUID_LIST	(0x14)
+#define AD_TYPE_SERV_SOLICIT_32_BIT_UUID_LIST	(0x15)
+
+/* service data AD type */
+#define AD_TYPE_SERVICE_DATA					(0x16)	
+
+/* manufaturer specific data AD type */
+#define AD_TYPE_MANUFACTURER_SPECIFIC_DATA		(0xFF)
+
+#define MAX_ADV_DATA_LEN						(31)
+
+#define DEVICE_NAME_LEN			  				(7)
+#define BD_ADDR_SIZE							(6)
+
+/* privacy flag values */
+#define PRIVACY_ENABLED							(0x01)
+#define PRIVACY_DISABLED						(0x00)
+
+/* conection intervals in terms of 625 micro sec */
+#define DIR_CONN_ADV_INT_MIN					(0x190)/*250ms*/
+#define DIR_CONN_ADV_INT_MAX					(0x320)/*500ms*/
+#define UNDIR_CONN_ADV_INT_MIN					(0x800)/*1.28s*/
+#define UNDIR_CONN_ADV_INT_MAX					(0x1000)/*2.56s*/
+#define LIM_DISC_ADV_INT_MIN					(0x190)/*250ms*/
+#define LIM_DISC_ADV_INT_MAX					(0x320)/*500ms*/
+#define GEN_DISC_ADV_INT_MIN					(0x800)/*1.28s*/
+#define GEN_DISC_ADV_INT_MAX					(0x1000)/*2.56s*/
+
+/* time out values */
+#define LIM_DISC_MODE_TIMEOUT					(180000)/* 180 seconds. according to the errata published */
+#define PRIVATE_ADDR_INT_TIMEOUT				(900000)/* 15 minutes */
+
+
+#define GAP_PERIPHERAL_ROLE						(0x01)
+#define GAP_BROADCASTER_ROLE					(0x02)
+#define GAP_CENTRAL_ROLE						(0x03)
+#define GAP_OBSERVER_ROLE						(0x04)
+
+
+#define GAP_NON_DISC_MODE						(0x01)
+#define GAP_LIM_DISC_MODE						(0x02)
+#define GAP_GEN_DISC_MODE						(0x04)
+#define GAP_NON_CONN_MODE						(0x08)
+#define GAP_DIRECT_CONN_MODE					(0x10)
+#define GAP_UNDIRECTED_CONN_MODE				(0x20)
+
+/* SECURITY MANAGER OOB FLAGS */
+#define SM_OOB_FLAGS_FIELD                      (0x01)
+#define SM_OOB_LE_SUPPORTED                     (0x02)
+#define SM_OOB_SIMULTANEOUS_LE_BREDR            (0x04)
+#define SM_OOB_ADDR_TYPE                        (0x08)
+
+/**
+ * @defgroup gap_procedure_codes GAP procedure codes
+ * @brief Procedure codes for EVT_BLUE_GAP_PROCEDURE_COMPLETE event
+ * and aci_gap_terminate_gap_procedure() command.
+ * @{
+ */
+#define GAP_LIMITED_DISCOVERY_PROC                  (0x01)
+#define GAP_GENERAL_DISCOVERY_PROC                  (0x02)
+#define GAP_NAME_DISCOVERY_PROC                     (0x04)
+#define GAP_AUTO_CONNECTION_ESTABLISHMENT_PROC      (0x08)
+#define GAP_GENERAL_CONNECTION_ESTABLISHMENT_PROC   (0x10)
+#define GAP_SELECTIVE_CONNECTION_ESTABLISHMENT_PROC (0x20)
+#define GAP_DIRECT_CONNECTION_ESTABLISHMENT_PROC    (0x40)
+/**
+ * @}
+ */
+
+#endif /* __GAP_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/gatt_server.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/gatt_server.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,189 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : gatt_server.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file for BlueNRG's GATT server layer.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __GATT_SERVER_H__
+#define __GATT_SERVER_H__
+
+#include "compiler.h"
+#include "ble_status.h"
+
+/**
+ * @defgroup Well_known_UUIDs Well-Known UUIDs
+ * @{
+ */
+#define PRIMARY_SERVICE_UUID                       (0x2800)
+#define SECONDARY_SERVICE_UUID                     (0x2801)
+#define INCLUDE_SERVICE_UUID                       (0x2802)
+#define CHARACTERISTIC_UUID                        (0x2803)
+#define CHAR_EXTENDED_PROP_DESC_UUID               (0x2900)
+#define CHAR_USER_DESC_UUID                        (0x2901)
+#define CHAR_CLIENT_CONFIG_DESC_UUID               (0x2902)
+#define CHAR_SERVER_CONFIG_DESC_UUID               (0x2903)
+#define CHAR_FORMAT_DESC_UUID                      (0x2904)
+#define CHAR_AGGR_FMT_DESC_UUID                    (0x2905)
+#define GATT_SERVICE_UUID                          (0x1801)
+#define GAP_SERVICE_UUID                           (0x1800)
+#define SERVICE_CHANGED_UUID                       (0x2A05)
+/**
+ * @}
+ */
+
+/******************************************************************************
+ * Types
+ *****************************************************************************/
+
+/** 
+ * @defgroup Access_permissions Access permissions
+ * @brief Access permissions for an attribute
+ * @{
+ */
+#define ATTR_NO_ACCESS                             (0x00)
+#define ATTR_ACCESS_READ_ONLY                      (0x01) 
+#define ATTR_ACCESS_WRITE_REQ_ONLY                 (0x02)
+#define ATTR_ACCESS_READ_WRITE                     (0x03)
+#define ATTR_ACCESS_WRITE_WITHOUT_RESPONSE         (0x04)
+#define ATTR_ACCESS_SIGNED_WRITE_ALLOWED           (0x08)
+/**
+ * @}
+ */
+
+/**
+ * Allows all write procedures
+ */
+#define ATTR_ACCESS_WRITE_ANY                      (0x0E)
+
+/**
+ * @defgroup Char_properties Characteristic properties.
+ * @brief Characteristic properties.
+ * @{
+ */
+#define CHAR_PROP_BROADCAST 					(0x01)
+#define CHAR_PROP_READ							(0x02)
+#define CHAR_PROP_WRITE_WITHOUT_RESP			(0x04)
+#define CHAR_PROP_WRITE			                (0x08)
+#define CHAR_PROP_NOTIFY			            (0x10)
+#define CHAR_PROP_INDICATE			            (0x20)
+#define CHAR_PROP_SIGNED_WRITE                  (0x40)
+#define CHAR_PROP_EXT           	            (0x80)
+/**
+ * @}
+ */
+
+
+/** 
+ * @defgroup Security_permissions Security permissions
+ * @brief Security permissions for an attribute.
+ * @{
+ */
+#define ATTR_PERMISSION_NONE                       (0x00) /**< No security. */
+#define ATTR_PERMISSION_AUTHEN_READ                (0x01) /**< Need authentication to read */
+#define ATTR_PERMISSION_AUTHOR_READ                (0x02) /**< Need authorization to read */
+#define ATTR_PERMISSION_ENCRY_READ                 (0x04) /**< Link must be encrypted to read */
+#define ATTR_PERMISSION_AUTHEN_WRITE               (0x08) /**< Need authentication to write */
+#define ATTR_PERMISSION_AUTHOR_WRITE               (0x10) /**< Need authorization to write */
+#define ATTR_PERMISSION_ENCRY_WRITE                (0x20) /**< Link must be encrypted for write */
+/**
+ * @}
+ */
+
+/** 
+ * @defgroup UUID_Types UUID type
+ * @brief Type of UUID (16 bit or 128 bit).
+ * @{
+ */
+#define UUID_TYPE_16                               (0x01)
+#define UUID_TYPE_128                              (0x02)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Service_type Type of service
+ * @brief Type of service (primary or secondary)
+ * @{
+ */
+#define PRIMARY_SERVICE                            (0x01)
+#define SECONDARY_SERVICE                          (0x02)
+/**
+ * @}
+ */
+
+/** 
+ * @defgroup Gatt_Event_Mask GATT Server event bit mask
+ * @brief Type of event generated by GATT server
+ * @{
+ */
+#define GATT_DONT_NOTIFY_EVENTS                       (0x00) /**< Do not notify events. */
+#define GATT_NOTIFY_ATTRIBUTE_WRITE                   (0x01) /**< The application will be notified when a client writes to this attribute.
+                                                                  An @ref EVT_BLUE_GATT_ATTRIBUTE_MODIFIED will be issued. */
+#define GATT_NOTIFY_WRITE_REQ_AND_WAIT_FOR_APPL_RESP  (0x02) /**< The application will be notified when a write request, a write cmd
+                                                                    or a signed write cmd are received by the server for this attribute.
+                                                                    An @ref EVT_BLUE_GATT_WRITE_PERMIT_REQ will be issued. */
+#define GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP   (0x04) /**< The application will be notified when a read request of any type is
+                                                                  received for this attribute. An @ref EVT_BLUE_GATT_READ_PERMIT_REQ will be issued. */
+/**
+ * @}
+ */
+
+/** 
+ * @defgroup Charac_len Characteristic length
+ * @brief See aci_gatt_add_char()
+ * @{
+ */
+#define CHAR_VALUE_LEN_CONSTANT           (0x00)
+#define CHAR_VALUE_LEN_VARIABLE           (0x01)
+/**
+ * @}
+ */
+
+
+/**
+ * Min encryption key size
+ */
+#define MIN_ENCRY_KEY_SIZE                (7)
+
+/**
+ * Max encryption key size
+ */
+#define MAX_ENCRY_KEY_SIZE                (0x10)
+
+
+typedef __packed struct _charactFormat {
+    uint8_t format;
+    int8_t exp;
+    uint16_t unit;
+    uint8_t name_space;
+    uint16_t desc;
+} PACKED charactFormat;
+
+#define FORMAT_UINT8         0x04
+#define FORMAT_UINT16        0x06
+#define FORMAT_SINT16        0x0E
+#define FORMAT_SINT24        0x0F
+
+
+#define UNIT_UNITLESS        0x2700
+#define UNIT_TEMP_CELSIUS    0x272F
+#define UNIT_PRESSURE_BAR    0x2780
+
+
+/*
+ * Default MTU size
+ */
+#define ATT_DEFAULT_MTU       (23)
+
+
+#endif /* __GATT_SERVER_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/gp_timer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/gp_timer.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,93 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : gp_timer.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : General purpose timer library.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __GP_TIMER_H__
+#define __GP_TIMER_H__
+
+#include "clock.h"
+
+/**
+ * timer
+ *
+ * A structure that represents a timer. Use Timer_Set() to set the timer.
+ *
+ */
+struct timer {
+    
+#ifndef DOXYGEN_SHOULD_SKIP_THIS
+    
+  tClockTime start;
+  tClockTime interval;
+  
+#endif
+};
+
+
+/**
+ * Timer_Set
+ *
+ * @param[in] t             Pointer to a timer structure
+ * @param[in] interval      timeout value
+ *
+ * This function sets the timeout value of a timer.
+ *
+ */
+void Timer_Set(struct timer *t, tClockTime interval);
+
+/**
+ * Timer_Reset
+ * 
+ * @param[in] t     Pointer to a timer structure
+ * 
+ * This function resets the timer with the same interval given
+ * with Timer_Set, starting from the time it previously expired.
+ * 
+ */ 
+void Timer_Reset(struct timer *t);
+
+/**
+ * Timer_Restart
+ * 
+ * @param[in]  t   Pointer to a timer structure
+ * 
+ * This function resets the timer with the same interval given
+ * with Timer_Set, starting from the current time.
+ * 
+ */ 
+void Timer_Restart(struct timer *t);
+
+/**
+ * Timer_Expired
+ *
+ * @param[in] t    Pointer to a timer structure
+ *
+ * This function returns TRUE if timer is expired, FALSE otherwise.
+ *
+ */
+int Timer_Expired(struct timer *t);
+
+/**
+ * Timer_Expired
+ *
+ * @param[in] t    Pointer to a timer structure
+ *
+ * This function returns the time needed for expiration.
+ *
+ * @return  Time before timer's expiration.
+ */
+tClockTime Timer_Remaining(struct timer *t);
+
+#endif /* __GP_TIMER_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/hal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/hal.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,99 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : hal.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file which defines Hardware abstraction layer APIs
+*                       used by the BLE stack. It defines the set of functions
+*                       which needs to be ported to the target platform.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+#ifndef __HAL_H__
+#define __HAL_H__
+
+/******************************************************************************
+ * Includes
+ *****************************************************************************/
+#include <hal_types.h>
+#include <ble_status.h>
+
+
+/******************************************************************************
+ * Macros
+ *****************************************************************************/
+/* Little Endian buffer to host endianess conversion */
+#define LE_TO_HOST_16(ptr)  (uint16_t) ( ((uint16_t) \
+                                           *((uint8_t *)ptr)) | \
+                                          ((uint16_t) \
+                                           *((uint8_t *)ptr + 1) << 8 ) )
+
+#define LE_TO_HOST_32(ptr)   (uint32_t) ( ((uint32_t) \
+                                           *((uint8_t *)ptr)) | \
+                                           ((uint32_t) \
+                                            *((uint8_t *)ptr + 1) << 8)  | \
+                                           ((uint32_t) \
+                                            *((uint8_t *)ptr + 2) << 16) | \
+                                           ((uint32_t) \
+                                            *((uint8_t *)ptr + 3) << 24) )
+
+/* Big Endian buffer to host endianess conversion */
+#define BE_TO_HOST_16(ptr)  (uint16_t) ( ((uint16_t) \
+                                           *((uint8_t *)ptr)) << 8 | \
+                                          ((uint16_t) \
+                                           *((uint8_t *)ptr + 1) ) )
+											
+/* Store Value into a buffer in Little Endian Format */
+#define HOST_TO_LE_16(buf, val)    ( ((buf)[0] =  (uint8_t) (val)    ) , \
+                                   ((buf)[1] =  (uint8_t) (val>>8) ) )
+
+#define HOST_TO_LE_32(buf, val)    ( ((buf)[0] =  (uint8_t) (val)     ) , \
+                                   ((buf)[1] =  (uint8_t) (val>>8)  ) , \
+                                   ((buf)[2] =  (uint8_t) (val>>16) ) , \
+                                   ((buf)[3] =  (uint8_t) (val>>24) ) ) 
+
+
+/* Store Value into a buffer in Big Endian Format */
+#define HOST_TO_BE_16(buf, val)    ( ((buf)[1] =  (uint8_t) (val)    ) , \
+                                   ((buf)[0] =  (uint8_t) (val>>8) ) )
+ 
+/******************************************************************************
+ * Types
+ *****************************************************************************/
+
+/******************************************************************************
+ * Function Prototypes
+ *****************************************************************************/
+
+/**
+ * Writes data to a serial interface.
+ *
+ * @param[in]  data1    1st buffer
+ * @param[in]  data2    2nd buffer
+ * @param[in]  n_bytes1 number of bytes in 1st buffer
+ * @param[in]  n_bytes2 number of bytes in 2nd buffer
+ */
+//void Hal_Write_Serial(const void* data1, const void* data2, uint16_t n_bytes1, uint16_t n_bytes2);
+
+/**
+ * Enable interrupts from HCI controller.
+ */
+void Enable_SPI_IRQ(void);
+
+/**
+ * Disable interrupts from BLE controller.
+ */
+void Disable_SPI_IRQ(void);
+
+void Hal_Init_Timer();
+uint32_t Hal_Get_Timer_Value();
+void Hal_Start_Timer(uint32_t timeout);
+void Hal_Stop_Timer();
+
+#endif /* __HAL_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/hal_types.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/hal_types.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,59 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : hal_types.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : This header file defines the basic data types used by the
+*                       BLE stack.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+#ifndef __HAL_TYPES_H__
+#define __HAL_TYPES_H__
+
+#include <stdint.h>
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#ifndef __LITTLE_ENDIAN
+#define __LITTLE_ENDIAN 0
+#define __BIG_ENDIAN    1
+#endif
+
+/* Byte order conversions */
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define htobs(d)  (d)
+#define htobl(d)  (d)
+#define btohs(d)  (d)
+#define btohl(d)  (d)
+#elif __BYTE_ORDER == __BIG_ENDIAN
+#define htobs(d)  (d<<8|d>>8)
+#define htobl(d)  (d<<24|((d<<8)&0x00ff0000)|((d>>8)&0x0000ff00)|((d>>24)&0x000000ff))
+#define btohs(d)  (d<<8|d>>8)
+#define btohl(d)  (d<<24|((d<<8)&0x00ff0000)|((d>>8)&0x0000ff00)|((d>>24)&0x000000ff))
+#else
+#error "Unknown byte order"
+#endif
+
+typedef uint8_t BOOL;
+
+#ifndef TRUE 
+#define TRUE (1)
+#endif
+
+#ifndef FALSE
+#define FALSE (0)
+#endif
+
+
+
+#endif /* __HAL_TYPES_H__ */ 
+
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/hci.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/hci.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,215 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : hci.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Constants and functions for HCI layer. See Bluetooth Core
+*                       v 4.0, Vol. 2, Part E.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __HCI_H_
+#define __HCI_H_
+
+#include "hal_types.h"
+#include "link_layer.h"
+#include <list.h>
+
+
+#define HCI_PACKET_SIZE				        128 //71
+
+
+/*** Data types ***/
+
+/* structure used to read received data */
+typedef struct _tHciDataPacket
+{
+    tListNode currentNode;
+	uint8_t dataBuff[HCI_PACKET_SIZE];
+}tHciDataPacket;
+
+/**
+ * @defgroup HCI_Error_codes HCI Error codes
+ * @{
+ */
+#define HCI_UNKNOWN_COMMAND					0x01
+#define HCI_NO_CONNECTION					0x02
+#define HCI_HARDWARE_FAILURE				0x03
+#define HCI_PAGE_TIMEOUT					0x04
+#define HCI_AUTHENTICATION_FAILURE			0x05
+#define HCI_PIN_OR_KEY_MISSING				0x06
+#define HCI_MEMORY_FULL						0x07
+#define HCI_CONNECTION_TIMEOUT				0x08
+#define HCI_MAX_NUMBER_OF_CONNECTIONS		0x09
+#define HCI_MAX_NUMBER_OF_SCO_CONNECTIONS	0x0a
+#define HCI_ACL_CONNECTION_EXISTS			0x0b
+#define HCI_COMMAND_DISALLOWED				0x0c
+#define HCI_REJECTED_LIMITED_RESOURCES		0x0d
+#define HCI_REJECTED_SECURITY				0x0e
+#define HCI_REJECTED_PERSONAL				0x0f
+#define HCI_HOST_TIMEOUT					0x10
+#define HCI_UNSUPPORTED_FEATURE				0x11
+#define HCI_INVALID_PARAMETERS				0x12
+#define HCI_OE_USER_ENDED_CONNECTION		0x13
+#define HCI_OE_LOW_RESOURCES				0x14
+#define HCI_OE_POWER_OFF					0x15
+#define HCI_CONNECTION_TERMINATED			0x16
+#define HCI_REPEATED_ATTEMPTS				0x17
+#define HCI_PAIRING_NOT_ALLOWED				0x18
+#define HCI_UNKNOWN_LMP_PDU					0x19
+#define HCI_UNSUPPORTED_REMOTE_FEATURE		0x1a
+#define HCI_SCO_OFFSET_REJECTED				0x1b
+#define HCI_SCO_INTERVAL_REJECTED			0x1c
+#define HCI_AIR_MODE_REJECTED				0x1d
+#define HCI_INVALID_LMP_PARAMETERS			0x1e
+#define HCI_UNSPECIFIED_ERROR				0x1f
+#define HCI_UNSUPPORTED_LMP_PARAMETER_VALUE	0x20
+#define HCI_ROLE_CHANGE_NOT_ALLOWED			0x21
+#define HCI_LMP_RESPONSE_TIMEOUT			0x22
+#define HCI_LMP_ERROR_TRANSACTION_COLLISION	0x23
+#define HCI_LMP_PDU_NOT_ALLOWED				0x24
+#define HCI_ENCRYPTION_MODE_NOT_ACCEPTED	0x25
+#define HCI_UNIT_LINK_KEY_USED				0x26
+#define HCI_QOS_NOT_SUPPORTED				0x27
+#define HCI_INSTANT_PASSED					0x28
+#define HCI_PAIRING_NOT_SUPPORTED			0x29
+#define HCI_TRANSACTION_COLLISION			0x2a
+#define HCI_QOS_UNACCEPTABLE_PARAMETER		0x2c
+#define HCI_QOS_REJECTED					0x2d
+#define HCI_CLASSIFICATION_NOT_SUPPORTED	0x2e
+#define HCI_INSUFFICIENT_SECURITY			0x2f
+#define HCI_PARAMETER_OUT_OF_RANGE			0x30
+#define HCI_ROLE_SWITCH_PENDING				0x32
+#define HCI_SLOT_VIOLATION					0x34
+#define HCI_ROLE_SWITCH_FAILED				0x35
+#define HCI_EIR_TOO_LARGE					0x36
+#define HCI_SIMPLE_PAIRING_NOT_SUPPORTED	0x37
+#define HCI_HOST_BUSY_PAIRING				0x38
+#define HCI_CONN_REJ_NO_CH_FOUND			0x39
+#define HCI_CONTROLLER_BUSY					0x3A
+#define HCI_UNACCEPTABLE_CONN_INTERV		0x3B
+#define HCI_DIRECTED_ADV_TIMEOUT			0x3C
+#define HCI_CONN_TERM_MIC_FAIL				0x3D
+#define HCI_CONN_FAIL_TO_BE_ESTABL			0x3E
+#define HCI_MAC_CONN_FAILED					0x3F
+/**
+ * @}
+ */
+
+
+/*
+ * HCI library functions.
+ * Each function returns 0 in case of success, -1 otherwise.
+ */
+
+int hci_reset(void);
+
+int hci_disconnect(uint16_t	handle, uint8_t reason);
+
+int hci_le_set_advertise_enable(uint8_t enable);
+
+int hci_le_set_advertising_parameters(uint16_t min_interval, uint16_t max_interval, uint8_t advtype,
+		uint8_t own_bdaddr_type, uint8_t direct_bdaddr_type, tBDAddr direct_bdaddr, uint8_t chan_map,
+		uint8_t filter);
+
+int hci_le_set_advertising_data(uint8_t length, const uint8_t data[]);
+
+int hci_le_set_scan_resp_data(uint8_t length, const uint8_t data[]);
+
+int hci_le_rand(uint8_t random_number[8]);
+
+int hci_le_read_advertising_channel_tx_power(int8_t *tx_power_level);
+
+int hci_acl_data(const uint8_t * data, uint16_t len);
+
+int hci_le_set_random_address(tBDAddr bdaddr);
+
+int hci_read_bd_addr(tBDAddr bdaddr);
+
+int hci_le_read_white_list_size(uint8_t *size);
+
+int hci_le_clear_white_list();
+
+int hci_le_add_device_to_white_list(uint8_t	bdaddr_type, tBDAddr bdaddr);
+
+int hci_le_remove_device_from_white_list(uint8_t bdaddr_type, tBDAddr bdaddr);
+
+int hci_le_encrypt(uint8_t key[16], uint8_t plaintextData[16], uint8_t encryptedData[16]);
+
+int hci_le_ltk_request_reply(uint8_t key[16]);
+
+int hci_le_ltk_request_neg_reply();
+
+int hci_le_read_buffer_size(uint16_t *pkt_len, uint8_t *max_pkt);
+
+int hci_le_create_connection(uint16_t interval,	uint16_t window, uint8_t initiator_filter, uint8_t peer_bdaddr_type,
+                             const tBDAddr peer_bdaddr,	uint8_t	own_bdaddr_type, uint16_t min_interval,	uint16_t max_interval,
+                             uint16_t latency,	uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length);
+
+int hci_read_transmit_power_level(uint16_t *conn_handle, uint8_t type, int8_t * tx_level);
+
+int hci_read_rssi(uint16_t *conn_handle, int8_t * rssi);
+
+int hci_le_read_local_supported_features(uint8_t *features);
+
+int hci_le_read_channel_map(uint16_t conn_handle, uint8_t ch_map[5]);
+
+int hci_le_read_supported_states(uint8_t states[8]);
+
+int hci_le_receiver_test(uint8_t frequency);
+
+int hci_le_transmitter_test(uint8_t frequency, uint8_t length, uint8_t payload);
+
+int hci_le_test_end(uint16_t *num_pkts);
+
+int hci_le_read_local_version(uint8_t *hci_version, uint16_t *hci_revision, uint8_t *lmp_pal_version, 
+			      uint16_t *manufacturer_name, uint16_t *lmp_pal_subversion);
+
+/**
+ * This function must be used to pass the packet received from the HCI
+ * interface to the BLE Stack HCI state machine.
+ *
+ * @param[in] hciReadPacket    The packet that is received from HCI interface.
+ *
+ */
+void HCI_Input(tHciDataPacket * hciReadPacket);
+
+/**
+ * Initialization function. Must be done before any data can be received from
+ * BLE controller.
+ */
+void HCI_Init(void);
+
+/**
+ * Callback used to pass events to application.
+ *
+ * @param[in] pckt    The event.
+ *
+ */
+extern void HCI_Event_CB(void *pckt);
+
+/**
+ * Processing function that must be called after an event is received from
+ * HCI interface. Must be called outside ISR. It will call HCI_Event_CB if
+ * necessary.
+*/
+void HCI_Process(void);
+
+/**
+ * Iterrupt service routine that must be called when the BlueNRG 
+ * reports a packet received or an event to the host through the 
+ * BlueNRG interrupt line.
+ */
+void HCI_Isr(void);
+
+extern tListNode hciReadPktPool;
+extern tListNode hciReadPktRxQueue;
+
+#endif /* __HCI_H_ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/hci_const.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/hci_const.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,563 @@
+/******************************************************************************
+*
+*  File Description 
+*  ---------------------
+* This file defines constants and functions for HCI layer.
+* See Bluetooth Core v 4.0, Vol. 2, Part E.
+* 
+*******************************************************************************/
+
+#ifndef __HCI_INTERNAL_H_
+#define __HCI_INTERNAL_H_
+
+#include "compiler.h"
+#include "hal_types.h"
+#include "clock.h"
+#include "link_layer.h"
+#include "hci.h"
+
+#define DEFAULT_TIMEOUT (CLOCK_SECOND/10)
+
+#define HCI_MAX_PACKET_SIZE 128
+
+/* HCI Packet types */
+#define HCI_COMMAND_PKT		0x01
+#define HCI_ACLDATA_PKT		0x02
+#define HCI_SCODATA_PKT		0x03
+#define HCI_EVENT_PKT		0x04
+#define HCI_VENDOR_PKT		0xff
+
+
+typedef __packed struct _hci_uart_pckt{
+	uint8_t	type;
+	uint8_t	data[0];
+} PACKED hci_uart_pckt;
+#define HCI_HDR_SIZE 1
+
+typedef __packed struct _hci_command_hdr{
+	uint16_t	opcode;		/* OCF & OGF */
+	uint8_t		plen;
+} PACKED hci_command_hdr;
+#define HCI_COMMAND_HDR_SIZE 	3
+
+typedef __packed struct _hci_event_pckt{
+	uint8_t		evt;
+	uint8_t		plen;
+    uint8_t	    data[0];
+} PACKED hci_event_pckt;
+#define HCI_EVENT_HDR_SIZE 	2
+
+typedef __packed struct _hci_acl_hdr{
+	uint16_t	handle;		/* Handle & Flags(PB, BC) */
+	uint16_t	dlen;
+} PACKED hci_acl_hdr;
+#define HCI_ACL_HDR_SIZE 	4
+
+
+/* Link Control */
+#define OGF_LINK_CTL		            0x01
+
+#define OCF_DISCONNECT			        0x0006
+typedef __packed struct _disconnect_cp{
+	uint16_t	handle;
+	uint8_t		reason;
+} PACKED disconnect_cp;
+#define DISCONNECT_CP_SIZE 3
+
+
+/* Host Controller and Baseband */
+#define OGF_HOST_CTL		            0x03
+
+#define OCF_SET_EVENT_MASK              0x0001
+#define OCF_RESET			            0x0003
+
+#define OCF_READ_TRANSMIT_POWER_LEVEL	0x002D
+typedef __packed struct _read_transmit_power_level_cp{
+	uint16_t	handle;
+	uint8_t		type;
+} PACKED read_transmit_power_level_cp;
+#define READ_TRANSMIT_POWER_LEVEL_CP_SIZE 3
+typedef __packed struct _read_transmit_power_level_rp{
+	uint8_t		status;
+	uint16_t	handle;
+	int8_t		level;
+} PACKED read_transmit_power_level_rp;
+#define READ_TRANSMIT_POWER_LEVEL_RP_SIZE 4
+
+#define OCF_SET_CONTROLLER_TO_HOST_FC	0x0031
+#define OCF_HOST_BUFFER_SIZE		    0x0033
+#define OCF_HOST_NUM_COMP_PKTS		    0x0035
+
+/* Informational Parameters */
+#define OGF_INFO_PARAM		            0x04
+
+#define OCF_READ_LOCAL_VERSION		    0x0001
+typedef __packed struct _read_local_version_rp{
+	uint8_t		status;
+	uint8_t		hci_version;
+    uint16_t    hci_revision;
+    uint8_t		lmp_pal_version;
+    uint16_t	manufacturer_name;
+    uint16_t	lmp_pal_subversion;
+} PACKED read_local_version_rp;
+#define READ_LOCAL_VERSION_RP_SIZE 9
+
+#define OCF_READ_LOCAL_COMMANDS		    0x0002
+#define OCF_READ_LOCAL_FEATURES		    0x0003
+
+#define OCF_READ_BD_ADDR		0x0009
+typedef __packed struct _read_bd_addr_rp{
+	uint8_t		status;
+	tBDAddr		bdaddr;
+} PACKED read_bd_addr_rp;
+#define READ_BD_ADDR_RP_SIZE 7
+
+/* Status params */
+#define OGF_STATUS_PARAM	            0x05
+
+#define OCF_READ_RSSI                   0x0005
+typedef __packed struct _read_rssi_cp{
+	uint16_t	handle;
+} PACKED read_rssi_cp;
+#define READ_RSSI_CP_SIZE 2
+typedef __packed struct _read_rssi_rp{
+	uint8_t		status;
+	uint16_t	handle;
+	int8_t		rssi;
+} PACKED read_rssi_rp;
+#define READ_RSSI_RP_SIZE 4
+
+
+/* LE commands */
+#define OGF_LE_CTL		0x08
+
+#define OCF_LE_SET_EVENT_MASK			0x0001
+typedef __packed struct _le_set_event_mask_cp{
+	uint8_t		mask[8];
+} PACKED le_set_event_mask_cp;
+#define LE_SET_EVENT_MASK_CP_SIZE 8
+
+#define OCF_LE_READ_BUFFER_SIZE			0x0002
+typedef __packed struct _le_read_buffer_size_rp{
+	uint8_t		status;
+	uint16_t	pkt_len;
+	uint8_t		max_pkt;
+} PACKED le_read_buffer_size_rp;
+#define LE_READ_BUFFER_SIZE_RP_SIZE 4
+
+#define OCF_LE_READ_LOCAL_SUPPORTED_FEATURES	0x0003
+typedef __packed struct _le_read_local_supported_features_rp{
+	uint8_t		status;
+	uint8_t		features[8];
+} PACKED le_read_local_supported_features_rp;
+#define LE_READ_LOCAL_SUPPORTED_FEATURES_RP_SIZE 9
+
+#define OCF_LE_SET_RANDOM_ADDRESS		0x0005
+typedef __packed struct _le_set_random_address_cp{
+	tBDAddr	bdaddr;
+} PACKED le_set_random_address_cp;
+#define LE_SET_RANDOM_ADDRESS_CP_SIZE 6
+
+#define OCF_LE_SET_ADV_PARAMETERS	0x0006
+typedef __packed struct _le_set_adv_parameters_cp{
+	uint16_t	min_interval;
+	uint16_t	max_interval;
+	uint8_t		advtype;
+	uint8_t		own_bdaddr_type;
+	uint8_t		direct_bdaddr_type;
+	tBDAddr		direct_bdaddr;
+	uint8_t		chan_map;
+	uint8_t		filter;
+} PACKED le_set_adv_parameters_cp;
+#define LE_SET_ADV_PARAMETERS_CP_SIZE 15
+
+#define OCF_LE_READ_ADV_CHANNEL_TX_POWER	0x0007
+typedef __packed struct _le_read_adv_channel_tx_power_rp{
+	uint8_t		status;
+	int8_t		level;
+} PACKED le_read_adv_channel_tx_power_rp;
+#define LE_READ_ADV_CHANNEL_TX_POWER_RP_SIZE 2
+
+#define OCF_LE_SET_ADV_DATA		0x0008
+typedef __packed struct _le_set_adv_data_cp{
+	uint8_t		length;
+	uint8_t		data[31];
+} PACKED le_set_adv_data_cp;
+#define LE_SET_ADV_DATA_CP_SIZE 32
+
+#define OCF_LE_SET_SCAN_RESPONSE_DATA		0x0009
+typedef __packed struct _le_set_scan_response_data_cp{
+	uint8_t		length;
+	uint8_t		data[31];
+} PACKED le_set_scan_response_data_cp;
+#define LE_SET_SCAN_RESPONSE_DATA_CP_SIZE 32
+
+#define OCF_LE_SET_ADVERTISE_ENABLE		0x000A
+typedef __packed struct _le_set_advertise_enable_cp{
+	uint8_t		enable;
+} PACKED le_set_advertise_enable_cp;
+#define LE_SET_ADVERTISE_ENABLE_CP_SIZE 1
+
+#define OCF_LE_SET_SCAN_PARAMETERS		0x000B
+typedef __packed struct _le_set_scan_parameters_cp{
+	uint8_t		type;
+	uint16_t	interval;
+	uint16_t	window;
+	uint8_t		own_bdaddr_type;
+	uint8_t		filter;
+} PACKED le_set_scan_parameters_cp;
+#define LE_SET_SCAN_PARAMETERS_CP_SIZE 7
+
+#define OCF_LE_SET_SCAN_ENABLE			0x000C
+typedef __packed struct _le_set_scan_enable_cp{
+	uint8_t		enable;
+	uint8_t		filter_dup;
+} PACKED le_set_scan_enable_cp;
+#define LE_SET_SCAN_ENABLE_CP_SIZE 2
+
+#define OCF_LE_CREATE_CONN			0x000D
+typedef __packed struct _le_create_connection_cp{
+	uint16_t	interval;
+	uint16_t	window;
+	uint8_t		initiator_filter;
+	uint8_t		peer_bdaddr_type;
+	tBDAddr	  peer_bdaddr;
+	uint8_t		own_bdaddr_type;
+	uint16_t	min_interval;
+	uint16_t	max_interval;
+	uint16_t	latency;
+	uint16_t	supervision_timeout;
+	uint16_t	min_ce_length;
+	uint16_t	max_ce_length;
+} PACKED le_create_connection_cp;
+#define LE_CREATE_CONN_CP_SIZE 25
+
+#define OCF_LE_CREATE_CONN_CANCEL		0x000E
+
+#define OCF_LE_READ_WHITE_LIST_SIZE		0x000F
+typedef __packed struct _le_read_white_list_size_rp{
+	uint8_t		status;
+	uint8_t		size;
+} PACKED le_read_white_list_size_rp;
+#define LE_READ_WHITE_LIST_SIZE_RP_SIZE 2
+
+#define OCF_LE_CLEAR_WHITE_LIST			0x0010
+
+#define OCF_LE_ADD_DEVICE_TO_WHITE_LIST		0x0011
+typedef __packed struct _le_add_device_to_white_list_cp{
+	uint8_t		bdaddr_type;
+	tBDAddr 	bdaddr;
+} PACKED le_add_device_to_white_list_cp;
+#define LE_ADD_DEVICE_TO_WHITE_LIST_CP_SIZE 7
+
+#define OCF_LE_REMOVE_DEVICE_FROM_WHITE_LIST	0x0012
+typedef __packed struct _le_remove_device_from_white_list_cp{
+	uint8_t		bdaddr_type;
+	tBDAddr 	bdaddr;
+} PACKED le_remove_device_from_white_list_cp;
+#define LE_REMOVE_DEVICE_FROM_WHITE_LIST_CP_SIZE 7
+
+#define OCF_LE_CONN_UPDATE			0x0013
+typedef __packed struct _le_connection_update_cp{
+	uint16_t	handle;
+	uint16_t	min_interval;
+	uint16_t	max_interval;
+	uint16_t	latency;
+	uint16_t	supervision_timeout;
+	uint16_t	min_ce_length;
+	uint16_t	max_ce_length;
+} PACKED le_connection_update_cp;
+#define LE_CONN_UPDATE_CP_SIZE 14
+
+#define OCF_LE_SET_HOST_CHANNEL_CLASSIFICATION	0x0014
+typedef __packed struct _le_set_host_channel_classification_cp{
+	uint8_t		map[5];
+} PACKED le_set_host_channel_classification_cp;
+#define LE_SET_HOST_CHANNEL_CLASSIFICATION_CP_SIZE 5
+
+#define OCF_LE_READ_CHANNEL_MAP			0x0015
+typedef __packed struct _le_read_channel_map_cp{
+	uint16_t	handle;
+} PACKED le_read_channel_map_cp;
+#define LE_READ_CHANNEL_MAP_CP_SIZE 2
+
+typedef __packed struct _le_read_channel_map_rp{
+	uint8_t		status;
+	uint16_t	handle;
+	uint8_t		map[5];
+}  le_read_channel_map_rp;
+#define LE_READ_CHANNEL_MAP_RP_SIZE 8
+
+#define OCF_LE_READ_REMOTE_USED_FEATURES	0x0016
+typedef __packed struct _le_read_remote_used_features_cp{
+	uint16_t	handle;
+} PACKED le_read_remote_used_features_cp;
+#define LE_READ_REMOTE_USED_FEATURES_CP_SIZE 2
+
+#define OCF_LE_ENCRYPT				0x0017
+typedef __packed struct _le_encrypt_cp{
+	uint8_t		key[16];
+	uint8_t		plaintext[16];
+} PACKED le_encrypt_cp;
+#define LE_ENCRYPT_CP_SIZE 32
+
+typedef __packed struct _le_encrypt_rp{
+	uint8_t		status;
+	uint8_t		encdata[16];
+} PACKED le_encrypt_rp;
+#define LE_ENCRYPT_RP_SIZE 17
+
+#define OCF_LE_RAND				0x0018
+typedef __packed struct _le_rand_rp{
+	uint8_t	status;
+	uint8_t	random[8];
+} PACKED le_rand_rp;
+#define LE_RAND_RP_SIZE 9
+
+#define OCF_LE_START_ENCRYPTION			0x0019
+typedef __packed struct _le_start_encryption_cp{
+	uint16_t	handle;
+	uint8_t	    random[8];
+	uint16_t	diversifier;
+	uint8_t		key[16];
+} PACKED le_start_encryption_cp;
+#define LE_START_ENCRYPTION_CP_SIZE 28
+
+#define OCF_LE_LTK_REPLY			0x001A
+typedef __packed struct _le_ltk_reply_cp{
+	uint16_t	handle;
+	uint8_t		key[16];
+} PACKED le_ltk_reply_cp;
+#define LE_LTK_REPLY_CP_SIZE 18
+  
+typedef __packed struct _le_ltk_reply_rp{
+	uint8_t		status;
+	uint16_t	handle;
+} PACKED le_ltk_reply_rp;
+#define LE_LTK_REPLY_RP_SIZE 3
+
+#define OCF_LE_LTK_NEG_REPLY			0x001B
+typedef __packed struct _le_ltk_neg_reply_cp{
+	uint16_t	handle;
+} PACKED le_ltk_neg_reply_cp;
+#define LE_LTK_NEG_REPLY_CP_SIZE 2
+
+typedef __packed struct _le_ltk_neg_reply_rp{
+	uint8_t		status;
+	uint16_t	handle;
+} PACKED le_ltk_neg_reply_rp;
+#define LE_LTK_NEG_REPLY_RP_SIZE 3
+
+#define OCF_LE_READ_SUPPORTED_STATES		0x001C
+typedef __packed struct _le_read_supported_states_rp{
+	uint8_t		status;
+	uint8_t	    states[8];
+} PACKED le_read_supported_states_rp;
+#define LE_READ_SUPPORTED_STATES_RP_SIZE 9
+
+#define OCF_LE_RECEIVER_TEST			0x001D
+typedef __packed struct _le_receiver_test_cp{
+	uint8_t		frequency;
+} PACKED le_receiver_test_cp;
+#define LE_RECEIVER_TEST_CP_SIZE 1
+
+#define OCF_LE_TRANSMITTER_TEST			0x001E
+typedef __packed struct _le_transmitter_test_cp{
+	uint8_t		frequency;
+	uint8_t		length;
+	uint8_t		payload;
+} PACKED le_transmitter_test_cp;
+#define LE_TRANSMITTER_TEST_CP_SIZE 3
+
+#define OCF_LE_TEST_END				0x001F
+typedef __packed struct _le_test_end_rp{
+	uint8_t		status;
+	uint16_t	num_pkts;
+} PACKED le_test_end_rp;
+#define LE_TEST_END_RP_SIZE 3
+
+/* Vendor specific commands */
+#define OGF_VENDOR_CMD		0x3f
+
+
+/*------------- Events -------------*/
+#define EVT_CONN_COMPLETE		0x03
+typedef __packed struct _evt_conn_complete{
+	uint8_t		status;
+	uint16_t	handle;
+	tBDAddr 	bdaddr;
+	uint8_t		link_type;
+	uint8_t		encr_mode;
+} PACKED evt_conn_complete;
+#define EVT_CONN_COMPLETE_SIZE 13
+
+#define EVT_DISCONN_COMPLETE		0x05
+typedef __packed struct _evt_disconn_complete{
+	uint8_t		status;
+	uint16_t	handle;
+	uint8_t		reason;
+} PACKED evt_disconn_complete;
+#define EVT_DISCONN_COMPLETE_SIZE 4
+
+#define EVT_ENCRYPT_CHANGE		0x08
+typedef __packed struct _evt_encrypt_change{
+	uint8_t		status;
+	uint16_t	handle;
+	uint8_t		encrypt;
+} PACKED evt_encrypt_change;
+#define EVT_ENCRYPT_CHANGE_SIZE 5
+
+#define EVT_READ_REMOTE_VERSION_COMPLETE	0x0C
+
+#define EVT_CMD_COMPLETE 		0x0E
+typedef __packed struct _evt_cmd_complete{
+	uint8_t		ncmd;
+	uint16_t	opcode;
+} PACKED evt_cmd_complete;
+#define EVT_CMD_COMPLETE_SIZE 3
+
+#define EVT_CMD_STATUS 			0x0F
+typedef __packed struct _evt_cmd_status{
+	uint8_t		status;
+	uint8_t		ncmd;
+	uint16_t	opcode;
+} PACKED evt_cmd_status;
+#define EVT_CMD_STATUS_SIZE 4
+
+#define EVT_HARDWARE_ERROR		0x10
+typedef __packed struct _evt_hardware_error{
+	uint8_t		code;
+} PACKED evt_hardware_error;
+#define EVT_HARDWARE_ERROR_SIZE 1
+
+#define EVT_NUM_COMP_PKTS		0x13
+typedef __packed struct _evt_num_comp_pkts{
+	uint8_t		num_hndl;
+	/* variable length part */
+} PACKED evt_num_comp_pkts;
+#define EVT_NUM_COMP_PKTS_SIZE 1
+
+/* variable length part of evt_num_comp_pkts. */
+typedef __packed struct _evt_num_comp_pkts_param{
+	uint16_t		hndl;
+	uint16_t		num_comp_pkts;
+} PACKED evt_num_comp_pkts_param;
+#define EVT_NUM_COMP_PKTS_PARAM_SIZE 1
+
+#define EVT_DATA_BUFFER_OVERFLOW		0x1A
+typedef __packed struct _evt_data_buffer_overflow{
+	uint8_t		link_type;
+} PACKED evt_data_buffer_overflow;
+#define EVT_DATA_BUFFER_OVERFLOW_SIZE 1
+
+#define EVT_ENCRYPTION_KEY_REFRESH_COMPLETE	0x30
+typedef __packed struct _evt_encryption_key_refresh_complete{
+	uint8_t		status;
+	uint16_t	handle;
+} PACKED evt_encryption_key_refresh_complete;
+#define EVT_ENCRYPTION_KEY_REFRESH_COMPLETE_SIZE 3
+
+#define EVT_LE_META_EVENT	0x3E
+typedef __packed struct _evt_le_meta_event{
+	uint8_t		subevent;
+	uint8_t		data[0];
+} PACKED evt_le_meta_event;
+#define EVT_LE_META_EVENT_SIZE 1
+
+#define EVT_LE_CONN_COMPLETE	0x01
+typedef __packed struct _evt_le_connection_complete{
+	uint8_t		status;
+	uint16_t	handle;
+	uint8_t		role;
+	uint8_t		peer_bdaddr_type;
+	tBDAddr	    peer_bdaddr;
+	uint16_t	interval;
+	uint16_t	latency;
+	uint16_t	supervision_timeout;
+	uint8_t		master_clock_accuracy;
+} PACKED evt_le_connection_complete;
+#define EVT_LE_CONN_COMPLETE_SIZE 18
+
+#define EVT_LE_ADVERTISING_REPORT	0x02
+typedef __packed struct _le_advertising_info{
+	uint8_t		evt_type;
+	uint8_t		bdaddr_type;
+	tBDAddr	    bdaddr;
+	uint8_t		length;
+	uint8_t		data_RSSI[0]; // RSSI is last octect (signed integer).
+} PACKED le_advertising_info;
+#define LE_ADVERTISING_INFO_SIZE 9
+
+#define EVT_LE_CONN_UPDATE_COMPLETE	0x03
+typedef __packed struct _evt_le_connection_update_complete{
+	uint8_t		status;
+	uint16_t	handle;
+	uint16_t	interval;
+	uint16_t	latency;
+	uint16_t	supervision_timeout;
+} PACKED evt_le_connection_update_complete;
+#define EVT_LE_CONN_UPDATE_COMPLETE_SIZE 9
+
+#define EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE	0x04
+typedef __packed struct _evt_le_read_remote_used_features_complete{
+	uint8_t		status;
+	uint16_t	handle;
+	uint8_t		features[8];
+} PACKED evt_le_read_remote_used_features_complete;
+#define EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE_SIZE 11
+
+#define EVT_LE_LTK_REQUEST	0x05
+typedef __packed struct _evt_le_long_term_key_request{
+	uint16_t	handle;
+	uint8_t	    random[8];
+	uint16_t	ediv;
+} PACKED evt_le_long_term_key_request;
+#define EVT_LE_LTK_REQUEST_SIZE 12
+
+/**
+ * The event code in the @ref hci_event_pckt structure. If event code is EVT_VENDOR,
+ * application can use @ref evt_blue_aci structure to parse the packet.
+ */
+#define EVT_VENDOR	0xFF
+
+
+/* Command opcode pack/unpack */
+#define cmd_opcode_pack(ogf, ocf)	(uint16_t)((ocf & 0x03ff)|(ogf << 10))
+#define cmd_opcode_ogf(op)		(op >> 10)
+#define cmd_opcode_ocf(op)		(op & 0x03ff)
+
+
+struct hci_request {
+	uint16_t ogf;
+	uint16_t ocf;
+	int      event;
+	void     *cparam;
+	int      clen;
+	void     *rparam;
+	int      rlen;
+};
+
+int hci_send_cmd(uint16_t ogf, uint16_t ocf, uint8_t plen, void *param);
+
+typedef enum {
+	WAITING_TYPE,
+    WAITING_OPCODE1,
+    WAITING_OPCODE2,
+	WAITING_EVENT_CODE,
+	WAITING_HANDLE,
+	WAITING_HANDLE_FLAG,
+	WAITING_PARAM_LEN,
+	WAITING_DATA_LEN1,
+	WAITING_DATA_LEN2,
+	WAITING_PAYLOAD
+}hci_state;
+
+typedef void (*hci_packet_complete_callback)(void *pckt, uint16_t len);
+
+/* HCI library functions. */
+void hci_init(void);
+
+int hci_send_req(struct hci_request *r);
+
+#endif /* __HCI_INTERNAL_H_ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/link_layer.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/link_layer.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,102 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : link_layer.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file for BlueNRG's link layer. It contains
+*                      definition of functions for link layer, most of which are
+*                      mapped to HCI commands.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef _LINK_LAYER_H
+#define _LINK_LAYER_H
+
+#include <ble_status.h>
+
+/**
+ * advertising policy for filtering (white list related) 
+ */
+#define NO_WHITE_LIST_USE           (0x00)  /** Process scan and connection requests from all devices (i.e., the White List is not in use) */
+#define WHITE_LIST_FOR_ONLY_SCAN    (0x01)  /** Process connection requests from all devices and only scan requests from devices that are in the White List */
+#define WHITE_LIST_FOR_ONLY_CONN    (0x02)  /** Process scan requests from all devices and only connection requests from devices that are in the White List */
+#define WHITE_LIST_FOR_ALL          (0x03)  /** Process scan and connection requests only from devices in the White List. */
+
+/**
+ * Bluetooth 48 bit address (in little-endian order).
+ */
+typedef	uint8_t	tBDAddr[6];
+
+
+/** 
+ * Bluetooth address type
+ */
+#define RANDOM_ADDR     (1)
+#define PUBLIC_ADDR     (0)
+
+/** 
+ * Advertising type
+ */
+
+/**
+ * undirected scannable and connectable 
+ */ 
+#define ADV_IND         (0x00)
+
+/** 
+ * directed non scannable
+ */
+#define ADV_DIRECT_IND  (0x01)
+
+/**
+ * scannable non connectable
+ */
+#define ADV_SCAN_IND    (0x02)
+
+/**
+ * non-connectable and no scan response (used for passive scan)
+ */
+#define ADV_NONCONN_IND (0x03)
+
+
+/* 0X04-0XFF RESERVED */
+
+
+/** 
+ * lowest allowed interval value for connectable types(20ms)..multiple of 625us
+ */
+#define ADV_INTERVAL_LOWEST_CONN    (0X0020)
+
+/** 
+ * highest allowed interval value (10.24s)..multiple of 625us.
+ */
+#define ADV_INTERVAL_HIGHEST        (0X4000)
+
+/** 
+ * lowest allowed interval value for non connectable types
+ * (100ms)..multiple of 625us.
+ */
+#define ADV_INTERVAL_LOWEST_NONCONN (0X00a0)
+
+/** 
+ * Default value of advertising interval for both min/max values.
+ * This will be used if host does not specify any advertising parameters 
+ * including advIntervalMax and advIntervalMin
+ * value = 1.28 sec (in units of 625 us)
+ */
+#define ADV_INTERVAL_DEFAULT        (0x0800)
+
+#define ADV_CH_37 0x01
+#define ADV_CH_38 0x02
+#define ADV_CH_39 0x04
+
+
+
+#endif /* _LINK_LAYER_H */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/list.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/list.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,48 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : list.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file for linked list library.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+#ifndef _LIST_H_
+#define _LIST_H_
+
+typedef struct _tListNode {
+	struct _tListNode * next;
+	struct _tListNode * prev;
+}tListNode, *pListNode;
+
+void list_init_head (tListNode * listHead);
+
+uint8_t list_is_empty (tListNode * listHead);
+
+void list_insert_head (tListNode * listHead, tListNode * node);
+
+void list_insert_tail (tListNode * listHead, tListNode * node);
+
+void list_remove_node (tListNode * node);
+
+void list_remove_head (tListNode * listHead, tListNode ** node );
+
+void list_remove_tail (tListNode * listHead, tListNode ** node );
+
+void list_insert_node_after (tListNode * node, tListNode * ref_node);
+
+void list_insert_node_before (tListNode * node, tListNode * ref_node);
+
+int list_get_size (tListNode * listHead);
+
+void list_get_next_node (tListNode * ref_node, tListNode ** node);
+
+void list_get_prev_node (tListNode * ref_node, tListNode ** node);
+
+#endif /* _LIST_H_ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/osal.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/osal.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,82 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : osal.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : This header file defines the OS abstraction layer used by
+*                      the BLE stack. OSAL defines the set of functions
+*                      which needs to be ported to target operating system and
+*                      target platform.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __OSAL_H__
+#define __OSAL_H__
+
+/******************************************************************************
+ * Includes
+ *****************************************************************************/
+#include <hal_types.h>
+#ifdef __ICCARM__
+#include <intrinsics.h>
+#endif
+
+/******************************************************************************
+ * Macros
+ *****************************************************************************/
+
+
+/******************************************************************************
+ * Function Prototypes
+ *****************************************************************************/
+
+/**
+ * This function copies size number of bytes from a 
+ * memory location pointed by src to a destination 
+ * memory location pointed by dest
+ * 
+ * @param[in] dest Destination address
+ * @param[in] src  Source address
+ * @param[in] size size in the bytes  
+ * 
+ * @return  Address of the destination
+ */
+ 
+extern void* Osal_MemCpy(void *dest,const void *src, unsigned int size);
+
+
+/**
+ * This function sets first number of bytes, specified
+ * by size, to the destination memory pointed by ptr 
+ * to the specified value
+ * 
+ * @param[in] ptr    Destination address
+ * @param[in] value  Value to be set
+ * @param[in] size   Size in the bytes  
+ * 
+ * @return  Address of the destination
+ */
+ 
+extern void* Osal_MemSet(void *ptr, int value, unsigned int size);
+
+/**
+ * Osal_Get_Cur_Time
+ * 
+ * returns the current time in milliseconds
+ */
+/**
+ * Returns the number of ticks (1 tick = 1 millisecond)
+ * 
+ * @return  Time in milliseconds
+ */
+uint32_t Osal_Get_Cur_Time(void);
+
+
+#endif /* __OSAL_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/sensor_service.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/sensor_service.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,93 @@
+/**
+  ******************************************************************************
+  * @file    sensor_service.h 
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+  
+/* Define to prevent recursive inclusion -------------------------------------*/  
+#ifndef _SENSOR_SERVICE_H_
+#define _SENSOR_SERVICE_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif 
+
+/* Includes ------------------------------------------------------------------*/
+#include "cube_hal.h"
+#include "hal_types.h"
+#include "gatt_server.h"
+#include "gap.h"
+#include "string.h"
+#include "bluenrg_gap_aci.h"
+#include "bluenrg_gatt_aci.h"
+#include "hci_const.h"
+#include "gp_timer.h"
+#include "bluenrg_hal_aci.h"
+#include "bluenrg_aci_const.h"   
+#include "hci.h"
+#include "hal.h"
+#include "sm.h"
+#include "debug.h"
+
+#include <stdlib.h>
+
+typedef int i32_t;
+
+/** 
+ * @brief Structure containing acceleration value (in mg) of each axis.
+ */
+typedef struct {
+  i32_t AXIS_X;
+  i32_t AXIS_Y;
+  i32_t AXIS_Z;
+} AxesRaw_t;
+
+tBleStatus Add_Acc_Service(void);
+tBleStatus Acc_Update(AxesRaw_t *data);
+tBleStatus Add_Environmental_Sensor_Service(void);
+void       setConnectable(void);
+void       enableNotification(void);
+void       GAP_ConnectionComplete_CB(uint8_t addr[6], uint16_t handle);
+void       GAP_DisconnectionComplete_CB(void);
+void       HCI_Event_CB(void *pckt);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _SENSOR_SERVICE_H_ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/sm.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/sm.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,141 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : sm.h
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Header file for BlueNRG's security manager.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#ifndef __SM_H__
+#define __SM_H__
+
+/******************************************************************************
+* Macros
+*****************************************************************************/
+
+/* IO capabilities */
+/**
+ * @defgroup IO_capabilities IO capabilities
+ * @{
+ */
+#define IO_CAP_DISPLAY_ONLY				(0x00)
+#define IO_CAP_DISPLAY_YES_NO			(0x01)
+#define IO_CAP_KEYBOARD_ONLY			(0x02)
+#define IO_CAP_NO_INPUT_NO_OUTPUT		(0x03)
+#define IO_CAP_KEYBOARD_DISPLAY			(0x04)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Auth_req Authentication requirements
+ * @{
+ */
+#define BONDING				            (0x01)
+#define NO_BONDING				        (0x00)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup MITM_req MITM protection requirements
+ * @{
+ */
+#define MITM_PROTECTION_NOT_REQUIRED	(0x00)
+#define MITM_PROTECTION_REQUIRED        (0x01)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup OOB_Data Out-Of-Band data
+ * @{
+ */
+#define OOB_AUTH_DATA_ABSENT		    (0x00)
+#define OOB_AUTH_DATA_PRESENT      		(0x01)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Author_req Authorization requirements
+ * @{
+ */
+#define AUTHORIZATION_NOT_REQUIRED	     (0x00)
+#define AUTHORIZATION_REQUIRED			 (0x01)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup Conn_authorization Connection authorization
+ * @{
+ */
+#define CONNECTION_AUTHORIZED			(0x01)
+#define CONNECTION_REJECTED				(0x02)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup  Use_fixed_pin Use fixed pin
+ * @{
+ */
+#define USE_FIXED_PIN_FOR_PAIRING		(0x0)
+#define DONOT_USE_FIXED_PIN_FOR_PAIRING	(0x01)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup  link_security_status Link security status
+ * @{
+ */
+#define SM_LINK_AUTHENTICATED               (0x01)
+#define SM_LINK_AUTHORIZED                  (0x02)
+#define SM_LINK_ENCRYPTED                   (0x04)
+/**
+ * @}
+ */
+
+/**
+ * @defgroup  SMP_pairing_failed_codes SMP pairing failed reason codes
+ * @{
+ */
+#define PASSKEY_ENTRY_FAILED			(0x01)
+#define OOB_NOT_AVAILABLE				(0x02)
+#define AUTH_REQ_CANNOT_BE_MET			(0x03)
+#define CONFIRM_VALUE_FAILED			(0x04)
+#define PAIRING_NOT_SUPPORTED			(0x05)
+#define INSUFF_ENCRYPTION_KEY_SIZE		(0x06)
+#define CMD_NOT_SUPPORTED				(0x07)
+#define UNSPECIFIED_REASON				(0x08)
+#define VERY_EARLY_NEXT_ATTEMPT			(0x09)
+#define SM_INVALID_PARAMS				(0x0A)
+/**
+ * @}
+ */
+
+/* error codes to be sent with the pairing complete event */
+/**
+ * @defgroup  pairing_failed_codes Pairing failed error codes
+ * @brief     Error codes in @ref EVT_BLUE_GAP_PAIRING_CMPLT event
+ * @{
+ */
+#define SM_PAIRING_SUCCESS              (0x00)
+#define SM_PAIRING_TIMEOUT              (0x01)
+#define SM_PAIRING_FAILED               (0x02)
+/**
+ * @}
+ */
+
+
+#endif /* __SM_H__ */
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32_bluenrg_ble.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32_bluenrg_ble.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,85 @@
+/**
+  ******************************************************************************
+  * @file    stm32_bluenrg_ble.h
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+  
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32_BLUENRG_BLE_H
+#define __STM32_BLUENRG_BLE_H
+#define USE_STM32F4XX_NUCLEO
+#ifdef __cplusplus
+ extern "C" {
+#endif 
+
+/* Includes ------------------------------------------------------------------*/ 
+#ifdef USE_STM32F4XX_NUCLEO
+  #include "stm32f4xx_hal.h"
+  #include "stm32f4xx_nucleo.h"
+  #include "stm32f4xx_nucleo_bluenrg.h"
+   
+  #define SYSCLK_FREQ 84000000
+#endif
+   
+#ifdef USE_STM32L0XX_NUCLEO
+  #include "stm32l0xx_hal.h"
+  #include "stm32l0xx_nucleo.h"
+  #include "stm32l0xx_nucleo_bluenrg.h"
+   
+  #define SYSCLK_FREQ 32000000
+#endif
+
+// FIXME: add prototypes for BlueNRG here!!!!!!!!!!!!!!!!!!
+void    BNRG_SPI_Init(void);
+void    BlueNRG_RST(void);
+uint8_t BlueNRG_DataPresent(void);
+void    BlueNRG_HW_Bootloader(void);
+int32_t BlueNRG_SPI_Read_All(SPI_HandleTypeDef *hspi,
+                             uint8_t *buffer,
+                             uint8_t buff_size);
+int32_t BlueNRG_SPI_Write(SPI_HandleTypeDef *hspi,
+                          uint8_t* data1,
+                          uint8_t* data2,
+                          uint8_t Nb_bytes1,
+                          uint8_t Nb_bytes2);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32_BLUENRG_BLE_H */
+    
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32f4xx_hal_conf.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32f4xx_hal_conf.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,406 @@
+/**
+  ******************************************************************************
+  * @file    stm32f4xx_hal_conf.h
+  * @author  MCD Application Team
+  * @version V1.0.1
+  * @date    26-February-2014
+  * @brief   HAL configuration file.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32F4xx_HAL_CONF_H
+#define __STM32F4xx_HAL_CONF_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Exported types ------------------------------------------------------------*/
+/* Exported constants --------------------------------------------------------*/
+
+/* ########################## Module Selection ############################## */
+/**
+  * @brief This is the list of modules to be used in the HAL driver 
+  */
+#define HAL_MODULE_ENABLED         
+#define HAL_ADC_MODULE_ENABLED
+/* #define HAL_CAN_MODULE_ENABLED      */
+/* #define HAL_CRC_MODULE_ENABLED      */ 
+/* #define HAL_CRYP_MODULE_ENABLED     */ 
+/* #define HAL_DAC_MODULE_ENABLED      */ 
+/* #define HAL_DCMI_MODULE_ENABLED     */ 
+#define HAL_DMA_MODULE_ENABLED
+/* #define HAL_DMA2D_MODULE_ENABLED    */ 
+/* #define HAL_ETH_MODULE_ENABLED      */
+#define HAL_FLASH_MODULE_ENABLED
+/* #define HAL_NAND_MODULE_ENABLED     */
+/* #define HAL_NOR_MODULE_ENABLED      */
+/* #define HAL_PCCARD_MODULE_ENABLED   */
+/* #define HAL_SRAM_MODULE_ENABLED     */
+/* #define HAL_SDRAM_MODULE_ENABLED    */
+/* #define HAL_HASH_MODULE_ENABLED     */  
+#define HAL_GPIO_MODULE_ENABLED
+/* #define HAL_I2C_MODULE_ENABLED      */
+/* #define HAL_I2S_MODULE_ENABLED      */
+/* #define HAL_IWDG_MODULE_ENABLED     */ 
+/* #define HAL_LTDC_MODULE_ENABLED     */
+#define HAL_PWR_MODULE_ENABLED
+#define HAL_RCC_MODULE_ENABLED
+/* #define HAL_RNG_MODULE_ENABLED      */   
+/* #define HAL_RTC_MODULE_ENABLED      */
+/* #define HAL_SAI_MODULE_ENABLED      */   
+/* #define HAL_SD_MODULE_ENABLED       */
+#define HAL_SPI_MODULE_ENABLED
+/* #define HAL_TIM_MODULE_ENABLED      */
+/* #define HAL_UART_MODULE_ENABLED     */
+/* #define HAL_USART_MODULE_ENABLED    */ 
+/* #define HAL_IRDA_MODULE_ENABLED     */
+/* #define HAL_SMARTCARD_MODULE_ENABLED*/
+/* #define HAL_WWDG_MODULE_ENABLED     */
+#define HAL_CORTEX_MODULE_ENABLED   
+/* #define HAL_PCD_MODULE_ENABLED      */
+/* #define HAL_HCD_MODULE_ENABLED      */
+
+
+/* ########################## HSE/HSI Values adaptation ##################### */
+/**
+  * @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
+  *        This value is used by the RCC HAL module to compute the system frequency
+  *        (when HSE is used as system clock source, directly or through the PLL).  
+  */
+#if !defined  (HSE_VALUE) 
+  #define HSE_VALUE    ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */
+#endif /* HSE_VALUE */
+
+#if !defined  (HSE_STARTUP_TIMEOUT)
+  #define HSE_STARTUP_TIMEOUT    ((uint32_t)5000)   /*!< Time out for HSE start up, in ms */
+#endif /* HSE_STARTUP_TIMEOUT */
+
+/**
+  * @brief Internal High Speed oscillator (HSI) value.
+  *        This value is used by the RCC HAL module to compute the system frequency
+  *        (when HSI is used as system clock source, directly or through the PLL). 
+  */
+#if !defined  (HSI_VALUE)
+  #define HSI_VALUE    ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/
+#endif /* HSI_VALUE */
+
+/**
+  * @brief Internal Low Speed oscillator (LSI) value.
+  */
+#if !defined  (LSI_VALUE) 
+ #define LSI_VALUE  ((uint32_t)40000)    
+#endif /* LSI_VALUE */                      /*!< Value of the Internal Low Speed oscillator in Hz
+                                             The real value may vary depending on the variations
+                                             in voltage and temperature.  */
+/**
+  * @brief External Low Speed oscillator (LSE) value.
+  */
+#if !defined  (LSE_VALUE)
+ #define LSE_VALUE  ((uint32_t)32768)    /*!< Value of the External Low Speed oscillator in Hz */
+#endif /* LSE_VALUE */
+
+/**
+  * @brief External clock source for I2S peripheral
+  *        This value is used by the I2S HAL module to compute the I2S clock source 
+  *        frequency, this source is inserted directly through I2S_CKIN pad. 
+  */
+#if !defined  (EXTERNAL_CLOCK_VALUE)
+  #define EXTERNAL_CLOCK_VALUE    ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/
+#endif /* EXTERNAL_CLOCK_VALUE */
+
+/* Tip: To avoid modifying this file each time you need to use different HSE,
+   ===  you can define the HSE value in your toolchain compiler preprocessor. */
+
+/* ########################### System Configuration ######################### */
+/**
+  * @brief This is the HAL system configuration section
+  */     
+#define  VDD_VALUE                    ((uint32_t)3300) /*!< Value of VDD in mv */
+#define  TICK_INT_PRIORITY            ((uint32_t)0x0F) /*!< tick interrupt priority */           
+#define  USE_RTOS                     0     
+#define  PREFETCH_ENABLE              1              
+#define  INSTRUCTION_CACHE_ENABLE     1
+#define  DATA_CACHE_ENABLE            1
+
+/* ########################## Assert Selection ############################## */
+/**
+  * @brief Uncomment the line below to expanse the "assert_param" macro in the 
+  *        HAL drivers code
+  */
+/* #define USE_FULL_ASSERT    1 */
+
+/* ################## Ethernet peripheral configuration ##################### */
+
+/* Section 1 : Ethernet peripheral configuration */
+
+/* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */
+#define MAC_ADDR0   2
+#define MAC_ADDR1   0
+#define MAC_ADDR2   0
+#define MAC_ADDR3   0
+#define MAC_ADDR4   0
+#define MAC_ADDR5   0
+
+/* Definition of the Ethernet driver buffers size and count */   
+#define ETH_RX_BUF_SIZE                ETH_MAX_PACKET_SIZE /* buffer size for receive               */
+#define ETH_TX_BUF_SIZE                ETH_MAX_PACKET_SIZE /* buffer size for transmit              */
+#define ETH_RXBUFNB                    ((uint32_t)4)       /* 4 Rx buffers of size ETH_RX_BUF_SIZE  */
+#define ETH_TXBUFNB                    ((uint32_t)4)       /* 4 Tx buffers of size ETH_TX_BUF_SIZE  */
+
+/* Section 2: PHY configuration section */
+
+/* DP83848 PHY Address*/ 
+#define DP83848_PHY_ADDRESS             0x01
+/* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ 
+#define PHY_RESET_DELAY                 ((uint32_t)0x000000FF)
+/* PHY Configuration delay */
+#define PHY_CONFIG_DELAY                ((uint32_t)0x00000FFF)
+
+#define PHY_READ_TO                     ((uint32_t)0x0000FFFF)
+#define PHY_WRITE_TO                    ((uint32_t)0x0000FFFF)
+
+/* Section 3: Common PHY Registers */
+
+#define PHY_BCR                         ((uint16_t)0x00)    /*!< Transceiver Basic Control Register   */
+#define PHY_BSR                         ((uint16_t)0x01)    /*!< Transceiver Basic Status Register    */
+ 
+#define PHY_RESET                       ((uint16_t)0x8000)  /*!< PHY Reset */
+#define PHY_LOOPBACK                    ((uint16_t)0x4000)  /*!< Select loop-back mode */
+#define PHY_FULLDUPLEX_100M             ((uint16_t)0x2100)  /*!< Set the full-duplex mode at 100 Mb/s */
+#define PHY_HALFDUPLEX_100M             ((uint16_t)0x2000)  /*!< Set the half-duplex mode at 100 Mb/s */
+#define PHY_FULLDUPLEX_10M              ((uint16_t)0x0100)  /*!< Set the full-duplex mode at 10 Mb/s  */
+#define PHY_HALFDUPLEX_10M              ((uint16_t)0x0000)  /*!< Set the half-duplex mode at 10 Mb/s  */
+#define PHY_AUTONEGOTIATION             ((uint16_t)0x1000)  /*!< Enable auto-negotiation function     */
+#define PHY_RESTART_AUTONEGOTIATION     ((uint16_t)0x0200)  /*!< Restart auto-negotiation function    */
+#define PHY_POWERDOWN                   ((uint16_t)0x0800)  /*!< Select the power down mode           */
+#define PHY_ISOLATE                     ((uint16_t)0x0400)  /*!< Isolate PHY from MII                 */
+
+#define PHY_AUTONEGO_COMPLETE           ((uint16_t)0x0020)  /*!< Auto-Negotiation process completed   */
+#define PHY_LINKED_STATUS               ((uint16_t)0x0004)  /*!< Valid link established               */
+#define PHY_JABBER_DETECTION            ((uint16_t)0x0002)  /*!< Jabber condition detected            */
+  
+/* Section 4: Extended PHY Registers */
+
+#define PHY_SR                          ((uint16_t)0x10)    /*!< PHY status register Offset                      */
+#define PHY_MICR                        ((uint16_t)0x11)    /*!< MII Interrupt Control Register                  */
+#define PHY_MISR                        ((uint16_t)0x12)    /*!< MII Interrupt Status and Misc. Control Register */
+ 
+#define PHY_LINK_STATUS                 ((uint16_t)0x0001)  /*!< PHY Link mask                                   */
+#define PHY_SPEED_STATUS                ((uint16_t)0x0002)  /*!< PHY Speed mask                                  */
+#define PHY_DUPLEX_STATUS               ((uint16_t)0x0004)  /*!< PHY Duplex mask                                 */
+
+#define PHY_MICR_INT_EN                 ((uint16_t)0x0002)  /*!< PHY Enable interrupts                           */
+#define PHY_MICR_INT_OE                 ((uint16_t)0x0001)  /*!< PHY Enable output interrupt events              */
+
+#define PHY_MISR_LINK_INT_EN            ((uint16_t)0x0020)  /*!< Enable Interrupt on change of link status       */
+#define PHY_LINK_INTERRUPT              ((uint16_t)0x2000)  /*!< PHY link status interrupt mask                  */
+
+/* Includes ------------------------------------------------------------------*/
+/**
+  * @brief Include module's header file 
+  */
+
+#ifdef HAL_RCC_MODULE_ENABLED
+  #include "stm32f4xx_hal_rcc.h"
+#endif /* HAL_RCC_MODULE_ENABLED */
+
+#ifdef HAL_GPIO_MODULE_ENABLED
+  #include "stm32f4xx_hal_gpio.h"
+#endif /* HAL_GPIO_MODULE_ENABLED */
+
+#ifdef HAL_DMA_MODULE_ENABLED
+  #include "stm32f4xx_hal_dma.h"
+#endif /* HAL_DMA_MODULE_ENABLED */
+   
+#ifdef HAL_CORTEX_MODULE_ENABLED
+  #include "stm32f4xx_hal_cortex.h"
+#endif /* HAL_CORTEX_MODULE_ENABLED */
+
+#ifdef HAL_ADC_MODULE_ENABLED
+  #include "stm32f4xx_hal_adc.h"
+#endif /* HAL_ADC_MODULE_ENABLED */
+
+#ifdef HAL_CAN_MODULE_ENABLED
+  #include "stm32f4xx_hal_can.h"
+#endif /* HAL_CAN_MODULE_ENABLED */
+
+#ifdef HAL_CRC_MODULE_ENABLED
+  #include "stm32f4xx_hal_crc.h"
+#endif /* HAL_CRC_MODULE_ENABLED */
+
+#ifdef HAL_CRYP_MODULE_ENABLED
+  #include "stm32f4xx_hal_cryp.h" 
+#endif /* HAL_CRYP_MODULE_ENABLED */
+
+#ifdef HAL_DMA2D_MODULE_ENABLED
+  #include "stm32f4xx_hal_dma2d.h"
+#endif /* HAL_DMA2D_MODULE_ENABLED */
+
+#ifdef HAL_DAC_MODULE_ENABLED
+  #include "stm32f4xx_hal_dac.h"
+#endif /* HAL_DAC_MODULE_ENABLED */
+
+#ifdef HAL_DCMI_MODULE_ENABLED
+  #include "stm32f4xx_hal_dcmi.h"
+#endif /* HAL_DCMI_MODULE_ENABLED */
+
+#ifdef HAL_ETH_MODULE_ENABLED
+  #include "stm32f4xx_hal_eth.h"
+#endif /* HAL_ETH_MODULE_ENABLED */
+
+#ifdef HAL_FLASH_MODULE_ENABLED
+  #include "stm32f4xx_hal_flash.h"
+#endif /* HAL_FLASH_MODULE_ENABLED */
+ 
+#ifdef HAL_SRAM_MODULE_ENABLED
+  #include "stm32f4xx_hal_sram.h"
+#endif /* HAL_SRAM_MODULE_ENABLED */
+
+#ifdef HAL_NOR_MODULE_ENABLED
+  #include "stm32f4xx_hal_nor.h"
+#endif /* HAL_NOR_MODULE_ENABLED */
+
+#ifdef HAL_NAND_MODULE_ENABLED
+  #include "stm32f4xx_hal_nand.h"
+#endif /* HAL_NAND_MODULE_ENABLED */
+
+#ifdef HAL_PCCARD_MODULE_ENABLED
+  #include "stm32f4xx_hal_pccard.h"
+#endif /* HAL_PCCARD_MODULE_ENABLED */ 
+  
+#ifdef HAL_SDRAM_MODULE_ENABLED
+  #include "stm32f4xx_hal_sdram.h"
+#endif /* HAL_SDRAM_MODULE_ENABLED */      
+
+#ifdef HAL_HASH_MODULE_ENABLED
+ #include "stm32f4xx_hal_hash.h"
+#endif /* HAL_HASH_MODULE_ENABLED */
+
+#ifdef HAL_I2C_MODULE_ENABLED
+ #include "stm32f4xx_hal_i2c.h"
+#endif /* HAL_I2C_MODULE_ENABLED */
+
+#ifdef HAL_I2S_MODULE_ENABLED
+ #include "stm32f4xx_hal_i2s.h"
+#endif /* HAL_I2S_MODULE_ENABLED */
+
+#ifdef HAL_IWDG_MODULE_ENABLED
+ #include "stm32f4xx_hal_iwdg.h"
+#endif /* HAL_IWDG_MODULE_ENABLED */
+
+#ifdef HAL_LTDC_MODULE_ENABLED
+ #include "stm32f4xx_hal_ltdc.h"
+#endif /* HAL_LTDC_MODULE_ENABLED */
+
+#ifdef HAL_PWR_MODULE_ENABLED
+ #include "stm32f4xx_hal_pwr.h"
+#endif /* HAL_PWR_MODULE_ENABLED */
+
+#ifdef HAL_RNG_MODULE_ENABLED
+ #include "stm32f4xx_hal_rng.h"
+#endif /* HAL_RNG_MODULE_ENABLED */
+
+#ifdef HAL_RTC_MODULE_ENABLED
+ #include "stm32f4xx_hal_rtc.h"
+#endif /* HAL_RTC_MODULE_ENABLED */
+
+#ifdef HAL_SAI_MODULE_ENABLED
+ #include "stm32f4xx_hal_sai.h"
+#endif /* HAL_SAI_MODULE_ENABLED */
+
+#ifdef HAL_SD_MODULE_ENABLED
+ #include "stm32f4xx_hal_sd.h"
+#endif /* HAL_SD_MODULE_ENABLED */
+
+#ifdef HAL_SPI_MODULE_ENABLED
+ #include "stm32f4xx_hal_spi.h"
+#endif /* HAL_SPI_MODULE_ENABLED */
+
+#ifdef HAL_TIM_MODULE_ENABLED
+ #include "stm32f4xx_hal_tim.h"
+#endif /* HAL_TIM_MODULE_ENABLED */
+
+#ifdef HAL_UART_MODULE_ENABLED
+ #include "stm32f4xx_hal_uart.h"
+#endif /* HAL_UART_MODULE_ENABLED */
+
+#ifdef HAL_USART_MODULE_ENABLED
+ #include "stm32f4xx_hal_usart.h"
+#endif /* HAL_USART_MODULE_ENABLED */
+
+#ifdef HAL_IRDA_MODULE_ENABLED
+ #include "stm32f4xx_hal_irda.h"
+#endif /* HAL_IRDA_MODULE_ENABLED */
+
+#ifdef HAL_SMARTCARD_MODULE_ENABLED
+ #include "stm32f4xx_hal_smartcard.h"
+#endif /* HAL_SMARTCARD_MODULE_ENABLED */
+
+#ifdef HAL_WWDG_MODULE_ENABLED
+ #include "stm32f4xx_hal_wwdg.h"
+#endif /* HAL_WWDG_MODULE_ENABLED */
+
+#ifdef HAL_PCD_MODULE_ENABLED
+ #include "stm32f4xx_hal_pcd.h"
+#endif /* HAL_PCD_MODULE_ENABLED */
+
+#ifdef HAL_HCD_MODULE_ENABLED
+ #include "stm32f4xx_hal_hcd.h"
+#endif /* HAL_HCD_MODULE_ENABLED */
+   
+/* Exported macro ------------------------------------------------------------*/
+#ifdef  USE_FULL_ASSERT
+/**
+  * @brief  The assert_param macro is used for function's parameters check.
+  * @param  expr: If expr is false, it calls assert_failed function
+  *         which reports the name of the source file and the source
+  *         line number of the call that failed. 
+  *         If expr is true, it returns no value.
+  * @retval None
+  */
+  #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
+/* Exported functions ------------------------------------------------------- */
+  void assert_failed(uint8_t* file, uint32_t line);
+#else
+  #define assert_param(expr) ((void)0)
+#endif /* USE_FULL_ASSERT */
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32F4xx_HAL_CONF_H */
+
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32f4xx_nucleo.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32f4xx_nucleo.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,276 @@
+/** 
+  ******************************************************************************
+  * @file    stm32f4xx_nucleo.h
+  * @author  MCD Application Team
+  * @version V1.1.0
+  * @date    19-June-2014
+  * @cond DOXYGEN_EXCLUDE
+  * @brief   This file contains definitions for:
+  *          + LEDs and push-button available on STM32F4XX-Nucleo Kit from
+  *          STMicroelectronics.
+  *          + LCD, joystick and microSD available on Adafruit 1.8" TFT LCD
+  *          Expansion Board (reference ID 802).
+  * @endcond
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************  
+  */ 
+  
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32F4XX_NUCLEO_H
+#define __STM32F4XX_NUCLEO_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+   
+/** @addtogroup BSP
+  * @{
+  */
+
+/** @addtogroup STM32F4XX_NUCLEO
+  * @{
+  */
+
+/** @addtogroup STM32F4XX_NUCLEO_LOW_LEVEL
+  * @{
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Exported_Types
+  * @{
+  */
+typedef enum 
+{
+  LED20 = 0
+}Led_TypeDef;
+
+typedef enum 
+{  
+  BUTTON_KEY = 0
+}Button_TypeDef;
+
+typedef enum 
+{  
+  BUTTON_MODE_GPIO = 0,
+  BUTTON_MODE_EXTI = 1
+}ButtonMode_TypeDef;
+
+typedef enum 
+{ 
+  JOY_NONE  = 0,
+  JOY_SEL   = 1,
+  JOY_DOWN  = 2,
+  JOY_LEFT  = 3,
+  JOY_RIGHT = 4,
+  JOY_UP    = 5
+}JOYState_TypeDef;
+
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Exported_Constants
+  * @{
+  */ 
+
+/** 
+  * @brief Define for STM32F4XX_NUCLEO board  
+  */ 
+#if !defined (USE_STM32F4XX_NUCLEO)
+ #define USE_STM32F4XX_NUCLEO
+#endif
+
+/** @addtogroup STM32F4XX_NUCLEO_LOW_LEVEL_LED
+  * @{
+  */
+#define LEDn                                    1
+
+#define LED2_PIN                                GPIO_PIN_5
+#define LED2_GPIO_PORT                          GPIOA
+#define LED2_GPIO_CLK_ENABLE()                  __GPIOA_CLK_ENABLE()
+#define LED2_GPIO_CLK_DISABLE()                 __GPIOA_CLK_DISABLE()  
+
+#define LEDx_GPIO_CLK_ENABLE(__INDEX__)   (((__INDEX__) == 0) ? LED2_GPIO_CLK_ENABLE() : 0)
+#define LEDx_GPIO_CLK_DISABLE(__INDEX__)  (((__INDEX__) == 0) ? LED2_GPIO_CLK_DISABLE() : 0)
+/**
+  * @}
+  */ 
+  
+/** @addtogroup STM32F4XX_NUCLEO_LOW_LEVEL_BUTTON
+  * @{
+  */  
+#define BUTTONn                                 1  
+
+/**
+ * @brief Key push-button
+ */
+#define KEY_BUTTON_PIN                          GPIO_PIN_13
+#define KEY_BUTTON_GPIO_PORT                    GPIOC
+#define KEY_BUTTON_GPIO_CLK_ENABLE()            __GPIOC_CLK_ENABLE()
+#define KEY_BUTTON_GPIO_CLK_DISABLE()           __GPIOC_CLK_DISABLE()
+#define KEY_BUTTON_EXTI_IRQn                    EXTI15_10_IRQn
+
+#define BUTTONx_GPIO_CLK_ENABLE(__INDEX__)   (((__INDEX__) == 0) ? KEY_BUTTON_GPIO_CLK_ENABLE() : 0)
+#define BUTTONx_GPIO_CLK_DISABLE(__INDEX__)  (((__INDEX__) == 0) ? KEY_BUTTON_GPIO_CLK_DISABLE() : 0)
+/**
+  * @}
+  */ 
+
+/** @addtogroup STM32F4XX_NUCLEO_LOW_LEVEL_BUS
+  * @{
+  */
+/*############################### SPI1 #######################################*/
+#define NUCLEO_SPIx                                     SPI1
+#define NUCLEO_SPIx_CLK_ENABLE()                        __SPI1_CLK_ENABLE()
+
+#define NUCLEO_SPIx_SCK_AF                              GPIO_AF5_SPI1
+#define NUCLEO_SPIx_SCK_GPIO_PORT                       GPIOA
+#define NUCLEO_SPIx_SCK_PIN                             GPIO_PIN_5
+#define NUCLEO_SPIx_SCK_GPIO_CLK_ENABLE()               __GPIOA_CLK_ENABLE()
+#define NUCLEO_SPIx_SCK_GPIO_CLK_DISABLE()              __GPIOA_CLK_DISABLE()
+
+#define NUCLEO_SPIx_MISO_MOSI_AF                        GPIO_AF5_SPI1
+#define NUCLEO_SPIx_MISO_MOSI_GPIO_PORT                 GPIOA
+#define NUCLEO_SPIx_MISO_MOSI_GPIO_CLK_ENABLE()         __GPIOA_CLK_ENABLE()
+#define NUCLEO_SPIx_MISO_MOSI_GPIO_CLK_DISABLE()        __GPIOA_CLK_DISABLE()
+#define NUCLEO_SPIx_MISO_PIN                            GPIO_PIN_6
+#define NUCLEO_SPIx_MOSI_PIN                            GPIO_PIN_7
+/* Maximum Timeout values for flags waiting loops. These timeouts are not based
+   on accurate values, they just guarantee that the application will not remain
+   stuck if the SPI communication is corrupted.
+   You may modify these timeout values depending on CPU frequency and application
+   conditions (interrupts routines ...). */   
+#define NUCLEO_SPIx_TIMEOUT_MAX                   1000
+
+/**
+  * @brief  SD Control Lines management
+  */
+#define SD_CS_LOW()       HAL_GPIO_WritePin(SD_CS_GPIO_PORT, SD_CS_PIN, GPIO_PIN_RESET)
+#define SD_CS_HIGH()      HAL_GPIO_WritePin(SD_CS_GPIO_PORT, SD_CS_PIN, GPIO_PIN_SET)
+
+/**
+  * @brief  LCD Control Lines management
+  */
+#define LCD_CS_LOW()      HAL_GPIO_WritePin(LCD_CS_GPIO_PORT, LCD_CS_PIN, GPIO_PIN_RESET)
+#define LCD_CS_HIGH()     HAL_GPIO_WritePin(LCD_CS_GPIO_PORT, LCD_CS_PIN, GPIO_PIN_SET)
+#define LCD_DC_LOW()      HAL_GPIO_WritePin(LCD_DC_GPIO_PORT, LCD_DC_PIN, GPIO_PIN_RESET)
+#define LCD_DC_HIGH()     HAL_GPIO_WritePin(LCD_DC_GPIO_PORT, LCD_DC_PIN, GPIO_PIN_SET)
+     
+/**
+  * @brief  SD Control Interface pins
+  */
+#define SD_CS_PIN                                 GPIO_PIN_5
+#define SD_CS_GPIO_PORT                           GPIOB
+#define SD_CS_GPIO_CLK_ENABLE()                 __GPIOB_CLK_ENABLE()
+#define SD_CS_GPIO_CLK_DISABLE()                __GPIOB_CLK_DISABLE()
+
+/**
+  * @brief  LCD Control Interface pins
+  */
+#define LCD_CS_PIN                                 GPIO_PIN_6
+#define LCD_CS_GPIO_PORT                           GPIOB
+#define LCD_CS_GPIO_CLK_ENABLE()                 __GPIOB_CLK_ENABLE()
+#define LCD_CS_GPIO_CLK_DISABLE()                __GPIOB_CLK_DISABLE()
+    
+/**
+  * @brief  LCD Data/Command Interface pins
+  */
+#define LCD_DC_PIN                                 GPIO_PIN_9
+#define LCD_DC_GPIO_PORT                           GPIOA
+#define LCD_DC_GPIO_CLK_ENABLE()                 __GPIOA_CLK_ENABLE()
+#define LCD_DC_GPIO_CLK_DISABLE()                __GPIOA_CLK_DISABLE()
+
+/*################################ ADC1 ######################################*/
+/**
+  * @brief  ADC Interface pins
+  *         used to detect motion of Joystick available on Adafruit 1.8" TFT shield
+  */
+#define NUCLEO_ADCx                                 ADC1
+#define NUCLEO_ADCx_CLK_ENABLE()                  __ADC1_CLK_ENABLE()
+
+#define NUCLEO_ADCx_CHANNEL                       ADC_CHANNEL_8
+   
+#define NUCLEO_ADCx_GPIO_PORT                       GPIOB
+#define NUCLEO_ADCx_GPIO_PIN                        GPIO_PIN_0
+#define NUCLEO_ADCx_GPIO_CLK_ENABLE()             __GPIOB_CLK_ENABLE()
+#define NUCLEO_ADCx_GPIO_CLK_DISABLE()            __GPIOB_CLK_DISABLE()
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Exported_Macros
+  * @{
+  */  
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Exported_Functions
+  * @{
+  */
+uint32_t         BSP_GetVersion(void);  
+void             BSP_LED_Init(Led_TypeDef Led);
+void             BSP_LED_On(Led_TypeDef Led);
+void             BSP_LED_Off(Led_TypeDef Led);
+void             BSP_LED_Toggle(Led_TypeDef Led);
+void             BSP_PB_Init(Button_TypeDef Button, ButtonMode_TypeDef ButtonMode);
+uint32_t         BSP_PB_GetState(Button_TypeDef Button);
+uint8_t          BSP_JOY_Init(void);
+JOYState_TypeDef BSP_JOY_GetState(void);
+  
+/**
+  * @}
+  */ 
+
+/**
+  * @}
+  */ 
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32F4XX_NUCLEO_H */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32f4xx_nucleo_bluenrg.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32f4xx_nucleo_bluenrg.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,156 @@
+/**
+  ******************************************************************************
+  * @file    stm32f4xx_nucleo_bluenrg.h
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   This file contains definitions for SPI communication on
+  *          STM32F4XX-Nucleo Kit from STMicroelectronics for BLE BlueNRG
+  *          Expansion Board (reference X-NUCLEO-IDB04A1).
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+  
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32F4XX_NUCLEO_BLUENRG_H
+#define __STM32F4XX_NUCLEO_BLUENRG_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_hal.h"
+#include "stm32f4xx_nucleo.h"
+
+
+/**
+* @brief SPI communication details between Nucleo F4 and BlueNRG
+*        Expansion Board.
+*/
+// SPI Instance
+#define BNRG_SPI_INSTANCE		        SPI1
+#define BNRG_SPI_CLK_ENABLE()		    __SPI1_CLK_ENABLE()
+
+// SPI Configuration
+#define BNRG_SPI_MODE			        SPI_MODE_MASTER
+#define BNRG_SPI_DIRECTION		        SPI_DIRECTION_2LINES
+#define BNRG_SPI_DATASIZE		        SPI_DATASIZE_8BIT
+#define BNRG_SPI_CLKPOLARITY		    SPI_POLARITY_LOW
+#define BNRG_SPI_CLKPHASE	        	SPI_PHASE_1EDGE
+#define BNRG_SPI_NSS			        SPI_NSS_SOFT
+#define BNRG_SPI_FIRSTBIT	        	SPI_FIRSTBIT_MSB
+#define BNRG_SPI_TIMODE		        	SPI_TIMODE_DISABLED
+#define BNRG_SPI_CRCPOLYNOMIAL	        7
+#define BNRG_SPI_BAUDRATEPRESCALER      SPI_BAUDRATEPRESCALER_4
+#define BNRG_SPI_CRCCALCULATION		    SPI_CRCCALCULATION_DISABLED
+
+// SPI Reset Pin: PA.8
+#define BNRG_SPI_RESET_PIN	        	GPIO_PIN_8
+#define BNRG_SPI_RESET_MODE	        	GPIO_MODE_OUTPUT_PP
+#define BNRG_SPI_RESET_PULL	        	GPIO_PULLUP/*[RG:]fixme!!! GPIO_PULLUP (original GPIO_NOPULL)*/
+#define BNRG_SPI_RESET_SPEED		    GPIO_SPEED_LOW
+#define BNRG_SPI_RESET_ALTERNATE	    0
+#define BNRG_SPI_RESET_PORT		        GPIOA
+#define BNRG_SPI_RESET_CLK_ENABLE()     __GPIOA_CLK_ENABLE()
+
+// SCLK: PB.3
+#define BNRG_SPI_SCLK_PIN		        GPIO_PIN_3
+#define BNRG_SPI_SCLK_MODE		        GPIO_MODE_AF_PP
+#define BNRG_SPI_SCLK_PULL		        GPIO_PULLDOWN //[RG:] fixme!!! GPIO_PULLDOWN (original GPIO_PULLUP)
+#define BNRG_SPI_SCLK_SPEED		        GPIO_SPEED_HIGH
+#define BNRG_SPI_SCLK_ALTERNATE		    GPIO_AF5_SPI1
+#define BNRG_SPI_SCLK_PORT		        GPIOB
+#define BNRG_SPI_SCLK_CLK_ENABLE()	    __GPIOB_CLK_ENABLE()
+
+// MISO (Master Input Slave Output): PA.6
+#define BNRG_SPI_MISO_PIN		        GPIO_PIN_6
+#define BNRG_SPI_MISO_MODE		        GPIO_MODE_AF_PP
+#define BNRG_SPI_MISO_PULL		        GPIO_NOPULL //[RG:] fixme!!! GPIO_NOPULL (original GPIO_PULLDOWN)
+#define BNRG_SPI_MISO_SPEED		        GPIO_SPEED_HIGH
+#define BNRG_SPI_MISO_ALTERNATE		    GPIO_AF5_SPI1
+#define BNRG_SPI_MISO_PORT		        GPIOA
+#define BNRG_SPI_MISO_CLK_ENABLE()	    __GPIOA_CLK_ENABLE()
+
+
+// MOSI (Master Output Slave Input): PA.7
+#define BNRG_SPI_MOSI_PIN			GPIO_PIN_7
+#define BNRG_SPI_MOSI_MODE			GPIO_MODE_AF_PP
+/*[RG:] sometimes at the end of a SPI receive phase MOSI is left high (even if the NCS rises)*/
+#define BNRG_SPI_MOSI_PULL			GPIO_NOPULL //[RG:] fixme!!! GPIO_PULLDOWN/GPIO_NOPULL (original GPIO_PULLUP)
+#define BNRG_SPI_MOSI_SPEED			GPIO_SPEED_HIGH
+#define BNRG_SPI_MOSI_ALTERNATE		GPIO_AF5_SPI1
+#define BNRG_SPI_MOSI_PORT			GPIOA
+#define BNRG_SPI_MOSI_CLK_ENABLE()	__GPIOA_CLK_ENABLE()
+
+// NSS/CSN/CS: PA.1
+#define BNRG_SPI_CS_PIN				GPIO_PIN_1
+#define BNRG_SPI_CS_MODE			GPIO_MODE_OUTPUT_PP
+#define BNRG_SPI_CS_PULL			GPIO_PULLUP/*[RG:]fixme!!! GPIO_PULLUP (original GPIO_NOPULL)*/
+#define BNRG_SPI_CS_SPEED			GPIO_SPEED_HIGH
+#define BNRG_SPI_CS_ALTERNATE		0
+#define BNRG_SPI_CS_PORT			GPIOA
+#define BNRG_SPI_CS_CLK_ENABLE()	__GPIOA_CLK_ENABLE()
+
+// IRQ: PA.0
+#define BNRG_SPI_IRQ_PIN			GPIO_PIN_0
+#define BNRG_SPI_IRQ_MODE			GPIO_MODE_IT_RISING
+#define BNRG_SPI_IRQ_PULL			GPIO_NOPULL
+#define BNRG_SPI_IRQ_SPEED			GPIO_SPEED_HIGH
+#define BNRG_SPI_IRQ_ALTERNATE		0
+#define BNRG_SPI_IRQ_PORT			GPIOA
+#define BNRG_SPI_IRQ_CLK_ENABLE()	__GPIOA_CLK_ENABLE()
+
+// EXTI External Interrupt for SPI
+// NOTE: if you change the IRQ pin remember to implement a corresponding handler
+// function like EXTI0_IRQHandler() in the user project
+#define BNRG_SPI_EXTI_IRQn			EXTI0_IRQn
+#define BNRG_SPI_EXTI_IRQHandler	EXTI0_IRQHandler
+#define BNRG_SPI_EXTI_PIN			BNRG_SPI_IRQ_PIN
+#define BNRG_SPI_EXTI_PORT			BNRG_SPI_IRQ_PORT
+#define RTC_WAKEUP_IRQHandler                   RTC_WKUP_IRQHandler
+
+void    Enable_SPI_IRQ(void);
+void    Disable_SPI_IRQ(void);
+void    Clear_SPI_IRQ(void);
+void    Clear_SPI_EXTI_Flag(void);
+/**
+  * @}
+  */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32F4XX_NUCLEO_BLUENRG_H */
+
+    
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32l0xx_hal_conf.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32l0xx_hal_conf.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,287 @@
+/**
+  ******************************************************************************
+  * @file    stm32l0xx_hal_conf.h
+  * @author  MCD Application Team
+  * @version V1.0.0
+  * @date    24-April-2014
+  * @brief   HAL configuration file.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32L0xx_HAL_CONF_H
+#define __STM32L0xx_HAL_CONF_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Exported types ------------------------------------------------------------*/
+/* Exported constants --------------------------------------------------------*/
+
+/* ########################## Module Selection ############################## */
+/**
+  * @brief This is the list of modules to be used in the HAL driver
+  */
+#define HAL_MODULE_ENABLED
+#define HAL_ADC_MODULE_ENABLED 
+/* #define HAL_COMP_MODULE_ENABLED */
+/* #define HAL_CRC_MODULE_ENABLED */
+/* #define HAL_CRYP_MODULE_ENABLED */
+/* #define HAL_DAC_MODULE_ENABLED */
+#define HAL_DMA_MODULE_ENABLED
+#define HAL_FLASH_MODULE_ENABLED
+#define HAL_GPIO_MODULE_ENABLED
+/* #define HAL_I2C_MODULE_ENABLED */
+/* #define HAL_I2S_MODULE_ENABLED */
+/* #define HAL_IWDG_MODULE_ENABLED */
+/* #define HAL_LCD_MODULE_ENABLED */
+/* #define HAL_LPTIM_MODULE_ENABLED */
+#define HAL_PWR_MODULE_ENABLED
+#define HAL_RCC_MODULE_ENABLED
+/* #define HAL_RNG_MODULE_ENABLED */
+#define HAL_RTC_MODULE_ENABLED
+#define HAL_SPI_MODULE_ENABLED 
+/* #define HAL_TIM_MODULE_ENABLED */
+/* #define HAL_UART_MODULE_ENABLED */
+/* #define HAL_USART_MODULE_ENABLED */
+/* #define HAL_IRDA_MODULE_ENABLED */
+/* #define HAL_SMARTCARD_MODULE_ENABLED */
+/* #define HAL_SMBUS_MODULE_ENABLED */
+/* #define HAL_WWDG_MODULE_ENABLED */
+#define HAL_CORTEX_MODULE_ENABLED
+/* #define HAL_PCD_MODULE_ENABLED */
+
+
+/* ########################## Oscillator Values adaptation ####################*/
+/**
+  * @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
+  *        This value is used by the RCC HAL module to compute the system frequency
+  *        (when HSE is used as system clock source, directly or through the PLL).
+  */
+#if !defined  (HSE_VALUE) 
+  #define HSE_VALUE    ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */
+#endif /* HSE_VALUE */
+
+#if !defined  (HSE_STARTUP_TIMEOUT)
+  #define HSE_STARTUP_TIMEOUT    ((uint32_t)5000)   /*!< Time out for HSE start up, in ms */
+#endif /* HSE_STARTUP_TIMEOUT */
+
+/**
+  * @brief Internal Multiple Speed oscillator (MSI) default value.
+  *        This value is the default MSI range value after Reset.
+  */
+#if !defined  (MSI_VALUE)
+  #define MSI_VALUE    ((uint32_t)2000000) /*!< Value of the Internal oscillator in Hz*/
+#endif /* MSI_VALUE */
+   
+/**
+  * @brief Internal High Speed oscillator (HSI) value.
+  *        This value is used by the RCC HAL module to compute the system frequency
+  *        (when HSI is used as system clock source, directly or through the PLL).
+  */
+#if !defined  (HSI_VALUE)
+  #define HSI_VALUE    ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/
+#endif /* HSI_VALUE */
+   
+/**
+  * @brief External Low Speed oscillator (LSE) value.
+  *        This value is used by the UART, RTC HAL module to compute the system frequency
+  */
+#if !defined  (LSE_VALUE)
+  #define LSE_VALUE    ((uint32_t)32768) /*!< Value of the External oscillator in Hz*/
+#endif /* LSE_VALUE */
+
+
+#if !defined  (LSE_STARTUP_TIMEOUT)
+  #define LSE_STARTUP_TIMEOUT    ((uint32_t)5000)   /*!< Time out for LSE start up, in ms */
+#endif /* HSE_STARTUP_TIMEOUT */
+
+   
+/* Tip: To avoid modifying this file each time you need to use different HSE,
+   ===  you can define the HSE value in your toolchain compiler preprocessor. */
+
+/* ########################### System Configuration ######################### */
+/**
+  * @brief This is the HAL system configuration section
+  */     
+#define  VDD_VALUE                    ((uint32_t)3300) /*!< Value of VDD in mv */
+#define  TICK_INT_PRIORITY            ((uint32_t)3)    /*!< tick interrupt priority */
+#define  USE_RTOS                     0     
+#define  PREFETCH_ENABLE              1
+#define  PREREAD_ENABLE               1
+#define  BUFFER_CACHE_DISABLE         0
+
+/* ########################## Assert Selection ############################## */
+/**
+  * @brief Uncomment the line below to expanse the "assert_param" macro in the
+  *        HAL drivers code
+  */
+/* #define USE_FULL_ASSERT    1 */
+
+/* Includes ------------------------------------------------------------------*/
+/**
+  * @brief Include module's header file
+  */
+
+#ifdef HAL_RCC_MODULE_ENABLED
+  #include "stm32l0xx_hal_rcc.h"
+#endif /* HAL_RCC_MODULE_ENABLED */
+
+#ifdef HAL_GPIO_MODULE_ENABLED
+  #include "stm32l0xx_hal_gpio.h"
+#endif /* HAL_GPIO_MODULE_ENABLED */
+
+#ifdef HAL_DMA_MODULE_ENABLED
+  #include "stm32l0xx_hal_dma.h"
+#endif /* HAL_DMA_MODULE_ENABLED */
+   
+#ifdef HAL_CORTEX_MODULE_ENABLED
+  #include "stm32l0xx_hal_cortex.h"
+#endif /* HAL_CORTEX_MODULE_ENABLED */
+
+#ifdef HAL_ADC_MODULE_ENABLED
+  #include "stm32l0xx_hal_adc.h"
+#endif /* HAL_ADC_MODULE_ENABLED */
+
+#ifdef HAL_COMP_MODULE_ENABLED
+  #include "stm32l0xx_hal_comp.h"
+#endif /* HAL_COMP_MODULE_ENABLED */
+   
+#ifdef HAL_CRC_MODULE_ENABLED
+  #include "stm32l0xx_hal_crc.h"
+#endif /* HAL_CRC_MODULE_ENABLED */
+
+#ifdef HAL_CRYP_MODULE_ENABLED
+  #include "stm32l0xx_hal_cryp.h"
+#endif /* HAL_CRYP_MODULE_ENABLED */
+
+#ifdef HAL_DAC_MODULE_ENABLED
+  #include "stm32l0xx_hal_dac.h"
+#endif /* HAL_DAC_MODULE_ENABLED */
+
+#ifdef HAL_FLASH_MODULE_ENABLED
+  #include "stm32l0xx_hal_flash.h"
+#endif /* HAL_FLASH_MODULE_ENABLED */
+ 
+#ifdef HAL_I2C_MODULE_ENABLED
+ #include "stm32l0xx_hal_i2c.h"
+#endif /* HAL_I2C_MODULE_ENABLED */
+
+#ifdef HAL_I2S_MODULE_ENABLED
+ #include "stm32l0xx_hal_i2s.h"
+#endif /* HAL_I2S_MODULE_ENABLED */
+
+#ifdef HAL_IWDG_MODULE_ENABLED
+ #include "stm32l0xx_hal_iwdg.h"
+#endif /* HAL_IWDG_MODULE_ENABLED */
+
+#ifdef HAL_LCD_MODULE_ENABLED
+ #include "stm32l0xx_hal_lcd.h"
+#endif /* HAL_LCD_MODULE_ENABLED */
+
+#ifdef HAL_LPTIM_MODULE_ENABLED
+#include "stm32l0xx_hal_lptim.h"
+#endif /* HAL_LPTIM_MODULE_ENABLED */
+   
+#ifdef HAL_PWR_MODULE_ENABLED
+ #include "stm32l0xx_hal_pwr.h"
+#endif /* HAL_PWR_MODULE_ENABLED */
+
+#ifdef HAL_RNG_MODULE_ENABLED
+ #include "stm32l0xx_hal_rng.h"
+#endif /* HAL_RNG_MODULE_ENABLED */
+
+#ifdef HAL_RTC_MODULE_ENABLED
+ #include "stm32l0xx_hal_rtc.h"
+
+#endif /* HAL_RTC_MODULE_ENABLED */
+
+#ifdef HAL_SPI_MODULE_ENABLED
+ #include "stm32l0xx_hal_spi.h"
+#endif /* HAL_SPI_MODULE_ENABLED */
+
+#ifdef HAL_TIM_MODULE_ENABLED
+ #include "stm32l0xx_hal_tim.h"
+#endif /* HAL_TIM_MODULE_ENABLED */
+
+#ifdef HAL_UART_MODULE_ENABLED
+ #include "stm32l0xx_hal_uart.h"
+#endif /* HAL_UART_MODULE_ENABLED */
+
+#ifdef HAL_USART_MODULE_ENABLED
+ #include "stm32l0xx_hal_usart.h"
+#endif /* HAL_USART_MODULE_ENABLED */
+
+#ifdef HAL_IRDA_MODULE_ENABLED
+ #include "stm32l0xx_hal_irda.h"
+#endif /* HAL_IRDA_MODULE_ENABLED */
+
+#ifdef HAL_SMARTCARD_MODULE_ENABLED
+ #include "stm32l0xx_hal_smartcard.h"
+#endif /* HAL_SMARTCARD_MODULE_ENABLED */
+
+#ifdef HAL_SMBUS_MODULE_ENABLED
+ #include "stm32l0xx_hal_smbus.h"
+#endif /* HAL_SMBUS_MODULE_ENABLED */
+
+#ifdef HAL_WWDG_MODULE_ENABLED
+ #include "stm32l0xx_hal_wwdg.h"
+#endif /* HAL_WWDG_MODULE_ENABLED */
+
+#ifdef HAL_PCD_MODULE_ENABLED
+ #include "stm32l0xx_hal_pcd.h"
+#endif /* HAL_PCD_MODULE_ENABLED */
+
+/* Exported macro ------------------------------------------------------------*/
+#ifdef  USE_FULL_ASSERT
+/**
+  * @brief  The assert_param macro is used for function's parameters check.
+  * @param  expr: If expr is false, it calls assert_failed function
+  *         which reports the name of the source file and the source
+  *         line number of the call that failed.
+  *         If expr is true, it returns no value.
+  * @retval None
+  */
+  #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
+/* Exported functions ------------------------------------------------------- */
+  void assert_failed(uint8_t* file, uint32_t line);
+#else
+  #define assert_param(expr) ((void)0)
+#endif /* USE_FULL_ASSERT */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32L0xx_HAL_CONF_H */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 inc/stm32xx_it.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/inc/stm32xx_it.h	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,69 @@
+/**
+  ******************************************************************************
+  * @file    stm32xx_it.h 
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   This file contains the headers of the interrupt handlers.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32xx_IT_H
+#define __STM32xx_IT_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif 
+
+/* Includes ------------------------------------------------------------------*/
+#include "cube_hal.h"
+
+/* Exported types ------------------------------------------------------------*/
+/* Exported constants --------------------------------------------------------*/
+/* Exported macro ------------------------------------------------------------*/
+/* Exported functions ------------------------------------------------------- */
+void NMI_Handler(void);
+void HardFault_Handler(void);
+void SVC_Handler(void);
+void DebugMon_Handler(void);
+void PendSV_Handler(void);
+void SysTick_Handler(void);
+void BNRG_SPI_EXTI_IRQHandler(void);
+void PUSH_BUTTON_EXTI_IRQHandler(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32xx_IT_H */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 main.cpp
--- a/main.cpp	Thu Nov 06 10:13:20 2014 +0000
+++ b/main.cpp	Wed Apr 08 14:17:20 2015 +0000
@@ -1,12 +1,136 @@
-#include "mbed.h"
+#include "mbed.h"  
+#include "cube_hal.h"
+
+#include "osal.h"
+#include "sensor_service.h"
+#include "debug.h"
+#include "stm32_bluenrg_ble.h"
+
 
-DigitalOut myled(LED1);
+Serial pc(USBTX, USBRX); // tx, rx
+/* Private macro -------------------------------------------------------------*/
+#define BDADDR_SIZE 6
 
+/* Private variables ---------------------------------------------------------*/
+extern volatile uint8_t set_connectable;
+extern volatile int connected;
+extern AxesRaw_t axes_data;
+
+/* Private function prototypes -----------------------------------------------*/
+void User_Process(AxesRaw_t* p_axes);
+
+
+float tri;
 int main() {
-    while(1) {
-        myled = 1; // LED is ON
-        wait(0.2); // 200 ms
-        myled = 0; // LED is OFF
-        wait(1.0); // 1 sec
+    const char *name = "BlueNRG";
+  uint8_t SERVER_BDADDR[] = {0x12, 0x34, 0x00, 0xE1, 0x80, 0x02};
+  //uint8_t bdaddr[BDADDR_SIZE];
+  uint8_t bdaddr[BDADDR_SIZE] = {0x12, 0x34, 0x00, 0xE1, 0x80, 0x02} ;
+  uint16_t service_handle, dev_name_char_handle, appearance_char_handle;
+  int ret;  
+  
+  HAL_Init();
+  /* Configure the User Button in GPIO Mode */
+  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);
+  /* Configure the system clock */
+//  SystemClock_Config();
+  /* Initialize the BlueNRG SPI driver */
+  BNRG_SPI_Init();
+  /* Initialize the BlueNRG HCI */
+  HCI_Init();
+  /* Reset BlueNRG hardware */
+  BlueNRG_RST();
+  /* The Nucleo board must be configured as SERVER */
+  //Osal_MemCpy(bdaddr, SERVER_BDADDR, sizeof(SERVER_BDADDR));
+  
+  ret = aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET,
+                                  CONFIG_DATA_PUBADDR_LEN,
+                                  bdaddr);
+    
+    pc.printf("Hello World!\n");
+
+ if(ret){
+    PRINTF("Setting BD_ADDR failed.\n");
+  }
+  
+  ret = aci_gatt_init();    
+  if(ret){
+    PRINTF("GATT_Init failed.\n");
+  }
+  
+  ret = aci_gap_init(GAP_PERIPHERAL_ROLE, &service_handle, 
+                     &dev_name_char_handle, &appearance_char_handle);
+  if(ret != BLE_STATUS_SUCCESS){
+    PRINTF("GAP_Init failed.\n");
+  }
+
+  ret = aci_gatt_update_char_value(service_handle, dev_name_char_handle, 0,
+                                   strlen(name), (uint8_t *)name);
+
+  if(ret){
+    PRINTF("aci_gatt_update_char_value failed.\n");            
+    while(1);
+  }
+  
+  ret = aci_gap_set_auth_requirement(MITM_PROTECTION_REQUIRED,
+                                     OOB_AUTH_DATA_ABSENT,
+                                     NULL,
+                                     7,
+                                     16,
+                                     USE_FIXED_PIN_FOR_PAIRING,
+                                     123456,
+                                     BONDING);
+  if (ret == BLE_STATUS_SUCCESS) {
+    PRINTF("BLE Stack Initialized.\n");
+  }
+  
+  PRINTF("SERVER: BLE Stack Initialized\n");
+  
+  ret = Add_Acc_Service();
+  
+  if(ret == BLE_STATUS_SUCCESS)
+    PRINTF("Acc service added successfully.\n");
+  else
+    PRINTF("Error while adding Acc service.\n");
+  
+  ret = Add_Environmental_Sensor_Service();
+  
+  if(ret == BLE_STATUS_SUCCESS)
+    PRINTF("Environmental Sensor service added successfully.\n");
+  else
+    PRINTF("Error while adding Environmental Sensor service.\n");
+
+  /* Set output power level */
+  ret = aci_hal_set_tx_power_level(1,4);
+
+  while(1)
+  {
+    HCI_Process();
+    User_Process(&axes_data);
+  }
+}
+
+void User_Process(AxesRaw_t* p_axes)
+{
+  if(set_connectable){
+    setConnectable();
+    set_connectable = FALSE;
+  }  
+
+  /* Check if the user has pushed the button */
+  if(BSP_PB_GetState(BUTTON_KEY) == RESET)
+  {
+    while (BSP_PB_GetState(BUTTON_KEY) == RESET);
+    
+    //BSP_LED_Toggle(LED2); //used for debugging
+    
+    if(connected){
+      /* Update acceleration data */
+      p_axes->AXIS_X += 100;
+      p_axes->AXIS_Y += 100;
+      p_axes->AXIS_Z += 100;
+      //PRINTF("ACC: X=%6d Y=%6d Z=%6d\r\n", p_axes->AXIS_X, p_axes->AXIS_Y, p_axes->AXIS_Z);
+      Acc_Update(p_axes);
     }
-}
+  }
+}
\ No newline at end of file
diff -r f57d754b1814 -r 987b201ec4b1 mbed.bld
--- a/mbed.bld	Thu Nov 06 10:13:20 2014 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/users/mbed_official/code/mbed/builds/031413cf7a89
\ No newline at end of file
diff -r f57d754b1814 -r 987b201ec4b1 mbed.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.lib	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/users/filartrix/code/mbed/#4298809c7c9e
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_IFR.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_IFR.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,281 @@
+
+#include "hal.h"
+#include "hal_types.h"
+#include "ble_status.h"
+#include "bluenrg_updater_aci.h"
+#include "bluenrg_utils.h"
+//#include "SDK_EVAL_Spi_Driver.h"
+
+/************** Do not change this define section ************/
+
+#define BLUENRG_32_MHZ          1
+#define BLUENRG_32_MHZ_RO       2
+#define BLUENRG_16_MHZ          3
+#define BLUENRG_16_MHZ_RO       4
+
+#define MASTER_SCA_500ppm       0 // 251 ppm to 500 ppm
+#define MASTER_SCA_250ppm       1 // 151 ppm to 250 ppm
+#define MASTER_SCA_150ppm       2 // 101 ppm to 150 ppm
+#define MASTER_SCA_100ppm       3 // 76 ppm to 100 ppm
+#define MASTER_SCA_75ppm        4 // 51 ppm to 75 ppm
+#define MASTER_SCA_50ppm        5 // 31 ppm to 50 ppm
+#define MASTER_SCA_30ppm        6 // 21 ppm to 30 ppm
+#define MASTER_SCA_20ppm        7 // 0 ppm to 20 ppm
+
+/************************************************************/
+
+
+/************** Definitions that can be changed. ************/
+
+#define STACK_MODE              2
+#define SLAVE_SCA_PPM           100
+#define MASTER_SCA              MASTER_SCA_100ppm
+#define HS_STARTUP_TIME_US      512
+#define DAY                     27
+#define MONTH                   01
+#define YEAR                    14
+
+/************************************************************/
+
+#if BLUENRG_CONFIG == BLUENRG_32_MHZ
+
+const IFR_config_TypeDef IFR_config = {
+  0x02,0x3A,0x5C,0x02,
+  0x34,0x5F,0x02,0x39,
+  0xA2,0x00,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  0x02,0x1C,0x53,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  STACK_MODE,
+  0xFF,0xFF,0xFF,
+  0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
+  htobl(0x00190000),
+  htobl(0x0028F5C2),
+  htobs(SLAVE_SCA_PPM),
+  MASTER_SCA,
+  0xFF,
+  htobs(FROM_US_TO_SYS_TIME(HS_STARTUP_TIME_US)),
+  0xEF,
+  0x5F,
+  0xFF,0xFF,0xFF,
+  0xFF,
+  0xFF,   
+  INT_TO_BCD(YEAR),INT_TO_BCD(MONTH),INT_TO_BCD(DAY),
+  0xFFFFFFFF,  
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF
+};
+
+#elif BLUENRG_CONFIG == BLUENRG_32_MHZ_RO
+
+const IFR_config_TypeDef IFR_config = {
+  0x02,0x3A,0x5C,0x02,
+  0x34,0x1F,0x02,0x39,
+  0xA2,0x00,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  0x02,0x1C,0x53,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  STACK_MODE,
+  0xFF,0xFF,0xFF,
+  0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  htobs(0x01F4), 
+  0x00,
+  0xFF,
+  htobs(FROM_US_TO_SYS_TIME(HS_STARTUP_TIME_US)),
+  0xFF,
+  0x5F,
+  0xFF,0xFF,0xFF,
+  0xFF,
+  0xFF,   
+  INT_TO_BCD(YEAR),INT_TO_BCD(MONTH),INT_TO_BCD(DAY),
+  0xFFFFFFFF,  
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF  
+};
+
+#elif BLUENRG_CONFIG == BLUENRG_16_MHZ
+
+const IFR_config_TypeDef IFR_config = {
+  0x02,0x34,0x5B,0x03,
+  0x39,0xA2,0x58,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  0x02,0x1C,0x53,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  STACK_MODE,
+  0xFF,0xFF,0xFF,
+  0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
+  htobl(0x00190000),
+  htobl(0x0028F5C2),
+  htobs(SLAVE_SCA_PPM), 
+  MASTER_SCA,
+  0xFF,
+  htobs(FROM_US_TO_SYS_TIME(HS_STARTUP_TIME_US)),
+  0xEE,
+  0x5F,
+  0xFF,0xFF,0xFF,
+  0xFF,
+  0xFF,   
+  INT_TO_BCD(YEAR),INT_TO_BCD(MONTH),INT_TO_BCD(DAY),
+  0xFFFFFFFF,  
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF
+
+};
+
+#elif BLUENRG_CONFIG == BLUENRG_16_MHZ_RO
+
+const IFR_config_TypeDef IFR_config = {
+  0x02,0x34,0x1B,0x03,
+  0x39,0xA2,0x58,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  0x02,0x1C,0x53,0x00,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  0xFF,0xFF,0xFF,0xFF,
+  
+  STACK_MODE,
+  0xFF,0xFF,0xFF,
+  0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  htobs(0x01F4), 
+  0x00,
+  0xFF,
+  htobs(FROM_US_TO_SYS_TIME(HS_STARTUP_TIME_US)),
+  0xFE,
+  0x5F,
+  0xFF,0xFF,0xFF,
+  0xFF,
+  0xFF,   
+  INT_TO_BCD(YEAR),INT_TO_BCD(MONTH),INT_TO_BCD(DAY),
+  0xFFFFFFFF,  
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF,
+  0xFFFFFFFF  
+};
+
+#else
+#warning BLUENRG_CONFIG not valid
+#endif
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_gap_aci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_gap_aci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,762 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_hci.c
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 4-Oct-2013
+* Description        : File with HCI commands for BlueNRG FW6.0 and above.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "osal.h"
+#include "hci_const.h"
+#include "bluenrg_aci_const.h"
+#include "bluenrg_gap_aci.h"
+#include "gatt_server.h"
+#include "gap.h"
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+
+tBleStatus aci_gap_init(uint8_t role, uint16_t* service_handle, uint16_t* dev_name_char_handle, uint16_t* appearance_char_handle)
+{
+  struct hci_request rq;
+  gap_init_cp cp;
+  gap_init_rp resp;
+
+  cp.role = role;
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_INIT;
+  rq.cparam = &cp;
+  rq.clen = GAP_INIT_CP_SIZE;
+  rq.rparam = &resp;
+  rq.rlen = GAP_INIT_RP_SIZE;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  if (resp.status) {
+    return resp.status;
+  }
+  
+  *service_handle = btohs(resp.service_handle);
+  *dev_name_char_handle = btohs(resp.dev_name_char_handle);
+  *appearance_char_handle = btohs(resp.appearance_char_handle);
+  
+  return 0;
+}
+
+tBleStatus aci_gap_set_non_discoverable(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_NON_DISCOVERABLE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;  
+}
+
+tBleStatus aci_gap_set_limited_discoverable(uint8_t AdvType, uint16_t AdvIntervMin, uint16_t AdvIntervMax,
+					    uint8_t OwnAddrType, uint8_t AdvFilterPolicy, uint8_t LocalNameLen,
+					    const char *LocalName, uint8_t ServiceUUIDLen, uint8_t* ServiceUUIDList,
+					    uint16_t SlaveConnIntervMin, uint16_t SlaveConnIntervMax)
+{
+  struct hci_request rq;
+  uint8_t status;    
+  uint8_t buffer[40];
+  uint8_t indx = 0;
+    
+  if ((LocalNameLen+ServiceUUIDLen+14) > sizeof(buffer))
+    return BLE_STATUS_INVALID_PARAMS;
+
+  buffer[indx] = AdvType;
+  indx++;
+    
+  AdvIntervMin = htobs(AdvIntervMin);
+  Osal_MemCpy(buffer + indx, &AdvIntervMin, 2);
+  indx +=  2;
+    
+  AdvIntervMax = htobs(AdvIntervMax);
+  Osal_MemCpy(buffer + indx, &AdvIntervMax, 2);
+  indx +=  2;
+    
+  buffer[indx] = OwnAddrType;
+  indx++;
+    
+  buffer[indx] = AdvFilterPolicy;
+  indx++;
+    
+  buffer[indx] = LocalNameLen;
+  indx++;
+    
+  Osal_MemCpy(buffer + indx, LocalName, LocalNameLen);
+  indx +=  LocalNameLen;
+
+  buffer[indx] = ServiceUUIDLen;
+  indx++;
+
+  Osal_MemCpy(buffer + indx, ServiceUUIDList, ServiceUUIDLen);
+  indx +=  ServiceUUIDLen;
+
+  Osal_MemCpy(buffer + indx, &SlaveConnIntervMin, 2);
+  indx +=  2;
+
+  Osal_MemCpy(buffer + indx, &SlaveConnIntervMax, 2);
+  indx +=  2;    
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_LIMITED_DISCOVERABLE;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_set_discoverable(uint8_t AdvType, uint16_t AdvIntervMin, uint16_t AdvIntervMax,
+                             uint8_t OwnAddrType, uint8_t AdvFilterPolicy, uint8_t LocalNameLen,
+                             const char *LocalName, uint8_t ServiceUUIDLen, uint8_t* ServiceUUIDList,
+                             uint16_t SlaveConnIntervMin, uint16_t SlaveConnIntervMax)
+{
+  struct hci_request rq;
+  uint8_t status;    
+  uint8_t buffer[40];
+  uint8_t indx = 0;
+  
+  if ((LocalNameLen+ServiceUUIDLen+14) > sizeof(buffer))
+    return BLE_STATUS_INVALID_PARAMS;
+
+  buffer[indx] = AdvType;
+  indx++;
+  
+  AdvIntervMin = htobs(AdvIntervMin);
+  Osal_MemCpy(buffer + indx, &AdvIntervMin, 2);
+  indx +=  2;
+    
+  AdvIntervMax = htobs(AdvIntervMax);
+  Osal_MemCpy(buffer + indx, &AdvIntervMax, 2);
+  indx +=  2;
+    
+  buffer[indx] = OwnAddrType;
+  indx++;
+    
+  buffer[indx] = AdvFilterPolicy;
+  indx++;
+    
+  buffer[indx] = LocalNameLen;
+  indx++;
+    
+  Osal_MemCpy(buffer + indx, LocalName, LocalNameLen);
+  indx +=  LocalNameLen;
+  
+  buffer[indx] = ServiceUUIDLen;
+  indx++;
+
+  Osal_MemCpy(buffer + indx, ServiceUUIDList, ServiceUUIDLen);
+  indx +=  ServiceUUIDLen;  
+
+  SlaveConnIntervMin = htobs(SlaveConnIntervMin);
+  Osal_MemCpy(buffer + indx, &SlaveConnIntervMin, 2);
+  indx +=  2;
+  
+  SlaveConnIntervMax = htobs(SlaveConnIntervMax);
+  Osal_MemCpy(buffer + indx, &SlaveConnIntervMax, 2);
+  indx +=  2;    
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_DISCOVERABLE;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+
+  return 0;
+}
+
+tBleStatus aci_gap_set_direct_connectable(uint8_t own_addr_type, uint8_t initiator_addr_type, const uint8_t *initiator_addr)
+{
+  struct hci_request rq;
+  gap_set_direct_conectable_cp cp;
+  uint8_t status;    
+
+  cp.own_bdaddr_type = own_addr_type;
+  cp.direct_bdaddr_type = initiator_addr_type;
+  Osal_MemCpy(cp.direct_bdaddr, initiator_addr, 6);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_DIRECT_CONNECTABLE;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_DIRECT_CONNECTABLE_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+    
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  return status;
+}
+
+tBleStatus aci_gap_set_io_capabilitiy(uint8_t io_capability)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gap_set_io_capability_cp cp;
+    
+  cp.io_capability = io_capability;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_IO_CAPABILITY;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_IO_CAPABILITY_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+    
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  return status;
+}
+
+tBleStatus aci_gap_set_auth_requirement(uint8_t mitm_mode,
+                                        uint8_t oob_enable,
+                                        uint8_t oob_data[16],
+                                        uint8_t min_encryption_key_size,
+                                        uint8_t max_encryption_key_size,
+                                        uint8_t use_fixed_pin,
+                                        uint32_t fixed_pin,
+                                        uint8_t bonding_mode)
+{
+  struct hci_request rq;
+  gap_set_auth_requirement_cp cp;    
+  uint8_t status;
+    
+  cp.mitm_mode = mitm_mode;
+  cp.oob_enable = oob_enable;
+  Osal_MemCpy(cp.oob_data, oob_data, 16);
+  cp.min_encryption_key_size = min_encryption_key_size;
+  cp.max_encryption_key_size = max_encryption_key_size;
+  cp.use_fixed_pin = use_fixed_pin;
+  cp.fixed_pin = htobl(fixed_pin);
+  cp.bonding_mode = bonding_mode;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_AUTH_REQUIREMENT;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_AUTH_REQUIREMENT_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+    
+  return 0;
+}
+
+tBleStatus aci_gap_set_author_requirement(uint16_t conn_handle, uint8_t authorization_enable)
+{
+  struct hci_request rq;
+  gap_set_author_requirement_cp cp;    
+  uint8_t status;
+    
+  cp.conn_handle = htobs(conn_handle);
+  cp.authorization_enable = authorization_enable;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_AUTHOR_REQUIREMENT;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_AUTHOR_REQUIREMENT_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gap_pass_key_response(uint16_t conn_handle, uint32_t passkey)
+{
+  struct hci_request rq;
+  gap_passkey_response_cp cp;    
+  uint8_t status;
+    
+  cp.conn_handle = htobs(conn_handle);
+  cp.passkey = htobl(passkey);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_PASSKEY_RESPONSE;
+  rq.cparam = &cp;
+  rq.clen = GAP_PASSKEY_RESPONSE_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gap_authorization_response(uint16_t conn_handle, uint8_t authorize)
+{
+  struct hci_request rq;
+  gap_authorization_response_cp cp;    
+  uint8_t status;
+    
+  cp.conn_handle = htobs(conn_handle);
+  cp.authorize = authorize;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_AUTHORIZATION_RESPONSE;
+  rq.cparam = &cp;
+  rq.clen = GAP_AUTHORIZATION_RESPONSE_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gap_set_non_connectable(uint8_t adv_type)
+{
+  struct hci_request rq;
+  gap_set_non_connectable_cp cp;    
+  uint8_t status;
+    
+  cp.advertising_event_type = adv_type;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_NON_CONNECTABLE;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_NON_CONNECTABLE_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gap_set_undirected_connectable(uint8_t own_addr_type, uint8_t adv_filter_policy)
+{
+  struct hci_request rq;
+  gap_set_undirected_connectable_cp cp;    
+  uint8_t status;
+    
+  cp.own_addr_type = own_addr_type;
+  cp.adv_filter_policy = adv_filter_policy;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SET_UNDIRECTED_CONNECTABLE;
+  rq.cparam = &cp;
+  rq.clen = GAP_SET_UNDIRECTED_CONNECTABLE_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gap_slave_security_request(uint16_t conn_handle, uint8_t bonding, uint8_t mitm_protection)
+{
+  struct hci_request rq;
+  gap_slave_security_request_cp cp;
+  uint8_t status;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.bonding = bonding;
+  cp.mitm_protection = mitm_protection;
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SLAVE_SECURITY_REQUEST;
+  rq.cparam = &cp;
+  rq.clen = GAP_SLAVE_SECURITY_REQUEST_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+
+}
+
+tBleStatus aci_gap_update_adv_data(uint8_t AdvLen, uint8_t *AdvData)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[32];
+  uint8_t indx = 0;
+    
+  if (AdvLen > (sizeof(buffer)-1))
+    return BLE_STATUS_INVALID_PARAMS;
+
+  buffer[indx] = AdvLen;
+  indx++;
+    
+  Osal_MemCpy(buffer + indx, AdvData, AdvLen);
+  indx +=  AdvLen;
+    
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_UPDATE_ADV_DATA;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+    
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  return status;
+}
+
+tBleStatus aci_gap_configure_whitelist(void)
+{
+  struct hci_request rq;
+  uint8_t status, dummy;
+  
+  dummy = 0;
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_CONFIGURE_WHITELIST;
+  rq.cparam = (void*)&dummy;
+  rq.clen = 0;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_terminate(uint16_t conn_handle, uint8_t reason)
+{
+  struct hci_request rq;
+  gap_terminate_cp cp;
+  uint8_t status;  
+
+  cp.handle = htobs(conn_handle);
+  cp.reason = reason;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_TERMINATE;
+  rq.cparam = &cp;
+  rq.clen = GAP_TERMINATE_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status; 
+}
+
+tBleStatus aci_gap_clear_security_database(void)
+{
+  struct hci_request rq;
+  uint8_t status, dummy;
+  
+  dummy = 0;
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_CLEAR_SECURITY_DB;
+  rq.cparam = (void*)&dummy;
+  rq.clen = 0;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_allow_rebond(void)
+{
+  struct hci_request rq;
+  uint8_t status, dummy;
+  
+  dummy = 0;
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_ALLOW_REBOND_DB;
+  rq.cparam = (void*)&dummy;
+  rq.clen = 0;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_start_limited_discovery_proc(uint16_t scanInterval, uint16_t scanWindow,
+						uint8_t own_address_type, uint8_t filterDuplicates)
+{
+  struct hci_request rq;
+  gap_start_limited_discovery_proc_cp cp;
+  uint8_t status;  
+
+  cp.scanInterval = htobs(scanInterval);
+  cp.scanWindow = htobs(scanWindow);
+  cp.own_address_type = own_address_type;
+  cp.filterDuplicates = filterDuplicates;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_START_LIMITED_DISCOVERY_PROC;
+  rq.cparam = &cp;
+  rq.clen = GAP_START_LIMITED_DISCOVERY_PROC_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_start_general_discovery_proc(uint16_t scanInterval, uint16_t scanWindow,
+						uint8_t own_address_type, uint8_t filterDuplicates)
+{
+  struct hci_request rq;
+  gap_start_general_discovery_proc_cp cp;
+  uint8_t status;  
+
+  cp.scanInterval = htobs(scanInterval);
+  cp.scanWindow = htobs(scanWindow);
+  cp.own_address_type = own_address_type;
+  cp.filterDuplicates = filterDuplicates;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_START_GENERAL_DISCOVERY_PROC;
+  rq.cparam = &cp;
+  rq.clen = GAP_START_GENERAL_DISCOVERY_PROC_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+
+tBleStatus aci_gap_start_auto_conn_establishment(uint16_t scanInterval, uint16_t scanWindow,
+						 uint8_t own_bdaddr_type, uint16_t conn_min_interval,	
+						 uint16_t conn_max_interval, uint16_t conn_latency,	
+						 uint16_t supervision_timeout, uint16_t min_conn_length, 
+						 uint16_t max_conn_length, uint8_t num_whitelist_entries,
+						 uint8_t *addr_array)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if (((num_whitelist_entries*7)+18) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  scanInterval = htobs(scanInterval);
+  Osal_MemCpy(buffer + indx, &scanInterval, 2);
+  indx += 2;
+    
+  scanWindow = htobs(scanWindow);
+  Osal_MemCpy(buffer + indx, &scanWindow, 2);
+  indx += 2;
+
+  buffer[indx] = own_bdaddr_type;
+  indx++;
+  
+  conn_min_interval = htobs(conn_min_interval);
+  Osal_MemCpy(buffer + indx, &conn_min_interval, 2);
+  indx +=  2;
+
+  conn_max_interval = htobs(conn_max_interval);
+  Osal_MemCpy(buffer + indx, &conn_max_interval, 2);
+  indx +=  2;
+
+  conn_latency = htobs(conn_latency);
+  Osal_MemCpy(buffer + indx, &conn_latency, 2);
+  indx +=  2;
+
+  supervision_timeout = htobs(supervision_timeout);
+  Osal_MemCpy(buffer + indx, &supervision_timeout, 2);
+  indx +=  2;
+
+  min_conn_length = htobs(min_conn_length);
+  Osal_MemCpy(buffer + indx, &min_conn_length, 2);
+  indx +=  2;
+
+  max_conn_length = htobs(max_conn_length);
+  Osal_MemCpy(buffer + indx, &max_conn_length, 2);
+  indx +=  2;
+
+  buffer[indx] = num_whitelist_entries;
+  indx++;
+
+  Osal_MemCpy(buffer + indx, addr_array, (num_whitelist_entries*7));
+  indx +=  num_whitelist_entries * 7;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_START_AUTO_CONN_ESTABLISHMENT;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;  
+}
+
+tBleStatus aci_gap_create_connection(uint16_t scanInterval, uint16_t scanWindow,
+				     uint8_t peer_bdaddr_type, tBDAddr peer_bdaddr,	
+				     uint8_t own_bdaddr_type, uint16_t conn_min_interval,	
+				     uint16_t conn_max_interval, uint16_t conn_latency,	
+				     uint16_t supervision_timeout, uint16_t min_conn_length, 
+				     uint16_t max_conn_length)
+{
+  struct hci_request rq;
+  gap_create_connection_cp cp;
+  uint8_t status;  
+
+  cp.scanInterval = htobs(scanInterval);
+  cp.scanWindow = htobs(scanWindow);
+  cp.peer_bdaddr_type = peer_bdaddr_type;
+  Osal_MemCpy(cp.peer_bdaddr, peer_bdaddr, 6);
+  cp.own_bdaddr_type = own_bdaddr_type;
+  cp.conn_min_interval = htobs(conn_min_interval);
+  cp.conn_max_interval = htobs(conn_max_interval);
+  cp.conn_latency = htobs(conn_latency);
+  cp.supervision_timeout = htobs(supervision_timeout);
+  cp.min_conn_length = htobs(min_conn_length);
+  cp.max_conn_length = htobs(max_conn_length);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_CREATE_CONNECTION;
+  rq.cparam = &cp;
+  rq.clen = GAP_CREATE_CONNECTION_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gap_terminate_gap_procedure(uint8_t procedure_code)
+{
+  struct hci_request rq;
+  uint8_t status;  
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_TERMINATE_GAP_PROCEDURE;
+  rq.cparam = &procedure_code;
+  rq.clen = 1;
+  rq.rparam = &status;
+  rq.rlen = 1;
+  
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+
+}
+
+tBleStatus aci_gap_send_pairing_request(uint16_t conn_handle, uint8_t force_rebond)
+{
+  struct hci_request rq;
+  gap_send_pairing_request_cp cp;
+  uint8_t status;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.force_rebond = force_rebond;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GAP_SEND_PAIRING_REQUEST;
+  rq.cparam = &cp;
+  rq.clen = GAP_SEND_PAIRING_REQUEST_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_gatt_aci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_gatt_aci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,999 @@
+/******************** (C) COPYRIGHT 2014 STMicroelectronics ********************
+* File Name          : bluenrg_gatt_aci.c
+* Author             : AMS - AAS
+* Version            : V1.0.0
+* Date               : 26-Jun-2014
+* Description        : File with GATT commands for BlueNRG FW6.3.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "osal.h"
+#include "hci_const.h"
+#include "bluenrg_aci_const.h"
+#include "bluenrg_gatt_aci.h"
+#include "gatt_server.h"
+#include "gap.h"
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+
+tBleStatus aci_gatt_init(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_INIT;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_add_serv(uint8_t service_uuid_type, const uint8_t* service_uuid, uint8_t service_type, uint8_t max_attr_records, uint16_t *serviceHandle)
+{
+  struct hci_request rq;
+  gatt_add_serv_rp resp;    
+  uint8_t buffer[19];
+  uint8_t uuid_len;
+  uint8_t indx = 0;
+    
+  buffer[indx] = service_uuid_type;
+  indx++;
+    
+  if(service_uuid_type == 0x01){
+    uuid_len = 2;
+  }
+  else {
+    uuid_len = 16;
+  }        
+  Osal_MemCpy(buffer + indx, service_uuid, uuid_len);
+  indx +=  uuid_len;
+    
+  buffer[indx] = service_type;
+  indx++;
+    
+  buffer[indx] = max_attr_records;
+  indx++;
+    
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_ADD_SERV;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &resp;
+  rq.rlen = GATT_ADD_SERV_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (resp.status) {
+    return resp.status;
+  }
+    
+  *serviceHandle = btohs(resp.handle);
+
+  return 0;
+}
+
+tBleStatus aci_gatt_include_service(uint16_t service_handle, uint16_t included_start_handle,
+				    uint16_t included_end_handle, uint8_t included_uuid_type,
+				    const uint8_t* included_uuid, uint16_t *included_handle)
+{
+  struct hci_request rq;
+  gatt_include_serv_rp resp;    
+  uint8_t buffer[23];
+  uint8_t uuid_len;
+  uint8_t indx = 0;
+
+  service_handle = htobs(service_handle);
+  Osal_MemCpy(buffer, &service_handle, 2);
+  indx += 2;
+    
+  included_start_handle = htobs(included_start_handle);
+  Osal_MemCpy(buffer+indx, &included_start_handle, 2);
+  indx += 2;
+
+  included_end_handle = htobs(included_end_handle);
+  Osal_MemCpy(buffer+indx, &included_end_handle, 2);
+  indx += 2;
+
+  if(included_uuid_type == 0x01){
+    uuid_len = 2;
+  } else {
+    uuid_len = 16;
+  }        
+
+  buffer[indx] = included_uuid_type;
+  indx++;
+
+  Osal_MemCpy(buffer + indx, included_uuid, uuid_len);
+  indx += uuid_len;
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_INCLUDE_SERV;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &resp;
+  rq.rlen = GATT_INCLUDE_SERV_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (resp.status) {
+    return resp.status;
+  }
+    
+  *included_handle = btohs(resp.handle);
+
+  return 0;
+}
+
+tBleStatus aci_gatt_add_char(uint16_t serviceHandle,
+			     uint8_t charUuidType,
+			     const uint8_t* charUuid, 
+			     uint8_t charValueLen, 
+			     uint8_t charProperties,
+			     uint8_t secPermissions,
+			     uint8_t gattEvtMask,
+			     uint8_t encryKeySize,
+			     uint8_t isVariable,
+			     uint16_t* charHandle)                     
+{
+  struct hci_request rq;
+  gatt_add_serv_rp resp;
+  uint8_t buffer[25];
+  uint8_t uuid_len;
+  uint8_t indx = 0;
+    
+  serviceHandle = htobs(serviceHandle);
+  Osal_MemCpy(buffer + indx, &serviceHandle, 2);
+  indx += 2;
+    
+  buffer[indx] = charUuidType;
+  indx++;
+    
+  if(charUuidType == 0x01){
+    uuid_len = 2;
+  }
+  else {
+    uuid_len = 16;
+  }        
+  Osal_MemCpy(buffer + indx, charUuid, uuid_len);
+  indx +=  uuid_len;
+    
+  buffer[indx] = charValueLen;
+  indx++;
+    
+  buffer[indx] = charProperties;
+  indx++;
+    
+  buffer[indx] = secPermissions;
+  indx++;
+    
+  buffer[indx] = gattEvtMask;
+  indx++;
+    
+  buffer[indx] = encryKeySize;
+  indx++;
+    
+  buffer[indx] = isVariable;
+  indx++;
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_ADD_CHAR;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &resp;
+  rq.rlen = GATT_ADD_CHAR_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (resp.status) {
+    return resp.status;
+  }
+    
+  *charHandle = btohs(resp.handle);
+
+  return 0;
+}
+
+tBleStatus aci_gatt_add_char_desc(uint16_t serviceHandle,
+                                  uint16_t charHandle,
+                                  uint8_t descUuidType,
+                                  const uint8_t* uuid, 
+                                  uint8_t descValueMaxLen,
+                                  uint8_t descValueLen,
+                                  const void* descValue, 
+                                  uint8_t secPermissions,
+                                  uint8_t accPermissions,
+                                  uint8_t gattEvtMask,
+                                  uint8_t encryKeySize,
+                                  uint8_t isVariable,
+                                  uint16_t* descHandle)                     
+{
+  struct hci_request rq;
+  gatt_add_char_desc_rp resp;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t uuid_len;
+  uint8_t indx = 0;
+    
+  serviceHandle = htobs(serviceHandle);
+  Osal_MemCpy(buffer + indx, &serviceHandle, 2);
+  indx += 2;
+    
+  charHandle = htobs(charHandle);
+  Osal_MemCpy(buffer + indx, &charHandle, 2);
+  indx += 2;
+    
+  buffer[indx] = descUuidType;
+  indx++;
+    
+  if(descUuidType == 0x01){
+    uuid_len = 2;
+  }
+  else {
+    uuid_len = 16;
+  }        
+  Osal_MemCpy(buffer + indx, uuid, uuid_len);
+  indx +=  uuid_len;
+    
+  buffer[indx] = descValueMaxLen;
+  indx++;
+    
+  buffer[indx] = descValueLen;
+  indx++;
+
+  if ((descValueLen+indx+5) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+  
+  Osal_MemCpy(buffer + indx, descValue, descValueLen);
+  indx += descValueLen;
+    
+  buffer[indx] = secPermissions;
+  indx++;
+    
+  buffer[indx] = accPermissions;
+  indx++;
+    
+  buffer[indx] = gattEvtMask;
+  indx++;
+    
+  buffer[indx] = encryKeySize;
+  indx++;
+    
+  buffer[indx] = isVariable;
+  indx++;
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_ADD_CHAR_DESC;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &resp;
+  rq.rlen = GATT_ADD_CHAR_DESC_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (resp.status) {
+    return resp.status;
+  }
+    
+  *descHandle = btohs(resp.handle);
+
+  return 0;
+}
+
+
+tBleStatus aci_gatt_update_char_value(uint16_t servHandle, 
+				      uint16_t charHandle,
+				      uint8_t charValOffset,
+				      uint8_t charValueLen,   
+				      const uint8_t *charValue)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((charValueLen+6) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  servHandle = htobs(servHandle);
+  Osal_MemCpy(buffer + indx, &servHandle, 2);
+  indx += 2;
+    
+  charHandle = htobs(charHandle);
+  Osal_MemCpy(buffer + indx, &charHandle, 2);
+  indx += 2;
+    
+  buffer[indx] = charValOffset;
+  indx++;
+    
+  buffer[indx] = charValueLen;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, charValue, charValueLen);
+  indx +=  charValueLen;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_UPD_CHAR_VAL;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+
+  return 0;
+}
+
+tBleStatus aci_gatt_del_char(uint16_t servHandle, uint16_t charHandle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_del_char_cp cp;
+
+  cp.service_handle = htobs(servHandle);
+  cp.char_handle = htobs(charHandle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DEL_CHAR;
+  rq.cparam = &cp;
+  rq.clen = GATT_DEL_CHAR_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+                                      
+tBleStatus aci_gatt_del_service(uint16_t servHandle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_del_serv_cp cp;
+
+  cp.service_handle = htobs(servHandle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DEL_SERV;
+  rq.cparam = &cp;
+  rq.clen = GATT_DEL_SERV_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_del_include_service(uint16_t servHandle, uint16_t includeServHandle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_del_inc_serv_cp cp;
+
+  cp.service_handle = htobs(servHandle);
+  cp.inc_serv_handle = htobs(includeServHandle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DEL_INC_SERV;
+  rq.cparam = &cp;
+  rq.clen = GATT_DEL_INC_SERV_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_set_event_mask(uint32_t event_mask)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_set_evt_mask_cp cp;
+
+  cp.evt_mask = htobs(event_mask);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_SET_EVT_MASK;
+  rq.cparam = &cp;
+  rq.clen = GATT_SET_EVT_MASK_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+  
+tBleStatus aci_gatt_exchange_configuration(uint16_t conn_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_exchange_config_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_EXCHANGE_CONFIG;
+  rq.cparam = &cp;
+  rq.clen = GATT_EXCHANGE_CONFIG_CP_SIZE;
+  rq.event = EVT_CMD_STATUS; 
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+  
+tBleStatus aci_gatt_find_information_req(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_find_info_req_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.start_handle = htobs(start_handle);
+  cp.end_handle = htobs(end_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_FIND_INFO_REQ;
+  rq.cparam = &cp;
+  rq.clen = GATT_GATT_FIND_INFO_REQ_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_disc_all_prim_services(uint16_t conn_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_disc_all_prim_services_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DISC_ALL_PRIM_SERVICES;
+  rq.cparam = &cp;
+  rq.clen = GATT_DISC_ALL_PRIM_SERVICES_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_find_included_services(uint16_t conn_handle, uint16_t start_service_handle, 
+					   uint16_t end_service_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_find_included_services_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.start_handle = htobs(start_service_handle);
+  cp.end_handle = htobs(end_service_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_FIND_INCLUDED_SERVICES;
+  rq.cparam = &cp;
+  rq.clen = GATT_FIND_INCLUDED_SERVICES_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_disc_all_charac_of_serv(uint16_t conn_handle, uint16_t start_attr_handle, 
+					    uint16_t end_attr_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_disc_all_charac_of_serv_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.start_attr_handle = htobs(start_attr_handle);
+  cp.end_attr_handle = htobs(end_attr_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DISC_ALL_CHARAC_OF_SERV;
+  rq.cparam = &cp;
+  rq.clen = GATT_DISC_ALL_CHARAC_OF_SERV_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_discovery_characteristic_by_uuid(uint16_t conn_handle, uint16_t start_handle,
+				                     uint16_t end_handle, uint8_t charUuidType,
+                                                     const uint8_t* charUuid)
+{
+  struct hci_request rq;
+  uint8_t status;
+  
+  uint8_t buffer[23];
+  uint8_t uuid_len;
+  uint8_t indx = 0;
+    
+  conn_handle = htobs(conn_handle);
+  Osal_MemCpy(buffer + indx, &conn_handle, 2);
+  indx += 2;
+    
+  start_handle = htobs(start_handle);
+  Osal_MemCpy(buffer + indx, &start_handle, 2);
+  indx += 2;
+  
+  end_handle = htobs(end_handle);
+  Osal_MemCpy(buffer + indx, &end_handle, 2);
+  indx += 2;
+  
+  buffer[indx] = charUuidType;
+  indx++;
+    
+  if(charUuidType == 0x01){
+    uuid_len = 2;
+  }
+  else {
+    uuid_len = 16;
+  }        
+  Osal_MemCpy(buffer + indx, charUuid, uuid_len);
+  indx +=  uuid_len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DISC_CHARAC_BY_UUID;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_disc_all_charac_descriptors(uint16_t conn_handle, uint16_t char_val_handle, 
+						uint16_t char_end_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_disc_all_charac_descriptors_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.char_val_handle = htobs(char_val_handle);
+  cp.char_end_handle = htobs(char_end_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_DISC_ALL_CHARAC_DESCRIPTORS;
+  rq.cparam = &cp;
+  rq.clen = GATT_DISC_ALL_CHARAC_DESCRIPTORS_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_read_charac_val(uint16_t conn_handle, uint16_t attr_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_read_charac_val_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.attr_handle = htobs(attr_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_READ_CHARAC_VAL;
+  rq.cparam = &cp;
+  rq.clen = GATT_READ_CHARAC_VAL_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gatt_read_long_charac_val(uint16_t conn_handle, uint16_t attr_handle, 
+					 uint16_t val_offset)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_read_long_charac_val_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.attr_handle = htobs(attr_handle);
+  cp.val_offset = htobs(val_offset);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_READ_LONG_CHARAC_VAL;
+  rq.cparam = &cp;
+  rq.clen = GATT_READ_LONG_CHARAC_VAL_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_write_charac_value(uint16_t conn_handle, uint16_t attr_handle, 
+				       uint8_t value_len, uint8_t *attr_value)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((value_len+5) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  conn_handle = htobs(conn_handle);
+  Osal_MemCpy(buffer + indx, &conn_handle, 2);
+  indx += 2;
+    
+  attr_handle = htobs(attr_handle);
+  Osal_MemCpy(buffer + indx, &attr_handle, 2);
+  indx += 2;
+
+  buffer[indx] = value_len;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, attr_value, value_len);
+  indx +=  value_len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_WRITE_CHAR_VALUE;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_write_charac_descriptor(uint16_t conn_handle, uint16_t attr_handle, 
+					   uint8_t value_len, uint8_t *attr_value)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((value_len+5) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  conn_handle = htobs(conn_handle);
+  Osal_MemCpy(buffer + indx, &conn_handle, 2);
+  indx += 2;
+    
+  attr_handle = htobs(attr_handle);
+  Osal_MemCpy(buffer + indx, &attr_handle, 2);
+  indx += 2;
+
+  buffer[indx] = value_len;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, attr_value, value_len);
+  indx +=  value_len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_WRITE_CHAR_DESCRIPTOR;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.event = EVT_CMD_STATUS; 
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_write_without_response(uint16_t conn_handle, uint16_t attr_handle, 
+					   uint8_t value_len, uint8_t *attr_value)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((value_len+5) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  conn_handle = htobs(conn_handle);
+  Osal_MemCpy(buffer + indx, &conn_handle, 2);
+  indx += 2;
+    
+  attr_handle = htobs(attr_handle);
+  Osal_MemCpy(buffer + indx, &attr_handle, 2);
+  indx += 2;
+
+  buffer[indx] = value_len;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, attr_value, value_len);
+  indx +=  value_len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_WRITE_WITHOUT_RESPONSE;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+
+}
+
+tBleStatus aci_gatt_confirm_indication(uint16_t conn_handle)
+{
+  struct hci_request rq;
+  uint8_t status;
+  gatt_confirm_indication_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_CONFIRM_INDICATION;
+  rq.cparam = &cp;
+  rq.clen = GATT_CONFIRM_INDICATION_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;
+}
+
+tBleStatus aci_gatt_write_response(uint16_t conn_handle,
+                                   uint16_t attr_handle,
+                                   uint8_t write_status,
+                                   uint8_t err_code,
+                                   uint8_t att_val_len,
+                                   uint8_t *att_val)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+  
+  if ((att_val_len+7) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  conn_handle = htobs(conn_handle);  
+  Osal_MemCpy(buffer + indx, &conn_handle, 2);
+  indx += 2;
+    
+  attr_handle = htobs(attr_handle);
+  Osal_MemCpy(buffer + indx, &attr_handle, 2);
+  indx += 2;
+    
+  buffer[indx] = write_status;
+  indx += 1;
+    
+  buffer[indx] = err_code;
+  indx += 1;
+    
+  buffer[indx] = att_val_len;
+  indx += 1;
+    
+  Osal_MemCpy(buffer + indx, att_val, att_val_len);
+  indx += att_val_len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_WRITE_RESPONSE;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+
+  return 0;
+}
+
+tBleStatus aci_gatt_allow_read(uint16_t conn_handle)
+{
+    struct hci_request rq;
+    gatt_allow_read_cp cp;
+    uint8_t status;
+    
+    cp.conn_handle = htobs(conn_handle);
+
+    Osal_MemSet(&rq, 0, sizeof(rq));
+    rq.ogf = OGF_VENDOR_CMD;
+    rq.ocf = OCF_GATT_ALLOW_READ;
+    rq.cparam = &cp;
+    rq.clen = GATT_ALLOW_READ_CP_SIZE;
+    rq.rparam = &status;
+    rq.rlen = 1;
+
+    if (hci_send_req(&rq) < 0)
+      return BLE_STATUS_TIMEOUT;
+
+    return status;
+}
+
+tBleStatus aci_gatt_set_desc_value(uint16_t servHandle, 
+				   uint16_t charHandle,
+				   uint16_t charDescHandle,
+				   uint16_t charDescValOffset,
+				   uint8_t charDescValueLen,   
+				   const uint8_t *charDescValue)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((charDescValueLen+9) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  servHandle = htobs(servHandle);
+  Osal_MemCpy(buffer + indx, &servHandle, 2);
+  indx += 2;
+    
+  charHandle = htobs(charHandle);
+  Osal_MemCpy(buffer + indx, &charHandle, 2);
+  indx += 2;
+    
+  charDescHandle = htobs(charDescHandle);
+  Osal_MemCpy(buffer + indx, &charDescHandle, 2);
+  indx += 2;
+    
+  Osal_MemCpy(buffer + indx, &charDescValOffset, 2);
+  indx += 2;
+    
+  buffer[indx] = charDescValueLen;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, charDescValue, charDescValueLen);
+  indx +=  charDescValueLen;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_SET_DESC_VAL;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_gatt_read_handle_value(uint16_t attr_handle, uint16_t data_len, uint16_t *data_len_out_p, uint8_t *data)
+{
+  struct hci_request rq;
+  gatt_read_handle_val_cp cp;
+
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+ 
+  if ((data_len+2) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  cp.attr_handle = htobs(attr_handle);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GATT_READ_HANDLE_VALUE;
+  rq.cparam = &cp;
+  rq.clen = GATT_READ_HANDLE_VALUE_CP_SIZE;
+  rq.rparam = buffer;
+  rq.rlen = data_len+2;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  *data_len_out_p = LE_TO_HOST_16(buffer+2);
+
+  Osal_MemCpy(data, buffer + 2, MIN(data_len, *data_len_out_p));
+
+  return buffer[0]; 
+}
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_hal_aci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_hal_aci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,155 @@
+/******************** (C) COPYRIGHT 2013 STMicroelectronics ********************
+* File Name          : bluenrg_hci.c
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 4-Oct-2013
+* Description        : File with HCI commands for BlueNRG FW6.0 and above.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "osal.h"
+#include "hci_const.h"
+#include "bluenrg_aci_const.h"
+#include "bluenrg_hal_aci.h"
+#include "gatt_server.h"
+#include "gap.h"
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+
+tBleStatus aci_hal_write_config_data(uint8_t offset, 
+                                    uint8_t len,
+                                    const uint8_t *val)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if ((len+2) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+
+  buffer[indx] = offset;
+  indx++;
+    
+  buffer[indx] = len;
+  indx++;
+        
+  Osal_MemCpy(buffer + indx, val, len);
+  indx +=  len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_HAL_WRITE_CONFIG_DATA;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+
+  return 0;
+}
+
+tBleStatus aci_hal_set_tx_power_level(uint8_t en_high_power, uint8_t pa_level)
+{
+  struct hci_request rq;
+  hal_set_tx_power_level_cp cp;    
+  uint8_t status;
+    
+  cp.en_high_power = en_high_power;
+  cp.pa_level = pa_level;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_HAL_SET_TX_POWER_LEVEL;
+  rq.cparam = &cp;
+  rq.clen = HAL_SET_TX_POWER_LEVEL_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  if (status) {
+    return status;
+  }
+
+  return 0;
+}
+
+tBleStatus aci_hal_device_standby(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_HAL_DEVICE_STANDBY;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_hal_tone_start(uint8_t rf_channel)
+{
+  struct hci_request rq;
+  hal_tone_start_cp cp;    
+  uint8_t status;
+    
+  cp.rf_channel = rf_channel;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_HAL_TONE_START;
+  rq.cparam = &cp;
+  rq.clen = HAL_TONE_START_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  return status;
+}
+
+tBleStatus aci_hal_tone_stop(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_HAL_TONE_STOP;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_interface.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_interface.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,59 @@
+/**
+  ******************************************************************************
+  * @file    bluenrg_interface.h 
+  * @author  MCD Application Team
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   This file provides code for the BlueNRG Expansion board driver
+  *          based on STM32Cube HAL for STM32 Nucleo boards.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+/* Includes ------------------------------------------------------------------*/
+#include "bluenrg_interface.h"
+
+#include "debug.h"
+#include "ble_status.h"
+#include "hci.h"
+#include "stm32_bluenrg_ble.h"
+
+extern SPI_HandleTypeDef SpiHandle;
+
+/**
+ * @brief  EXTI line detection callback.
+ * @param  Specifies the pins connected EXTI line
+ * @retval None
+ */
+void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
+{
+  HCI_Isr();
+}
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_l2cap_aci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_l2cap_aci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,91 @@
+/******************** (C) COPYRIGHT 2013 STMicroelectronics ********************
+* File Name          : bluenrg_hci.c
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 4-Oct-2013
+* Description        : File with HCI commands for BlueNRG FW6.0 and above.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "osal.h"
+#include "hci_const.h"
+#include "bluenrg_aci_const.h"
+#include "bluenrg_hal_aci.h"
+#include "gap.h"
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+tBleStatus aci_l2cap_connection_parameter_update_request(uint16_t conn_handle, uint16_t interval_min,
+							 uint16_t interval_max, uint16_t slave_latency,
+							 uint16_t timeout_multiplier)
+{
+  struct hci_request rq;
+  uint8_t status;
+  l2cap_conn_param_update_req_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.interval_min = htobs(interval_min);
+  cp.interval_max = htobs(interval_max);
+  cp.slave_latency = htobs(slave_latency);
+  cp.timeout_multiplier = htobs(timeout_multiplier);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_L2CAP_CONN_PARAM_UPDATE_REQ;
+  rq.cparam = &cp;
+  rq.clen = L2CAP_CONN_PARAM_UPDATE_REQ_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+  
+  return status;  
+}
+
+tBleStatus aci_l2cap_connection_parameter_update_response(uint16_t conn_handle, uint16_t interval_min,
+							 uint16_t interval_max, uint16_t slave_latency,
+							 uint16_t timeout_multiplier, uint8_t id, uint8_t accept)
+{
+  struct hci_request rq;
+  uint8_t status;
+  l2cap_conn_param_update_resp_cp cp;
+
+  cp.conn_handle = htobs(conn_handle);
+  cp.interval_min = htobs(interval_min);
+  cp.interval_max = htobs(interval_max);
+  cp.slave_latency = htobs(slave_latency);
+  cp.timeout_multiplier = htobs(timeout_multiplier);
+  cp.id = id;
+  cp.accept = accept;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_L2CAP_CONN_PARAM_UPDATE_REQ;
+  rq.cparam = &cp;
+  rq.clen = L2CAP_CONN_PARAM_UPDATE_REQ_CP_SIZE;
+  rq.event = EVT_CMD_STATUS;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_updater_aci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_updater_aci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,281 @@
+/******************** (C) COPYRIGHT 2013 STMicroelectronics ********************
+* File Name          : bluenrg_hci.c
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 4-Oct-2013
+* Description        : File with HCI commands for BlueNRG FW6.0 and above.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "osal.h"
+#include "hci_const.h"
+#include "bluenrg_aci_const.h"
+#include "bluenrg_updater_aci.h"
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+tBleStatus aci_updater_start(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_START;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;  
+}
+
+tBleStatus aci_updater_reboot(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_REBOOT;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;  
+}
+
+tBleStatus aci_get_updater_version(uint8_t *version)
+{
+  struct hci_request rq;
+  get_updater_version_rp resp;
+
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GET_UPDATER_VERSION;
+  rq.rparam = &resp;
+  rq.rlen = GET_UPDATER_VERSION_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  *version = resp.version;
+
+  return resp.status;
+}
+
+tBleStatus aci_get_updater_buffer_size(uint8_t *buffer_size)
+{
+  struct hci_request rq;
+  get_updater_bufsize_rp resp;
+
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_GET_UPDATER_BUFSIZE;
+  rq.rparam = &resp;
+  rq.rlen = GET_UPDATER_BUFSIZE_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  *buffer_size = resp.buffer_size;
+
+  return resp.status;
+}
+
+tBleStatus aci_erase_blue_flag(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_ERASE_BLUE_FLAG;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;  
+}
+
+tBleStatus aci_reset_blue_flag(void)
+{
+  struct hci_request rq;
+  uint8_t status;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_RESET_BLUE_FLAG;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;  
+}
+
+tBleStatus aci_updater_erase_sector(uint32_t address)
+{
+  struct hci_request rq;
+  updater_erase_sector_cp cp;    
+  uint8_t status;
+    
+  cp.address = htobl(address);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_ERASE_SECTOR;
+  rq.cparam = &cp;
+  rq.clen = UPDATER_ERASE_SECTOR_CP_SIZE;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+
+  return status;
+}
+
+tBleStatus aci_updater_program_data_block(uint32_t address, 
+				   uint16_t len,
+				   const uint8_t *data)
+{
+  struct hci_request rq;
+  uint8_t status;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+  uint8_t indx = 0;
+    
+  if((len+6) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+    
+  address = htobl(address);
+  Osal_MemCpy(buffer + indx, &address, 4);
+  indx += 4;
+    
+  len = htobs(len);
+  Osal_MemCpy(buffer + indx, &len, 2);
+  indx += 2;
+        
+  Osal_MemCpy(buffer + indx, data, len);
+  indx +=  len;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_PROG_DATA_BLOCK;
+  rq.cparam = (void *)buffer;
+  rq.clen = indx;
+  rq.rparam = &status;
+  rq.rlen = 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  return status;
+}
+
+tBleStatus aci_updater_read_data_block(uint32_t address,
+				uint16_t data_len,
+				uint8_t *data)
+{
+  struct hci_request rq;
+  updater_read_data_block_cp cp;
+  uint8_t buffer[HCI_MAX_PACKET_SIZE];
+    
+  if((data_len+1) > HCI_MAX_PACKET_SIZE)
+    return BLE_STATUS_INVALID_PARAMS;
+    
+  cp.address = htobl(address);
+  cp.data_len = htobs(data_len);
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_READ_DATA_BLOCK;
+  rq.cparam = &cp;
+  rq.clen = UPDATER_READ_DATA_BLOCK_CP_SIZE;
+  rq.rparam = buffer;
+  rq.rlen = data_len + 1;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  // First byte is status
+  Osal_MemCpy(data, buffer+1, data_len);
+
+  return buffer[0];
+}
+
+tBleStatus aci_updater_calc_crc(uint32_t address,
+                         uint8_t num_sectors,
+                         uint32_t *crc)
+{
+  struct hci_request rq;
+  updater_calc_crc_cp cp;
+  updater_calc_crc_rp resp;
+    
+  Osal_MemSet(&resp, 0, sizeof(resp));
+    
+  cp.address = htobl(address);
+  cp.num_sectors = num_sectors;
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_CALC_CRC;
+  rq.cparam = &cp;
+  rq.clen = UPDATER_CALC_CRC_CP_SIZE;
+  rq.rparam = &resp;
+  rq.rlen = UPDATER_CALC_CRC_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  *crc = btohl(resp.crc);
+    
+  return resp.status;
+}
+
+tBleStatus aci_updater_hw_version(uint8_t *version)
+{
+  struct hci_request rq;
+  updater_hw_version_rp resp;
+
+  Osal_MemSet(&resp, 0, sizeof(resp));
+
+  Osal_MemSet(&rq, 0, sizeof(rq));
+  rq.ogf = OGF_VENDOR_CMD;
+  rq.ocf = OCF_UPDATER_HW_VERSION;
+  rq.rparam = &resp;
+  rq.rlen = UPDATER_HW_VERSION_RP_SIZE;
+
+  if (hci_send_req(&rq) < 0)
+    return BLE_STATUS_TIMEOUT;
+    
+  *version = resp.version;
+
+  return resp.status;
+}
+
+
+
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/bluenrg_utils.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/bluenrg_utils.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,378 @@
+
+#include "hal.h"
+#include "hal_types.h"
+#include "ble_status.h"
+#include "bluenrg_aci.h"
+#include "bluenrg_utils.h"
+#include "hci.h"
+#include "osal.h"
+#include "string.h"
+//#include "SDK_EVAL_Spi_Driver.h"
+
+#define SUPPORTED_BOOTLOADER_VERSION_MIN  3
+#define SUPPORTED_BOOTLOADER_VERSION_MAX  5
+
+#define BASE_ADDRESS 0x10010000
+
+#define FW_OFFSET       (2*1024)  // 2 KB
+#define FULL_STACK_SIZE (66*1024) // 66 KB
+#define BOOTLOADER_SIZE (2*1024)  // 2 kB
+#define DATA_SIZE       64        // 64 bytes
+#define SECTOR_SIZE     (2*1024)  // 2 KB
+
+// x**32 + x**26 + x**23 + x ** 22 + x**16 + x**12 + x**11 +
+// x**10 + x**8 + x**7 + x**5 + x**4 + x**2 + x**1 + x**0
+#define CRC_POLY        0x04C11DB7      // the poly without the x**32
+
+#define IFR_SIZE 192
+#define IFR_BASE_ADDRESS 0x10020000
+
+typedef struct{
+  uint8_t cold_ana_act_config_table[64];
+}cold_table_TypeDef;
+
+static uint32_t updater_calc_crc(const uint8_t* data, uint16_t nr_of_bytes)
+{
+    uint32_t i, j, a1;
+    uint32_t crc, value;
+
+    crc = 0;
+    for (i = 0; i < nr_of_bytes; i += 4) {
+      value = data[i]|((uint32_t)data[i+1]<<8)|((uint32_t)data[i+2]<<16)|((uint32_t)data[i+3]<<24);
+      
+        crc = crc ^ value;
+        for (j = 0; j < 32; j ++) {
+            a1 = (crc >> 31) & 0x1;
+            crc = (crc << 1) ^ (a1 * CRC_POLY);
+        }
+    }
+    return crc;
+}
+
+int program_device(const uint8_t *fw_image, uint32_t fw_size, uint8_t skip_bootloader_verif)
+{
+  uint8_t version;
+  uint8_t verify_from_sector = 0;
+  uint8_t number_sectors;
+  uint8_t last_sector[SECTOR_SIZE];
+  const uint8_t *last_image, *addr_image;
+  uint16_t last_size;
+  uint32_t address;
+  uint32_t crc, crc2;
+  tBleStatus ret;  
+  
+  BlueNRG_HW_Bootloader();
+  HCI_Process();
+
+  if(aci_get_updater_version(&version))
+    return BLE_UTIL_ACI_ERROR;
+  
+  if(version < SUPPORTED_BOOTLOADER_VERSION_MIN || version > SUPPORTED_BOOTLOADER_VERSION_MAX)
+    return BLE_UTIL_UNSUPPORTED_VERSION;
+  
+  if(skip_bootloader_verif){
+    verify_from_sector = 1;
+  }
+
+  if (fw_size > FULL_STACK_SIZE)
+    return BLE_UTIL_WRONG_IMAGE_SIZE;
+
+  /***********************************************************************
+  * Erase BLUE flag
+  ************************************************************************/
+  
+  if(aci_erase_blue_flag()) 
+    return BLE_UTIL_ACI_ERROR;
+  
+  /***********************************************************************
+  * Erase sectors
+  ************************************************************************/  
+  
+  for(int i = FW_OFFSET; i < FULL_STACK_SIZE; i += SECTOR_SIZE){
+    ret = aci_updater_erase_sector(BASE_ADDRESS + i);
+    if(ret) return BLE_UTIL_ACI_ERROR;
+    HCI_Process();
+  }
+  
+  /***********************************************************************
+  * Flashing firmware
+  ************************************************************************/
+
+  /* Calculate the number of sectors necessary to contain the fw image.
+     If the fw image is the bootloader we need to add a sector because 
+     the flashing start with an offset of 2 KB 
+  */
+  number_sectors = (fw_size / SECTOR_SIZE);
+  if (skip_bootloader_verif)
+    number_sectors++;
+
+  for(int i = FW_OFFSET; i < (number_sectors*SECTOR_SIZE); i += DATA_SIZE){
+    /* If bootloader image we need to subtract the 2KB offset */
+    if (skip_bootloader_verif)
+      addr_image = fw_image + i - FW_OFFSET;
+    else
+      addr_image = fw_image + i;
+    ret = aci_updater_program_data_block(BASE_ADDRESS+i, DATA_SIZE, addr_image);
+    if(ret) return BLE_UTIL_ACI_ERROR;
+    HCI_Process();
+  }
+  
+  /* If the image is not multiple of a sector size */
+  if (fw_size % SECTOR_SIZE) {
+    /* If bootloader image we need to subtract the 2KB offset */
+    if (skip_bootloader_verif) {
+      last_image = fw_image + (number_sectors-1) * SECTOR_SIZE;
+      last_size = fw_size -(number_sectors-1) * SECTOR_SIZE;
+    } else {
+      last_image = fw_image + number_sectors * SECTOR_SIZE;
+      last_size = fw_size - number_sectors * SECTOR_SIZE;
+    }
+    memset(last_sector, 0xFF, SECTOR_SIZE);
+    memcpy (last_sector, last_image, last_size);
+    address = BASE_ADDRESS + (number_sectors * SECTOR_SIZE);
+    for(int i = 0; i < SECTOR_SIZE; i += DATA_SIZE){
+      ret = aci_updater_program_data_block(address+i, DATA_SIZE, last_sector+i);
+      if(ret) return BLE_UTIL_ACI_ERROR;
+      HCI_Process();
+    }
+  }
+
+  /***********************************************************************
+  * Verify firmware
+  ************************************************************************/
+  
+  for(int i = (verify_from_sector*SECTOR_SIZE); i < (number_sectors*SECTOR_SIZE); i += SECTOR_SIZE){
+    address = BASE_ADDRESS + i;
+    if(aci_updater_calc_crc(address, 1, &crc))
+      return BLE_UTIL_ACI_ERROR;
+    
+    /* If bootloader image we need to subtract the 2KB offset */
+    if (skip_bootloader_verif) {
+      crc2 = updater_calc_crc(fw_image+i-FW_OFFSET,SECTOR_SIZE);
+    } else {
+      crc2 = updater_calc_crc(fw_image+i,SECTOR_SIZE);
+    }
+    
+    if(crc!=crc2)
+      return BLE_UTIL_CRC_ERROR;
+
+    HCI_Process();
+  }
+
+  /* If the image is not multiple of a sector size */
+  if (fw_size % SECTOR_SIZE) {
+    address = BASE_ADDRESS + (number_sectors*SECTOR_SIZE);
+    if(aci_updater_calc_crc(address, 1, &crc))
+      return BLE_UTIL_ACI_ERROR;
+    
+    crc2 = updater_calc_crc(last_sector,SECTOR_SIZE);
+    
+    if(crc!=crc2)
+      return BLE_UTIL_CRC_ERROR;
+
+    HCI_Process();
+
+  }    
+  
+  if(aci_reset_blue_flag())
+    return BLE_UTIL_ACI_ERROR;
+  
+  BlueNRG_RST();
+  
+  HCI_Process();
+
+  return 0;
+}
+
+int read_IFR(uint8_t *data)
+{
+  uint8_t version;
+  tBleStatus ret;
+  
+  aci_updater_start();
+  if(aci_get_updater_version(&version))
+    return BLE_UTIL_ACI_ERROR;
+  
+  if(version < SUPPORTED_BOOTLOADER_VERSION_MIN || version > SUPPORTED_BOOTLOADER_VERSION_MAX)
+    return BLE_UTIL_UNSUPPORTED_VERSION;
+  
+  /***********************************************************************
+  * Reading last 3 IFR 64-byte blocks
+  ************************************************************************/
+  
+  for(int i = 66*1024 - 3*64; i < 66*1024; i += 64){
+    ret = aci_updater_read_data_block(BASE_ADDRESS+i, 64, data);
+    if(ret) return BLE_UTIL_ACI_ERROR;
+  }
+  
+  BlueNRG_RST();
+
+  return 0;
+  
+}
+
+void parse_IFR_data_config(const uint8_t data[64], IFR_config2_TypeDef *IFR_config)
+{
+  IFR_config->stack_mode = data[0];
+  IFR_config->slave_sca_ppm = LE_TO_HOST_16(data+28);
+  IFR_config->master_sca = data[30];
+  IFR_config->hs_startup_time = LE_TO_HOST_16(data+32);
+  IFR_config->year = BCD_TO_INT(data[41]);
+  IFR_config->month = BCD_TO_INT(data[42]);
+  IFR_config->day = BCD_TO_INT(data[43]);    
+}
+
+int IFR_validate(IFR_config2_TypeDef *IFR_config)
+{
+  if(IFR_config->stack_mode < 1 || IFR_config->stack_mode > 3)
+    return BLE_UTIL_PARSE_ERROR; // Unknown Stack Mode
+  if(IFR_config->master_sca > 7)
+    return BLE_UTIL_PARSE_ERROR; // Invalid Master SCA
+  if(IFR_config->month > 12 || IFR_config->month < 1)
+    return BLE_UTIL_PARSE_ERROR; // Invalid date
+  if(IFR_config->day > 31 || IFR_config->day < 1)
+    return BLE_UTIL_PARSE_ERROR; // Invalid date
+  if(IFR_config->month > 12 || IFR_config->month < 1)
+    return BLE_UTIL_PARSE_ERROR; // Invalid date
+  
+  return 0;
+}
+
+/* TODO: Function to generate data from given options. */
+
+void change_IFR_data_config(IFR_config2_TypeDef *IFR_config, uint8_t data[64])
+{
+  data[0] = IFR_config->stack_mode;
+  HOST_TO_LE_16(data+28, IFR_config->slave_sca_ppm);
+  data[30] = IFR_config->master_sca;
+  HOST_TO_LE_16(data+32, IFR_config->hs_startup_time);  
+  data[41] = INT_TO_BCD(IFR_config->year);
+  data[42] = INT_TO_BCD(IFR_config->month);
+  data[43] = INT_TO_BCD(IFR_config->day);
+}
+
+
+int program_IFR(const IFR_config_TypeDef *ifr_image)
+{
+  uint8_t version;
+  tBleStatus ret;  
+  uint8_t ifr_data[2*1024];
+  
+  aci_updater_start();
+  if(aci_get_updater_version(&version))
+    return BLE_UTIL_ACI_ERROR;
+  
+  if(version < SUPPORTED_BOOTLOADER_VERSION_MIN || version > SUPPORTED_BOOTLOADER_VERSION_MAX)
+    return BLE_UTIL_UNSUPPORTED_VERSION;
+  
+  /***********************************************************************
+   * READ IFR data
+   ************************************************************************/  
+  for(int i = 0; i < (2*1024); i += 64){
+    ret = aci_updater_read_data_block(IFR_BASE_ADDRESS+i, 64, ifr_data+i);
+    if(ret != BLE_STATUS_SUCCESS){
+      return ret;
+    }
+  }
+  
+  /***********************************************************************
+  * Erase IFR sectors
+  ************************************************************************/  
+  ret = aci_updater_erase_sector(IFR_BASE_ADDRESS);
+  if(ret != BLE_STATUS_SUCCESS) 
+    return BLE_UTIL_ACI_ERROR;
+  
+  /***********************************************************************
+  * Flashing IFR
+  ************************************************************************/
+  Osal_MemCpy(&ifr_data[2*1024-IFR_SIZE], ifr_image, IFR_SIZE);
+  for(int i = 0; i < (2*1024); i += 64){
+    ret = aci_updater_program_data_block(IFR_BASE_ADDRESS+i, 64, ifr_data+i);
+    if(ret != BLE_STATUS_SUCCESS) 
+      return BLE_UTIL_ACI_ERROR;
+  }
+
+  /***********************************************************************
+  * Verify IFR
+  ************************************************************************/  
+  {
+    uint8_t ifr_updated[64];
+    for(int i = 0; i < (2*1024); i += 64){
+      ret = aci_updater_read_data_block(IFR_BASE_ADDRESS+i, 64, ifr_updated);
+      if(ret != BLE_STATUS_SUCCESS){
+	return ret;
+      }
+      if (memcmp(ifr_updated, ifr_data+i, 64) != 0)
+	return BLE_UTIL_WRONG_VERIFY;
+    }
+  }
+
+  BlueNRG_RST();
+    
+  return 0;
+}
+
+uint8_t verify_IFR(const IFR_config_TypeDef *ifr_data)
+{
+  uint8_t ifr_updated[64];
+  uint8_t version, ret;
+    
+  aci_updater_start();
+  if(aci_get_updater_version(&version))
+    return BLE_UTIL_ACI_ERROR;
+  for(int i = 0; i < (3*64); i += 64){
+    ret = aci_updater_read_data_block((IFR_BASE_ADDRESS+2048-IFR_SIZE)+i, 64, ifr_updated);
+    if(ret != BLE_STATUS_SUCCESS){
+      return ret;
+    }
+    if (memcmp(ifr_updated, ((uint8_t*)ifr_data)+i, 64) != 0)
+      return BLE_UTIL_WRONG_VERIFY;
+  }
+
+  BlueNRG_RST();
+  
+  return 0;
+}
+
+uint8_t getBlueNRGVersion(uint8_t *hwVersion, uint16_t *fwVersion)
+{
+  uint8_t status;
+  uint8_t hci_version, lmp_pal_version;
+  uint16_t hci_revision, manufacturer_name, lmp_pal_subversion;
+
+  status = hci_le_read_local_version(&hci_version, &hci_revision, &lmp_pal_version, 
+				     &manufacturer_name, &lmp_pal_subversion);
+
+  if (status == BLE_STATUS_SUCCESS) {
+    *hwVersion = hci_revision >> 8;
+    *fwVersion = (hci_revision & 0xFF) << 8;              // Major Version Number
+    *fwVersion |= ((lmp_pal_subversion >> 4) & 0xF) << 4; // Minor Version Number
+    *fwVersion |= lmp_pal_subversion & 0xF;               // Patch Version Number
+  }
+
+  HCI_Process();
+
+  return status;
+}
+
+uint8_t getBlueNRGUpdaterVersion(uint8_t *version)
+{
+  HCI_Process();
+
+  BlueNRG_HW_Bootloader();
+
+  HCI_Process();
+
+  if(aci_get_updater_version(version))
+    return BLE_UTIL_ACI_ERROR;
+  
+  if(*version < SUPPORTED_BOOTLOADER_VERSION_MIN || *version > SUPPORTED_BOOTLOADER_VERSION_MAX)
+    return BLE_UTIL_UNSUPPORTED_VERSION;
+
+  BlueNRG_RST();
+
+  HCI_Process();
+
+  return BLE_STATUS_SUCCESS;
+}
+
diff -r f57d754b1814 -r 987b201ec4b1 src/clock.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/clock.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,77 @@
+/**
+******************************************************************************
+* @file    clock.c 
+* @author  CL
+* @version V1.0.0
+* @date    04-July-2014
+* @brief   
+******************************************************************************
+* @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+  
+/* Includes ------------------------------------------------------------------*/
+#include "clock.h"
+#include "cube_hal.h"
+
+const uint32_t CLOCK_SECOND = 1000;
+
+/**
+ * @brief  Clock_Init
+ * @param  None
+ * @retval None
+ */
+void Clock_Init(void)
+{
+  // FIXME: as long as Cube HAL is initialized this is OK
+  // Cube HAL default is one clock each 1 ms
+}
+
+/**
+ * @brief  Clock_Time
+ * @param  None
+ * @retval tClockTime
+ */
+tClockTime Clock_Time(void)
+{
+  return HAL_GetTick();
+}
+
+/**
+ * @brief  Clock_Wait Wait for a multiple of 1 ms.
+ * @param  int i
+ * @retval None
+ */
+void Clock_Wait(uint32_t i)
+{
+  HAL_Delay(i);
+}
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/cube_hal_f4.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cube_hal_f4.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,68 @@
+/**
+  ******************************************************************************
+  * @file    cube_hal_f4.c
+  * @author  CL
+  * @version V1.0.0
+  * @date    03-November-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+
+/* Includes ------------------------------------------------------------------*/
+#include "cube_hal.h"
+
+/**
+ * @brief  System Clock Configuration
+ * @param  None
+ * @retval None
+ */
+void SystemClock_Config(void)
+{
+  RCC_ClkInitTypeDef RCC_ClkInitStruct;
+  RCC_OscInitTypeDef RCC_OscInitStruct;
+
+  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
+  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
+  RCC_OscInitStruct.HSICalibrationValue = 6;
+  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
+  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
+  RCC_OscInitStruct.PLL.PLLM = 16;
+  RCC_OscInitStruct.PLL.PLLN = 256;
+  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV8;
+  RCC_OscInitStruct.PLL.PLLQ = 4;
+  HAL_RCC_OscConfig(&RCC_OscInitStruct);
+
+  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK;
+  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
+  HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1);
+}
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/gp_timer.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/gp_timer.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2004, Swedish Institute of Computer Science.
+ * 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 Institute 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 INSTITUTE 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 INSTITUTE 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.
+ *
+ * This file is part of the Contiki operating system.
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ */
+
+#include "clock.h"
+#include "gp_timer.h"
+
+/*---------------------------------------------------------------------------*/
+/**
+ * Set a timer.
+ *
+ * This function sets a timer for a time sometime in the
+ * future. The function timer_expired() will evaluate to true after
+ * the timer has expired.
+ *
+ * @param[in] t         A pointer to the timer
+ * @param[in] interval  The interval before the timer expires.
+ *
+ */
+void
+Timer_Set(struct timer *t, tClockTime interval)
+{
+  t->interval = interval;
+  t->start = Clock_Time();
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Reset the timer with the same interval.
+ *
+ * This function resets the timer with the same interval that was
+ * given to the timer_set() function. The start point of the interval
+ * is the exact time that the timer last expired. Therefore, this
+ * function will cause the timer to be stable over time, unlike the
+ * timer_restart() function.
+ *
+ * \param t A pointer to the timer.
+ *
+ * \sa timer_restart()
+ */
+void
+Timer_Reset(struct timer *t)
+{
+  t->start += t->interval;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Restart the timer from the current point in time
+ *
+ * This function restarts a timer with the same interval that was
+ * given to the timer_set() function. The timer will start at the
+ * current time.
+ *
+ * \note A periodic timer will drift if this function is used to reset
+ * it. For preioric timers, use the timer_reset() function instead.
+ *
+ * \param t A pointer to the timer.
+ *
+ * \sa timer_reset()
+ */
+void
+Timer_Restart(struct timer *t)
+{
+  t->start = Clock_Time();
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Check if a timer has expired.
+ *
+ * This function tests if a timer has expired and returns true or
+ * false depending on its status.
+ *
+ * \param t A pointer to the timer
+ *
+ * \return Non-zero if the timer has expired, zero otherwise.
+ *
+ */
+int
+Timer_Expired(struct timer *t)
+{
+  /* Note: Can not return diff >= t->interval so we add 1 to diff and return
+     t->interval < diff - required to avoid an internal error in mspgcc. */
+  tClockTime diff = (Clock_Time() - t->start) + 1;
+  return t->interval < diff;
+
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * The time until the timer expires
+ *
+ * This function returns the time until the timer expires.
+ *
+ * \param t A pointer to the timer
+ *
+ * \return The time until the timer expires
+ *
+ */
+tClockTime
+Timer_Remaining(struct timer *t)
+{
+  return t->start + t->interval - Clock_Time();
+}
+/*---------------------------------------------------------------------------*/
+
+/** @} */
+
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/hci.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hci.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,1186 @@
+/**
+  ******************************************************************************
+  * @file    hci.c 
+  * @author  AMS/HESA Application Team
+  * @brief   Function for managing HCI interface.
+  ******************************************************************************
+  *
+  *
+  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
+  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
+  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
+  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
+  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+  *
+  * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2>
+  */ 
+
+#include "hal_types.h"
+#include "osal.h"
+#include "ble_status.h"
+#include "hal.h"
+#include "hci_const.h"
+#include "gp_timer.h"
+
+#include "stm32_bluenrg_ble.h"
+
+extern SPI_HandleTypeDef SpiHandle;
+
+#if BLE_CONFIG_DBG_ENABLE
+#define PRINTF(...) printf(__VA_ARGS__)
+#else
+#define PRINTF(...)
+#endif
+
+#define HCI_LOG_ON 0
+
+#define HCI_READ_PACKET_NUM_MAX 		 (5)
+
+#define MIN(a,b)            ((a) < (b) )? (a) : (b)
+#define MAX(a,b)            ((a) > (b) )? (a) : (b)
+
+static void enqueue_packet(tHciDataPacket * hciReadPacket);
+
+tListNode hciReadPktPool;
+tListNode hciReadPktRxQueue;
+/* pool of hci read packets */
+static tHciDataPacket     hciReadPacketBuffer[HCI_READ_PACKET_NUM_MAX];
+
+static uint8_t *hci_buffer = NULL;
+static volatile uint16_t hci_pckt_len;
+
+volatile uint8_t readPacketListFull=FALSE;
+
+void HCI_Init(void)
+{
+    uint8_t index;
+    
+    /* Initialize list heads of ready and free hci data packet queues */
+    list_init_head (&hciReadPktPool);
+    list_init_head (&hciReadPktRxQueue);
+    
+    /* Initialize the queue of free hci data packets */
+    for (index = 0; index < HCI_READ_PACKET_NUM_MAX; index++)
+    {
+        list_insert_tail(&hciReadPktPool, (tListNode *)&hciReadPacketBuffer[index]);
+    }
+}
+
+static volatile hci_packet_complete_callback packet_complete_callback = NULL;
+
+static void hci_set_packet_complete_callback(hci_packet_complete_callback cb)
+{
+	packet_complete_callback = cb;
+}
+
+void HCI_Input(tHciDataPacket * hciReadPacket)
+{
+    uint8_t byte;
+    hci_acl_hdr *acl_hdr;
+
+	static hci_state state = WAITING_TYPE;
+
+        uint16_t collected_payload_len = 0;
+	uint16_t payload_len;
+    
+    hci_buffer = hciReadPacket->dataBuff;
+    
+    if(state == WAITING_TYPE)
+        hci_pckt_len = 0;
+    
+    while(hci_pckt_len < HCI_PACKET_SIZE){
+
+        byte = hci_buffer[hci_pckt_len++];
+
+        if(state == WAITING_TYPE){
+            /* Only ACL Data and Events packets are accepted. */
+            if(byte == HCI_EVENT_PKT){
+                 state = WAITING_EVENT_CODE;
+            }
+//            else if(byte == HCI_ACLDATA_PKT){
+//                state = WAITING_HANDLE;
+//            }
+            else{
+                /* Incorrect type. Reset state machine. */
+                state = WAITING_TYPE;
+                break;
+            }
+        }
+        else if(state == WAITING_EVENT_CODE)
+            state = WAITING_PARAM_LEN;
+        else if(state == WAITING_HANDLE)
+            state = WAITING_HANDLE_FLAG;
+        else if(state == WAITING_HANDLE_FLAG)
+            state = WAITING_DATA_LEN1;
+        else if(state == WAITING_DATA_LEN1)
+            state = WAITING_DATA_LEN2;
+
+        else if(state == WAITING_DATA_LEN2){
+            acl_hdr = (void *)&hci_buffer[HCI_HDR_SIZE];
+            payload_len = acl_hdr->dlen;
+            collected_payload_len = 0;
+            state = WAITING_PAYLOAD;
+        }
+        else if(state == WAITING_PARAM_LEN){
+             payload_len = byte;
+             collected_payload_len = 0;
+             state = WAITING_PAYLOAD;
+        }
+        else if(state == WAITING_PAYLOAD){
+            collected_payload_len += 1;
+            if(collected_payload_len >= payload_len){
+                /* Reset state machine. */
+                state = WAITING_TYPE;
+                enqueue_packet(hciReadPacket);
+                
+                if(packet_complete_callback){
+                  uint16_t len = hci_pckt_len;
+                  packet_complete_callback(hci_buffer, len);
+                }
+                break;
+            }
+        }
+    }        
+}
+
+void enqueue_packet(tHciDataPacket * hciReadPacket)
+{
+    hci_uart_pckt *hci_pckt = (void*)hciReadPacket->dataBuff;
+    hci_event_pckt *event_pckt = (void*)hci_pckt->data;
+    
+    // Do not enqueue Command Complete or Command Status events
+    
+    if((hci_pckt->type != HCI_EVENT_PKT) ||
+       event_pckt->evt == EVT_CMD_COMPLETE ||
+           event_pckt->evt == EVT_CMD_STATUS){
+        // Insert the packet back into the pool.
+        list_insert_tail(&hciReadPktPool, (tListNode *)hciReadPacket);
+    }
+    else {    
+        // Insert the packet into the queue of events to be processed.
+        list_insert_tail(&hciReadPktRxQueue, (tListNode *)hciReadPacket);
+    }
+}
+
+void HCI_Process(void)
+{
+    uint8_t data_len;
+    uint8_t buffer[HCI_PACKET_SIZE];
+    tHciDataPacket * hciReadPacket = NULL;
+
+    Disable_SPI_IRQ();
+    uint8_t list_empty = list_is_empty(&hciReadPktRxQueue);        
+    /* process any pending events read */
+    while(list_empty == FALSE)
+    {
+        list_remove_head (&hciReadPktRxQueue, (tListNode **)&hciReadPacket);
+        Enable_SPI_IRQ();
+        HCI_Event_CB(hciReadPacket->dataBuff);
+        Disable_SPI_IRQ();
+        list_insert_tail(&hciReadPktPool, (tListNode *)hciReadPacket);
+        list_empty = list_is_empty(&hciReadPktRxQueue);
+    }
+    if (readPacketListFull) {
+      while(BlueNRG_DataPresent()) {
+	data_len = BlueNRG_SPI_Read_All(&SpiHandle, buffer, HCI_PACKET_SIZE);
+	if(data_len > 0)
+	  HCI_Event_CB(buffer);
+      }
+      readPacketListFull = FALSE;
+    }
+
+    Enable_SPI_IRQ();    
+}
+
+void HCI_Isr(void)
+{
+  tHciDataPacket * hciReadPacket = NULL;
+  uint8_t data_len;
+    
+  Clear_SPI_EXTI_Flag();
+  while(BlueNRG_DataPresent()){        
+    if (list_is_empty (&hciReadPktPool) == FALSE){
+            
+      /* enqueueing a packet for read */
+      list_remove_head (&hciReadPktPool, (tListNode **)&hciReadPacket);
+            
+      data_len = BlueNRG_SPI_Read_All(&SpiHandle, hciReadPacket->dataBuff, HCI_PACKET_SIZE);
+      if(data_len > 0){                    
+	HCI_Input(hciReadPacket);
+	// Packet will be inserted to te correct queue by 
+      }
+      else {
+	// Insert the packet back into the pool.
+	list_insert_head(&hciReadPktPool, (tListNode *)hciReadPacket);
+      }
+            
+    }
+    else{
+      // HCI Read Packet Pool is empty, wait for a free packet.
+      readPacketListFull = TRUE;
+      Clear_SPI_EXTI_Flag();
+      return;
+    }
+        
+    Clear_SPI_EXTI_Flag();
+  }
+}
+
+void hci_write(const void* data1, const void* data2, uint16_t n_bytes1, uint16_t n_bytes2){
+#if  HCI_LOG_ON
+  PRINTF("HCI <- ");
+  for(int i=0; i < n_bytes1; i++)
+    PRINTF("%02X ", *((uint8_t*)data1 + i));
+  for(int i=0; i < n_bytes2; i++)
+    PRINTF("%02X ", *((uint8_t*)data2 + i));
+  PRINTF("\n");    
+#endif
+  
+  Hal_Write_Serial(data1, data2, n_bytes1, n_bytes2);
+}
+
+int hci_send_cmd(uint16_t ogf, uint16_t ocf, uint8_t plen, void *param)
+{
+	hci_command_hdr hc;
+
+	hc.opcode = htobs(cmd_opcode_pack(ogf, ocf));
+	hc.plen= plen;
+	
+	uint8_t header[HCI_HDR_SIZE + HCI_COMMAND_HDR_SIZE];
+	header[0] = HCI_COMMAND_PKT;
+	Osal_MemCpy(header+1, &hc, sizeof(hc));
+    
+	hci_write(header, param, sizeof(header), plen);
+
+	return 0;
+}
+
+static uint8_t new_packet;
+
+void new_hci_event(void *pckt, uint16_t len)
+{
+	Disable_SPI_IRQ(); /* Must be re-enabled after packet processing. */
+
+	new_packet = TRUE;
+}
+
+/* 'to' is timeout in system clock ticks.  */
+int hci_send_req(struct hci_request *r)
+{
+	uint8_t *ptr;
+	uint16_t opcode = htobs(cmd_opcode_pack(r->ogf, r->ocf));
+	hci_event_pckt *event_pckt;
+	hci_uart_pckt *hci_hdr;
+	int try;
+    int to = DEFAULT_TIMEOUT;
+    
+	new_packet = FALSE;
+	hci_set_packet_complete_callback(new_hci_event);
+	if (hci_send_cmd(r->ogf, r->ocf, r->clen, r->cparam) < 0)
+		goto failed;
+    
+	try = 10;
+	while (try--) {
+		evt_cmd_complete *cc;
+		evt_cmd_status *cs;
+		evt_le_meta_event *me;
+		int len;
+        
+        /* Minimum timeout is 1. */
+        if(to == 0)
+            to = 1;
+        
+		if (to > 0) {
+			struct timer t;
+            
+			Timer_Set(&t, to);
+            
+			while(1){
+				if(Timer_Expired(&t)){
+					goto failed;
+				}
+				if(new_packet){
+					break;
+				}
+			}
+		}
+        
+		hci_hdr = (void *)hci_buffer;
+		if(hci_hdr->type != HCI_EVENT_PKT){
+            new_packet = FALSE;
+            Enable_SPI_IRQ();
+            continue;
+        }
+        
+		event_pckt = (void *) (hci_hdr->data);
+        
+		ptr = hci_buffer + (1 + HCI_EVENT_HDR_SIZE);
+		len = hci_pckt_len - (1 + HCI_EVENT_HDR_SIZE);
+        
+		switch (event_pckt->evt) {
+            
+		case EVT_CMD_STATUS:
+			cs = (void *) ptr;
+            
+			if (cs->opcode != opcode)
+				break;
+            
+			if (r->event != EVT_CMD_STATUS) {
+				if (cs->status) {
+					goto failed;
+				}
+				break;
+			}
+            
+			r->rlen = MIN(len, r->rlen);
+			Osal_MemCpy(r->rparam, ptr, r->rlen);
+			goto done;
+            
+		case EVT_CMD_COMPLETE:
+			cc = (void *) ptr;
+            
+			if (cc->opcode != opcode)
+				break;
+            
+			ptr += EVT_CMD_COMPLETE_SIZE;
+			len -= EVT_CMD_COMPLETE_SIZE;
+            
+			r->rlen = MIN(len, r->rlen);
+			Osal_MemCpy(r->rparam, ptr, r->rlen);
+			goto done;
+            
+		case EVT_LE_META_EVENT:
+			me = (void *) ptr;
+            
+			if (me->subevent != r->event)
+				break;
+            
+			len -= 1;
+			r->rlen = MIN(len, r->rlen);
+			Osal_MemCpy(r->rparam, me->data, r->rlen);
+			goto done;
+            
+        case EVT_HARDWARE_ERROR:            
+            goto failed;
+            
+		default:
+            break; // In the meantime there could be other events from the controller.
+		}
+        
+		new_packet = FALSE;
+		Enable_SPI_IRQ();
+        
+	}
+    
+failed:
+	hci_set_packet_complete_callback(NULL);
+	Enable_SPI_IRQ();
+	return -1;
+    
+done:
+	hci_set_packet_complete_callback(NULL);
+	Enable_SPI_IRQ();
+	return 0;
+}
+
+int hci_reset()
+{
+  	struct hci_request rq;
+	uint8_t status;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_HOST_CTL;
+	rq.ocf = OCF_RESET;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;  
+}
+
+int hci_disconnect(uint16_t	handle, uint8_t reason)
+{
+  struct hci_request rq;
+	disconnect_cp cp;
+	uint8_t status;
+  
+	cp.handle = handle;
+	cp.reason = reason;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LINK_CTL;
+	rq.ocf = OCF_DISCONNECT;
+    rq.cparam = &cp;
+	rq.clen = DISCONNECT_CP_SIZE;
+    rq.event = EVT_CMD_STATUS;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;  
+}
+
+int hci_le_read_local_version(uint8_t *hci_version, uint16_t *hci_revision, uint8_t *lmp_pal_version, 
+			      uint16_t *manufacturer_name, uint16_t *lmp_pal_subversion)
+{
+	struct hci_request rq;
+	read_local_version_rp resp;
+
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_INFO_PARAM;
+	rq.ocf = OCF_READ_LOCAL_VERSION;
+	rq.cparam = NULL;
+	rq.clen = 0;
+	rq.rparam = &resp;
+	rq.rlen = READ_LOCAL_VERSION_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+
+
+	*hci_version = resp.hci_version;
+	*hci_revision =  btohs(resp.hci_revision);
+	*lmp_pal_version = resp.lmp_pal_version;
+	*manufacturer_name = btohs(resp.manufacturer_name);
+	*lmp_pal_subversion = btohs(resp.lmp_pal_subversion);
+
+	return 0;
+}
+
+int hci_le_read_buffer_size(uint16_t *pkt_len, uint8_t *max_pkt)
+{
+	struct hci_request rq;
+	le_read_buffer_size_rp resp;
+
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_BUFFER_SIZE;
+	rq.cparam = NULL;
+	rq.clen = 0;
+	rq.rparam = &resp;
+	rq.rlen = LE_READ_BUFFER_SIZE_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+	
+	*pkt_len = resp.pkt_len;
+	*max_pkt = resp.max_pkt;
+
+	return 0;
+}
+
+int hci_le_set_advertising_parameters(uint16_t min_interval, uint16_t max_interval, uint8_t advtype,
+		uint8_t own_bdaddr_type, uint8_t direct_bdaddr_type, tBDAddr direct_bdaddr, uint8_t chan_map,
+		uint8_t filter)
+{
+	struct hci_request rq;
+	le_set_adv_parameters_cp adv_cp;
+	uint8_t status;
+
+	Osal_MemSet(&adv_cp, 0, sizeof(adv_cp));
+	adv_cp.min_interval = min_interval;
+	adv_cp.max_interval = max_interval;
+	adv_cp.advtype = advtype;
+	adv_cp.own_bdaddr_type = own_bdaddr_type;
+	adv_cp.direct_bdaddr_type = direct_bdaddr_type;
+    Osal_MemCpy(adv_cp.direct_bdaddr,direct_bdaddr,sizeof(adv_cp.direct_bdaddr));
+	adv_cp.chan_map = chan_map;
+	adv_cp.filter = filter;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_SET_ADV_PARAMETERS;
+	rq.cparam = &adv_cp;
+	rq.clen = LE_SET_ADV_PARAMETERS_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_set_advertising_data(uint8_t length, const uint8_t data[])
+{
+	struct hci_request rq;
+	le_set_adv_data_cp adv_cp;
+	uint8_t status;
+
+	Osal_MemSet(&adv_cp, 0, sizeof(adv_cp));
+	adv_cp.length = length;
+	Osal_MemCpy(adv_cp.data, data, MIN(31,length));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_SET_ADV_DATA;
+	rq.cparam = &adv_cp;
+	rq.clen = LE_SET_ADV_DATA_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_set_advertise_enable(uint8_t enable)
+{
+	struct hci_request rq;
+	le_set_advertise_enable_cp adv_cp;
+	uint8_t status;
+
+	Osal_MemSet(&adv_cp, 0, sizeof(adv_cp));
+	adv_cp.enable = enable?1:0;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_SET_ADVERTISE_ENABLE;
+	rq.cparam = &adv_cp;
+	rq.clen = LE_SET_ADVERTISE_ENABLE_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_rand(uint8_t random_number[8])
+{
+	struct hci_request rq;
+	le_rand_rp resp;
+
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_RAND;
+	rq.cparam = NULL;
+	rq.clen = 0;
+	rq.rparam = &resp;
+	rq.rlen = LE_RAND_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    Osal_MemCpy(random_number, resp.random, 8);
+
+	return 0;
+}
+
+int hci_le_set_scan_resp_data(uint8_t length, const uint8_t data[])
+{
+	struct hci_request rq;
+	le_set_scan_response_data_cp scan_resp_cp;
+	uint8_t status;
+
+	Osal_MemSet(&scan_resp_cp, 0, sizeof(scan_resp_cp));
+	scan_resp_cp.length = length;
+	Osal_MemCpy(scan_resp_cp.data, data, MIN(31,length));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_SET_SCAN_RESPONSE_DATA;
+	rq.cparam = &scan_resp_cp;
+	rq.clen = LE_SET_SCAN_RESPONSE_DATA_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_read_advertising_channel_tx_power(int8_t *tx_power_level)
+{
+	struct hci_request rq;
+	le_read_adv_channel_tx_power_rp resp;
+
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_ADV_CHANNEL_TX_POWER;
+	rq.cparam = NULL;
+	rq.clen = 0;
+	rq.rparam = &resp;
+	rq.rlen = LE_RAND_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+
+	*tx_power_level = resp.level;
+
+	return 0;
+}
+
+int hci_le_set_random_address(tBDAddr bdaddr)
+{
+	struct hci_request rq;
+	le_set_random_address_cp set_rand_addr_cp;
+	uint8_t status;
+
+	Osal_MemSet(&set_rand_addr_cp, 0, sizeof(set_rand_addr_cp));
+	Osal_MemCpy(set_rand_addr_cp.bdaddr, bdaddr, sizeof(tBDAddr));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_SET_RANDOM_ADDRESS;
+	rq.cparam = &set_rand_addr_cp;
+	rq.clen = LE_SET_RANDOM_ADDRESS_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_read_bd_addr(tBDAddr bdaddr)
+{
+	struct hci_request rq;
+	read_bd_addr_rp resp;
+
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_INFO_PARAM;
+	rq.ocf = OCF_READ_BD_ADDR;
+	rq.cparam = NULL;
+	rq.clen = 0;
+	rq.rparam = &resp;
+	rq.rlen = READ_BD_ADDR_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+	Osal_MemCpy(bdaddr, resp.bdaddr, sizeof(tBDAddr));
+
+	return 0;
+}
+
+int hci_le_create_connection(uint16_t interval,	uint16_t window, uint8_t initiator_filter, uint8_t peer_bdaddr_type,
+                             const tBDAddr peer_bdaddr,	uint8_t	own_bdaddr_type, uint16_t min_interval,	uint16_t max_interval,
+                             uint16_t latency,	uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length)
+{
+	struct hci_request rq;
+	le_create_connection_cp create_cp;
+	uint8_t status;
+
+	Osal_MemSet(&create_cp, 0, sizeof(create_cp));
+	create_cp.interval = interval;
+	create_cp.window =  window;
+	create_cp.initiator_filter = initiator_filter;
+	create_cp.peer_bdaddr_type = peer_bdaddr_type;
+	Osal_MemCpy(create_cp.peer_bdaddr, peer_bdaddr, sizeof(tBDAddr));
+	create_cp.own_bdaddr_type = own_bdaddr_type;
+	create_cp.min_interval=min_interval;
+	create_cp.max_interval=max_interval;
+	create_cp.latency = latency;
+	create_cp.supervision_timeout=supervision_timeout;
+	create_cp.min_ce_length=min_ce_length;
+	create_cp.max_ce_length=max_ce_length;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_CREATE_CONN;
+	rq.cparam = &create_cp;
+	rq.clen = LE_CREATE_CONN_CP_SIZE;
+    rq.event = EVT_CMD_STATUS;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_encrypt(uint8_t key[16], uint8_t plaintextData[16], uint8_t encryptedData[16])
+{
+	struct hci_request rq;
+	le_encrypt_cp params;
+	le_encrypt_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemCpy(params.key, key, 16);
+	Osal_MemCpy(params.plaintext, plaintextData, 16);
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_ENCRYPT;
+	rq.cparam = &params;
+	rq.clen = LE_ENCRYPT_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = LE_ENCRYPT_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+	
+	Osal_MemCpy(encryptedData, resp.encdata, 16);
+
+	return 0;
+}
+
+int hci_le_ltk_request_reply(uint8_t key[16])
+{
+	struct hci_request rq;
+	le_ltk_reply_cp params;
+	le_ltk_reply_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	params.handle = 1;
+	Osal_MemCpy(params.key, key, 16);
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_LTK_REPLY;
+	rq.cparam = &params;
+	rq.clen = LE_LTK_REPLY_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = LE_LTK_REPLY_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_ltk_request_neg_reply()
+{
+	struct hci_request rq;
+	le_ltk_neg_reply_cp params;
+	le_ltk_neg_reply_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	params.handle = 1;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_LTK_NEG_REPLY;
+	rq.cparam = &params;
+	rq.clen = LE_LTK_NEG_REPLY_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = LE_LTK_NEG_REPLY_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0)
+		return -1;
+
+	if (resp.status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_read_white_list_size(uint8_t *size)
+{
+	struct hci_request rq;
+    le_read_white_list_size_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_WHITE_LIST_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = LE_READ_WHITE_LIST_SIZE_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    *size = resp.size;
+
+	return 0;
+}
+
+int hci_le_clear_white_list()
+{
+	struct hci_request rq;
+	uint8_t status;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_CLEAR_WHITE_LIST;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_add_device_to_white_list(uint8_t	bdaddr_type, tBDAddr bdaddr)
+{
+	struct hci_request rq;
+	le_add_device_to_white_list_cp params;
+	uint8_t status;
+
+	params.bdaddr_type = bdaddr_type;
+	Osal_MemCpy(params.bdaddr, bdaddr, 6);
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_ADD_DEVICE_TO_WHITE_LIST;
+	rq.cparam = &params;
+	rq.clen = LE_ADD_DEVICE_TO_WHITE_LIST_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_remove_device_from_white_list(uint8_t bdaddr_type, tBDAddr bdaddr)
+{
+	struct hci_request rq;
+	le_remove_device_from_white_list_cp params;
+	uint8_t status;
+
+	params.bdaddr_type = bdaddr_type;
+	Osal_MemCpy(params.bdaddr, bdaddr, 6);
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_REMOVE_DEVICE_FROM_WHITE_LIST;
+	rq.cparam = &params;
+	rq.clen = LE_REMOVE_DEVICE_FROM_WHITE_LIST_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_read_transmit_power_level(uint16_t *conn_handle, uint8_t type, int8_t * tx_level)
+{
+    struct hci_request rq;
+	read_transmit_power_level_cp params;
+	read_transmit_power_level_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	params.handle = *conn_handle;
+	params.type = type;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_HOST_CTL;
+	rq.ocf = OCF_READ_TRANSMIT_POWER_LEVEL;
+	rq.cparam = &params;
+	rq.clen = READ_TRANSMIT_POWER_LEVEL_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = READ_TRANSMIT_POWER_LEVEL_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+	
+    *conn_handle = resp.handle;
+    *tx_level = resp.handle;
+
+	return 0;
+}
+
+int hci_read_rssi(uint16_t *conn_handle, int8_t * rssi)
+{
+    struct hci_request rq;
+	read_rssi_cp params;
+	read_rssi_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	params.handle = *conn_handle;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_STATUS_PARAM;
+	rq.ocf = OCF_READ_RSSI;
+	rq.cparam = &params;
+	rq.clen = READ_RSSI_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = READ_RSSI_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+	
+    *conn_handle = resp.handle;
+    *rssi = resp.rssi;
+
+	return 0;
+}
+
+int hci_le_read_local_supported_features(uint8_t *features)
+{
+	struct hci_request rq;
+    le_read_local_supported_features_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_LOCAL_SUPPORTED_FEATURES;
+	rq.rparam = &resp;
+	rq.rlen = LE_READ_LOCAL_SUPPORTED_FEATURES_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    Osal_MemCpy(features, resp.features, sizeof(resp.features));
+
+	return 0;
+}
+
+int hci_le_read_channel_map(uint16_t conn_handle, uint8_t ch_map[5])
+{
+    struct hci_request rq;
+	le_read_channel_map_cp params;
+	le_read_channel_map_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	params.handle = conn_handle;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_CHANNEL_MAP;
+	rq.cparam = &params;
+	rq.clen = LE_READ_CHANNEL_MAP_CP_SIZE;
+	rq.rparam = &resp;
+	rq.rlen = LE_READ_CHANNEL_MAP_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    Osal_MemCpy(ch_map, resp.map, 5);
+
+	return 0;
+}
+
+int hci_le_read_supported_states(uint8_t states[8])
+{
+	struct hci_request rq;
+    le_read_supported_states_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_READ_SUPPORTED_STATES;
+	rq.rparam = &resp;
+	rq.rlen = LE_READ_SUPPORTED_STATES_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    Osal_MemCpy(states, resp.states, 8);
+
+	return 0;
+}
+
+int hci_le_receiver_test(uint8_t frequency)
+{
+	struct hci_request rq;
+	le_receiver_test_cp params;
+	uint8_t status;
+
+	params.frequency = frequency;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_RECEIVER_TEST;
+	rq.cparam = &params;
+	rq.clen = LE_RECEIVER_TEST_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_transmitter_test(uint8_t frequency, uint8_t length, uint8_t payload)
+{
+	struct hci_request rq;
+	le_transmitter_test_cp params;
+	uint8_t status;
+
+	params.frequency = frequency;
+    params.length = length;
+    params.payload = payload;
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_TRANSMITTER_TEST;
+	rq.cparam = &params;
+	rq.clen = LE_TRANSMITTER_TEST_CP_SIZE;
+	rq.rparam = &status;
+	rq.rlen = 1;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (status) {
+		return -1;
+	}
+
+	return 0;
+}
+
+int hci_le_test_end(uint16_t *num_pkts)
+{
+	struct hci_request rq;
+    le_test_end_rp resp;
+	
+	Osal_MemSet(&resp, 0, sizeof(resp));
+
+	Osal_MemSet(&rq, 0, sizeof(rq));
+	rq.ogf = OGF_LE_CTL;
+	rq.ocf = OCF_LE_TEST_END;
+	rq.rparam = &resp;
+	rq.rlen = LE_TEST_END_RP_SIZE;
+
+	if (hci_send_req(&rq) < 0){
+		return -1;
+	}
+
+	if (resp.status) {
+		return -1;
+	}
+    
+    *num_pkts = resp.num_pkts;
+
+	return 0;
+}
+
diff -r f57d754b1814 -r 987b201ec4b1 src/list.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/list.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,120 @@
+/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
+* File Name          : list.c
+* Author             : AMS - HEA&RF BU
+* Version            : V1.0.0
+* Date               : 19-July-2012
+* Description        : Circular Linked List Implementation.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+/******************************************************************************
+ * Include Files
+******************************************************************************/
+#include <hal_types.h>
+#include "list.h"
+
+/******************************************************************************
+ * Function Definitions 
+******************************************************************************/
+void list_init_head (tListNode * listHead)
+{
+	listHead->next = listHead;
+	listHead->prev = listHead;	
+}
+
+uint8_t list_is_empty (tListNode * listHead)
+{
+	return ((listHead->next == listHead)? TRUE:FALSE);
+}
+
+void list_insert_head (tListNode * listHead, tListNode * node)
+{
+	node->next = listHead->next;
+	node->prev = listHead;
+	listHead->next = node;
+	(node->next)->prev = node;
+}
+
+
+void list_insert_tail (tListNode * listHead, tListNode * node)
+{
+	node->next = listHead;
+	node->prev = listHead->prev;
+	listHead->prev = node;
+	(node->prev)->next = node;
+}
+
+
+void list_remove_node (tListNode * node)
+{
+	(node->prev)->next = node->next;
+	(node->next)->prev = node->prev;
+}
+
+
+void list_remove_head (tListNode * listHead, tListNode ** node )
+{
+	*node = listHead->next;
+	list_remove_node (listHead->next);
+	(*node)->next = NULL;
+	(*node)->prev = NULL;
+}
+
+
+void list_remove_tail (tListNode * listHead, tListNode ** node )
+{
+	*node = listHead->prev;
+	list_remove_node (listHead->prev);
+	(*node)->next = NULL;
+	(*node)->prev = NULL;
+}
+
+
+void list_insert_node_after (tListNode * node, tListNode * ref_node)
+{
+	node->next = ref_node->next;
+	node->prev = ref_node;
+	ref_node->next = node;
+	(node->next)->prev = node;
+}
+
+
+void list_insert_node_before (tListNode * node, tListNode * ref_node)
+{
+	node->next = ref_node;
+	node->prev = ref_node->prev;
+	ref_node->prev = node;
+	(node->prev)->next = node;
+}
+
+
+int list_get_size (tListNode * listHead)
+{
+	int size = 0;
+	tListNode * temp = listHead->next;
+	while (temp != listHead)
+	{
+		size++;
+		temp = temp->next;		
+	}
+	return (size);
+}
+
+void list_get_next_node (tListNode * ref_node, tListNode ** node)
+{
+    *node = ref_node->next;
+}
+
+
+void list_get_prev_node (tListNode * ref_node, tListNode ** node)
+{
+    *node = ref_node->prev;
+}
+
+
diff -r f57d754b1814 -r 987b201ec4b1 src/osal.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/osal.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,73 @@
+/**
+******************************************************************************
+* @file    osal.c 
+* @author  AMS - HEA&RF BU / CL
+* @version V1.0.0
+* @date    04-July-2014
+* @brief   Implementation of OS abstraction layer functions used by the
+*          library.
+******************************************************************************
+* @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+  
+/* Includes ------------------------------------------------------------------*/
+#include <string.h>
+#include <osal.h>
+ 
+ /**
+ * @brief  Osal_MemCpy
+ * @param  dest: Pointer to the destination buffer
+ * @param  src : Pointer to the source buffer
+ * @param  size: Number of bytes to copy from the source to the destination
+ *               buffer
+ * @retval Pointer to the destination buffer
+ */
+void* Osal_MemCpy(void *dest, const void *src, unsigned int size)
+{
+    return(memcpy(dest,src,size)); 
+}
+
+/**
+ * @brief  Osal_MemSet
+ * @param  ptr  : Pointer to block of memory to fill  
+ * @param  value: Value to assign to each byte of the memory block
+ * @param  size : Number of bytes to be set to "value"
+ * @retval Pointer to the filled block of memory
+ */
+void* Osal_MemSet(void *ptr, int value, unsigned int size)
+{
+    return(memset(ptr,value,size));
+}
+
+/******************************************************************************
+ * local Functions
+ *****************************************************************************/ 
+ 
+ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/sensor_service.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/sensor_service.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,512 @@
+/**
+  ******************************************************************************
+  * @file    sensor_service.c
+  * @author  MCD Application Team
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   Add a sample service using a vendor specific profile.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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 "sensor_service.h"
+
+/* Private variables ---------------------------------------------------------*/
+volatile int connected = FALSE;
+volatile uint8_t set_connectable = 1;
+volatile uint16_t connection_handle = 0;
+volatile uint8_t notification_enabled = FALSE;
+volatile AxesRaw_t axes_data = {0, 0, 0};
+uint16_t sampleServHandle, TXCharHandle, RXCharHandle;
+uint16_t accServHandle, freeFallCharHandle, accCharHandle;
+uint16_t envSensServHandle, tempCharHandle, pressCharHandle, humidityCharHandle;
+
+#define COPY_UUID_128(uuid_struct, uuid_15, uuid_14, uuid_13, uuid_12, uuid_11, uuid_10, uuid_9, uuid_8, uuid_7, uuid_6, uuid_5, uuid_4, uuid_3, uuid_2, uuid_1, uuid_0) \
+do {\
+    uuid_struct[0] = uuid_0; uuid_struct[1] = uuid_1; uuid_struct[2] = uuid_2; uuid_struct[3] = uuid_3; \
+        uuid_struct[4] = uuid_4; uuid_struct[5] = uuid_5; uuid_struct[6] = uuid_6; uuid_struct[7] = uuid_7; \
+            uuid_struct[8] = uuid_8; uuid_struct[9] = uuid_9; uuid_struct[10] = uuid_10; uuid_struct[11] = uuid_11; \
+                uuid_struct[12] = uuid_12; uuid_struct[13] = uuid_13; uuid_struct[14] = uuid_14; uuid_struct[15] = uuid_15; \
+}while(0)
+
+#define COPY_ACC_SERVICE_UUID(uuid_struct)  COPY_UUID_128(uuid_struct,0x02,0x36,0x6e,0x80, 0xcf,0x3a, 0x11,0xe1, 0x9a,0xb4, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+#define COPY_FREE_FALL_UUID(uuid_struct)    COPY_UUID_128(uuid_struct,0xe2,0x3e,0x78,0xa0, 0xcf,0x4a, 0x11,0xe1, 0x8f,0xfc, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+#define COPY_ACC_UUID(uuid_struct)          COPY_UUID_128(uuid_struct,0x34,0x0a,0x1b,0x80, 0xcf,0x4b, 0x11,0xe1, 0xac,0x36, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+
+#define COPY_ENV_SENS_SERVICE_UUID(uuid_struct)  COPY_UUID_128(uuid_struct,0x42,0x82,0x1a,0x40, 0xe4,0x77, 0x11,0xe2, 0x82,0xd0, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+#define COPY_TEMP_CHAR_UUID(uuid_struct)         COPY_UUID_128(uuid_struct,0xa3,0x2e,0x55,0x20, 0xe4,0x77, 0x11,0xe2, 0xa9,0xe3, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+#define COPY_PRESS_CHAR_UUID(uuid_struct)        COPY_UUID_128(uuid_struct,0xcd,0x20,0xc4,0x80, 0xe4,0x8b, 0x11,0xe2, 0x84,0x0b, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+#define COPY_HUMIDITY_CHAR_UUID(uuid_struct)     COPY_UUID_128(uuid_struct,0x01,0xc5,0x0b,0x60, 0xe4,0x8c, 0x11,0xe2, 0xa0,0x73, 0x00,0x02,0xa5,0xd5,0xc5,0x1b)
+
+/* Store Value into a buffer in Little Endian Format */
+#define STORE_LE_16(buf, val)    ( ((buf)[0] =  (uint8_t) (val)    ) , \
+                                   ((buf)[1] =  (uint8_t) (val>>8) ) )
+
+/**
+ * @brief  Add an accelerometer service using a vendor specific profile.
+ *
+ * @param  None
+ * @retval tBleStatus Status
+ */
+tBleStatus Add_Acc_Service(void)
+{
+  tBleStatus ret;
+
+  uint8_t uuid[16];
+  
+  COPY_ACC_SERVICE_UUID(uuid);
+  ret = aci_gatt_add_serv(UUID_TYPE_128,  uuid, PRIMARY_SERVICE, 7,
+                          &accServHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;    
+  
+  COPY_FREE_FALL_UUID(uuid);
+  ret =  aci_gatt_add_char(accServHandle, UUID_TYPE_128, uuid, 1,
+                           CHAR_PROP_NOTIFY, ATTR_PERMISSION_NONE, 0,
+                           16, 0, &freeFallCharHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;
+  
+  COPY_ACC_UUID(uuid);  
+  ret =  aci_gatt_add_char(accServHandle, UUID_TYPE_128, uuid, 6,
+                           CHAR_PROP_NOTIFY|CHAR_PROP_READ,
+                           ATTR_PERMISSION_NONE,
+                           GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP,
+                           16, 0, &accCharHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;
+  
+  PRINTF("Service ACC added. Handle 0x%04X, Free fall Charac handle: 0x%04X, Acc Charac handle: 0x%04X\n",accServHandle, freeFallCharHandle, accCharHandle);	
+  return BLE_STATUS_SUCCESS; 
+  
+fail:
+  PRINTF("Error while adding ACC service.\n");
+  return BLE_STATUS_ERROR ;
+    
+}
+
+/**
+ * @brief  Send a notification for a Free Fall detection.
+ *
+ * @param  None
+ * @retval tBleStatus Status
+ */
+tBleStatus Free_Fall_Notify(void)
+{  
+  uint8_t val;
+  tBleStatus ret;
+	
+  val = 0x01;	
+  ret = aci_gatt_update_char_value(accServHandle, freeFallCharHandle, 0, 1,
+                                   &val);
+	
+  if (ret != BLE_STATUS_SUCCESS){
+    PRINTF("Error while updating ACC characteristic.\n") ;
+    return BLE_STATUS_ERROR ;
+  }
+  return BLE_STATUS_SUCCESS;	
+}
+
+/**
+ * @brief  Update acceleration characteristic value.
+ *
+ * @param  Structure containing acceleration value in mg
+ * @retval Status
+ */
+tBleStatus Acc_Update(AxesRaw_t *data)
+{  
+  tBleStatus ret;    
+  uint8_t buff[6];
+    
+  STORE_LE_16(buff,data->AXIS_X);
+  STORE_LE_16(buff+2,data->AXIS_Y);
+  STORE_LE_16(buff+4,data->AXIS_Z);
+	
+  ret = aci_gatt_update_char_value(accServHandle, accCharHandle, 0, 6, buff);
+	
+  if (ret != BLE_STATUS_SUCCESS){
+    PRINTF("Error while updating ACC characteristic.\n") ;
+    return BLE_STATUS_ERROR ;
+  }
+  return BLE_STATUS_SUCCESS;	
+}
+
+/**
+ * @brief  Add the Environmental Sensor service.
+ *
+ * @param  None
+ * @retval Status
+ */
+tBleStatus Add_Environmental_Sensor_Service(void)
+{
+  tBleStatus ret;
+  uint8_t uuid[16];
+  uint16_t uuid16;
+  charactFormat charFormat;
+  uint16_t descHandle;
+  
+  COPY_ENV_SENS_SERVICE_UUID(uuid);
+  ret = aci_gatt_add_serv(UUID_TYPE_128,  uuid, PRIMARY_SERVICE, 10,
+                          &envSensServHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;
+  
+  /* Temperature Characteristic */
+  COPY_TEMP_CHAR_UUID(uuid);  
+  ret =  aci_gatt_add_char(envSensServHandle, UUID_TYPE_128, uuid, 2,
+                           CHAR_PROP_READ, ATTR_PERMISSION_NONE,
+                           GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP,
+                           16, 0, &tempCharHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;
+  
+  charFormat.format = FORMAT_SINT16;
+  charFormat.exp = -1;
+  charFormat.unit = UNIT_TEMP_CELSIUS;
+  charFormat.name_space = 0;
+  charFormat.desc = 0;
+  
+  uuid16 = CHAR_FORMAT_DESC_UUID;
+  
+  ret = aci_gatt_add_char_desc(envSensServHandle,
+                               tempCharHandle,
+                               UUID_TYPE_16,
+                               (uint8_t *)&uuid16, 
+                               7,
+                               7,
+                               (void *)&charFormat, 
+                               ATTR_PERMISSION_NONE,
+                               ATTR_ACCESS_READ_ONLY,
+                               0,
+                               16,
+                               FALSE,
+                               &descHandle);
+  if (ret != BLE_STATUS_SUCCESS) goto fail;
+  
+  /* Pressure Characteristic */
+  if(1){ //FIXME
+    COPY_PRESS_CHAR_UUID(uuid);  
+    ret =  aci_gatt_add_char(envSensServHandle, UUID_TYPE_128, uuid, 3,
+                             CHAR_PROP_READ, ATTR_PERMISSION_NONE,
+                             GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP,
+                             16, 0, &pressCharHandle);
+    if (ret != BLE_STATUS_SUCCESS) goto fail;
+    
+    charFormat.format = FORMAT_SINT24;
+    charFormat.exp = -5;
+    charFormat.unit = UNIT_PRESSURE_BAR;
+    charFormat.name_space = 0;
+    charFormat.desc = 0;
+    
+    uuid16 = CHAR_FORMAT_DESC_UUID;
+    
+    ret = aci_gatt_add_char_desc(envSensServHandle,
+                                 pressCharHandle,
+                                 UUID_TYPE_16,
+                                 (uint8_t *)&uuid16, 
+                                 7,
+                                 7,
+                                 (void *)&charFormat, 
+                                 ATTR_PERMISSION_NONE,
+                                 ATTR_ACCESS_READ_ONLY,
+                                 0,
+                                 16,
+                                 FALSE,
+                                 &descHandle);
+    if (ret != BLE_STATUS_SUCCESS) goto fail;
+  }    
+  /* Humidity Characteristic */
+  if(1){   //FIXME
+    COPY_HUMIDITY_CHAR_UUID(uuid);  
+    ret =  aci_gatt_add_char(envSensServHandle, UUID_TYPE_128, uuid, 2,
+                             CHAR_PROP_READ, ATTR_PERMISSION_NONE,
+                             GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP,
+                             16, 0, &humidityCharHandle);
+    if (ret != BLE_STATUS_SUCCESS) goto fail;
+    
+    charFormat.format = FORMAT_UINT16;
+    charFormat.exp = -1;
+    charFormat.unit = UNIT_UNITLESS;
+    charFormat.name_space = 0;
+    charFormat.desc = 0;
+    
+    uuid16 = CHAR_FORMAT_DESC_UUID;
+    
+    ret = aci_gatt_add_char_desc(envSensServHandle,
+                                 humidityCharHandle,
+                                 UUID_TYPE_16,
+                                 (uint8_t *)&uuid16, 
+                                 7,
+                                 7,
+                                 (void *)&charFormat, 
+                                 ATTR_PERMISSION_NONE,
+                                 ATTR_ACCESS_READ_ONLY,
+                                 0,
+                                 16,
+                                 FALSE,
+                                 &descHandle);
+    if (ret != BLE_STATUS_SUCCESS) goto fail;
+  } 
+  PRINTF("Service ENV_SENS added. Handle 0x%04X, TEMP Charac handle: 0x%04X, PRESS Charac handle: 0x%04X, HUMID Charac handle: 0x%04X\n",envSensServHandle, tempCharHandle, pressCharHandle, humidityCharHandle);	
+  return BLE_STATUS_SUCCESS; 
+  
+fail:
+  PRINTF("Error while adding ENV_SENS service.\n");
+  return BLE_STATUS_ERROR ;
+  
+}
+
+/**
+ * @brief  Update temperature characteristic value.
+ * @param  Temperature in tenths of degree 
+ * @retval Status
+ */
+tBleStatus Temp_Update(int16_t temp)
+{  
+  tBleStatus ret;
+  
+  ret = aci_gatt_update_char_value(envSensServHandle, tempCharHandle, 0, 2,
+                                   (uint8_t*)&temp);
+  
+  if (ret != BLE_STATUS_SUCCESS){
+    PRINTF("Error while updating TEMP characteristic.\n") ;
+    return BLE_STATUS_ERROR ;
+  }
+  return BLE_STATUS_SUCCESS;
+	
+}
+
+/**
+ * @brief  Update pressure characteristic value.
+ * @param  int32_t Pressure in mbar 
+ * @retval tBleStatus Status
+ */
+tBleStatus Press_Update(int32_t press)
+{  
+  tBleStatus ret;
+  
+  ret = aci_gatt_update_char_value(envSensServHandle, pressCharHandle, 0, 3,
+                                   (uint8_t*)&press);
+  
+  if (ret != BLE_STATUS_SUCCESS){
+    PRINTF("Error while updating TEMP characteristic.\n") ;
+    return BLE_STATUS_ERROR ;
+  }
+  return BLE_STATUS_SUCCESS;
+	
+}
+
+/**
+ * @brief  Update humidity characteristic value.
+ * @param  uint16_thumidity RH (Relative Humidity) in thenths of %
+ * @retval tBleStatus      Status
+ */
+tBleStatus Humidity_Update(uint16_t humidity)
+{  
+  tBleStatus ret;
+  
+  ret = aci_gatt_update_char_value(envSensServHandle, humidityCharHandle, 0, 2,
+                                   (uint8_t*)&humidity);
+  
+  if (ret != BLE_STATUS_SUCCESS){
+    PRINTF("Error while updating TEMP characteristic.\n") ;
+    return BLE_STATUS_ERROR ;
+  }
+  return BLE_STATUS_SUCCESS;
+  
+}
+
+/**
+ * @brief  Puts the device in connectable mode.
+ *         If you want to specify a UUID list in the advertising data, those data can
+ *         be specified as a parameter in aci_gap_set_discoverable().
+ *         For manufacture data, aci_gap_update_adv_data must be called.
+ * @param  None 
+ * @retval None
+ */
+/* Ex.:
+ *
+ *  tBleStatus ret;    
+ *  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME,'B','l','u','e','N','R','G'};    
+ *  const uint8_t serviceUUIDList[] = {AD_TYPE_16_BIT_SERV_UUID,0x34,0x12};    
+ *  const uint8_t manuf_data[] = {4, AD_TYPE_MANUFACTURER_SPECIFIC_DATA, 0x05, 0x02, 0x01};
+ *  
+ *  ret = aci_gap_set_discoverable(ADV_IND, 0, 0, PUBLIC_ADDR, NO_WHITE_LIST_USE,
+ *                                 8, local_name, 3, serviceUUIDList, 0, 0);    
+ *  ret = aci_gap_update_adv_data(5, manuf_data);
+ *
+ */
+void setConnectable(void)
+{  
+  tBleStatus ret;
+  
+  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME,'B','l','u','e','N','R','G'};
+  
+  /* disable scan response */
+  hci_le_set_scan_resp_data(0,NULL);
+  PRINTF("General Discoverable Mode.\n");
+  
+  ret = aci_gap_set_discoverable(ADV_IND, 0, 0, PUBLIC_ADDR, NO_WHITE_LIST_USE,
+                                 sizeof(local_name), local_name, 0, NULL, 0, 0);
+  PRINTF("%d\n",ret);
+}
+
+/**
+ * @brief  This function is called when there is a LE Connection Complete event.
+ * @param  uint8_t Address of peer device
+ * @param  uint16_t Connection handle
+ * @retval None
+ */
+void GAP_ConnectionComplete_CB(uint8_t addr[6], uint16_t handle)
+{  
+  connected = TRUE;
+  connection_handle = handle;
+  
+  PRINTF("Connected to device:");
+  for(int i = 5; i > 0; i--){
+    PRINTF("%02X-", addr[i]);
+  }
+  PRINTF("%02X\n", addr[0]);
+}
+
+/**
+ * @brief  This function is called when the peer device get disconnected.
+ * @param  None 
+ * @retval None
+ */
+void GAP_DisconnectionComplete_CB(void)
+{
+  connected = FALSE;
+  PRINTF("Disconnected\n");
+  /* Make the device connectable again. */
+  set_connectable = TRUE;
+  notification_enabled = FALSE;
+}
+
+/**
+ * @brief  Read request callback.
+ * @param  uint16_t Handle of the attribute
+ * @retval None
+ */
+void Read_Request_CB(uint16_t handle)
+{
+  //signed short refvalue;
+  
+  if(handle == accCharHandle + 1){
+    Acc_Update((AxesRaw_t*)&axes_data);
+  }  
+  else if(handle == tempCharHandle + 1){
+    int16_t data;
+    data = 270 + ((uint64_t)rand()*15)/RAND_MAX; //sensor emulation        
+    Acc_Update((AxesRaw_t*)&axes_data); //FIXME: to overcome issue on Android App
+                                        // If the user button is not pressed within
+                                        // a short time after the connection,
+                                        // a pop-up reports a "No valid characteristics found" error.
+    Temp_Update(data);
+  }
+  else if(handle == pressCharHandle + 1){
+    int32_t data;
+    struct timer t;  
+    Timer_Set(&t, CLOCK_SECOND/10);
+    data = 100000 + ((uint64_t)rand()*1000)/RAND_MAX;
+    Press_Update(data);
+  }
+  else if(handle == humidityCharHandle + 1){
+    uint16_t data;
+    
+    data = 450 + ((uint64_t)rand()*100)/RAND_MAX;
+    
+    Humidity_Update(data);
+  }  
+  
+  //EXIT:
+  if(connection_handle != 0)
+    aci_gatt_allow_read(connection_handle);
+}
+
+/**
+ * @brief  Callback processing the ACI events.
+ * @note   Inside this function each event must be identified and correctly
+ *         parsed.
+ * @param  void* Pointer to the ACI packet
+ * @retval None
+ */
+void HCI_Event_CB(void *pckt)
+{
+  hci_uart_pckt *hci_pckt = pckt;
+  /* obtain event packet */
+  hci_event_pckt *event_pckt = (hci_event_pckt*)hci_pckt->data;
+  
+  if(hci_pckt->type != HCI_EVENT_PKT)
+    return;
+  
+  switch(event_pckt->evt){
+    
+  case EVT_DISCONN_COMPLETE:
+    {
+      GAP_DisconnectionComplete_CB();
+    }
+    break;
+    
+  case EVT_LE_META_EVENT:
+    {
+      evt_le_meta_event *evt = (void *)event_pckt->data;
+      
+      switch(evt->subevent){
+      case EVT_LE_CONN_COMPLETE:
+        {
+          evt_le_connection_complete *cc = (void *)evt->data;
+          GAP_ConnectionComplete_CB(cc->peer_bdaddr, cc->handle);
+        }
+        break;
+      }
+    }
+    break;
+    
+  case EVT_VENDOR:
+    {
+      evt_blue_aci *blue_evt = (void*)event_pckt->data;
+      switch(blue_evt->ecode){
+
+      case EVT_BLUE_GATT_READ_PERMIT_REQ:
+        {
+          evt_gatt_read_permit_req *pr = (void*)blue_evt->data;                    
+          Read_Request_CB(pr->attr_handle);                    
+        }
+        break;
+      }
+    }
+    break;
+  }    
+}
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/stm32_bluenrg_ble.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/stm32_bluenrg_ble.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,471 @@
+/**
+  ******************************************************************************
+  * @file    stm32_bluenrg_ble.c
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+  
+/* Includes ------------------------------------------------------------------*/
+#include "stm32_bluenrg_ble.h"
+#include "gp_timer.h"
+#include "debug.h"
+
+#define HEADER_SIZE 5
+#define MAX_BUFFER_SIZE 255
+#define TIMEOUT_DURATION 15
+
+SPI_HandleTypeDef SpiHandle;
+
+/* Private function prototypes -----------------------------------------------*/
+static void us150Delay(void);
+void set_irq_as_output(void);
+void set_irq_as_input(void);
+
+/**
+ * @brief  This function is used for low level initialization of the SPI 
+ *         communication with the BlueNRG Expansion Board.
+ * @param  Pointer to the handle of the STM32Cube HAL SPI interface.
+ * @retval None
+ */
+void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
+{
+  GPIO_InitTypeDef GPIO_InitStruct;
+  if(hspi->Instance==BNRG_SPI_INSTANCE)
+  {
+    /* Enable peripherals clock */
+    
+    /* Enable GPIO Ports Clock */  
+    BNRG_SPI_RESET_CLK_ENABLE();
+    BNRG_SPI_SCLK_CLK_ENABLE();
+    BNRG_SPI_MISO_CLK_ENABLE();
+    BNRG_SPI_MOSI_CLK_ENABLE();
+    BNRG_SPI_CS_CLK_ENABLE();
+    BNRG_SPI_IRQ_CLK_ENABLE();
+    
+    /* Enable SPI clock */
+    BNRG_SPI_CLK_ENABLE();
+    
+    /* Reset */
+    GPIO_InitStruct.Pin = BNRG_SPI_RESET_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_RESET_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_RESET_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_RESET_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_RESET_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_RESET_PORT, &GPIO_InitStruct);	
+    HAL_GPIO_WritePin(BNRG_SPI_RESET_PORT, BNRG_SPI_RESET_PIN, GPIO_PIN_RESET);	/*Added to avoid spurious interrupt from the BlueNRG */
+    
+    /* SCLK */
+    GPIO_InitStruct.Pin = BNRG_SPI_SCLK_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_SCLK_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_SCLK_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_SCLK_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_SCLK_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_SCLK_PORT, &GPIO_InitStruct); 
+    
+    /* MISO */
+    GPIO_InitStruct.Pin = BNRG_SPI_MISO_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_MISO_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_MISO_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_MISO_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_MISO_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_MISO_PORT, &GPIO_InitStruct);
+    
+    /* MOSI */
+    GPIO_InitStruct.Pin = BNRG_SPI_MOSI_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_MOSI_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_MOSI_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_MOSI_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_MOSI_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_MOSI_PORT, &GPIO_InitStruct);
+    
+    /* NSS/CSN/CS */
+    GPIO_InitStruct.Pin = BNRG_SPI_CS_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_CS_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_CS_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_CS_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_CS_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_CS_PORT, &GPIO_InitStruct);
+    HAL_GPIO_WritePin(BNRG_SPI_CS_PORT, BNRG_SPI_CS_PIN, GPIO_PIN_SET);
+    
+    /* IRQ -- INPUT */
+    GPIO_InitStruct.Pin = BNRG_SPI_IRQ_PIN;
+    GPIO_InitStruct.Mode = BNRG_SPI_IRQ_MODE;
+    GPIO_InitStruct.Pull = BNRG_SPI_IRQ_PULL;
+    GPIO_InitStruct.Speed = BNRG_SPI_IRQ_SPEED;
+    GPIO_InitStruct.Alternate = BNRG_SPI_IRQ_ALTERNATE;
+    HAL_GPIO_Init(BNRG_SPI_IRQ_PORT, &GPIO_InitStruct);
+    
+    /* Configure the NVIC for SPI */  
+    HAL_NVIC_SetPriority(BNRG_SPI_EXTI_IRQn, 4, 0);    
+    HAL_NVIC_EnableIRQ(BNRG_SPI_EXTI_IRQn);
+  }
+}
+
+/**
+ * @brief  Writes data to a serial interface.
+ * @param  data1   :  1st buffer
+ * @param  data2   :  2nd buffer
+ * @param  n_bytes1: number of bytes in 1st buffer
+ * @param  n_bytes2: number of bytes in 2nd buffer
+ * @retval None
+ */
+void Hal_Write_Serial(const void* data1, const void* data2, int32_t n_bytes1,
+                      int32_t n_bytes2)
+{
+  struct timer t;
+  
+  Timer_Set(&t, CLOCK_SECOND/10);
+  
+#ifdef PRINT_CSV_FORMAT
+  PRINT_CSV("00:00:00.000");
+  for (int i=0; i<n_bytes1; i++) {
+    PRINT_CSV(" %02x", ((uint8_t *)data1)[i]);
+  }
+  for (int i=0; i<n_bytes2; i++) {
+    PRINT_CSV(" %02x", ((uint8_t *)data2)[i]);
+  }
+  PRINT_CSV("\n");
+#endif
+
+  while(1){
+    if(BlueNRG_SPI_Write(&SpiHandle, (uint8_t *)data1,(uint8_t *)data2, n_bytes1, n_bytes2)==0) break;
+    if(Timer_Expired(&t)){
+      break;
+    }
+  }
+}
+
+/**
+* @brief  Initializes the SPI communication with the BlueNRG
+*         Expansion Board.
+* @param  None
+* @retval None
+*/
+void BNRG_SPI_Init(void)
+{
+  SpiHandle.Instance = BNRG_SPI_INSTANCE;
+  SpiHandle.Init.Mode = BNRG_SPI_MODE;
+  SpiHandle.Init.Direction = BNRG_SPI_DIRECTION;
+  SpiHandle.Init.DataSize = BNRG_SPI_DATASIZE;
+  SpiHandle.Init.CLKPolarity = BNRG_SPI_CLKPOLARITY;
+  SpiHandle.Init.CLKPhase = BNRG_SPI_CLKPHASE;
+  SpiHandle.Init.NSS = BNRG_SPI_NSS;
+  SpiHandle.Init.FirstBit = BNRG_SPI_FIRSTBIT;
+  SpiHandle.Init.TIMode = BNRG_SPI_TIMODE;
+  SpiHandle.Init.CRCPolynomial = BNRG_SPI_CRCPOLYNOMIAL;
+  SpiHandle.Init.BaudRatePrescaler = BNRG_SPI_BAUDRATEPRESCALER;
+  SpiHandle.Init.CRCCalculation = BNRG_SPI_CRCCALCULATION;
+  
+  HAL_SPI_Init(&SpiHandle);
+}
+
+/**
+ * @brief  Resets the BlueNRG.
+ * @param  None
+ * @retval None
+ */
+void BlueNRG_RST(void)
+{    
+  HAL_GPIO_WritePin(BNRG_SPI_RESET_PORT, BNRG_SPI_RESET_PIN, GPIO_PIN_RESET);
+  HAL_Delay(5);
+  HAL_GPIO_WritePin(BNRG_SPI_RESET_PORT, BNRG_SPI_RESET_PIN, GPIO_PIN_SET);
+  HAL_Delay(5);
+}
+
+
+/**
+  * @brief  Reports if the BlueNRG has data for the host micro.
+  * @param  None
+  * @retval 1 if data are present, 0 otherwise
+  */
+// FIXME: find a better way to handle this return value (bool type? TRUE and FALSE)
+uint8_t BlueNRG_DataPresent(void)
+{
+  if (HAL_GPIO_ReadPin(BNRG_SPI_EXTI_PORT, BNRG_SPI_EXTI_PIN) == GPIO_PIN_SET)
+      return 1;
+  else  
+      return 0;
+} /* end BlueNRG_DataPresent() */
+
+/**
+  * @brief  Activate internal bootloader using pin.
+  * @param  None
+  * @retval None
+  */
+void BlueNRG_HW_Bootloader(void)
+{
+  set_irq_as_output();
+  BlueNRG_RST();
+  set_irq_as_input();
+}
+
+/**
+* @brief  Reads from BlueNRG SPI buffer and store data into local buffer.
+* @param  hspi     : Handle of the STM32Cube HAL SPI interface
+* @param  buffer   : Buffer where data from SPI are stored
+* @param  buff_size: Buffer size
+* @retval int32_t  : Number of read bytes
+*/
+int32_t BlueNRG_SPI_Read_All(SPI_HandleTypeDef *hspi, uint8_t *buffer,
+                             uint8_t buff_size)
+{
+  uint16_t byte_count;
+  uint8_t len = 0;
+  uint8_t char_ff = 0xff;
+  volatile uint8_t read_char;
+  
+  uint8_t header_master[HEADER_SIZE] = {0x0b, 0x00, 0x00, 0x00, 0x00};
+  uint8_t header_slave[HEADER_SIZE];
+      
+  /* CS reset */
+  HAL_GPIO_WritePin(BNRG_SPI_CS_PORT, BNRG_SPI_CS_PIN, GPIO_PIN_RESET);
+
+  /* Read the header */  
+  HAL_SPI_TransmitReceive(hspi, header_master, header_slave, HEADER_SIZE, TIMEOUT_DURATION);
+   
+  if (header_slave[0] == 0x02) {
+    /* device is ready */
+    byte_count = (header_slave[4]<<8)|header_slave[3];
+    
+    if (byte_count > 0) {
+      
+      /* avoid to read more data that size of the buffer */
+      if (byte_count > buff_size){
+        byte_count = buff_size;
+      }
+      
+      for (len = 0; len < byte_count; len++){
+        HAL_SPI_TransmitReceive(hspi, &char_ff, (uint8_t*)&read_char, 1, TIMEOUT_DURATION);
+        buffer[len] = read_char;
+      }
+    }    
+  }
+  /* Release CS line */
+  HAL_GPIO_WritePin(BNRG_SPI_CS_PORT, BNRG_SPI_CS_PIN, GPIO_PIN_SET);
+  
+  // Add a small delay to give time to the BlueNRG to set the IRQ pin low
+  // to avoid a useless SPI read at the end of the transaction
+  for(volatile int i = 0; i < 2; i++)__NOP();
+
+#ifdef PRINT_CSV_FORMAT
+  if (len > 0) {
+    PRINT_CSV("00:00:00.000");
+    for (int i=0; i<len; i++) {
+      PRINT_CSV(" %02x", buffer[i]);
+    }
+    PRINT_CSV("\n");
+  }
+#endif
+
+  return len;   
+}
+
+/**
+* @brief  Writes data from local buffer to SPI.
+* @param  hspi     : Handle of the STM32Cube HAL SPI interface
+* @param  data1    : First data buffer to be written
+* @param  data2    : Second data buffer to be written
+* @param  Nb_bytes1: Size of first data buffer to be written
+* @param  Nb_bytes2: Size of second data buffer to be written
+* @retval Number of read bytes
+*/
+int32_t BlueNRG_SPI_Write(SPI_HandleTypeDef *hspi, uint8_t* data1,
+                          uint8_t* data2, uint8_t Nb_bytes1, uint8_t Nb_bytes2)
+{  
+  int32_t result = 0;
+  
+  int32_t spi_fix_enabled = 0;
+  
+#ifdef ENABLE_SPI_FIX
+  spi_fix_enabled = 1;
+#endif //ENABLE_SPI_FIX
+  
+  unsigned char header_master[HEADER_SIZE] = {0x0a, 0x00, 0x00, 0x00, 0x00};
+  unsigned char header_slave[HEADER_SIZE]  = {0xaa, 0x00, 0x00, 0x00, 0x00};
+  
+  unsigned char read_char_buf[MAX_BUFFER_SIZE];
+  
+  Disable_SPI_IRQ(); 
+  
+  /*
+   If the SPI_FIX is enabled the IRQ is set in Output mode, then it is pulled
+   high and, after a delay of at least 112us, the CS line is asserted and the
+   header transmit/receive operations are started.
+   After these transmit/receive operations the IRQ is reset in input mode.
+  */
+  if (spi_fix_enabled) {
+    set_irq_as_output();
+    
+    /* Assert CS line after at least 112us */
+    us150Delay();
+  }
+  
+  /* CS reset */
+  HAL_GPIO_WritePin(BNRG_SPI_CS_PORT, BNRG_SPI_CS_PIN, GPIO_PIN_RESET);
+  
+  /* Exchange header */  
+  HAL_SPI_TransmitReceive(hspi, header_master, header_slave, HEADER_SIZE, TIMEOUT_DURATION);
+  
+  if (spi_fix_enabled) {
+    set_irq_as_input();
+  }
+  
+  if (header_slave[0] == 0x02) {
+    /* SPI is ready */
+    if (header_slave[1] >= (Nb_bytes1+Nb_bytes2)) {
+      
+      /*  Buffer is big enough */
+      if (Nb_bytes1 > 0) {
+        HAL_SPI_TransmitReceive(hspi, data1, read_char_buf, Nb_bytes1, TIMEOUT_DURATION);
+      }
+      if (Nb_bytes2 > 0) {
+        HAL_SPI_TransmitReceive(hspi, data2, read_char_buf, Nb_bytes2, TIMEOUT_DURATION);
+      }
+            
+    } else {
+      /* Buffer is too small */
+      result = -2;
+    }
+  } else {
+    /* SPI is not ready */
+    result = -1;
+  }
+  
+  /* Release CS line */
+  HAL_GPIO_WritePin(BNRG_SPI_CS_PORT, BNRG_SPI_CS_PIN, GPIO_PIN_SET);
+  
+  Enable_SPI_IRQ();
+  
+  return result;
+}
+
+/**
+ * @brief  Set in Output mode the IRQ.
+ * @param  None
+ * @retval None
+ */
+void set_irq_as_output()
+{
+  GPIO_InitTypeDef  GPIO_InitStructure;
+  
+  /* Pull IRQ high */
+  GPIO_InitStructure.Pin = BNRG_SPI_IRQ_PIN;
+  GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
+  GPIO_InitStructure.Speed = BNRG_SPI_IRQ_SPEED;
+  GPIO_InitStructure.Pull = GPIO_NOPULL;
+  HAL_GPIO_Init(BNRG_SPI_IRQ_PORT, &GPIO_InitStructure);
+  HAL_GPIO_WritePin(BNRG_SPI_IRQ_PORT, BNRG_SPI_IRQ_PIN, GPIO_PIN_SET);
+}
+
+/**
+ * @brief  Set the IRQ in input mode.
+ * @param  None
+ * @retval None
+ */
+void set_irq_as_input()
+{
+  GPIO_InitTypeDef  GPIO_InitStructure;
+  
+  /* IRQ input */  
+  GPIO_InitStructure.Pin = BNRG_SPI_IRQ_PIN;
+  GPIO_InitStructure.Mode = BNRG_SPI_IRQ_MODE;
+  GPIO_InitStructure.Pull = GPIO_PULLDOWN;
+  GPIO_InitStructure.Speed = BNRG_SPI_IRQ_SPEED;
+  GPIO_InitStructure.Alternate = BNRG_SPI_IRQ_ALTERNATE;    
+  HAL_GPIO_Init(BNRG_SPI_IRQ_PORT, &GPIO_InitStructure);
+  
+  GPIO_InitStructure.Pull = BNRG_SPI_IRQ_PULL;
+  HAL_GPIO_Init(BNRG_SPI_IRQ_PORT, &GPIO_InitStructure);
+}
+
+/**
+  * @brief  Utility function for delay
+  * @param  None 
+  * @retval None
+  * NOTE: TODO: implement with clock-independent function.
+  */
+static void us150Delay()
+{ 
+#if SYSCLK_FREQ == 4000000
+  for(volatile int i = 0; i < 35; i++)__NOP();
+#elif SYSCLK_FREQ == 32000000
+  for(volatile int i = 0; i < 420; i++)__NOP();
+#elif SYSCLK_FREQ == 84000000
+  for(volatile int i = 0; i < 1125; i++)__NOP();
+#else
+#error Implement delay function.
+#endif    
+}
+
+/**
+ * @brief  Enable SPI IRQ.
+ * @param  None
+ * @retval None
+ */
+void Enable_SPI_IRQ(void)
+{  
+  HAL_NVIC_EnableIRQ(BNRG_SPI_EXTI_IRQn);  
+}
+
+/**
+ * @brief  Disable SPI IRQ.
+ * @param  None
+ * @retval None
+ */
+void Disable_SPI_IRQ(void)
+{  
+  HAL_NVIC_DisableIRQ(BNRG_SPI_EXTI_IRQn);
+}
+
+/**
+ * @brief  Clear Pending SPI IRQ.
+ * @param  None
+ * @retval None
+ */
+void Clear_SPI_IRQ(void)
+{
+  HAL_NVIC_ClearPendingIRQ(BNRG_SPI_EXTI_IRQn);
+}
+
+/**
+ * @brief  Clear EXTI (External Interrupt) line for SPI IRQ.
+ * @param  None
+ * @retval None
+ */
+void Clear_SPI_EXTI_Flag(void)
+{
+  __HAL_GPIO_EXTI_CLEAR_IT(BNRG_SPI_EXTI_PIN);
+}
+    
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/stm32f4xx_nucleo.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/stm32f4xx_nucleo.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,801 @@
+/**
+  ******************************************************************************
+  * @file    stm32f4xx_nucleo.c
+  * @author  MCD Application Team
+  * @version V1.1.0
+  * @date    19-June-2014
+  * @cond DOXYGEN_EXCLUDE
+  * @brief   This file provides set of firmware functions to manage:
+  *          + LEDs and push-button available on STM32F4XX-Nucleo Kit 
+  *            from STMicroelectronics.
+  *          + LCD, joystick and microSD available on Adafruit 1.8" TFT LCD 
+  *            Expansion Board (reference ID 802).
+  * @endcond
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */ 
+  
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f4xx_nucleo.h"
+
+/** @addtogroup BSP
+  * @{
+  */ 
+
+/** @addtogroup STM32F4XX_NUCLEO
+  * @{
+  */   
+    
+/** @addtogroup STM32F4XX_NUCLEO_LOW_LEVEL 
+  * @brief This file provides set of firmware functions to manage Leds and push-button
+  *        available on STM32F4xx-Nucleo Kit from STMicroelectronics.
+  * @{
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_TypesDefinitions
+  * @{
+  */ 
+/**
+  * @}
+  */ 
+
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_Defines
+  * @{
+  */ 
+
+/**
+  * @brief STM32F4xx NUCLEO BSP Driver version number V1.1.0
+  */
+#define __STM32F4xx_NUCLEO_BSP_VERSION_MAIN   (0x01) /*!< [31:24] main version */
+#define __STM32F4xx_NUCLEO_BSP_VERSION_SUB1   (0x01) /*!< [23:16] sub1 version */
+#define __STM32F4xx_NUCLEO_BSP_VERSION_SUB2   (0x00) /*!< [15:8]  sub2 version */
+#define __STM32F4xx_NUCLEO_BSP_VERSION_RC     (0x00) /*!< [7:0]  release candidate */ 
+#define __STM32F4xx_NUCLEO_BSP_VERSION        ((__STM32F4xx_NUCLEO_BSP_VERSION_MAIN << 24)\
+                                             |(__STM32F4xx_NUCLEO_BSP_VERSION_SUB1 << 16)\
+                                             |(__STM32F4xx_NUCLEO_BSP_VERSION_SUB2 << 8 )\
+                                             |(__STM32F4xx_NUCLEO_BSP_VERSION_RC))   
+
+/**
+  * @brief LINK SD Card
+  */
+#define SD_DUMMY_BYTE            0xFF    
+#define SD_NO_RESPONSE_EXPECTED  0x80
+
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_Macros
+  * @{
+  */ 
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_Variables
+  * @{
+  */ 
+GPIO_TypeDef* GPIO_PORT[LEDn] = {LED2_GPIO_PORT};
+
+const uint16_t GPIO_PIN[LEDn] = {LED2_PIN};
+
+GPIO_TypeDef* BUTTON_PORT[BUTTONn] = {KEY_BUTTON_GPIO_PORT}; 
+const uint16_t BUTTON_PIN[BUTTONn] = {KEY_BUTTON_PIN}; 
+const uint8_t BUTTON_IRQn[BUTTONn] = {KEY_BUTTON_EXTI_IRQn};
+
+/**
+ * @brief BUS variables
+ */
+
+uint32_t SpixTimeout = NUCLEO_SPIx_TIMEOUT_MAX; /*<! Value of Timeout when SPI communication fails */
+static SPI_HandleTypeDef hnucleo_Spi;
+static ADC_HandleTypeDef hnucleo_Adc;
+
+/* ADC channel configuration structure declaration */
+static ADC_ChannelConfTypeDef sConfig;
+
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_FunctionPrototypes
+  * @{
+  */
+static void       SPIx_Init(void);
+static void       SPIx_Write(uint8_t Value);
+static uint32_t   SPIx_Read(void);
+static void       SPIx_Error(void);
+static void       SPIx_MspInit(SPI_HandleTypeDef *hspi);
+
+static void       ADCx_Init(void);
+static void       ADCx_MspInit(ADC_HandleTypeDef *hadc);
+
+/* SD IO functions */
+void              SD_IO_Init(void);
+HAL_StatusTypeDef SD_IO_WriteCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc, uint8_t Response);
+HAL_StatusTypeDef SD_IO_WaitResponse(uint8_t Response);
+void              SD_IO_WriteDummy(void);
+void              SD_IO_WriteByte(uint8_t Data);
+uint8_t           SD_IO_ReadByte(void);
+
+/* LCD IO functions */
+void              LCD_IO_Init(void);
+void              LCD_IO_WriteData(uint8_t Data);
+void              LCD_IO_WriteReg(uint8_t LCDReg);
+void              LCD_Delay(uint32_t delay);
+/**
+  * @}
+  */ 
+
+/** @defgroup STM32F4XX_NUCLEO_LOW_LEVEL_Private_Functions
+  * @{
+  */ 
+
+/**
+  * @brief  This method returns the STM32F4xx NUCLEO BSP Driver revision
+  * @param  None
+  * @retval version: 0xXYZR (8bits for each decimal, R for RC)
+  */
+uint32_t BSP_GetVersion(void)
+{
+  return __STM32F4xx_NUCLEO_BSP_VERSION;
+}
+
+/**
+  * @brief  Configures LED GPIO.
+  * @param  Led: Specifies the Led to be configured. 
+  *   This parameter can be one of following parameters:
+  *     @arg LED2
+  * @retval None
+  */
+void BSP_LED_Init(Led_TypeDef Led)
+{
+  GPIO_InitTypeDef  GPIO_InitStruct;
+  
+  /* Enable the GPIO_LED Clock */
+  LEDx_GPIO_CLK_ENABLE(Led);
+  
+  /* Configure the GPIO_LED pin */
+  GPIO_InitStruct.Pin = GPIO_PIN[Led];
+  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+  GPIO_InitStruct.Pull = GPIO_PULLUP;
+  GPIO_InitStruct.Speed = GPIO_SPEED_FAST;
+  
+  HAL_GPIO_Init(GPIO_PORT[Led], &GPIO_InitStruct);
+  
+  HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_RESET); 
+}
+
+/**
+  * @brief  Turns selected LED On.
+  * @param  Led: Specifies the Led to be set on. 
+  *   This parameter can be one of following parameters:
+  *     @arg LED2
+  * @retval None
+  */
+void BSP_LED_On(Led_TypeDef Led)
+{
+  HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_SET); 
+}
+
+/**
+  * @brief  Turns selected LED Off.
+  * @param  Led: Specifies the Led to be set off. 
+  *   This parameter can be one of following parameters:
+  *     @arg LED2
+  * @retval None
+  */
+void BSP_LED_Off(Led_TypeDef Led)
+{
+  HAL_GPIO_WritePin(GPIO_PORT[Led], GPIO_PIN[Led], GPIO_PIN_RESET); 
+}
+
+/**
+  * @brief  Toggles the selected LED.
+  * @param  Led: Specifies the Led to be toggled. 
+  *   This parameter can be one of following parameters:
+  *     @arg LED2  
+  * @retval None
+  */
+void BSP_LED_Toggle(Led_TypeDef Led)
+{
+  HAL_GPIO_TogglePin(GPIO_PORT[Led], GPIO_PIN[Led]);
+}
+
+/**
+  * @brief  Configures Button GPIO and EXTI Line.
+  * @param  Button: Specifies the Button to be configured.
+  *   This parameter should be: BUTTON_KEY
+  * @param  ButtonMode: Specifies Button mode.
+  *   This parameter can be one of following parameters:   
+  *     @arg BUTTON_MODE_GPIO: Button will be used as simple IO 
+  *     @arg BUTTON_MODE_EXTI: Button will be connected to EXTI line with interrupt
+  *                            generation capability  
+  * @retval None
+  */
+void BSP_PB_Init(Button_TypeDef Button, ButtonMode_TypeDef ButtonMode)
+{
+  GPIO_InitTypeDef GPIO_InitStruct;
+  
+  /* Enable the BUTTON Clock */
+  BUTTONx_GPIO_CLK_ENABLE(Button);
+  
+  if(ButtonMode == BUTTON_MODE_GPIO)
+  {
+    /* Configure Button pin as input */
+    GPIO_InitStruct.Pin = BUTTON_PIN[Button];
+    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+    GPIO_InitStruct.Pull = GPIO_PULLDOWN;
+    GPIO_InitStruct.Speed = GPIO_SPEED_FAST;
+    HAL_GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStruct);
+  }
+  
+  if(ButtonMode == BUTTON_MODE_EXTI)
+  {
+    /* Configure Button pin as input with External interrupt */
+    GPIO_InitStruct.Pin = BUTTON_PIN[Button];
+    GPIO_InitStruct.Pull = GPIO_NOPULL;
+    GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; 
+    HAL_GPIO_Init(BUTTON_PORT[Button], &GPIO_InitStruct);
+    
+    /* Enable and set Button EXTI Interrupt to the lowest priority */
+    HAL_NVIC_SetPriority((IRQn_Type)(BUTTON_IRQn[Button]), 0x0F, 0x00);
+    HAL_NVIC_EnableIRQ((IRQn_Type)(BUTTON_IRQn[Button]));
+  }
+}
+
+/**
+  * @brief  Returns the selected Button state.
+  * @param  Button: Specifies the Button to be checked.
+  *   This parameter should be: BUTTON_KEY  
+  * @retval The Button GPIO pin value.
+  */
+uint32_t BSP_PB_GetState(Button_TypeDef Button)
+{
+  return HAL_GPIO_ReadPin(BUTTON_PORT[Button], BUTTON_PIN[Button]);
+}
+
+/******************************************************************************
+                            BUS OPERATIONS
+*******************************************************************************/
+/**
+  * @brief  Initializes SPI MSP.
+  * @param  None
+  * @retval None
+  */
+static void SPIx_MspInit(SPI_HandleTypeDef *hspi)
+{
+  GPIO_InitTypeDef  GPIO_InitStruct;  
+  
+  /*** Configure the GPIOs ***/  
+  /* Enable GPIO clock */
+  NUCLEO_SPIx_SCK_GPIO_CLK_ENABLE();
+  NUCLEO_SPIx_MISO_MOSI_GPIO_CLK_ENABLE();
+  
+  /* Configure SPI SCK */
+  GPIO_InitStruct.Pin = NUCLEO_SPIx_SCK_PIN;
+  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+  GPIO_InitStruct.Pull  = GPIO_PULLUP;
+  GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
+  GPIO_InitStruct.Alternate = NUCLEO_SPIx_SCK_AF;
+  HAL_GPIO_Init(NUCLEO_SPIx_SCK_GPIO_PORT, &GPIO_InitStruct);
+
+  /* Configure SPI MISO and MOSI */ 
+  GPIO_InitStruct.Pin = NUCLEO_SPIx_MOSI_PIN;
+  GPIO_InitStruct.Alternate = NUCLEO_SPIx_MISO_MOSI_AF;
+  GPIO_InitStruct.Pull  = GPIO_PULLDOWN;
+  HAL_GPIO_Init(NUCLEO_SPIx_MISO_MOSI_GPIO_PORT, &GPIO_InitStruct);
+  
+  GPIO_InitStruct.Pin = NUCLEO_SPIx_MISO_PIN;
+  HAL_GPIO_Init(NUCLEO_SPIx_MISO_MOSI_GPIO_PORT, &GPIO_InitStruct);
+
+  /*** Configure the SPI peripheral ***/ 
+  /* Enable SPI clock */
+  NUCLEO_SPIx_CLK_ENABLE();
+}
+
+/**
+  * @brief  Initializes SPI HAL.
+  * @param  None
+  * @retval None
+  */
+static void SPIx_Init(void)
+{
+  if(HAL_SPI_GetState(&hnucleo_Spi) == HAL_SPI_STATE_RESET)
+  {
+    /* SPI Config */
+    hnucleo_Spi.Instance = NUCLEO_SPIx;
+      /* SPI baudrate is set to 12,5 MHz maximum (PCLK2/SPI_BaudRatePrescaler = 100/8 = 12,5 MHz) 
+       to verify these constraints:
+          - ST7735 LCD SPI interface max baudrate is 15MHz for write and 6.66MHz for read
+            Since the provided driver doesn't use read capability from LCD, only constraint 
+            on write baudrate is considered.
+          - SD card SPI interface max baudrate is 25MHz for write/read
+          - PCLK2 max frequency is 100 MHz 
+       */ 
+    hnucleo_Spi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
+    hnucleo_Spi.Init.Direction = SPI_DIRECTION_2LINES;
+    hnucleo_Spi.Init.CLKPhase = SPI_PHASE_2EDGE;
+    hnucleo_Spi.Init.CLKPolarity = SPI_POLARITY_HIGH;
+    hnucleo_Spi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED;
+    hnucleo_Spi.Init.CRCPolynomial = 7;
+    hnucleo_Spi.Init.DataSize = SPI_DATASIZE_8BIT;
+    hnucleo_Spi.Init.FirstBit = SPI_FIRSTBIT_MSB;
+    hnucleo_Spi.Init.NSS = SPI_NSS_SOFT;
+    hnucleo_Spi.Init.TIMode = SPI_TIMODE_DISABLED;
+    hnucleo_Spi.Init.Mode = SPI_MODE_MASTER;
+
+    SPIx_MspInit(&hnucleo_Spi);
+    HAL_SPI_Init(&hnucleo_Spi);
+  }
+}
+
+/**
+  * @brief  SPI Read 4 bytes from device.
+  * @param  None
+  * @retval Read data
+*/
+static uint32_t SPIx_Read(void)
+{
+  HAL_StatusTypeDef status = HAL_OK;
+  uint32_t readvalue = 0;
+  uint32_t writevalue = 0xFFFFFFFF;
+  
+  status = HAL_SPI_TransmitReceive(&hnucleo_Spi, (uint8_t*) &writevalue, (uint8_t*) &readvalue, 1, SpixTimeout);
+  
+  /* Check the communication status */
+  if(status != HAL_OK)
+  {
+    /* Execute user timeout callback */
+    SPIx_Error();
+  }
+
+  return readvalue;
+}
+
+/**
+  * @brief  SPI Write a byte to device.
+  * @param  Value: value to be written
+  * @retval None
+  */
+static void SPIx_Write(uint8_t Value)
+{
+  HAL_StatusTypeDef status = HAL_OK;
+
+  status = HAL_SPI_Transmit(&hnucleo_Spi, (uint8_t*) &Value, 1, SpixTimeout);
+    
+  /* Check the communication status */
+  if(status != HAL_OK)
+  {
+    /* Execute user timeout callback */
+    SPIx_Error();
+  }
+}
+
+/**
+  * @brief  SPI error treatment function.
+  * @param  None
+  * @retval None
+  */
+static void SPIx_Error (void)
+{
+  /* De-initialize the SPI communication BUS */
+  HAL_SPI_DeInit(&hnucleo_Spi);
+  
+  /* Re-Initiaize the SPI communication BUS */
+  SPIx_Init();
+}
+
+/******************************************************************************
+                            LINK OPERATIONS
+*******************************************************************************/
+
+/********************************* LINK SD ************************************/
+/**
+  * @brief  Initializes the SD Card and put it into StandBy State (Ready for 
+  *         data transfer).
+  * @param  None
+  * @retval None
+  */
+void SD_IO_Init(void)
+{
+  GPIO_InitTypeDef  GPIO_InitStruct;
+  uint8_t counter;
+
+  /* SD_CS_GPIO Periph clock enable */
+  SD_CS_GPIO_CLK_ENABLE();
+
+  /* Configure SD_CS_PIN pin: SD Card CS pin */
+  GPIO_InitStruct.Pin = SD_CS_PIN;
+  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+  GPIO_InitStruct.Pull = GPIO_PULLUP;
+  GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
+  HAL_GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStruct);
+
+  /*------------Put SD in SPI mode--------------*/
+  /* SD SPI Config */
+  SPIx_Init();
+  
+  /* SD chip select high */
+  SD_CS_HIGH();
+  
+  /* Send dummy byte 0xFF, 10 times with CS high */
+  /* Rise CS and MOSI for 80 clocks cycles */
+  for (counter = 0; counter <= 9; counter++)
+  {
+    /* Send dummy byte 0xFF */
+    SD_IO_WriteByte(SD_DUMMY_BYTE);
+  }
+}
+
+/**
+  * @brief  Writes a byte on the SD.
+  * @param  Data: byte to send.
+  * @retval None
+  */
+void SD_IO_WriteByte(uint8_t Data)
+{
+  /* Send the byte */
+  SPIx_Write(Data);
+}
+
+/**
+  * @brief  Reads a byte from the SD.
+  * @param  None
+  * @retval The received byte.
+  */
+uint8_t SD_IO_ReadByte(void)
+{
+  uint8_t data = 0;
+  
+  /* Get the received data */
+  data = SPIx_Read();
+
+  /* Return the shifted data */
+  return data;
+}
+
+/**
+  * @brief  Sends 5 bytes command to the SD card and get response.
+  * @param  Cmd: The user expected command to send to SD card.
+  * @param  Arg: The command argument
+  * @param  Crc: The CRC
+  * @param  Response: Expected response from the SD card
+  * @retval HAL_StatusTypeDef HAL Status
+  */
+HAL_StatusTypeDef SD_IO_WriteCmd(uint8_t Cmd, uint32_t Arg, uint8_t Crc, uint8_t Response)
+{
+  uint32_t counter = 0x00;
+  uint8_t frame[6];
+
+  /* Prepare Frame to send */
+  frame[0] = (Cmd | 0x40);         /* Construct byte 1 */
+  frame[1] = (uint8_t)(Arg >> 24); /* Construct byte 2 */
+  frame[2] = (uint8_t)(Arg >> 16); /* Construct byte 3 */
+  frame[3] = (uint8_t)(Arg >> 8);  /* Construct byte 4 */
+  frame[4] = (uint8_t)(Arg);       /* Construct byte 5 */
+  frame[5] = (Crc);                /* Construct byte 6 */
+  
+  /* SD chip select low */
+  SD_CS_LOW();
+    
+  /* Send Frame */
+  for (counter = 0; counter < 6; counter++)
+  {
+    SD_IO_WriteByte(frame[counter]); /* Send the Cmd bytes */
+  }
+
+  if(Response != SD_NO_RESPONSE_EXPECTED)
+  {
+    return SD_IO_WaitResponse(Response);
+  }
+  
+  return HAL_OK;
+}
+
+/**
+  * @brief  Waits response from the SD card
+  * @param  Response: Expected response from the SD card
+  * @retval HAL_StatusTypeDef HAL Status
+  */
+HAL_StatusTypeDef SD_IO_WaitResponse(uint8_t Response)
+{
+  uint32_t timeout = 0xFFFF;
+
+  /* Check if response is got or a timeout is happen */
+  while ((SD_IO_ReadByte() != Response) && timeout)
+  {
+    timeout--;
+  }
+
+  if (timeout == 0)
+  {
+    /* After time out */
+    return HAL_TIMEOUT;
+  }
+  else
+  {
+    /* Right response got */
+    return HAL_OK;
+  }
+}
+
+/**
+  * @brief  Sends dummy byte with CS High.
+  * @param  None
+  * @retval None
+  */
+void SD_IO_WriteDummy(void)
+{
+  /* SD chip select high */
+  SD_CS_HIGH();
+  
+  /* Send Dummy byte 0xFF */
+  SD_IO_WriteByte(SD_DUMMY_BYTE);
+}
+
+/********************************* LINK LCD ***********************************/
+/**
+  * @brief  Initializes the LCD.
+  * @param  None
+  * @retval None
+  */
+void LCD_IO_Init(void)
+{
+  GPIO_InitTypeDef  GPIO_InitStruct;
+   
+  /* LCD_CS_GPIO and LCD_DC_GPIO Periph clock enable */
+  LCD_CS_GPIO_CLK_ENABLE();
+  LCD_DC_GPIO_CLK_ENABLE();
+  
+  /* Configure LCD_CS_PIN pin: LCD Card CS pin */
+  GPIO_InitStruct.Pin = LCD_CS_PIN;
+  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+  GPIO_InitStruct.Pull = GPIO_NOPULL;
+  GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
+  HAL_GPIO_Init(SD_CS_GPIO_PORT, &GPIO_InitStruct);
+
+  /* Configure LCD_DC_PIN pin: LCD Card DC pin */
+  GPIO_InitStruct.Pin = LCD_DC_PIN;
+  HAL_GPIO_Init(LCD_DC_GPIO_PORT, &GPIO_InitStruct);
+  
+  /* LCD chip select high */
+  LCD_CS_HIGH();
+  
+  /* LCD SPI Config */
+  SPIx_Init();
+}
+
+/**
+  * @brief  Writes command to select the LCD register.
+  * @param  LCDReg: Address of the selected register.
+  * @retval None
+  */
+void LCD_IO_WriteReg(uint8_t LCDReg)
+{
+  /* Reset LCD control line CS */
+  LCD_CS_LOW();
+  
+  /* Set LCD data/command line DC to Low */
+  LCD_DC_LOW();
+    
+  /* Send Command */
+  SPIx_Write(LCDReg);
+  
+  /* Deselect : Chip Select high */
+  LCD_CS_HIGH();
+}
+
+/**
+  * @brief  Writes data to select the LCD register.
+  *         This function must be used after st7735_WriteReg() function
+  * @param  Data: data to write to the selected register.
+  * @retval None
+  */
+void LCD_IO_WriteData(uint8_t Data)
+{
+  /* Reset LCD control line CS */
+  LCD_CS_LOW();
+  
+  /* Set LCD data/command line DC to High */
+  LCD_DC_HIGH();
+
+  /* Send Data */
+  SPIx_Write(Data);
+  
+  /* Deselect : Chip Select high */
+  LCD_CS_HIGH();
+}
+
+/**
+  * @brief  Wait for loop in ms.
+  * @param  Delay in ms.
+  * @retval None
+  */
+void LCD_Delay(uint32_t Delay)
+{
+  HAL_Delay(Delay);
+}
+
+/******************************* LINK JOYSTICK ********************************/
+/**
+  * @brief  Initializes ADC MSP.
+  * @param  None
+  * @retval None
+  */
+static void ADCx_MspInit(ADC_HandleTypeDef *hadc)
+{
+  GPIO_InitTypeDef  GPIO_InitStruct;
+  
+  /*** Configure the GPIOs ***/  
+  /* Enable GPIO clock */
+  NUCLEO_ADCx_GPIO_CLK_ENABLE();
+  
+  /* Configure the selected ADC Channel as analog input */
+  GPIO_InitStruct.Pin = NUCLEO_ADCx_GPIO_PIN ;
+  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+  GPIO_InitStruct.Pull = GPIO_NOPULL;
+  HAL_GPIO_Init(NUCLEO_ADCx_GPIO_PORT, &GPIO_InitStruct);
+  
+  /*** Configure the ADC peripheral ***/ 
+  /* Enable ADC clock */
+  NUCLEO_ADCx_CLK_ENABLE(); 
+}
+
+/**
+  * @brief  Initializes ADC HAL.
+  * @param  None
+  * @retval None
+  */
+static void ADCx_Init(void)
+{
+  if(HAL_ADC_GetState(&hnucleo_Adc) == HAL_ADC_STATE_RESET)
+  {
+    /* ADC Config */
+    hnucleo_Adc.Instance                   = NUCLEO_ADCx;
+    hnucleo_Adc.Init.ClockPrescaler        = ADC_CLOCKPRESCALER_PCLK_DIV4; /* (must not exceed 36MHz) */
+    hnucleo_Adc.Init.Resolution            = ADC_RESOLUTION12b;
+    hnucleo_Adc.Init.DataAlign             = ADC_DATAALIGN_RIGHT;
+    hnucleo_Adc.Init.ContinuousConvMode    = DISABLE;
+    hnucleo_Adc.Init.DiscontinuousConvMode = DISABLE;
+    hnucleo_Adc.Init.ExternalTrigConvEdge  = ADC_EXTERNALTRIGCONVEDGE_NONE;
+    hnucleo_Adc.Init.EOCSelection          = EOC_SINGLE_CONV;
+    hnucleo_Adc.Init.NbrOfConversion       = 1;
+    hnucleo_Adc.Init.DMAContinuousRequests = DISABLE;    
+    
+    ADCx_MspInit(&hnucleo_Adc);
+    HAL_ADC_Init(&hnucleo_Adc);
+  }
+}
+
+/**
+  * @brief  Configures joystick available on adafruit 1.8" TFT shield 
+  *         managed through ADC to detect motion.
+  * @param  None
+  * @retval Joystickstatus (0=> success, 1=> fail) 
+  */
+uint8_t BSP_JOY_Init(void)
+{
+  uint8_t status = 1;
+   
+  ADCx_Init();
+   
+  /* Select the ADC Channel to be converted */
+  sConfig.Channel = NUCLEO_ADCx_CHANNEL;
+  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
+  sConfig.Rank = 1;
+  status = HAL_ADC_ConfigChannel(&hnucleo_Adc, &sConfig);
+  
+  /* Return Joystick initialization status */
+  return status;
+}
+
+/**
+  * @brief  Returns the Joystick key pressed.
+  * @note   To know which Joystick key is pressed we need to detect the voltage
+  *         level on each key output
+  *           - None  : 3.3 V / 4095
+  *           - SEL   : 1.055 V / 1308
+  *           - DOWN  : 0.71 V / 88
+  *           - LEFT  : 3.0 V / 3720 
+  *           - RIGHT : 0.595 V / 737
+  *           - UP    : 1.65 V / 2046
+  * @retval JOYState_TypeDef: Code of the Joystick key pressed.
+  */
+JOYState_TypeDef BSP_JOY_GetState(void)
+{
+  JOYState_TypeDef state;
+  uint16_t  keyconvertedvalue = 0;
+  
+  /* Start the conversion process */
+  HAL_ADC_Start(&hnucleo_Adc);
+  
+  /* Wait for the end of conversion */
+  HAL_ADC_PollForConversion(&hnucleo_Adc, 10);
+  
+  /* Check if the continous conversion of regular channel is finished */
+  if(HAL_ADC_GetState(&hnucleo_Adc) == HAL_ADC_STATE_EOC_REG)
+  {
+    /* Get the converted value of regular channel */
+    keyconvertedvalue = HAL_ADC_GetValue(&hnucleo_Adc);
+  }
+  
+  if((keyconvertedvalue > 2010) && (keyconvertedvalue < 2090))
+  {
+    state = JOY_UP;
+  }
+  else if((keyconvertedvalue > 680) && (keyconvertedvalue < 780))
+  {
+    state = JOY_RIGHT;
+  }
+  else if((keyconvertedvalue > 1270) && (keyconvertedvalue < 1350))
+  {
+    state = JOY_SEL;
+  }
+  else if((keyconvertedvalue > 50) && (keyconvertedvalue < 130))
+  {
+    state = JOY_DOWN;
+  }
+  else if((keyconvertedvalue > 3680) && (keyconvertedvalue < 3760))
+  {
+    state = JOY_LEFT;
+  }
+  else
+  {
+    state = JOY_NONE;
+  }
+  
+  /* Loop while a key is pressed */
+  if(state != JOY_NONE)
+  { 
+    keyconvertedvalue = HAL_ADC_GetValue(&hnucleo_Adc);  
+  }
+  /* Return the code of the Joystick key pressed */
+  return state;
+}
+
+/**
+  * @}
+  */ 
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */    
+
+/**
+  * @}
+  */ 
+    
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+
diff -r f57d754b1814 -r 987b201ec4b1 src/stm32xx_it.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/stm32xx_it.c	Wed Apr 08 14:17:20 2015 +0000
@@ -0,0 +1,184 @@
+/**
+  ******************************************************************************
+  * @file    stm32xx_it.c 
+  * @author  CL
+  * @version V1.0.0
+  * @date    04-July-2014
+  * @brief   Main Interrupt Service Routines.
+  *          This file provides template for all exceptions handler and 
+  *          peripherals interrupt service routine.
+  ******************************************************************************
+  * @attention
+  *
+  * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
+  *
+  * 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 STMicroelectronics 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 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.
+  *
+  ******************************************************************************
+  */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32xx_it.h"
+#include "debug.h"
+
+/** @addtogroup STM32L0xx_HAL_Examples
+  * @{
+  */
+
+/** @addtogroup SPI_FullDuplex_ComIT
+  * @{
+  */
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+volatile uint8_t button_event = 0;
+
+/* SPI handler declared in "main.c" file */
+extern SPI_HandleTypeDef SpiHandle;
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+
+/******************************************************************************/
+/*            Cortex-M0+ Processor Exceptions Handlers                         */
+/******************************************************************************/
+
+/**
+  * @brief  NMI_Handler This function handles NMI exception.
+  * @param  None
+  * @retval None
+  */
+void NMI_Handler(void)
+{
+}
+
+/**
+  * @brief  HardFault_Handler This function handles Hard Fault exception.
+  * @param  None
+  * @retval None
+  */
+void HardFault_Handler(void)
+{
+  /* Go to infinite loop when Hard Fault exception occurs */
+  while (1)
+  {
+  }
+}
+
+/**
+  * @brief  SVC_Handler This function handles SVCall exception.
+  * @param  None
+  * @retval None
+  */
+void SVC_Handler(void)
+{
+}
+
+/**
+  * @brief  DebugMon_Handler This function handles Debug Monitor exception.
+  * @param  None
+  * @retval None
+  */
+void DebugMon_Handler(void)
+{
+}
+
+/**
+  * @brief  PendSV_Handler This function handles PendSVC exception.
+  * @param  None
+  * @retval None
+  */
+void PendSV_Handler(void)
+{
+}
+
+/**
+  * @brief  SysTick_Handler This function handles SysTick Handler.
+  * @param  None
+  * @retval None
+  */
+void SysTick_Handler(void)
+{
+  HAL_IncTick();
+}
+
+
+/******************************************************************************/
+/*                 STM32L0xx Peripherals Interrupt Handlers                   */
+/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
+/*  available peripheral interrupt handler's name please refer to the startup */
+/*  file (startup_stm32l0xx.s).                                               */
+/******************************************************************************/
+
+/**
+  * @brief  BNRG_SPI_EXTI_IRQHandler This function handles External line
+  *         interrupt request for BlueNRG.
+  * @param  None
+  * @retval None
+  */
+void BNRG_SPI_EXTI_IRQHandler(void)
+{
+  HAL_GPIO_EXTI_IRQHandler(BNRG_SPI_EXTI_PIN);
+}
+
+
+/**
+  * @brief  EXTI4_15_IRQHandler This function handles External lines 4 to 15 interrupt request.
+  * @param  None
+  * @retval None
+  */
+void PUSH_BUTTON_EXTI_IRQHandler(void)
+{
+  HAL_GPIO_EXTI_IRQHandler(KEY_BUTTON_PIN);
+  
+  button_event = 1;
+}
+
+/******************************************************************************/
+/*                 STM32L0xx Peripherals Interrupt Handlers                   */
+/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
+/*  available peripheral interrupt handler's name please refer to the startup */
+/*  file (startup_stm32l0xx.s).                                               */
+/******************************************************************************/
+
+/**
+  * @brief  This function handles PPP interrupt request.
+  * @param  None
+  * @retval None
+  */
+/*void PPP_IRQHandler(void)
+{
+}*/
+
+
+/**
+  * @}
+  */ 
+
+/**
+  * @}
+  */
+
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
+