#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include "nvs.h"
#include "nvs_flash.h"
#include "esp_bt.h"
#include "esp_gap_ble_api.h"
#include "esp_gattc_api.h"
#include "esp_gatt_defs.h"
#include "esp_bt_main.h"
#include "esp_gatt_common_api.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"


/*				+++++BLUETOOTH CONFIGURATION DEFINITION+++++				*/
#define GENERIC_ACCESS_UUID		           	0x1800    									// device name, appearance, peripheral preferred connection parameters
#define GENERIC_ATTRIBUTE_UUID         		0x1801    									// generic attribute
#define DEVICE_INFO_UUID	       			ESP_GATT_UUID_DEVICE_INFO_SVC    			// PNP ID (Vid & Pid)
#define REMOTE_SERVICE_UUID   				ESP_GATT_UUID_HID_SVC
#define BATTERY_SERVICE_UUID				ESP_GATT_UUID_BATTERY_SERVICE_SVC
#define PROFILE_NUM 						2
#define HID_PROFILE 						0
#define BATTERY_PROFILE						1
#define INVALID_HANDLE   					0


///Declare static functions
static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param, int idx);




static bool connect_ble = false;
static bool get_service = false;
static const char remote_device_name[] = "BLE_RMC";
//static const char remote_device_name[] = "Battery";

static esp_ble_scan_params_t ble_scan_params = {
    .scan_type              = BLE_SCAN_TYPE_ACTIVE,
    .own_addr_type          = BLE_ADDR_TYPE_PUBLIC,
    .scan_filter_policy     = BLE_SCAN_FILTER_ALLOW_ALL,
    .scan_interval          = 0x0060,
    .scan_window            = 0x0030,
    .scan_duplicate         = BLE_SCAN_DUPLICATE_DISABLE
};


struct gattc_profile_inst {
    esp_gattc_cb_t gattc_cb;
    uint16_t gattc_if;
    uint16_t app_id;
    uint16_t conn_id;
    uint16_t start_handle;
    uint16_t end_handle;
    uint16_t char_handle;
    esp_bd_addr_t remote_bda;
} gattc_profile_t;


// This is the GATT Client callback handler for the HID service
static void gattc_hid_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
  ESP_LOGI(TAG_BLUETOOTH,"****HID Profile Event****");
  gattc_profile_event_handler(event, gattc_if, param, HID_PROFILE);
}

// This is the GATT Client callback handler for the Battery service
static void gattc_battery_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
  ESP_LOGI(TAG_BLUETOOTH, "****Battery Profile Event****");
  gattc_profile_event_handler(event, gattc_if, param, BATTERY_PROFILE);
}



/* One gatt-based profile one app_id and one gattc_if, this array will store the gattc_if returned by ESP_GATTS_REG_EVT */
static struct gattc_profile_inst profiles[PROFILE_NUM] = {
    [HID_PROFILE] = {
        .gattc_cb = gattc_hid_event_handler,
        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    },
	[BATTERY_PROFILE] = {
	        .gattc_cb = gattc_battery_event_handler,
	        .gattc_if = ESP_GATT_IF_NONE,       /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
	},

};


static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param, int idx)
{
	uint16_t conn_id = 0;
    esp_ble_gattc_cb_param_t *p_data = (esp_ble_gattc_cb_param_t *)param;

    switch (event) {

    case ESP_GATTC_REG_EVT:
        ESP_LOGI(TAG_BLUETOOTH, "REG_EVT");
        esp_ble_gap_config_local_privacy(true);
        break;

    case ESP_GATTC_OPEN_EVT:
        if (param->open.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH, "open failed, error status = %x", p_data->open.status);
            break;
        }
        ESP_LOGI(TAG_BLUETOOTH, "open success");

        conn_id = p_data->open.conn_id;
        memcpy(profiles[HID_PROFILE].remote_bda,     p_data->open.remote_bda, sizeof(esp_bd_addr_t));
        memcpy(profiles[BATTERY_PROFILE].remote_bda, p_data->open.remote_bda, sizeof(esp_bd_addr_t));

        ESP_LOGI(TAG_BLUETOOTH, "REMOTE BDA: HID");
        esp_log_buffer_hex(TAG_BLUETOOTH, profiles[HID_PROFILE].remote_bda, sizeof(esp_bd_addr_t));

        ESP_LOGI(TAG_BLUETOOTH, "REMOTE BDA: BATTERY");
        esp_log_buffer_hex(TAG_BLUETOOTH, profiles[BATTERY_PROFILE].remote_bda, sizeof(esp_bd_addr_t));

        printf(" gattc_if: %d, conn_id: %d\n", gattc_if, conn_id);
        printf("Battery service gattc_if: %d, conn_id: %d\n", profiles[BATTERY_PROFILE].gattc_if, conn_id);


        if (profiles[HID_PROFILE].gattc_if == gattc_if)
		{
		// last parameter NULL -> find all services, UUID of a service -> find only that service
		esp_ble_gattc_search_service(profiles[HID_PROFILE].gattc_if, conn_id, NULL);
		}
		else if (profiles[BATTERY_PROFILE].gattc_if == gattc_if)
		{
		esp_ble_gattc_search_service(profiles[BATTERY_PROFILE].gattc_if, conn_id, NULL);
		}

        profiles[HID_PROFILE].conn_id      = conn_id;
        profiles[BATTERY_PROFILE].conn_id  = conn_id;

        break;

    case ESP_GATTC_CFG_MTU_EVT:
        if (param->cfg_mtu.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH,"config mtu failed, error status = %x", param->cfg_mtu.status);
        }
        ESP_LOGI(TAG_BLUETOOTH, "ESP_GATTC_CFG_MTU_EVT, Status %d, MTU %d, conn_id %d", param->cfg_mtu.status, param->cfg_mtu.mtu, param->cfg_mtu.conn_id);
//        esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, &remote_filter_service_uuid);
        esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, NULL);
        break;

/* this event occurs when GATT service discovery result happens
 * this event occurs once for each service discovered */
    case ESP_GATTC_SEARCH_RES_EVT: {

        ESP_LOGI(TAG_BLUETOOTH, "SEARCH RES: conn_id = %x is primary service %d", p_data->search_res.conn_id, p_data->search_res.is_primary);
        ESP_LOGI(TAG_BLUETOOTH, "start handle %d end handle %d current handle value %d", p_data->search_res.start_handle, p_data->search_res.end_handle, p_data->search_res.srvc_id.inst_id);

        esp_gatt_srvc_id_t *srvc_id = (esp_gatt_srvc_id_t *)&p_data->search_res.srvc_id;
        conn_id = p_data->search_res.conn_id;

        // see if the remote device has the services we are interested in
        if (srvc_id->id.uuid.len == ESP_UUID_LEN_16)
        {
        	switch (srvc_id->id.uuid.uuid.uuid16)
        	{
        		case ESP_GATT_UUID_HID_SVC:
        		{
        			ESP_LOGI(TAG_BLUETOOTH, "HID SERVICE FOUND");
        			// save the start and end handles for the service's characteristics
        			profiles[HID_PROFILE].start_handle = p_data->search_res.start_handle;
        			profiles[HID_PROFILE].end_handle   = p_data->search_res.end_handle;
        			printf("HID handles: %d - %d\n", p_data->search_res.start_handle, p_data->search_res.end_handle);
        			break;
        		}
        		case ESP_GATT_UUID_BATTERY_SERVICE_SVC:
        		{
        			ESP_LOGI(TAG_BLUETOOTH, "BATTERY SERVICE FOUND");
        			// save the start and end handles for the service's characteristics
					profiles[BATTERY_PROFILE].start_handle = p_data->search_res.start_handle;
					profiles[BATTERY_PROFILE].end_handle   = p_data->search_res.end_handle;
					printf("Battery handles: %d - %d\n", p_data->search_res.start_handle, p_data->search_res.end_handle);
					break;
        		}
        		default:
        			printf("Service UUID: %X found\n", srvc_id->id.uuid.uuid.uuid16);
        			break;
        	}
        }

        break;
    }


    // this event occurs when GATT service discovery is completed
    case ESP_GATTC_SEARCH_CMPL_EVT:
    {
    	ESP_LOGI(TAG_BLUETOOTH, "ESP_GATTC_SEARCH_CMPL_EVT");
        if (p_data->search_cmpl.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH, "search service failed, error status = %x", p_data->search_cmpl.status);
            break;
        }

        // store connection id for later usage
        conn_id = p_data->search_cmpl.conn_id;

        esp_gattc_char_elem_t *char_elements;
		uint16_t char_offset = 0;
		uint16_t count = 0;

		// we need to do this for each service we are using
		esp_gatt_status_t status = esp_ble_gattc_get_attr_count(profiles[HID_PROFILE].gattc_if,
			                                       profiles[HID_PROFILE].conn_id,
			                                       ESP_GATT_DB_CHARACTERISTIC,
												   profiles[HID_PROFILE].start_handle,
												   profiles[HID_PROFILE].end_handle,
			                                       ESP_GATT_INVALID_HANDLE,
			                                       &count);
    	if (status != ESP_GATT_OK)
    	{
    		ESP_LOGE(TAG_BLUETOOTH, "esp_ble_gattc_get_attr_count error, %d", __LINE__);
        }
    	if (count > 0)
    	{
    		char_elements = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
    		status = esp_ble_gattc_get_all_char(profiles[HID_PROFILE].gattc_if,
    											profiles[HID_PROFILE].conn_id,
												profiles[HID_PROFILE].start_handle,
												profiles[HID_PROFILE].end_handle,
    		                                    char_elements, &count, char_offset);
    		for (int i = 0; i < count; i++)
    		{
    			printf("%d) char uuid = %x, char_handle = %d\n", i, char_elements[i].uuid.uuid.uuid16, char_elements[i].char_handle);
    			profiles[HID_PROFILE].char_handle = char_elements[i].char_handle;
    			if ((ESP_GATT_UUID_HID_REPORT == char_elements[i].uuid.uuid.uuid16) && (char_elements[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY))
    			{
    				printf("Register for notification:: HID\n");
    				esp_ble_gattc_register_for_notify (gattc_if, profiles[HID_PROFILE].remote_bda, char_elements[i].char_handle);
    			}
    		}

//    		free(char_elements);
    	}else{
    		printf("No characteristics found in hid profile\n");
    	}



    	// we need to do this for each service we are using
		status = esp_ble_gattc_get_attr_count(profiles[BATTERY_PROFILE].gattc_if,
												   profiles[BATTERY_PROFILE].conn_id,
												   ESP_GATT_DB_CHARACTERISTIC,
												   profiles[BATTERY_PROFILE].start_handle,
												   profiles[BATTERY_PROFILE].end_handle,
												   ESP_GATT_INVALID_HANDLE,
												   &count);
		if (status != ESP_GATT_OK)
		{
			ESP_LOGE(TAG_BLUETOOTH, "esp_ble_gattc_get_attr_count error, %d", __LINE__);
		}
		if (count > 0)
		{
			char_elements = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
			status = esp_ble_gattc_get_all_char(profiles[BATTERY_PROFILE].gattc_if,
												profiles[BATTERY_PROFILE].conn_id,
												profiles[BATTERY_PROFILE].start_handle,
												profiles[BATTERY_PROFILE].end_handle,
												char_elements, &count, char_offset);
			for (int i = 0; i < count; i++)
			{
				printf("%d) char uuid = %x, char_handle = %d\n", i, char_elements[i].uuid.uuid.uuid16, char_elements[i].char_handle);
				profiles[BATTERY_PROFILE].char_handle = char_elements[i].char_handle;
				if ((ESP_GATT_UUID_BATTERY_LEVEL == char_elements[i].uuid.uuid.uuid16) && (char_elements[i].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY))
				{
					printf("Register for notification:: BATTERY\n");
					esp_ble_gattc_register_for_notify (gattc_if, profiles[BATTERY_PROFILE].remote_bda, char_elements[i].char_handle);
				}
			}
			free(char_elements);
		}else{
    		printf("No characteristics found in battery profile\n");
    	}

        break;
    }


    case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
    	ESP_LOGI(TAG_BLUETOOTH,"");
    	ESP_LOGI(TAG_BLUETOOTH,"ESP_GATTC_REG_FOR_NOTIFY_EVT");
        if (p_data->reg_for_notify.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH, "reg for notify failed, error status = %x", p_data->reg_for_notify.status);
            break;
        }

        break;
    }
    case ESP_GATTC_NOTIFY_EVT:
    {
        ESP_LOGI(TAG_BLUETOOTH, "ESP_GATTC_NOTIFY_EVT, receive notify value:");
        esp_log_buffer_hex(TAG_BLUETOOTH, p_data->notify.value, p_data->notify.value_len);

        if(BATTERY_PROFILE)
        {
        	printf("Battery Data \n");
        	for (int i = 0; i < p_data->notify.value_len; i++)
        		printf("%02X ", p_data->notify.value[i]);
        	printf("\n ");
        }
        else if(HID_PROFILE)
        {
        	printf("HID Data \n");
        	for (int i = 0; i < p_data->notify.value_len; i++)
				printf("%02X ", p_data->notify.value[i]);
 
			printf(" \n");
        }


        break;
    }

    case ESP_GATTC_WRITE_DESCR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH, "write descr failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(TAG_BLUETOOTH, "write descr success");
        break;
    case ESP_GATTC_SRVC_CHG_EVT: {
        esp_bd_addr_t bda;
        memcpy(bda, p_data->srvc_chg.remote_bda, sizeof(esp_bd_addr_t));
        ESP_LOGI(TAG_BLUETOOTH, "ESP_GATTC_SRVC_CHG_EVT, bd_addr:");
        esp_log_buffer_hex(TAG_BLUETOOTH, bda, sizeof(esp_bd_addr_t));
        break;
    }
    case ESP_GATTC_WRITE_CHAR_EVT:
        if (p_data->write.status != ESP_GATT_OK){
            ESP_LOGE(TAG_BLUETOOTH, "write char failed, error status = %x", p_data->write.status);
            break;
        }
        ESP_LOGI(TAG_BLUETOOTH, "Write char success ");
        break;

    case ESP_GATTC_DISCONNECT_EVT:
        ESP_LOGI(TAG_BLUETOOTH, "ESP_GATTC_DISCONNECT_EVT, reason = 0x%x", p_data->disconnect.reason);
        connect_ble = false;
        get_service = false;
        break;
    default:
        printf("Unhandled GATT Profile Event: %X\n", event);
        break;
    }
}

static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    uint8_t *adv_name = NULL;
    uint8_t adv_name_len = 0;
    switch (event) {

    case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT:
    	 ESP_LOGI(TAG_BLUETOOTH, "ESP GAP SET LOCAL PRIVACY");
        if (param->local_privacy_cmpl.status != ESP_BT_STATUS_SUCCESS){
            ESP_LOGE(TAG_BLUETOOTH, "config local privacy failed, error code =%x", param->local_privacy_cmpl.status);
            break;
        }
        esp_err_t scan_ret = esp_ble_gap_set_scan_params(&ble_scan_params);
        if (scan_ret){
            ESP_LOGE(TAG_BLUETOOTH, "set scan params error, error code = %x", scan_ret);
        }
        break;

    case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
    {
    	ESP_LOGI(TAG_BLUETOOTH,"ESP GAP BLE SCAN  PARAM SET COMLETE EVT");
        //the unit of the duration is second
        uint32_t duration = 90;
        esp_ble_gap_start_scanning(duration);
        break;
    }

    case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
    {
        //scan start complete event to indicate scan start successfully or failed
        if (param->scan_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
            ESP_LOGE(TAG_BLUETOOTH, "scan start failed, error status = %x", param->scan_start_cmpl.status);
            break;
        }
        ESP_LOGI(TAG_BLUETOOTH, "Scan start success");
        break;
    }
    case ESP_GAP_BLE_SCAN_RESULT_EVT: {
    	ESP_LOGI(TAG_BLUETOOTH, "ESP_GAP_BLE_SCAN_RESULT_EVT");
        esp_ble_gap_cb_param_t *scan_result = (esp_ble_gap_cb_param_t *)param;
        switch (scan_result->scan_rst.search_evt) {
        case ESP_GAP_SEARCH_INQ_RES_EVT:
        	printf("ESP_GAP_SEARCH_INQ_RES_EVT\n");
            esp_log_buffer_hex(TAG_BLUETOOTH, scan_result->scan_rst.bda, 6);
            ESP_LOGI(TAG_BLUETOOTH, "Searched Adv Data Len %d, Scan Response Len %d", scan_result->scan_rst.adv_data_len, scan_result->scan_rst.scan_rsp_len);
            adv_name = esp_ble_resolve_adv_data(scan_result->scan_rst.ble_adv,
                                                ESP_BLE_AD_TYPE_NAME_CMPL, &adv_name_len);
            ESP_LOGI(TAG_BLUETOOTH, "Searched Device Name Len %d", adv_name_len);
            esp_log_buffer_char(TAG_BLUETOOTH, adv_name, adv_name_len);
            ESP_LOGI(TAG_BLUETOOTH, "\n");
            if (adv_name != NULL) {
                if (strlen(remote_device_name) == adv_name_len && strncmp((char *)adv_name, remote_device_name, adv_name_len) == 0) {
                    ESP_LOGI(TAG_BLUETOOTH, "searched device %s\n", remote_device_name);
                    if (connect_ble == false) {
                        connect_ble = true;
                        ESP_LOGI(TAG_BLUETOOTH, "connect to the remote device.");
                        esp_ble_gap_stop_scanning();
//                        esp_ble_gattc_open(profiles[HID_PROFILE].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, false);
                        esp_ble_gattc_open(profiles[HID_PROFILE].gattc_if, profiles[HID_PROFILE].remote_bda,scan_result->scan_rst.ble_addr_type, true);
                        ESP_LOGI(TAG_BLUETOOTH,"GATT Opening Battery service: %d\n", profiles[BATTERY_PROFILE].gattc_if);
//                        esp_ble_gattc_open(profiles[BATTERY_PROFILE].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, false);
                        esp_ble_gattc_open(profiles[BATTERY_PROFILE].gattc_if, profiles[BATTERY_PROFILE].remote_bda, scan_result->scan_rst.ble_addr_type, true);
                    }
                }
            }
            break;
        case ESP_GAP_SEARCH_INQ_CMPL_EVT:
        	printf("ESP_GAP_SEARCH_INQ_CMPL_EVT\n");
            break;
        default:
            break;
        }
        break;
    }

    case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
        if (param->scan_stop_cmpl.status != ESP_BT_STATUS_SUCCESS){
            ESP_LOGE(TAG_BLUETOOTH, "Scan stop failed, error status = %x", param->scan_stop_cmpl.status);
            break;
        }
        ESP_LOGI(TAG_BLUETOOTH, "Stop scan successfully");
        break;
    case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
    	printf("\nESP_GAP_BLE_ADV_STOP_COMPLETE_EVT\n");
    	if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS){
    		ESP_LOGE(TAG_BLUETOOTH,"Adv stop failed");
    	}
    	ESP_LOGI(TAG_BLUETOOTH, "Stop adv successfully");
    	break;

    default:
    	printf("Unhandled GAP event: %X\n", event);
        break;
    }
}


// This is the GATT event callback handler function. Handles GATTC events common
// to all services. Uses gattc_if parameter to decide which GATTC service
// handler to invoke.
static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
{
    ESP_LOGI(TAG_BLUETOOTH, "EVT %d, gattc if %d", event, gattc_if);

    /* If event is register event, store the gattc_if for each profile */
    if (event == ESP_GATTC_REG_EVT) {
        if (param->reg.status == ESP_GATT_OK) {
            // save gsttc_if value for the service profile selected by param->reg.app_id
        	profiles[param->reg.app_id].gattc_if = gattc_if;
//            gl_profile_tab[param->reg.app_id].gattc_if = gattc_if;

        } else {
            ESP_LOGI(TAG_BLUETOOTH, "Reg app failed, app_id %04x, status %d",
                    param->reg.app_id,
                    param->reg.status);
            return;
        }
    }

    /* If the gattc_if equal to profile A, call profile A cb handler,
     * so here call each profile's callback */
    do {
        int idx;
        for (idx = 0; idx < PROFILE_NUM; idx++) {
            if (gattc_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
                    gattc_if == profiles[idx].gattc_if) {
                if (profiles[idx].gattc_cb) {
                    profiles[idx].gattc_cb(event, gattc_if, param);
                }
            }
        }
    } while (0);
}

void bluetooth_remote_handler()
{

    ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));

    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
    nvs_error = esp_bt_controller_init(&bt_cfg);
    if (nvs_error) {
        ESP_LOGE(TAG_BLUETOOTH, "%s initialize controller failed: %s\n", __func__, esp_err_to_name(nvs_error));
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "Default config set");
    }

    nvs_error = esp_bt_controller_enable(ESP_BT_MODE_BLE);
    if (nvs_error) {
        ESP_LOGE(TAG_BLUETOOTH, "%s enable controller failed: %s\n", __func__, esp_err_to_name(nvs_error));
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "BLE enabled");
    }

    nvs_error = esp_bluedroid_init();
    if (nvs_error) {
        ESP_LOGE(TAG_BLUETOOTH, "%s init bluetooth failed: %s\n", __func__, esp_err_to_name(nvs_error));
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "bluedroid initalised");
    }

    nvs_error = esp_bluedroid_enable();
    if (nvs_error) {
        ESP_LOGE(TAG_BLUETOOTH, "%s enable bluetooth failed: %s\n", __func__, esp_err_to_name(nvs_error));
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "bluedroid enabled");
    }

    //register the  callback function to the gap module
    nvs_error = esp_ble_gap_register_callback(esp_gap_cb);
    if (nvs_error){
        ESP_LOGE(TAG_BLUETOOTH, "%s gap register error, error code = %x\n", __func__, nvs_error);
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "gap registered");
    }

    //register the callback function to the gattc module
    nvs_error = esp_ble_gattc_register_callback(esp_gattc_cb);
    if(nvs_error){
        ESP_LOGE(TAG_BLUETOOTH, "%s gattc register error, error code = %x\n", __func__, nvs_error);
        return;
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "gattc registered");
    }

    nvs_error = esp_ble_gattc_app_register(HID_PROFILE);
    if (nvs_error){
        ESP_LOGE(TAG_BLUETOOTH, "%s gattc app register error, error code = %x\n", __func__, nvs_error);
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "HID app registed");
    }

    nvs_error = esp_ble_gattc_app_register(BATTERY_PROFILE);
	if (nvs_error){
		ESP_LOGE(TAG_BLUETOOTH, "%s gattc app register error, error code = %x\n", __func__, nvs_error);
	}else{
    	ESP_LOGI(TAG_BLUETOOTH, "battery app registered");
    }

    nvs_error = esp_ble_gatt_set_local_mtu(200);
    if (nvs_error){
        ESP_LOGE(TAG_BLUETOOTH, "set local  MTU failed, error code = %x", nvs_error);
    }else{
    	ESP_LOGI(TAG_BLUETOOTH, "mtu set");
    }
}

void app_main()
{
    bluetooth_remote_handler();
}


