ble_error_t BlueNRGGattClient::launchServiceDiscovery(Gap::Handle_t                               connectionHandle,
                                                      ServiceDiscovery::ServiceCallback_t         sc,
                                                      ServiceDiscovery::CharacteristicCallback_t  cc,
                                                      const UUID                                 &matchingServiceUUID,
                                                      const UUID                                 &matchingCharacteristicUUIDIn)
{
  PRINTF("launchServiceDiscovery\n\r");
  
  tBleStatus ret;
  uint8_t uuid_type = UUID_TYPE_16;
  uint8_t short_uuid[2];
  uint8_t *uuid = NULL;
  unsigned j;
  
  _connectionHandle = connectionHandle;
  serviceDiscoveryCallback = sc;
  characteristicDiscoveryCallback = cc;
  _matchingServiceUUID = matchingServiceUUID;
  _matchingCharacteristicUUIDIn = matchingCharacteristicUUIDIn;

  //reset services
  _numServices = 0;
  _numChars = 0;
  _servIndex = 0;
  for(j = 0; j < BLE_TOTAL_DISCOVERED_SERVICES; j++) {
    discoveredService[j].setup(BLE_UUID_UNKNOWN, GattAttribute::INVALID_HANDLE, GattAttribute::INVALID_HANDLE);
  }
  
  if(matchingServiceUUID == BLE_UUID_UNKNOWN) {
    
    // Wildcard: search for all services
    ret = aci_gatt_disc_all_prim_services((uint16_t)connectionHandle);
    
  } else {
  
    uint8_t type = matchingServiceUUID.shortOrLong();
    //PRINTF("AddService(): Type:%d\n\r", type);
    
    if(type == UUID::UUID_TYPE_SHORT) {
      STORE_LE_16(short_uuid, matchingServiceUUID.getShortUUID());
      
      PRINTF("launchServiceDiscovery short_uuid=0x");
      for(j = 0; j < 2; j++) {
        PRINTF("%02X", short_uuid[j]);
      }
      PRINTF("\n\r");
      
      
      uuid_type = UUID_TYPE_16;
      uuid = short_uuid;
      
    } else if(type==UUID::UUID_TYPE_LONG) {

      uuid_type = UUID_TYPE_128;
      uuid = (unsigned char*)matchingServiceUUID.getBaseUUID();
      
      /*
      PRINTF("launchServiceDiscovery base_uuid=0x");
      for(j = 0; j < 16; j++) {
        PRINTF("%02X", uuid[j]);
      }
      PRINTF("\n\r");
      */
    }
    
    // search for specific service by UUID
    ret = aci_gatt_disc_prim_service_by_uuid((uint16_t)connectionHandle, uuid_type, uuid);
    //ret = aci_gatt_disc_all_prim_services((uint16_t)connectionHandle);
  }
    
  if(ret == BLE_STATUS_SUCCESS) {
    _currentState = GATT_SERVICE_DISCOVERY;
  }
  
  PRINTF("launchServiceDiscovery ret=%d\n\r", ret);
  
  return BLE_ERROR_NONE;
}
ble_error_t BlueNRGGattServer::addService(GattService &service)
{
    /* ToDo: Make sure we don't overflow the array, etc. */
    /* ToDo: Make sure this service UUID doesn't already exist (?) */
    /* ToDo: Basic validation */

    tBleStatus ret;
    uint8_t type;
    uint16_t short_uuid;
    uint8_t primary_short_uuid[2];
    uint8_t primary_base_uuid[16];
    uint8_t char_base_uuid[16];
    const uint8_t *base_uuid;
    const uint8_t *base_char_uuid;

    uint8_t charsCount = service.getCharacteristicCount();
    const uint8_t available_characteristics = BLE_TOTAL_CHARACTERISTICS - characteristicCount;

    // check that there is enough characteristics left in the
    // characteristic array.
    if (charsCount > available_characteristics) {
        PRINTF("charCount = %u and characteristicCount = %u\r\n", charsCount, available_characteristics);
        return BLE_ERROR_NO_MEM;
    }

    const uint16_t maxAttrRecords = computeAttributesRecord(service);

    type = (service.getUUID()).shortOrLong();
    PRINTF("AddService(): Type:%d\n\r", type);

    /* Add the service to the BlueNRG */
    short_uuid = (service.getUUID()).getShortUUID();
    STORE_LE_16(primary_short_uuid, short_uuid);

    if(type==UUID::UUID_TYPE_LONG) {
        base_uuid = (service.getUUID()).getBaseUUID();

        COPY_UUID_128(primary_base_uuid, base_uuid[15],base_uuid[14],primary_short_uuid[1],primary_short_uuid[0],base_uuid[11],base_uuid[10],base_uuid[9],base_uuid[8],base_uuid[7],base_uuid[6],base_uuid[5],base_uuid[4],base_uuid[3],base_uuid[2],base_uuid[1],base_uuid[0]);
    }

    ret = BLE_STATUS_SUCCESS;

    if(type==UUID::UUID_TYPE_SHORT) {
        ret = aci_gatt_add_serv(UUID_TYPE_16,
                                primary_short_uuid,
                                PRIMARY_SERVICE,
                                maxAttrRecords/*7*/,
                                &servHandle);
        PRINTF("aci_gatt_add_serv UUID_TYPE_SHORT ret=%d\n\r", ret);

    } else if(type==UUID::UUID_TYPE_LONG) {
        ret = aci_gatt_add_serv(UUID_TYPE_128,
                                primary_base_uuid,
                                PRIMARY_SERVICE,
                                maxAttrRecords/*7*/,
                                &servHandle);
        PRINTF("aci_gatt_add_serv UUID_TYPE_LONG ret=%d\n\r", ret);
    }

    switch (ret) {
        case BLE_STATUS_SUCCESS:
            break;

        case BLE_STATUS_INVALID_PARAMETER:
            return BLE_ERROR_INVALID_PARAM;

        case BLE_STATUS_OUT_OF_HANDLE:
        case BLE_STATUS_INSUFFICIENT_RESOURCES:
        case ERR_UNSPECIFIED_ERROR:
            return BLE_ERROR_NO_MEM;

        case BLE_STATUS_ERROR:
        default:
            return BLE_ERROR_INTERNAL_STACK_FAILURE;
    }



    service.setHandle(servHandle);
    //serviceHandleVector.push_back(servHandle);
    PRINTF("added servHandle handle =%u\n\r", servHandle);
    uint16_t bleCharacteristic;

    //iterate to include all characteristics
    for (uint8_t i = 0; i < charsCount; i++) {
        GattCharacteristic *p_char = service.getCharacteristic(i);
        uint16_t char_uuid = (p_char->getValueAttribute().getUUID()).getShortUUID();

        uint8_t int_8_uuid[2];
        STORE_LE_16(int_8_uuid, char_uuid);

        type = (p_char->getValueAttribute().getUUID()).shortOrLong();

        if(type==UUID::UUID_TYPE_LONG) {
            base_char_uuid = (p_char->getValueAttribute().getUUID()).getBaseUUID();
#ifdef DEBUG
            for(uint8_t j=0; j<16; j++) {
                PRINTF("base_char_uuid[%d] 0x%02x ", j, base_char_uuid[j]);
            }
            PRINTF("\n\r");
#endif
            COPY_UUID_128(char_base_uuid,base_char_uuid[15],base_char_uuid[14],int_8_uuid[1],int_8_uuid[0],base_char_uuid[11],base_char_uuid[10],base_char_uuid[9],base_char_uuid[8],base_char_uuid[7],base_char_uuid[6],base_char_uuid[5],base_char_uuid[4],base_char_uuid[3],base_char_uuid[2],base_char_uuid[1],base_char_uuid[0]);
        }

        PRINTF("Char Properties 0x%x\n\r", p_char->getProperties());
        /*
        * Gatt_Evt_Mask -> HardCoded (0)
        * Encryption_Key_Size -> Hardcoded (16)
        * isVariable (variable length value field) -> Hardcoded (1)
        */
        uint8_t Gatt_Evt_Mask = 0x0;

        if((p_char->getProperties() &
                    (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE|
                        GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE))) {
            PRINTF("Setting up Gatt GATT_NOTIFY_ATTRIBUTE_WRITE Mask\n\r");
            Gatt_Evt_Mask = Gatt_Evt_Mask | GATT_NOTIFY_ATTRIBUTE_WRITE  | GATT_NOTIFY_WRITE_REQ_AND_WAIT_FOR_APPL_RESP;
        }
        if((p_char->getProperties() &
                    (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ|
                        GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY| GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE))) {
            PRINTF("Setting up Gatt GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP Mask\n\r");
            Gatt_Evt_Mask = Gatt_Evt_Mask | GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP;
        }    //This will support also GATT_SERVER_ATTR_READ_WRITE since it will be covered by previous if() check.

        if(type==UUID::UUID_TYPE_SHORT) {
            ret =  aci_gatt_add_char(service.getHandle(),
                                     UUID_TYPE_16,
                                     int_8_uuid,
                                     p_char->getValueAttribute().getMaxLength() /*2*/ /*Value Length*/,
                                     p_char->getProperties(),
                                     ATTR_PERMISSION_NONE,
                                     Gatt_Evt_Mask /*Gatt_Evt_Mask*/,
                                     16 /*Encryption_Key_Size*/,
                                     1 /*isVariable*/,
                                     &bleCharacteristic);

            PRINTF("aci_gatt_add_char UUID_TYPE_16 props=%d MaxLength=%d ret=%d\n\r",
                    p_char->getProperties(), p_char->getValueAttribute().getMaxLength(), ret);

        } else if(type==UUID::UUID_TYPE_LONG) {
            ret =  aci_gatt_add_char(service.getHandle(),
                                     UUID_TYPE_128,
                                     char_base_uuid,
                                     p_char->getValueAttribute().getMaxLength() /*2*/ /*Value Length*/,
                                     p_char->getProperties(),
                                     ATTR_PERMISSION_NONE,
                                     Gatt_Evt_Mask /*Gatt_Evt_Mask*/,
                                     16 /*Encryption_Key_Size*/,
                                     1 /*isVariable*/,
                                     &bleCharacteristic);

            PRINTF("aci_gatt_add_char UUID_TYPE_128 props=%d MaxLength=%d ret=%d\n\r",
                    p_char->getProperties(), p_char->getValueAttribute().getMaxLength(), ret);
        }

        switch (ret) {
            case BLE_STATUS_SUCCESS:
                break;

            case ERR_UNSPECIFIED_ERROR:
            case BLE_STATUS_INSUFFICIENT_RESOURCES:
            case BLE_STATUS_OUT_OF_HANDLE:
                // TODO remove characteristics and the service previously added.
                // remove service in the stack by using: Aci_Gatt_Del_Service
                // remove characteristics in the stack by using: Aci_Gatt_Del_Char
                // update service counter
                // destroy registered characteristic and updat echaracteristic counter
                return BLE_ERROR_NO_MEM;

            case BLE_STATUS_INVALID_HANDLE:
            case BLE_STATUS_INVALID_PARAMETER:
            case BLE_STATUS_CHARAC_ALREADY_EXISTS:
            // TODO remove characteristics and the service previously added.
            // remove service in the stack by using: Aci_Gatt_Del_Service
            // remove characteristics in the stack by using: Aci_Gatt_Del_Char
            // update service counter
            // destroy registered characteristic and updat echaracteristic counter
                return BLE_ERROR_INVALID_PARAM;

            case BLE_STATUS_ERROR:
            default:
            // TODO remove characteristics and the service previously added.
            // remove service in the stack by using: Aci_Gatt_Del_Service
            // remove characteristics in the stack by using: Aci_Gatt_Del_Char
            // update service counter
            // destroy registered characteristic and updat echaracteristic counter
                return BLE_ERROR_INTERNAL_STACK_FAILURE;
        }

        bleCharHandleMap.insert(std::pair<uint16_t, uint16_t>(bleCharacteristic, servHandle));

        p_characteristics[characteristicCount++] = p_char;
        /* Set the characteristic value handle */
        p_char->getValueAttribute().setHandle(bleCharacteristic+BlueNRGGattServer::CHAR_VALUE_HANDLE);
        PRINTF("added bleCharacteristic (value handle =%u)\n\r", p_char->getValueAttribute().getHandle());

        if ((p_char->getValueAttribute().getValuePtr() != NULL) && (p_char->getValueAttribute().getLength() > 0)) {
            ble_error_t err = write(p_char->getValueAttribute().getHandle(),
                  p_char->getValueAttribute().getValuePtr(),
                  p_char->getValueAttribute().getLength(), false /* localOnly */);
            if (err) {
                PRINTF("ERROR HERE !!!!\r\n");
                return err;
            }
        }

        // add descriptors now
        uint16_t descHandle = 0;
        PRINTF("p_char->getDescriptorCount()=%d\n\r", p_char->getDescriptorCount());

        for(uint8_t descIndex=0; descIndex<p_char->getDescriptorCount(); descIndex++) {
            GattAttribute *descriptor = p_char->getDescriptor(descIndex);
            uint8_t desc_uuid[16] = { 0 };


            uint8_t desc_uuid_type = CHAR_DESC_TYPE_16_BIT;
            STORE_LE_16(desc_uuid, descriptor->getUUID().getShortUUID());

            if((descriptor->getUUID()).shortOrLong() == UUID::UUID_TYPE_LONG) {
                desc_uuid_type = CHAR_DESC_TYPE_128_BIT;
                const uint8_t* base_desc_uuid  = descriptor->getUUID().getBaseUUID();

                COPY_UUID_128(desc_uuid, base_desc_uuid[15], base_desc_uuid[14],base_desc_uuid[13],base_desc_uuid[12], base_desc_uuid[11], base_desc_uuid[10], base_desc_uuid[9], base_desc_uuid[8], base_desc_uuid[7], base_desc_uuid[6], base_desc_uuid[5], base_desc_uuid[4], base_desc_uuid[3], base_desc_uuid[2], base_desc_uuid[1], base_desc_uuid[0]);
            }

            ret = aci_gatt_add_char_desc(service.getHandle(),
                                         bleCharacteristic,
                                         desc_uuid_type,
                                         desc_uuid,
                                         descriptor->getMaxLength(),
                                         descriptor->getLength(),
                                         descriptor->getValuePtr(),
                                         CHAR_DESC_SECURITY_PERMISSION,
                                         CHAR_DESC_ACCESS_PERMISSION,
                                         GATT_NOTIFY_ATTRIBUTE_WRITE,
                                         MIN_ENCRY_KEY_SIZE,
                                         CHAR_ATTRIBUTE_LEN_IS_FIXED,
                                         &descHandle);
            PRINTF("Adding Descriptor descriptor handle=%d ret=%d\n\r", descHandle, ret);

            switch (ret) {
                case BLE_STATUS_SUCCESS:
                    PRINTF("Descriptor added successfully, descriptor handle=%d\n\r", descHandle);
                    descriptor->setHandle(descHandle);
                    break;

                case ERR_UNSPECIFIED_ERROR:
                case BLE_STATUS_INSUFFICIENT_RESOURCES:
                case BLE_STATUS_OUT_OF_HANDLE:
                    // TODO remove characteristics and the service previously added.
                    // remove service in the stack by using: Aci_Gatt_Del_Service
                    // remove characteristics in the stack by using: Aci_Gatt_Del_Char
                    // update service counter
                    // destroy registered characteristic and updat echaracteristic counter
                    return BLE_ERROR_NO_MEM;

                case BLE_STATUS_INVALID_HANDLE:
                case BLE_STATUS_INVALID_PARAMETER:
                // TODO remove characteristics and the service previously added.
                // remove service in the stack by using: Aci_Gatt_Del_Service
                // remove characteristics in the stack by using: Aci_Gatt_Del_Char
                // update service counter
                // destroy registered characteristic and updat echaracteristic counter
                    return BLE_ERROR_INVALID_PARAM;

                case BLE_STATUS_INVALID_OPERATION:
                    return BLE_ERROR_OPERATION_NOT_PERMITTED;

                case BLE_STATUS_ERROR:
                default:
                // TODO remove characteristics and the service previously added.
                // remove service in the stack by using: Aci_Gatt_Del_Service
                // remove characteristics in the stack by using: Aci_Gatt_Del_Char
                // update service counter
                // destroy registered characteristic and updat echaracteristic counter
                    return BLE_ERROR_INTERNAL_STACK_FAILURE;
            }
        }
    }

    serviceCount++;

    //FIXME: There is no GattService pointer array in GattServer.
    //        There should be one? (Only the user is aware of GattServices!) Report to forum.

    return BLE_ERROR_NONE;
}
ble_error_t BlueNRGGattClient::findServiceChars(Gap::Handle_t connectionHandle)
{
  PRINTF("findServiceChars\n\r");
  
  tBleStatus ret;
  uint8_t uuid_type = UUID_TYPE_16;
  uint8_t short_uuid[2];
  uint8_t *uuid = NULL;
  
  DiscoveredService *service;
  
  // We finished chars discovery for all services
  if(_servIndex >= _numServices) {
    PRINTF("!!!We finished chars discovery for all services!!!\n\r");
    _currentState = GATT_CHARS_DISCOVERY_COMPLETE;
    
    terminateServiceDiscovery();
    
    return BLE_ERROR_NONE;
  }
    
  service = &discoveredService[_servIndex];
  /*
  if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
    PRINTF("S UUID-%X\r\n", service->getUUID().getShortUUID());
  } else {
    PRINTF("S UUID-");
    const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
    for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
      PRINTF("%02X", longUUIDBytes[i]);
    }
    PRINTF("\r\n");
  }
  */
  
  PRINTF("findServiceChars (_servIndex=%d)\n\r", _servIndex);
  //ret = aci_gatt_disc_all_charac_of_serv(connectionHandle, service->getStartHandle(), service->getEndHandle());

  if(_matchingCharacteristicUUIDIn == BLE_UUID_UNKNOWN) {
    PRINTF("findServiceChars (BLE_UUID_UNKNOWN)\n\r");
    ret = aci_gatt_disc_all_charac_of_serv(connectionHandle, service->getStartHandle(), service->getEndHandle());
  } else {
    
    uint8_t type = _matchingCharacteristicUUIDIn.shortOrLong();
    
    if(type == UUID::UUID_TYPE_SHORT) {
      STORE_LE_16(short_uuid, _matchingCharacteristicUUIDIn.getShortUUID());
      
      uuid_type = UUID_TYPE_16;
      uuid = short_uuid;
      
      PRINTF("findServiceChars C UUID-");
      for(unsigned i = 0; i < 2; i++) {
        PRINTF("%02X", short_uuid[i]);
      }
      PRINTF("\n\r");

    } else if(type==UUID::UUID_TYPE_LONG) {
      
      uuid_type = UUID_TYPE_128;
      uuid = (unsigned char*)_matchingCharacteristicUUIDIn.getBaseUUID();
      
      PRINTF("(findServiceChars) C UUID-");
      for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
        PRINTF("%02X", uuid[i]);
      }
      PRINTF("\r\n");
    }

    ret = aci_gatt_disc_charac_by_uuid(connectionHandle,
                                       service->getStartHandle(),
                                       service->getEndHandle(),
                                       uuid_type,
                                       uuid);
  }
  
  if(ret == BLE_STATUS_SUCCESS) {
    _servIndex++;
  }
  
  PRINTF("findServiceChars ret=%d\n\r", ret);
  
  return BLE_ERROR_NONE;
}
ble_error_t BlueNRGGattServer::addService(GattService &service)
{
    /* ToDo: Make sure we don't overflow the array, etc. */
    /* ToDo: Make sure this service UUID doesn't already exist (?) */
    /* ToDo: Basic validation */
    
    tBleStatus ret;
    uint8_t type;
    uint16_t short_uuid;
    uint8_t primary_short_uuid[2];
    uint8_t primary_base_uuid[16];
    uint8_t char_base_uuid[16];
    const uint8_t *base_uuid;
    const uint8_t *base_char_uuid;
    
    uint8_t charsCount = 0;
    uint8_t maxAttrRecords = 0;

    type = (service.getUUID()).shortOrLong();
    PRINTF("AddService(): Type:%d\n\r", type);
    
    /* Add the service to the BlueNRG */
    short_uuid = (service.getUUID()).getShortUUID();
    STORE_LE_16(primary_short_uuid, short_uuid);
    
    if(type==UUID::UUID_TYPE_LONG) {
        base_uuid = (service.getUUID()).getBaseUUID();   
        
        COPY_UUID_128(primary_base_uuid, base_uuid[15],base_uuid[14],primary_short_uuid[1],primary_short_uuid[0],base_uuid[11],base_uuid[10],base_uuid[9],base_uuid[8],base_uuid[7],base_uuid[6],base_uuid[5],base_uuid[4],base_uuid[3],base_uuid[2],base_uuid[1],base_uuid[0]);
    }

    charsCount = service.getCharacteristicCount();
    //1(service record)+2records*char+1record*char_desc
    maxAttrRecords = 1+3*charsCount;

    if(type==UUID::UUID_TYPE_SHORT) {
        ret = aci_gatt_add_serv(UUID_TYPE_16,
                                primary_short_uuid,
                                PRIMARY_SERVICE,
                                maxAttrRecords/*7*/,
                                &servHandle);
        PRINTF("aci_gatt_add_serv UUID_TYPE_LONG ret=%d\n\r", ret);
    }
    else if(type==UUID::UUID_TYPE_LONG) {
        ret = aci_gatt_add_serv(UUID_TYPE_128,
                                primary_base_uuid,
                                PRIMARY_SERVICE,
                                maxAttrRecords/*7*/,
                                &servHandle);
        PRINTF("aci_gatt_add_serv UUID_TYPE_LONG ret=%d\n\r", ret);
    }
    
    service.setHandle(servHandle);
    //serviceHandleVector.push_back(servHandle);
    PRINTF("added servHandle handle =%u\n\r", servHandle);
    uint16_t bleCharacteristic;
    
    //iterate to include all characteristics
    for (uint8_t i = 0; i < charsCount; i++) {
        GattCharacteristic *p_char = service.getCharacteristic(i);
        uint16_t char_uuid = (p_char->getValueAttribute().getUUID()).getShortUUID();   
        
        uint8_t int_8_uuid[2];
        STORE_LE_16(int_8_uuid, char_uuid);
        
        if(type==UUID::UUID_TYPE_LONG) {
            base_char_uuid = (p_char->getValueAttribute().getUUID()).getBaseUUID();
            
            COPY_UUID_128(char_base_uuid,base_char_uuid[15],base_char_uuid[14],int_8_uuid[1],int_8_uuid[0],base_char_uuid[11],base_char_uuid[10],base_char_uuid[9],base_char_uuid[8],base_char_uuid[7],base_char_uuid[6],base_char_uuid[5],base_char_uuid[4],base_char_uuid[3],base_char_uuid[2],base_char_uuid[1],base_char_uuid[0]);
        }
        
        PRINTF("Char Properties 0x%x\n\r", p_char->getProperties());
        /*
        * Gatt_Evt_Mask -> HardCoded (0)
        * Encryption_Key_Size -> Hardcoded (16)
        * isVariable (variable length value field) -> Hardcoded (1)
        */
        uint8_t Gatt_Evt_Mask = 0x0;

        if((p_char->getProperties() &
                    (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE|
                        GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE))) {
            PRINTF("Setting up Gatt GATT_NOTIFY_ATTRIBUTE_WRITE Mask\n\r");
            Gatt_Evt_Mask = Gatt_Evt_Mask | GATT_NOTIFY_ATTRIBUTE_WRITE;
        }
        if((p_char->getProperties() &
                    (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ|
                        GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY| GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE))) {
            PRINTF("Setting up Gatt GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP Mask\n\r");
            Gatt_Evt_Mask = Gatt_Evt_Mask | GATT_NOTIFY_READ_REQ_AND_WAIT_FOR_APPL_RESP; 
        }    //This will support also GATT_SERVER_ATTR_READ_WRITE since it will be covered by previous if() check.

        if(type==UUID::UUID_TYPE_SHORT) {
            ret =  aci_gatt_add_char(service.getHandle(),
                                     UUID_TYPE_16,
                                     int_8_uuid,
                                     p_char->getValueAttribute().getMaxLength() /*2*/ /*Value Length*/,
                                     p_char->getProperties(),
                                     ATTR_PERMISSION_NONE,
                                     Gatt_Evt_Mask /*Gatt_Evt_Mask*/,
                                     16 /*Encryption_Key_Size*/,
                                     1 /*isVariable*/,
                                     &bleCharacteristic);
            
            PRINTF("aci_gatt_add_char UUID_TYPE_16 props=%d MaxLength=%d ret=%d\n\r", p_char->getProperties(), p_char->getValueAttribute().getMaxLength(), ret);

        } else if(type==UUID::UUID_TYPE_LONG) {
            ret =  aci_gatt_add_char(service.getHandle(),
                                     UUID_TYPE_128,
                                     char_base_uuid,
                                     p_char->getValueAttribute().getMaxLength() /*2*/ /*Value Length*/,
                                     p_char->getProperties(),
                                     ATTR_PERMISSION_NONE,
                                     Gatt_Evt_Mask /*Gatt_Evt_Mask*/,
                                     16 /*Encryption_Key_Size*/,
                                     1 /*isVariable*/,
                                     &bleCharacteristic);
            
            PRINTF("aci_gatt_add_char UUID_TYPE_128 props=%d MaxLength=%d ret=%d\n\r", p_char->getProperties(), p_char->getValueAttribute().getMaxLength(), ret);
        }

        /* Update the characteristic handle */
        //uint16_t charHandle = characteristicCount;   
        
        bleCharHanldeMap.insert(std::pair<uint16_t, uint16_t>(bleCharacteristic, servHandle)); 
        
        p_characteristics[characteristicCount++] = p_char;
        p_char->getValueAttribute().setHandle(bleCharacteristic);    //Set the characteristic count as the corresponding char handle
        PRINTF("added bleCharacteristic handle =%u\n\r", bleCharacteristic);

        if ((p_char->getValueAttribute().getValuePtr() != NULL) && (p_char->getValueAttribute().getLength() > 0)) {
            write(p_char->getValueAttribute().getHandle(), p_char->getValueAttribute().getValuePtr(), p_char->getValueAttribute().getLength(), false /* localOnly */);
        }

        // add descriptors now
        uint16_t descHandle = 0;
        PRINTF("p_char->getDescriptorCount()=%d\n\r", p_char->getDescriptorCount());
        
        for(uint8_t descIndex=0; descIndex<p_char->getDescriptorCount(); descIndex++) {
            GattAttribute *descriptor = p_char->getDescriptor(descIndex);
            uint16_t shortUUID = descriptor->getUUID().getShortUUID();
            const uint8_t uuidArray[] = {(uint8_t)((shortUUID>>8)&0xFF), (uint8_t)((shortUUID&0xFF))};
            ret = aci_gatt_add_char_desc(service.getHandle(), p_char->getValueAttribute().getHandle(), 
            CHAR_DESC_TYPE_16_BIT, uuidArray, descriptor->getMaxLength(), descriptor->getLength(),
            descriptor->getValuePtr(), CHAR_DESC_SECURITY_PERMISSION, CHAR_DESC_ACCESS_PERMISSION, GATT_NOTIFY_ATTRIBUTE_WRITE,
            MIN_ENCRY_KEY_SIZE, CHAR_ATTRIBUTE_LEN_IS_FIXED, &descHandle);
            PRINTF("Adding Descriptor descriptor handle=%d ret=%d\n\r", descHandle, ret);
            if(ret==(tBleStatus)0) {
                PRINTF("Descriptor added successfully, descriptor handle=%d\n\r", descHandle);
                descriptor->setHandle(descHandle);
            }
        }

    }    
    
    serviceCount++;
    
    //FIXME: There is no GattService pointer array in GattServer. 
    //        There should be one? (Only the user is aware of GattServices!) Report to forum.
    
    return BLE_ERROR_NONE;
}