repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
tizenorg/platform.core.pim.contacts-service
|
src/cts-normalize.c
|
<reponame>tizenorg/platform.core.pim.contacts-service<filename>src/cts-normalize.c
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string.h>
#include "cts-internal.h"
#include "cts-normalize.h"
#include "cts-socket.h"
#include "cts-pthread.h"
#include "cts-utils.h"
static int (*extra_normalize_fn)(char dest[][CTS_SQL_MAX_LEN]);
static inline int check_utf8(char c)
{
if ((c & 0xff) < (128 & 0xff))
return 1;
else if ((c & (char)0xe0) == (char)0xc0)
return 2;
else if ((c & (char)0xf0) == (char)0xe0)
return 3;
else if ((c & (char)0xf8) == (char)0xf0)
return 4;
else if ((c & (char)0xfc) == (char)0xf8)
return 5;
else if ((c & (char)0xfe) == (char)0xfc)
return 6;
else
return CTS_ERR_FAIL;
}
static inline bool check_dirty_number(char digit)
{
switch (digit)
{
case '0' ... '9':
case 'p':
case 'w':
case 'P':
case 'W':
case '#':
case '*':
return false;
case '+': //only first position
default:
return true;
}
}
int cts_clean_number(const char *src, char *dest, int dest_size)
{
int s_pos=0, d_pos=0, char_type;
if (NULL == src)
ERR("The parameter(src) is NULL");
else
{
if ('+' == src[s_pos])
dest[d_pos++] = src[s_pos++];
while (src[s_pos] != 0)
{
if (d_pos >= dest_size-2) break;
char_type = check_utf8(src[s_pos]);
if (char_type <= 1) {
if (check_dirty_number(src[s_pos])) {
s_pos++;
continue;
}
dest[d_pos++] = src[s_pos++];
}
else
s_pos += char_type;
}
}
dest[d_pos] = 0;
return d_pos;
}
static int cts_remove_special_char(const char *src, char *dest, int dest_size)
{
int s_pos=0, d_pos=0, char_type, src_size;
if (NULL == src) {
ERR("The parameter(src) is NULL");
dest[d_pos] = '\0';
return 0;
}
src_size = strlen(src);
while (src[s_pos] != 0)
{
char_type = check_utf8(src[s_pos]);
if (0 < char_type && char_type < dest_size - d_pos && char_type <= src_size - s_pos) {
memcpy(dest+d_pos, src+s_pos, char_type);
d_pos += char_type;
s_pos += char_type;
}
else {
ERR("The parameter(src:%s) has invalid character set", src);
dest[d_pos] = '\0';
return CTS_ERR_ARG_INVALID;
}
}
dest[d_pos] = '\0';
return d_pos;
}
int cts_normalize_str(const char *src, char *dest, int dest_size)
{
int ret;
ret = cts_remove_special_char(src, dest, dest_size);
retvm_if(ret < CTS_SUCCESS, ret, "cts_remove_special_char() Failed(%d)", ret);
ret = CTS_SUCCESS;
cts_mutex_lock(CTS_MUTEX_SOCKET_FD);
ret = cts_request_normalize_str(dest, dest, dest_size);
cts_mutex_unlock(CTS_MUTEX_SOCKET_FD);
return ret;
}
void cts_set_extra_normalize_fn(int (*fn)(char dest[][CTS_SQL_MAX_LEN]))
{
extra_normalize_fn = fn;
}
int cts_normalize_name(cts_name *src,
char dest[][CTS_SQL_MAX_LEN], bool is_display)
{
int ret;
if (is_display) {
ret = cts_remove_special_char(src->display, dest[CTS_NN_FIRST],
sizeof(dest[CTS_NN_FIRST]));
warn_if(ret < CTS_SUCCESS, "cts_remove_special_char() Failed(%d)", ret);
snprintf(dest[CTS_NN_SORTKEY], sizeof(dest[CTS_NN_SORTKEY]), "%s", dest[CTS_NN_FIRST]);
ret = CTS_SUCCESS;
}
else {
ret = cts_remove_special_char(src->first, dest[CTS_NN_FIRST],
sizeof(dest[CTS_NN_FIRST]));
warn_if(ret < CTS_SUCCESS, "cts_remove_special_char() Failed(%d)", ret);
ret = CTS_SUCCESS;
ret = cts_remove_special_char(src->last, dest[CTS_NN_LAST],
sizeof(dest[CTS_NN_LAST]));
warn_if(ret < CTS_SUCCESS, "cts_remove_special_char() Failed(%d)", ret);
ret = CTS_SUCCESS;
if (!*dest[CTS_NN_LAST])
snprintf(dest[CTS_NN_SORTKEY], sizeof(dest[CTS_NN_SORTKEY]), "%s", dest[CTS_NN_FIRST]);
else if (!*dest[CTS_NN_FIRST])
snprintf(dest[CTS_NN_SORTKEY], sizeof(dest[CTS_NN_SORTKEY]), "%s", dest[CTS_NN_LAST]);
else if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
snprintf(dest[CTS_NN_SORTKEY], sizeof(dest[CTS_NN_SORTKEY]), "%s %s", dest[CTS_NN_FIRST], dest[CTS_NN_LAST]);
else
snprintf(dest[CTS_NN_SORTKEY], sizeof(dest[CTS_NN_SORTKEY]), "%s, %s", dest[CTS_NN_LAST], dest[CTS_NN_FIRST]);
}
if (extra_normalize_fn)
ret = extra_normalize_fn(dest);
else {
cts_mutex_lock(CTS_MUTEX_SOCKET_FD);
ret = cts_request_normalize_name(dest);
cts_mutex_unlock(CTS_MUTEX_SOCKET_FD);
}
return ret;
}
/**
* This function make searchable string.
* The string can use at contacts_svc_normalized_strstr().
*
* @param[in] src the string to convert
* @param[out] dest The pointer to get normalized string.
* @param[out] dest_len the size of dest.
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @par example
* @code
char normalized_str[512];
const char *name = "Test"
ret = contacts_svc_normalize_str(name, normalized_str, sizeof(normalized_str));
if(CTS_SUCCESS != ret)
printf("Error : contacts_svc_normalize_str() Failed(%d)", ret);
else
printf("original string is %s, normalized string is %s", name, normalized_str);
* @endcode
*/
API int contacts_svc_normalize_str(const char *src, char *dest, const int dest_len)
{
int ret;
retv_if(NULL == dest, CTS_ERR_ARG_NULL);
retvm_if(dest_len <= 0, CTS_ERR_ARG_INVALID, "dest_len(%d) is Invalid", dest_len);
ret = cts_normalize_str(src, dest, dest_len);
retvm_if(ret < CTS_SUCCESS, ret, "cts_normalize_str() Failed(%d)", ret);
return CTS_SUCCESS;
}
static inline bool is_choseong(const char *src)
{
unsigned short tmp;
tmp = (src[1] << 8) | src[2];
if (((char)0xE1 == src[0] && CTS_COMPARE_BETWEEN(0x8480, tmp, 0x859F)) /* korean -Hangul Jamo*/
|| ((char)0xEA == src[0] && CTS_COMPARE_BETWEEN(0xA5A0, tmp, 0xA5BC))) /* korean -Hangul Jamo extended A*/
{
return true;
}
return false;
}
static inline bool is_jungseong(const char *src)
{
unsigned short tmp;
tmp = (src[1] << 8) | src[2];
if (((char)0xE1 == src[0] && CTS_COMPARE_BETWEEN(0x85A0, tmp, 0x86A7))/* korean -Hangul Jamo*/
|| ((char)0xED == src[0] && CTS_COMPARE_BETWEEN(0x9EB0, tmp, 0x9F86)))/* korean -Hangul Jamo extended B */
{
return true;
}
return false;
}
static inline bool is_diacritical(const char *src)
{
unsigned short tmp;
if (!src || !*src || !*(src+1))
return false;
tmp = (src[0] << 8) | src[1];
if (CTS_COMPARE_BETWEEN(0xCC80, tmp, 0xCCBF)
|| CTS_COMPARE_BETWEEN(0xCD80, tmp, 0xCDAF))
{
return true;
}
return false;
}
static inline bool compare_unicode(const char *str1, const char *str2, int str2_len)
{
int k;
for (k=0; k<str2_len;k++)
if (!str1[k] || !str2[k] || str1[k] != str2[k])
return false;
return true;
}
/**
* This function compares compares two strings which must have been normalized already.
* If search_str is included in str, this function return #CTS_SUCCESS. \n
* The behavior of this function cannot fix because of localization.
* So, The behavior can be different from each other.
*
* @param[in] haystack Base string.
* @param[in] needle searching string
* @param[out] len substring length
* @return a position of the beginning of the substring, Negative value(#cts_error) on error or difference.
* @par example
* @code
ret = contacts_svc_compare_normalized_str(str1, str2, &len);
if(CTS_SUCCESS == ret) {
snprintf(first, ret+1, "%s", item_data->display);
snprintf(middle, len+1, "%s", item_data->display + ret);
printf("%s -> %s, %s, %s", item_data->display, first, middle, item_data->display + ret + len);
} else
printf("str1 doesn't has str2");
* @endcode
*/
API int contacts_svc_normalized_strstr(const char *haystack,
const char *needle, int *len)
{
int i, j, wind, h_len, n_len;
int first_needle_len;
int equal_index;
int equal_length;
int equal_wind = 0;
bool counted = false;
retvm_if(NULL == haystack, -1, "The parameter(haystack) is NULL");
retvm_if(NULL == needle, -1, "The parameter(needle) is NULL");
CTS_DBG("haystack = %s, needle = %s", haystack, needle);
h_len = 1;
n_len = 1;
equal_index = 0;
first_needle_len = check_utf8(needle[0]);
for (i=0, j=0;i<strlen(haystack);i = wind?wind:(i+h_len)) {
if (equal_wind) {
equal_index = equal_wind;
counted = false;
}
wind = 0;
equal_length = 0;
equal_wind = 0;
for (j=0;j<strlen(needle);) {
bool equal;
h_len = check_utf8(haystack[i]);
if (h_len == 1 && haystack[i] == 0x1) { //skip seperator
counted = false;
i+=h_len;
continue;
}
n_len = check_utf8(needle[j]);
if (n_len == 1 && needle[j] == 0x1) { //skip seperator
j++;
continue;
}
if (wind == 0 && j && 0 < i) {
if (h_len == first_needle_len && compare_unicode(&haystack[i], needle, first_needle_len)
&& !is_diacritical(&haystack[i])) {
unsigned short tmp;
tmp = (haystack[i+1] << 8) | haystack[i+2];
if (!counted) {
wind = i;
equal_wind = equal_index + equal_length;
}
}
}
if ((2 == h_len && is_diacritical(&haystack[i]))
&& (2 != n_len || !is_diacritical(&needle[j]))) {
if (j == 0) {
if (counted)
equal_index++;
else {
equal_index += h_len;
counted = true;
}
}
else if (!counted) {
equal_length += h_len;
counted = true;
}
else if (counted)
equal_length++;
i+=h_len;
continue;
}
if (h_len != n_len) {
if (!counted) {
equal_index += (equal_length + h_len);
counted = true;
}
break;
}
if (3 == n_len && is_choseong(&needle[j]) && !(is_choseong(&haystack[i]))) {
if (j < (n_len+1) || !is_choseong(&needle[j-n_len-1])) { // skip 강나 search by 가나
if (!counted) {
equal_index += (equal_length + h_len);
counted = true;
}
break;
}
else {
if (j == 0) {
if (!counted) {
equal_index += h_len;
counted = true;
}
}
else if (!counted) {
equal_length += h_len;
counted = true;
}
i+=h_len;
continue;
}
}
equal = compare_unicode(&haystack[i], &needle[j], n_len);
if (equal) {
if (!counted) {
equal_length += h_len;
counted = true;
}
else if (2 == n_len && is_diacritical(&needle[j]))
equal_length ++;
j += n_len;
i+=h_len;
continue;
}
else {
if (!counted) {
equal_index += (equal_length + h_len);
counted = true;
}
else {
if (2 == n_len && is_diacritical(&needle[j]))
equal_index += (equal_length + 1);
else
equal_index += equal_length;
}
break;
}
}
if ('\0' == needle[j]) {
if ('\0' != haystack[i]) {
h_len = check_utf8(haystack[i]);
if(h_len == 2 && is_diacritical(&haystack[i]))
equal_length++;
}
*len = equal_length;
return equal_index;
}
}
CTS_DBG("NOT match");
return -1;
}
static inline const char* cts_clean_country_code(const char *src)
{
int ret = 1;
switch (src[ret++]-'0')
{
case 1:
case 7:
break;
case 2:
switch (src[ret++]-'0')
{
case 0:
case 7:
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 8:
case 9:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 3:
switch (src[ret++]-'0')
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 6:
case 9:
break;
case 5:
case 7:
case 8:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 4:
switch (src[ret++]-'0')
{
case 0:
case 1:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
break;
case 2:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 5:
switch (src[ret++]-'0')
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 0:
case 9:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 6:
switch (src[ret++]-'0')
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
break;
case 7:
case 8:
case 9:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 8:
switch (src[ret++]-'0')
{
case 1:
case 2:
case 4:
case 6:
break;
case 0:
case 3:
case 5:
case 7:
case 8:
case 9:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 9:
switch (src[ret++]-'0')
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 8:
break;
case 6:
case 7:
case 9:
ret += 1;
break;
default:
ERR("The parameter(src:%s) has invalid character set", src);
}
break;
case 0:
default:
ERR("The parameter(src:%s) has invalid character set", src);
return src;
}
return &src[ret];
}
const char* cts_normalize_number(const char *src)
{
const char *normalized_number;
if ('+' == src[0])
normalized_number = cts_clean_country_code(src);
else if ('0' == src[0])
normalized_number = src+1;
else
normalized_number = src;
CTS_DBG("src = %s, normalized = %s", src, normalized_number);
return normalized_number;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/contact-test.c
|
<reponame>tizenorg/platform.core.pim.contacts-service
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <unistd.h>
#include <fcntl.h>
#include <contacts-svc.h>
static int insert_test(void)
{
CTSstruct *contact;
CTSvalue *name, *number1, *number2;
CTSvalue *nick, *event;
GSList *numbers, *nicknames, *events;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
CTSvalue *base = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO);
if (base) {
//contacts_svc_value_set_str(base, CTS_BASE_VAL_IMG_PATH_STR, "/opt/media/Images and videos/Wallpapers/Wallpaper3.jpg");
}
contacts_svc_struct_store_value(contact, CTS_CF_BASE_INFO_VALUE, base);
contacts_svc_value_free(base);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if (name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "gildong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Hong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_SUFFIX_STR, "engineer");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
numbers = NULL;
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "0987654321");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
number2 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number2) {
contacts_svc_value_set_str(number2, CTS_NUM_VAL_NUMBER_STR, "0123456789");
contacts_svc_value_set_int(number2, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_WORK|CTS_NUM_TYPE_VOICE);
}
numbers = g_slist_append(numbers, number2);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
contacts_svc_value_free(number2);
g_slist_free(numbers);
nicknames = NULL;
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "Samm");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
g_slist_free(nicknames);
nicknames = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &nicknames);
if (nicknames)
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "3star");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
//never free nicknames
events = NULL;
event = contacts_svc_value_new(CTS_VALUE_EVENT);
if (event) {
contacts_svc_value_set_int(event, CTS_EVENT_VAL_DATE_INT, 20110526);
contacts_svc_value_set_int(event, CTS_EVENT_VAL_TYPE_INT, CTS_EVENT_TYPE_BIRTH);
}
events = g_slist_append(events, event);
contacts_svc_struct_store_list(contact, CTS_CF_EVENT_LIST, events);
contacts_svc_value_free(event);
g_slist_free(events);
int ret = contacts_svc_insert_contact(0, contact);
contacts_svc_struct_free(contact);
return ret;
}
void delete_test(void)
{
//get contact
//CTSstruct *contact;
//contacts_svc_struct_get_value(contact, CTS_CF_INDEX_INT, &value);
//int index = contacts_svc_value_get_int(value, CTS_BASIC_VAL_INT);
contacts_svc_delete_contact(2);
//contacts_svc_struct_free(contact);
#if DELETE_CONTACTS
// TODO: get each index of contacts
int i, index_list[10] ={1,3,4,65,345,54,5,2,9,10};
int ret;
ret = contacts_svc_begin_trans();
if (CTS_SUCCESS != ret) return;
for (i=0;i<10;i++) {
ret = contacts_svc_delete_contact(index_list[i]);
if (CTS_SUCCESS != ret) {
contacts_svc_end_trans(false);
return;
}
}
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS){
printf("all work were rollbacked");
return;
}
#endif
}
void update_test()
{
int ret;
GSList *numbers, *cursor, *groupList, *nicknames;
CTSvalue *number=NULL, *name=NULL, *group = NULL, *company, *nick;
CTSstruct *contact=NULL;
ret = contacts_svc_get_contact(1, &contact);
if (ret < CTS_SUCCESS) return;
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &name);
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "Changed first");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Changed last");
contacts_svc_value_set_str(name, CTS_NAME_VAL_PREFIX_STR, "Changed prefix");
contacts_svc_value_set_str(name, CTS_NAME_VAL_SUFFIX_STR, NULL);
numbers = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &numbers);
cursor = numbers;
if (cursor) {
//char *temp = contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR);
contacts_svc_value_set_str(cursor->data, CTS_NUM_VAL_NUMBER_STR, "0987651234");
cursor = g_slist_next(cursor);
if (cursor)
contacts_svc_value_set_bool(cursor->data, CTS_NUM_VAL_DELETE_BOOL, true);
number = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number) {
contacts_svc_value_set_str(number, CTS_NUM_VAL_NUMBER_STR, "+82125439876");
contacts_svc_value_set_int(number, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_WORK|CTS_NUM_TYPE_FAX);
// contacts_svc_value_set_bool(number, CTS_NUM_VAL_DEFAULT_BOOL, true);
numbers = g_slist_append(numbers, number);
}
}
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number);
//free("+82125439876");
groupList = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_GROUPREL_LIST, &groupList);
cursor = groupList;
cursor=g_slist_next(groupList);
if (cursor)
contacts_svc_value_set_bool(cursor->data, CTS_GROUPREL_VAL_DELETE_BOOL, true);
group = contacts_svc_value_new(CTS_VALUE_GROUP_RELATION);
if (group) {
contacts_svc_value_set_int(group, CTS_GROUPREL_VAL_ID_INT, 2);
groupList = g_slist_append(groupList, group);
}
contacts_svc_struct_store_list(contact, CTS_CF_GROUPREL_LIST, groupList);
contacts_svc_value_free(group);
company = contacts_svc_value_new(CTS_VALUE_COMPANY);
if (company) {
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_NAME_STR, "Company");
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_DEPARTMENT_STR, "department");
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_JOB_TITLE_STR, "engineer");
}
contacts_svc_struct_store_value(contact, CTS_CF_COMPANY_VALUE, company);
nicknames = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &nicknames);
cursor = nicknames;
if (cursor) {
contacts_svc_value_set_bool(cursor->data, CTS_NICKNAME_VAL_DELETE_BOOL, true);
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick) {
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "good company");
nicknames = g_slist_append(nicknames, nick);
}
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
}
contacts_svc_update_contact(contact);
contacts_svc_struct_free(contact);
}
static void translation_type(int type, char *dest, int dest_size)
{
const char *type_str;
if (type & CTS_NUM_TYPE_CUSTOM)
{
char *custom;
custom = contacts_svc_get_custom_type(CTS_TYPE_CLASS_NUM, type);
if (NULL == custom)
type_str = "Other";
else {
snprintf(dest, dest_size, custom);
free(custom);
return;
}
}
else if (type & CTS_NUM_TYPE_CELL)
type_str = "Mobile";
else if (type & CTS_NUM_TYPE_VOICE)
{
if (type & CTS_NUM_TYPE_HOME)
type_str = "Home";
else if (type & CTS_NUM_TYPE_WORK)
type_str = "Work";
else
type_str = "Telephone";
}
else if (type & CTS_NUM_TYPE_FAX)
{
if (type & CTS_NUM_TYPE_HOME)
type_str = "Fax(home)";
else if (type & CTS_NUM_TYPE_WORK)
type_str = "Fax(work)";
else
type_str = "Fax";
}
else if (type & CTS_NUM_TYPE_PAGER)
type_str = "Pager";
else if (type & CTS_NUM_TYPE_CAR)
type_str = "Car Telephone";
else if (type & CTS_NUM_TYPE_ASSISTANT)
type_str = "Assistant";
else
type_str = "Other";
snprintf(dest, dest_size, type_str);
}
void get_contact(CTSstruct *contact)
{
int index=0, ret=-1;
CTSvalue *value=NULL;
GSList *get_list, *cursor;
if (!contact) {
index = contacts_svc_find_contact_by(CTS_FIND_BY_NUMBER, "125439876");
if (index > CTS_SUCCESS)
ret = contacts_svc_get_contact(index, &contact);
if (ret < 0)
{
printf("No found record\n");
return;
}
}
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
printf("Additional Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR));
printf("Display Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR));
printf("Prefix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR));
printf("Suffix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR));
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_COMPANY_VALUE, &value);
printf("Company Name : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_NAME_STR));
printf("Company Department : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR));
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
for (cursor=get_list;cursor;cursor=g_slist_next(cursor))
{
int type;
char type_str[100];
type = contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT);
translation_type(type, type_str, sizeof(type_str));
printf("number Type = %s ", type_str);
if (contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
if (index)
contacts_svc_set_favorite(CTS_FAVOR_NUMBER,
contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("email Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT));
printf("email = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_GROUPREL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("group = %s:",
contacts_svc_value_get_str(cursor->data, CTS_GROUPREL_VAL_NAME_STR));
printf("%d\n",
contacts_svc_value_get_int(cursor->data, CTS_GROUPREL_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
printf("nickname = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NICKNAME_VAL_NAME_STR));
if (index)
contacts_svc_struct_free(contact);
}
void get_contact_default_num(void)
{
int index, ret;
CTSvalue *number=NULL;
const char *default_num;
index = contacts_svc_find_contact_by(CTS_FIND_BY_NUMBER, "0125439876");
ret = contacts_svc_get_contact_value(CTS_GET_DEFAULT_NUMBER_VALUE, index, &number);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_contact_value() Failed(%d)\n", ret);
return;
}
default_num = contacts_svc_value_get_str(number, CTS_NUM_VAL_NUMBER_STR);
printf("The default Number is %s\n", default_num);
contacts_svc_value_free(number);
}
void get_contact_list(void)
{
CTSiter *iter = NULL;
printf("Phone contact NUM = %d\n",
contacts_svc_count_with_int(CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, 0));
contacts_svc_get_list(CTS_LIST_ALL_CONTACT, &iter);
//contacts_svc_get_list_with_int(CTS_LIST_MEMBERS_OF_ADDRESSBOOK_ID, 0, &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *contact = NULL;
const char *first, *last, *display;
contact = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(contact, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(contact);
}
contacts_svc_iter_remove(iter);
}
void sync_data(int ver)
{
int ret, index_num;
CTSiter *iter;
contacts_svc_get_updated_contacts(0, ver, &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSstruct *contact= NULL;
CTSvalue *row_info = NULL;
row_info = contacts_svc_iter_get_info(iter);
index_num = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT);
printf("(%8d)\n", index_num);
int type = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT);
int ver = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT);
if (CTS_OPERATION_UPDATED == type || CTS_OPERATION_INSERTED == type) {
contacts_svc_get_contact(index_num, &contact);
char *vcard_stream, *new_stream;
char file[128];
snprintf(file, sizeof(file), "test%d.vcf", index_num);
ret = contacts_svc_get_vcard_from_contact(contact, &vcard_stream);
new_stream = contacts_svc_vcard_put_content(vcard_stream, "X-TEST", "1234");
printf("%s\n", (char *)new_stream);
free(new_stream);
if (CTS_SUCCESS == ret) {
//int fd = open(file, O_RDWR | O_CREAT);
//write(fd, (char *)vcard_stream, strlen((char *)vcard_stream));
//close(fd);
CTSstruct *new_contact = NULL;
ret = contacts_svc_get_contact_from_vcard(vcard_stream, &new_contact);
if (CTS_SUCCESS == ret) {
get_contact(new_contact);
contacts_svc_struct_free(new_contact);
}
free(vcard_stream);
}
if (CTS_OPERATION_INSERTED == type)
printf("Added : %d \n", ver);
else
printf("Updated : %d \n", ver);
contacts_svc_struct_free(contact);
}
else
printf("Deleted : %d \n", ver);
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
void search_contacts_by_name(void)
{
int ret;
CTSiter *iter;
ret = contacts_svc_get_list_with_str(CTS_LIST_CONTACTS_WITH_NAME,
"ch", &iter);
if (CTS_SUCCESS != ret) return;
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *row_info = NULL;
const char *first, *last, *display;
row_info = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(row_info, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
void get_favorite_list(void)
{
CTSiter *iter;
contacts_svc_get_list(CTS_LIST_ALL_NUMBER_FAVORITE, &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
CTSvalue *favorite = NULL;
const char *first, *last, *display;
favorite = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(favorite, CTS_LIST_SHORTCUT_ID_INT));
printf(":%d", contacts_svc_value_get_int(favorite, CTS_LIST_SHORTCUT_CONTACT_ID_INT));
display = contacts_svc_value_get_str(favorite, CTS_LIST_SHORTCUT_DISPLAY_NAME_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(favorite, CTS_LIST_SHORTCUT_FIRST_NAME_STR);
last = contacts_svc_value_get_str(favorite, CTS_LIST_SHORTCUT_LAST_NAME_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(favorite, CTS_LIST_SHORTCUT_NUMBER_STR));
printf("(%d)", contacts_svc_value_get_int(favorite, CTS_LIST_SHORTCUT_NUMBER_TYPE_INT));
printf("-%d)", contacts_svc_value_get_int(favorite, CTS_LIST_SHORTCUT_SPEEDDIAL_INT));
printf("%s", contacts_svc_value_get_str(favorite, CTS_LIST_SHORTCUT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(favorite);
}
contacts_svc_iter_remove(iter);
}
void put_value_test()
{
CTSvalue *value, *number;
value = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO);
if (value) {
contacts_svc_value_set_str(value, CTS_BASE_VAL_RINGTONE_PATH_STR,
"/opt/test/test.mp3");
contacts_svc_put_contact_value(CTS_PUT_VAL_REPLACE_RINGTONE, 1, value);
contacts_svc_value_free(value);
}
number = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number) {
contacts_svc_value_set_str(number, CTS_NUM_VAL_NUMBER_STR, "0123337777");
contacts_svc_value_set_int(number, CTS_NUM_VAL_TYPE_INT, CTS_NUM_TYPE_CELL);
// contacts_svc_value_set_bool(number, CTS_NUM_VAL_DEFAULT_BOOL, true);
contacts_svc_put_contact_value(CTS_PUT_VAL_ADD_NUMBER, 1, number);
contacts_svc_value_free(number);
}
}
static void print_extend_contact(CTSstruct *contact)
{
int ret;
CTSvalue *value;
GSList *get_list, *cursor;
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
value = NULL;
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
ret = contacts_svc_struct_get_value(contact, ret, &value);
if (CTS_SUCCESS == ret) {
printf("extend1 data2 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA2_STR));
printf("extend1 data3 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA3_STR));
printf("extend1 data4 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA4_STR));
}
value = NULL;
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
ret = contacts_svc_struct_get_value(contact, ret, &value);
if (CTS_SUCCESS == ret) {
printf("extend2 data2 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA2_STR));
printf("extend2 data3 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA3_STR));
printf("extend2 data4 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA4_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
int type;
char type_str[100];
type = contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT);
translation_type(type, type_str, sizeof(type_str));
printf("number Type = %s", type_str);
if (contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
}
}
void extend_data_test(void)
{
int ret, index;
CTSstruct *contact;
CTSvalue *name, *number1, *extend_value;
GSList *numbers=NULL;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if (name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "People");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Japan");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "0333333333");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT, CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
g_slist_free(numbers);
extend_value = contacts_svc_value_new(CTS_VALUE_EXTEND);
if (extend_value) {
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "YomiFirstName");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA3_STR, "YomiLastName");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA4_STR, "YomiCompanyName");
}
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
if (CTS_ERR_DB_RECORD_NOT_FOUND == ret)
ret = contacts_svc_insert_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
contacts_svc_struct_store_value(contact, ret, extend_value);
contacts_svc_value_free(extend_value);
extend_value = contacts_svc_value_new(CTS_VALUE_EXTEND);
if (extend_value) {
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "Children1");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA3_STR, "Children2");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA4_STR, "Children3");
}
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
if (CTS_ERR_DB_RECORD_NOT_FOUND == ret)
ret = contacts_svc_insert_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
contacts_svc_struct_store_value(contact, ret, extend_value);
contacts_svc_value_free(extend_value);
index = contacts_svc_insert_contact(0, contact);
contacts_svc_struct_free(contact);
contact = NULL;
ret = contacts_svc_get_contact(index, &contact);
if (ret < 0)
{
printf("No found record\n");
return;
}
print_extend_contact(contact);
//update test
extend_value = NULL;
int type = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
ret = contacts_svc_struct_get_value(contact, type, &extend_value);
if (CTS_SUCCESS == ret)
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "Children4");
contacts_svc_struct_store_value(contact, type, extend_value);
contacts_svc_update_contact(contact);
contacts_svc_struct_free(contact);
contact = NULL;
ret = contacts_svc_get_contact(index, &contact);
if (ret < 0)
{
printf("No found record\n");
return;
}
print_extend_contact(contact);
contacts_svc_struct_free(contact);
}
void get_number_list(void)
{
CTSiter *iter;
contacts_svc_get_list_with_str(CTS_LIST_NUMBERINFOS_WITH_NUM, "123", &iter);
//contacts_svc_get_list_with_str(CTS_LIST_NUMBERINFOS_WITH_NAME, "kim", &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *contact = NULL;
const char *first, *last, *display;
contact = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(contact, CTS_LIST_NUM_CONTACT_ID_INT));
display = contacts_svc_value_get_str(contact, CTS_LIST_NUM_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(contact, CTS_LIST_NUM_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(contact, CTS_LIST_NUM_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(contact, CTS_LIST_NUM_CONTACT_IMG_PATH_STR));
printf("\n");
printf("%s\n", contacts_svc_value_get_str(contact, CTS_LIST_NUM_NUMBER_STR));
contacts_svc_value_free(contact);
}
contacts_svc_iter_remove(iter);
}
static int get_search_cb(CTSvalue *value, void *user_data)
{
const char *number, *img_path;
const char *first, *last, *display;
printf("(%8d)", contacts_svc_value_get_int(value, CTS_LIST_NUM_CONTACT_ID_INT));
display = contacts_svc_value_get_str(value, CTS_LIST_NUM_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(value, CTS_LIST_NUM_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(value, CTS_LIST_NUM_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
img_path = contacts_svc_value_get_str(value, CTS_LIST_NUM_CONTACT_IMG_PATH_STR);
if (img_path)
printf("%s\n", img_path);
else
printf("\n");
number = contacts_svc_value_get_str(value, CTS_LIST_NUM_NUMBER_STR);
if (number)
printf("%s\n", number);
return CTS_SUCCESS;
}
void get_search(void)
{
contacts_svc_smartsearch_excl("fir", 0, 0, get_search_cb, NULL);
}
static int get_list_with_filter_cb(CTSvalue *value, void *user_data)
{
const char *img_path;
const char *first, *last, *display;
printf("(%8d)", contacts_svc_value_get_int(value, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(value, CTS_LIST_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(value, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(value, CTS_LIST_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
img_path = contacts_svc_value_get_str(value, CTS_LIST_CONTACT_IMG_PATH_STR);
if (img_path)
printf("%s\n", img_path);
else
printf("\n");
return CTS_SUCCESS;
}
void get_list_with_filter(void)
{
int ret;
CTSfilter *filter;
filter = contacts_svc_list_str_filter_new(CTS_FILTERED_CONTACTS_WITH_NAME,
"kim", CTS_LIST_FILTER_ADDRESBOOK_ID_INT, 0, CTS_LIST_FILTER_NONE);
if (NULL == filter) {
printf("contacts_svc_list_str_filter_new() Failed\n");
return;
}
ret = contacts_svc_list_with_filter_foreach(filter, get_list_with_filter_cb, NULL);
if (CTS_SUCCESS != ret)
printf("contacts_svc_list_with_filter_foreach() Failed(%d)\n", ret);
contacts_svc_list_filter_free(filter);
}
int main()
{
int ret, ver;
contacts_svc_connect();
printf("\n##Insert##\n");
contacts_svc_begin_trans();
ret = insert_test();
if (CTS_SUCCESS < ret)
ver = contacts_svc_end_trans(true);
else
contacts_svc_end_trans(false);
printf("\n##Insert##\n");
insert_test();
sleep(2);
printf("\n##Update test##\n");
update_test();
put_value_test();
printf("\n##All Contact Information##\n");
get_contact(NULL);
printf("\n##Default Number##\n");
get_contact_default_num();
printf("\n##Contact List##\n");
get_contact_list();
printf("\n##Delete Test##\n");
delete_test();
printf("\n##Sync Test##\n");
sync_data(ver);
printf("\n##Search Name##\n");
search_contacts_by_name();
printf("\n##Favorite List##\n");
get_favorite_list();
printf("\n##Favorite 1 Delete##\n");
contacts_svc_delete_favorite(1);
get_favorite_list();
printf("\n##Extend Data insert##\n");
extend_data_test();
printf("\n##Number List##\n");
get_number_list();
printf("\n##search##\n");
get_search();
printf("\n##list_with_filter##\n");
get_list_with_filter();
contacts_svc_disconnect();
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/change-noti-test.c
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <glib.h>
#include <contacts-svc.h>
static void favorite_change_callback(void *data)
{
printf("Favorite data of contacts service is changed\n");
}
static void plog_change_callback(void *data)
{
printf("Phone log data of contacts service is changed\n");
}
static void contact_change_callback(void *data)
{
int ret;
static int latest_ver = 0;
CTSiter *iter;
printf("Contact data of contacts service is changed\n");
ret = contacts_svc_get_updated_contacts(0, latest_ver, &iter);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_updated_contacts() Failed(%d)", ret);
return;
}
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int index;
CTSvalue *row_info = NULL;
row_info = contacts_svc_iter_get_info(iter);
index = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT);
printf("(%8d) is ", index);
int type = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT);
int ver = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT);
if (CTS_OPERATION_INSERTED == type) {
printf("Inserted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_UPDATED == type) {
printf("Updated at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_DELETED == type) {
printf("Deleted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else {
printf("unknown type (%d)", type);
}
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
static void missed_call_change_callback(void *data)
{
printf("Missed Call is changed\n");
}
static void group_change_callback(void *data)
{
int ret;
static int latest_ver = 0;
CTSiter *iter;
printf("Group data of contacts service is changed\n");
ret = contacts_svc_get_updated_groups(0, latest_ver, &iter);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_updated_groups() Failed(%d)", ret);
return;
}
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int index;
CTSvalue *row_info = NULL;
row_info = contacts_svc_iter_get_info(iter);
index = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT);
printf("(%8d) is ", index);
int type = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT);
int ver = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT);
if (CTS_OPERATION_INSERTED == type) {
printf("Inserted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_UPDATED == type) {
printf("Updated at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_DELETED == type) {
printf("Deleted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else {
printf("unknown type (%d)", type);
}
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
static void group_rel_change_callback(void *data)
{
int ret;
static int latest_ver = 0;
CTSiter *iter;
printf("Group relation of contacts service is changed\n");
ret = contacts_svc_group_get_relation_changes(0, latest_ver, &iter);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_group_get_relation_changes() Failed(%d)", ret);
return;
}
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int index;
CTSvalue *row_info = NULL;
row_info = contacts_svc_iter_get_info(iter);
index = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT);
printf("(%8d) is ", index);
int type = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT);
int ver = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT);
if (CTS_OPERATION_INSERTED == type) {
printf("Inserted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_UPDATED == type) {
printf("Updated at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else if (CTS_OPERATION_DELETED == type) {
printf("Deleted at %d\n", ver);
if (latest_ver < ver) latest_ver = ver;
}
else {
printf("unknown type (%d)", type);
}
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
int main()
{
GMainLoop *loop;
contacts_svc_connect();
contacts_svc_subscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, contact_change_callback, NULL);
contacts_svc_subscribe_change(CTS_SUBSCRIBE_PLOG_CHANGE, plog_change_callback, NULL);
contacts_svc_subscribe_change(CTS_SUBSCRIBE_FAVORITE_CHANGE, favorite_change_callback, NULL);
contacts_svc_subscribe_change(CTS_SUBSCRIBE_MISSED_CALL_CHANGE, missed_call_change_callback, NULL);
contacts_svc_subscribe_change(CTS_SUBSCRIBE_GROUP_CHANGE, group_change_callback, NULL);
contacts_svc_subscribe_change(CTS_SUBSCRIBE_GROUP_RELATION_CHANGE, group_rel_change_callback, NULL);
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, contact_change_callback);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_PLOG_CHANGE, plog_change_callback);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_FAVORITE_CHANGE, favorite_change_callback);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_MISSED_CALL_CHANGE, missed_call_change_callback);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_GROUP_CHANGE, group_change_callback);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_GROUP_RELATION_CHANGE, group_rel_change_callback);
contacts_svc_disconnect();
g_main_loop_unref(loop);
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/restriction-test.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <fcntl.h>
#include <contacts-svc.h>
#include "test-log.h"
static int fb_insert(int is_facebook)
{
CTSstruct *contact;
CTSvalue *name, *number1, *number2;
CTSvalue *nick, *event;
GSList *numbers, *nicknames, *events;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
CTSvalue *base = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO);
if (base) {
//contacts_svc_value_set_str(base, CTS_BASE_VAL_IMG_PATH_STR, "/opt/media/Images and videos/Wallpapers/Wallpaper3.jpg");
}
contacts_svc_struct_store_value(contact, CTS_CF_BASE_INFO_VALUE, base);
contacts_svc_value_free(base);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if (name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "gildong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Hong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_SUFFIX_STR, "engineer");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
numbers = NULL;
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "0987654321");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
number2 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number2) {
contacts_svc_value_set_str(number2, CTS_NUM_VAL_NUMBER_STR, "0123456789");
contacts_svc_value_set_int(number2, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_WORK|CTS_NUM_TYPE_VOICE);
}
numbers = g_slist_append(numbers, number2);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
contacts_svc_value_free(number2);
g_slist_free(numbers);
nicknames = NULL;
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "Samm");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
g_slist_free(nicknames);
nicknames = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &nicknames);
if (nicknames)
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "3star");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
//never free nicknames
events = NULL;
event = contacts_svc_value_new(CTS_VALUE_EVENT);
if (event) {
contacts_svc_value_set_int(event, CTS_EVENT_VAL_DATE_INT, 20110526);
contacts_svc_value_set_int(event, CTS_EVENT_VAL_TYPE_INT, CTS_EVENT_TYPE_BIRTH);
}
events = g_slist_append(events, event);
contacts_svc_struct_store_list(contact, CTS_CF_EVENT_LIST, events);
contacts_svc_value_free(event);
g_slist_free(events);
if (is_facebook)
contacts_svc_struct_set_restriction(contact);
int ret = contacts_svc_insert_contact(0, contact);
contacts_svc_struct_free(contact);
return ret;
}
static inline void get_contact(int index)
{
int ret;
CTSvalue *value=NULL;
GSList *get_list, *cursor;
CTSstruct *contact;
ret = contacts_svc_get_contact(index, &contact);
if (ret < CTS_SUCCESS) {
ERR("No found record");
return;
}
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
INFO("First Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
INFO("Last Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
INFO("Additional Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR));
INFO("Display Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR));
INFO("Prefix Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR));
INFO("Suffix Name : %s", contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR));
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_COMPANY_VALUE, &value);
INFO("Company Name : %s", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_NAME_STR));
INFO("Company Department : %s", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR));
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
for (cursor=get_list;cursor;cursor=g_slist_next(cursor))
{
int type;
type = contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT);
if (contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
INFO("number Type = %d : %s(favorite)", type,
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
else
INFO("number Type = %d : %s", type,
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
INFO("email Type = %d : %s",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT),
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_GROUPREL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
INFO("group = %s:%d",
contacts_svc_value_get_str(cursor->data, CTS_GROUPREL_VAL_NAME_STR),
contacts_svc_value_get_int(cursor->data, CTS_GROUPREL_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
INFO("nickname = %s",
contacts_svc_value_get_str(cursor->data, CTS_NICKNAME_VAL_NAME_STR));
contacts_svc_struct_free(contact);
}
static inline void get_contact_list(void)
{
CTSiter *iter = NULL;
INFO("Phone contact NUM = %d", contacts_svc_count(CTS_GET_ALL_CONTACT));
contacts_svc_get_list(CTS_LIST_ALL_CONTACT, &iter);
//contacts_svc_get_list_with_int(CTS_LIST_MEMBERS_OF_ADDRESSBOOK_ID, 0, &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
int index;
CTSvalue *contact = NULL;
const char *first, *last, *display, *img;
contact = contacts_svc_iter_get_info(iter);
index = contacts_svc_value_get_int(contact, CTS_LIST_CONTACT_ID_INT);
img = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_IMG_PATH_STR);
display = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_DISPLAY_STR);
if (display)
INFO("(%8d)%s : %s", index, display, img);
else
{
first = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
INFO("(%8d)%s %s : %s", index, first, last, img);
else
INFO("(%8d)%s %s : %s", index, last, first, img);
}
contacts_svc_value_free(contact);
}
contacts_svc_iter_remove(iter);
}
int main()
{
int id;
contacts_svc_connect();
id = fb_insert(1);
fb_insert(0);
get_contact(1);
get_contact_list();
contacts_svc_disconnect();
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/myprofile-test.c
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <contacts-svc.h>
static int insert_my_test(void)
{
CTSstruct *contact;
CTSvalue *name, *number1, *number2;
CTSvalue *nick, *event, *company;
GSList *numbers, *nicknames, *events;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
CTSvalue *base = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO);
if (base) {
//contacts_svc_value_set_str(base, CTS_BASE_VAL_IMG_PATH_STR, "/opt/media/Images and videos/Wallpapers/Wallpaper3.jpg");
}
contacts_svc_struct_store_value(contact, CTS_CF_BASE_INFO_VALUE, base);
contacts_svc_value_free(base);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if (name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "MY");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "NAME");
contacts_svc_value_set_str(name, CTS_NAME_VAL_SUFFIX_STR, "TEST");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
numbers = NULL;
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "7777777");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
number2 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number2) {
contacts_svc_value_set_str(number2, CTS_NUM_VAL_NUMBER_STR, "3333333");
contacts_svc_value_set_int(number2, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_WORK|CTS_NUM_TYPE_VOICE);
}
numbers = g_slist_append(numbers, number2);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
contacts_svc_value_free(number2);
g_slist_free(numbers);
nicknames = NULL;
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "MYnickname");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
g_slist_free(nicknames);
nicknames = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &nicknames);
if (nicknames)
nick = contacts_svc_value_new(CTS_VALUE_NICKNAME);
if (nick)
contacts_svc_value_set_str(nick, CTS_NICKNAME_VAL_NAME_STR, "MYnickname2");
nicknames = g_slist_append(nicknames, nick);
contacts_svc_struct_store_list(contact, CTS_CF_NICKNAME_LIST, nicknames);
contacts_svc_value_free(nick);
//never free nicknames
events = NULL;
event = contacts_svc_value_new(CTS_VALUE_EVENT);
if (event) {
contacts_svc_value_set_int(event, CTS_EVENT_VAL_DATE_INT, 20110526);
contacts_svc_value_set_int(event, CTS_EVENT_VAL_TYPE_INT, CTS_EVENT_TYPE_BIRTH);
}
events = g_slist_append(events, event);
contacts_svc_struct_store_list(contact, CTS_CF_EVENT_LIST, events);
contacts_svc_value_free(event);
g_slist_free(events);
company = contacts_svc_value_new(CTS_VALUE_COMPANY);
if (company) {
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_NAME_STR, "Company");
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_DEPARTMENT_STR, "department");
contacts_svc_value_set_str(company, CTS_COMPANY_VAL_JOB_TITLE_STR, "engineer");
}
contacts_svc_struct_store_value(contact, CTS_CF_COMPANY_VALUE, company);
int ret = contacts_svc_set_myprofile(contact);
contacts_svc_struct_free(contact);
return ret;
}
static void get_myprofile(void)
{
int index=0, ret=-1;
CTSstruct *contact;
CTSvalue *value=NULL;
GSList *get_list, *cursor;
ret = contacts_svc_get_contact(0, &contact);
if (ret < 0) {
printf("No found record\n");
return;
}
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
printf("Additional Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR));
printf("Display Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR));
printf("Prefix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR));
printf("Suffix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR));
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_COMPANY_VALUE, &value);
printf("Company Name : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_NAME_STR));
printf("Company Department : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR));
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
for (cursor=get_list;cursor;cursor=g_slist_next(cursor))
{
int type;
type = contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT);
printf("number Type = %d ", type);
if (contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("email Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT));
printf("email = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_GROUPREL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("group = %s:",
contacts_svc_value_get_str(cursor->data, CTS_GROUPREL_VAL_NAME_STR));
printf("%d\n",
contacts_svc_value_get_int(cursor->data, CTS_GROUPREL_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NICKNAME_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
printf("nickname = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NICKNAME_VAL_NAME_STR));
if (index)
contacts_svc_struct_free(contact);
}
int main()
{
contacts_svc_connect();
insert_my_test();
get_myprofile();
contacts_svc_disconnect();
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-list.c
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "cts-internal.h"
#include "cts-schema.h"
#include "cts-utils.h"
#include "cts-types.h"
#include "cts-normalize.h"
#include "cts-favorite.h"
#include "cts-restriction.h"
#include "cts-list.h"
#define CTS_MALLOC_DEFAULT_NUM 256 //4Kbytes
#define CTS_OFTEN_USED_NUM 1
static inline updated_record* cts_updated_info_add_mempool(void)
{
int i;
updated_record *mempool;
mempool = calloc(CTS_MALLOC_DEFAULT_NUM, sizeof(updated_record));
for (i=0;i<CTS_MALLOC_DEFAULT_NUM-1;i++)
mempool[i].next = &mempool[i+1];
return mempool;
}
static inline int cts_updated_contact_free_mempool(updated_record *mempool)
{
updated_record *memseg, *tmp;
retv_if(NULL == mempool, CTS_ERR_ARG_NULL);
memseg = mempool;
while (memseg) {
tmp = memseg[CTS_MALLOC_DEFAULT_NUM-1].next;
free(memseg);
memseg = tmp;
}
return CTS_SUCCESS;
}
API int contacts_svc_iter_next(CTSiter *iter)
{
int ret;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retvm_if(iter->i_type <= CTS_ITER_NONE || CTS_ITER_MAX <= iter->i_type,
CTS_ERR_ARG_INVALID, "iter is Invalid(type=%d", iter->i_type);
if (CTS_ITER_UPDATED_INFO_AFTER_VER == iter->i_type)
{
retv_if(NULL == iter->info, CTS_ERR_ARG_INVALID);
if (NULL == iter->info->cursor)
iter->info->cursor = iter->info->head;
else
iter->info->cursor = iter->info->cursor->next;
if (NULL == iter->info->cursor || 0 == iter->info->cursor->id) {
iter->info->cursor = NULL;
cts_updated_contact_free_mempool(iter->info->head);
iter->info->head = NULL;
return CTS_ERR_FINISH_ITER;
}
}
else
{
ret = cts_stmt_step(iter->stmt);
if (CTS_TRUE != ret) {
if (CTS_SUCCESS != ret)
ERR("cts_stmt_step() Failed(%d)", ret);
else
ret = CTS_ERR_FINISH_ITER;
cts_stmt_finalize(iter->stmt);
iter->stmt = NULL;
return ret;
}
}
return CTS_SUCCESS;
}
API int contacts_svc_iter_remove(CTSiter *iter)
{
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retvm_if(iter->i_type <= CTS_ITER_NONE || CTS_ITER_MAX <= iter->i_type,
CTS_ERR_ARG_INVALID, "iter is Invalid(type=%d", iter->i_type);
if (CTS_ITER_UPDATED_INFO_AFTER_VER == iter->i_type) {
retv_if(NULL == iter->info, CTS_ERR_ARG_INVALID);
if (iter->info->head)
cts_updated_contact_free_mempool(iter->info->head);
free(iter->info);
}
else {
cts_stmt_finalize(iter->stmt);
}
free(iter);
INFO(",CTSiter,0");
return CTS_SUCCESS;
}
static inline int cts_get_list(cts_get_list_op op_code, CTSiter *iter)
{
cts_stmt stmt = NULL;
const char *display, *data;
char query[CTS_SQL_MAX_LEN] = {0};
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
iter->i_type = CTS_ITER_NONE;
iter->stmt = NULL;
if (cts_restriction_get_permit())
data = CTS_TABLE_DATA;
else
data = CTS_TABLE_RESTRICTED_DATA_VIEW;
switch (op_code)
{
case CTS_LIST_ALL_CONTACT:
iter->i_type = CTS_ITER_CONTACTS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.person_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE A.datatype = %d AND B.person_id = B.contact_id "
"ORDER BY A.data1, A.%s",
display, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_ADDRESSBOOK:
iter->i_type = CTS_ITER_ADDRESSBOOKS;
snprintf(query, sizeof(query),
"SELECT addrbook_id, addrbook_name, acc_id, acc_type, mode "
"FROM %s ORDER BY acc_id, addrbook_id",
CTS_TABLE_ADDRESSBOOKS);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_GROUP:
iter->i_type = CTS_ITER_GROUPS;
snprintf(query, sizeof(query), "SELECT group_id, addrbook_id, group_name, ringtone "
"FROM %s ORDER BY addrbook_id, group_name COLLATE NOCASE",
CTS_TABLE_GROUPS);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CUSTOM_NUM_TYPE:
iter->i_type = CTS_ITER_ALL_CUSTOM_NUM_TYPE;
snprintf(query, sizeof(query), "SELECT id, name FROM %s WHERE class = %d",
CTS_TABLE_CUSTOM_TYPES, CTS_TYPE_CLASS_NUM);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_GROUPING_PLOG:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE A.log_type < %d "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"GROUP BY F.data2, F.data3, F.data5, C.number "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data,
CTS_DATA_NUMBER, CTS_PLOG_TYPE_EMAIL_RECEIVED,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_GROUPING_MSG_PLOG:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE (A.log_type BETWEEN %d AND %d) "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"GROUP BY F.data2, F.data3, F.data5, C.number "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data, CTS_DATA_NUMBER,
CTS_PLOG_TYPE_MMS_INCOMMING, CTS_PLOG_TYPE_MMS_BLOCKED,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_GROUPING_CALL_PLOG:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE A.log_type < %d "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"GROUP BY F.data2, F.data3, F.data5, C.number "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data, CTS_DATA_NUMBER,
CTS_PLOG_TYPE_MMS_INCOMMING, data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_PLOG:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE A.log_type < %d "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data,
CTS_DATA_NUMBER, CTS_PLOG_TYPE_EMAIL_RECEIVED,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_EMAIL_PLOG:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.number = B.data2 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id "
"AND A.number = data2)) "
"WHERE A.log_type >= %d "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_EMAIL, data, CTS_DATA_EMAIL,
CTS_PLOG_TYPE_EMAIL_RECEIVED,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_MISSED_CALL:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE (A.log_type BETWEEN %d AND %d) "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data, CTS_DATA_NUMBER,
CTS_PLOG_TYPE_VOICE_INCOMMING_UNSEEN, CTS_PLOG_TYPE_VIDEO_INCOMMING_SEEN,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_UNSEEN_MISSED_CALL:
iter->i_type = CTS_ITER_GROUPING_PLOG;
snprintf(query, sizeof(query),
"SELECT C.id, F.data1, F.data2, F.data3, F.data5, F.image0, C.number, "
"C.log_type, C.log_time, C.data1, C.data2, C.contact_id, C.number_type "
"FROM "
"(SELECT A.id, A.number, A.log_type, A.log_time, A.data1, A.data2, "
"MIN(B.contact_id) contact_id, B.data1 number_type "
"FROM %s A LEFT JOIN %s B ON B.datatype = %d AND A.normal_num = B.data3 AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id "
"AND A.normal_num = data3)) "
"WHERE (A.log_type = %d OR A.log_type = %d) "
"GROUP BY A.id) C "
"LEFT JOIN (SELECT D.contact_id, data1, data2, data3, data5, image0 "
"FROM %s D, %s E ON D.datatype = %d AND D.contact_id = E.contact_id) F "
"ON C.contact_id = F.contact_id "
"ORDER BY C.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data, CTS_DATA_NUMBER,
CTS_PLOG_TYPE_VOICE_INCOMMING_UNSEEN, CTS_PLOG_TYPE_VIDEO_INCOMMING_UNSEEN,
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_NUMBER_FAVORITE:
iter->i_type = CTS_ITER_ALL_NUM_FAVORITE;
snprintf(query, sizeof(query),
"SELECT D.person_id, A.data1, A.data2, A.data3, A.data5, D.image0, "
"B.id, B.data1, B.data2 "
"FROM %s A, %s B, %s C, %s D "
"ON A.contact_id = B.contact_id AND B.id = C.related_id AND A.contact_id = D.person_id "
"WHERE A.datatype = %d AND B.datatype = %d AND C.type = %d AND D.person_id = D.contact_id "
"ORDER BY C.favorite_prio",
data, data, CTS_TABLE_FAVORITES, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_NUMBER, CTS_FAVOR_NUMBER);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CONTACT_FAVORITE:
iter->i_type = CTS_ITER_ALL_CONTACT_FAVORITE;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, C.image0, B.id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = B.related_id AND A.contact_id = C.person_id "
"WHERE A.datatype = %d AND B.type = %d AND C.person_id = C.contact_id "
"ORDER BY B.favorite_prio",
data, CTS_TABLE_FAVORITES, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_FAVOR_PERSON);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CONTACT_FAVORITE_HAD_NUMBER:
iter->i_type = CTS_ITER_ALL_CONTACT_FAVORITE;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, C.image0, B.id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = B.related_id AND A.contact_id = C.person_id "
"WHERE A.datatype = %d AND B.type = %d AND C.default_num > 0 "
"GROUP BY C.person_id "
"ORDER BY B.favorite_prio",
data, CTS_TABLE_FAVORITES, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_FAVOR_PERSON);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CONTACT_FAVORITE_HAD_EMAIL:
iter->i_type = CTS_ITER_ALL_CONTACT_FAVORITE;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, C.image0, B.id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = B.related_id AND A.contact_id = C.person_id "
"WHERE A.datatype = %d AND B.type = %d AND C.default_email > 0 "
"GROUP BY C.person_id "
"ORDER BY B.favorite_prio",
data, CTS_TABLE_FAVORITES, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_FAVOR_PERSON);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_SPEEDDIAL:
iter->i_type = CTS_ITER_ALL_SPEEDDIAL;
snprintf(query, sizeof(query),
"SELECT D.contact_id, A.data1, A.data2, A.data3, A.data5, D.image0, "
"B.id, B.data1, B.data2, C.speed_num "
"FROM %s A, %s B, %s C, %s D "
"WHERE A.datatype = %d AND B.datatype = %d AND B.id = C.number_id "
"AND A.contact_id = B.contact_id AND A.contact_id = D.person_id "
"ORDER BY C.speed_num",
data, data, CTS_TABLE_SPEEDDIALS,
CTS_TABLE_CONTACTS, CTS_DATA_NAME, CTS_DATA_NUMBER);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_SDN:
iter->i_type = CTS_ITER_ALL_SDN;
snprintf(query, sizeof(query),"SELECT name, number FROM %s",
CTS_TABLE_SIM_SERVICES);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CONTACT_HAD_NUMBER:
iter->i_type = CTS_ITER_CONTACTS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT B.person_id, A.data1, A.data2, A.data3, A.data5, B.addrbook_id, B.image0, B.contact_id, A.%s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE A.datatype = %d AND B.default_num > 0 "
"GROUP BY B.person_id "
"ORDER BY A.data1, A.%s",
display, data, CTS_TABLE_CONTACTS, CTS_DATA_NAME, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_CONTACT_HAD_EMAIL:
iter->i_type = CTS_ITER_CONTACTS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT B.person_id, A.data1, A.data2, A.data3, A.data5, B.addrbook_id, B.image0, B.contact_id, A.%s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE A.datatype = %d AND B.default_email > 0 "
"GROUP BY B.person_id "
"ORDER BY A.data1, A.%s",
display, data, CTS_TABLE_CONTACTS, CTS_DATA_NAME, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_EMAIL_NUMBER:
iter->i_type = CTS_ITER_NUMBERS_EMAILS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, B.data2, C.image0, C.contact_id, C.addrbook_id, A.%s "
"FROM %s A, %s B, %s C "
"ON A.contact_id = B.contact_id AND A.contact_id = C.person_id "
"WHERE A.datatype = %d AND (B.datatype = %d OR B.datatype = %d) "
"ORDER BY A.data1, A.%s",
display, data, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_NUMBER, CTS_DATA_EMAIL, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_OFTEN_USED_CONTACT:
iter->i_type = CTS_ITER_CONTACTS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT A.person_id, data1, data2, data3, data5, C.addrbook_id, C.image0, C.person_id, %s "
"FROM %s A, %s B, %s C ON A.person_id = B.contact_id AND B.contact_id = C.contact_id "
"WHERE A.outgoing_count > %d AND B.datatype = %d "
"ORDER BY A.outgoing_count DESC, data1, %s",
display, CTS_TABLE_PERSONS, data, CTS_TABLE_CONTACTS,
CTS_OFTEN_USED_NUM, CTS_DATA_NAME, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ALL_NUMBER:
iter->i_type = CTS_ITER_NUMBERS_EMAILS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, B.data2, C.image0, C.contact_id, C.addrbook_id, A.%s "
"FROM %s A, %s B, %s C "
"ON A.contact_id = B.contact_id AND A.contact_id = C.person_id "
"WHERE A.datatype = %d AND B.datatype = %d "
"ORDER BY A.data1, A.%s",
display, data, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_NUMBER, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
default:
ERR("Invalid parameter : The op_code(%d) is not supported", op_code);
return CTS_ERR_ARG_INVALID;
}
return CTS_SUCCESS;
}
API int contacts_svc_get_list(cts_get_list_op op_code, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
ret = cts_get_list(op_code, result);
if (ret) {
ERR("cts_get_list() Failed(%d)", ret);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
static inline int cts_get_list_with_str(cts_get_list_str_op op_code,
const char *search_value, CTSiter *iter)
{
int ret;
cts_stmt stmt = NULL;
const char *display, *data;
char query[CTS_SQL_MAX_LEN] = {0};
char remake_val[CTS_SQL_MIN_LEN];
CTS_START_TIME_CHECK;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
iter->i_type = CTS_ITER_NONE;
iter->stmt = NULL;
retvm_if(NULL == search_value && CTS_LIST_PLOGS_OF_NUMBER != op_code,
CTS_ERR_ARG_NULL, "The search_value is NULL");
if (cts_restriction_get_permit())
data = CTS_TABLE_DATA;
else
data = CTS_TABLE_RESTRICTED_DATA_VIEW;
switch ((int)op_code)
{
case CTS_LIST_PLOGS_OF_NUMBER:
iter->i_type = CTS_ITER_PLOGS_OF_NUMBER;
if (search_value && *search_value) {
snprintf(query, sizeof(query),
"SELECT A.id, A.log_type, A.log_time, A.data1, A.data2, MIN(B.contact_id) "
"FROM %s A LEFT JOIN %s B ON A.normal_num = B.data3 AND B.datatype = %d AND "
"(A.related_id = B.contact_id OR A.related_id IS NULL OR "
"NOT EXISTS (SELECT id FROM %s "
"WHERE datatype = %d AND contact_id = A.related_id AND data3 = ?)) "
"WHERE A.number = ? "
"GROUP BY A.id "
"ORDER BY A.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, data, CTS_DATA_NUMBER);
}
else {
snprintf(query, sizeof(query),
"SELECT id, log_type, log_time, data1, data2, NULL "
"FROM %s WHERE number ISNULL AND log_type < %d ORDER BY id DESC",
CTS_TABLE_PHONELOGS, CTS_PLOG_TYPE_EMAIL_RECEIVED);
}
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
if (search_value) {
const char *normal_num;
ret = cts_clean_number(search_value, remake_val, sizeof(remake_val));
retvm_if(ret <= 0, CTS_ERR_ARG_INVALID, "Number(%s) is invalid", search_value);
normal_num = cts_normalize_number(remake_val);
cts_stmt_bind_copy_text(stmt, 1, normal_num, strlen(normal_num));
cts_stmt_bind_copy_text(stmt, 2, search_value, strlen(search_value));
}
iter->stmt = stmt;
break;
case CTS_LIST_CONTACTS_WITH_NAME:
retvm_if(CTS_SQL_MIN_LEN <= strlen(search_value), CTS_ERR_ARG_INVALID,
"search_value is too long");
iter->i_type = CTS_ITER_CONTACTS_WITH_NAME;
memset(remake_val, 0x00, sizeof(remake_val));
ret = cts_normalize_str(search_value, remake_val, CTS_SQL_MIN_LEN);
retvm_if(ret < CTS_SUCCESS, ret, "cts_normalize_str() Failed(%d)", ret);
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id "
"FROM %s A, %s B ON A.contact_id = B.contact_id "
"WHERE datatype = %d AND %s LIKE ('%%' || ? || '%%') "
"ORDER BY data1, %s",
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME, display, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_stmt_bind_copy_text(stmt, 1, remake_val, strlen(remake_val));
iter->stmt = stmt;
break;
case CTS_LIST_NUMBERINFOS_WITH_NAME:
retvm_if(CTS_SQL_MIN_LEN <= strlen(search_value), CTS_ERR_ARG_INVALID,
"search_value is too long");
iter->i_type = CTS_ITER_NUMBERINFOS;
memset(remake_val, 0x00, sizeof(remake_val));
ret = cts_normalize_str(search_value, remake_val, CTS_SQL_MIN_LEN);
retvm_if(ret < CTS_SUCCESS, ret, "cts_normalize_str() Failed(%d)", ret);
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, B.data2, C.image0, C.contact_id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = C.person_id AND B.contact_id = C.contact_id "
"WHERE A.datatype = %d AND B.datatype = %d AND A.%s LIKE ('%%' || ? || '%%') "
"ORDER BY A.data1, A.%s",
data, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_NUMBER, display, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_stmt_bind_copy_text(stmt, 1, remake_val, strlen(remake_val));
iter->stmt = stmt;
break;
case CTS_LIST_NUMBERINFOS_WITH_NUM:
iter->i_type = CTS_ITER_NUMBERINFOS;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, B.data2, C.image0, C.contact_id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = C.person_id AND B.contact_id = C.contact_id "
"WHERE A.datatype = %d AND B.datatype = %d AND B.data2 LIKE ('%%' || ? || '%%') "
"ORDER BY A.data1, A.%s",
data, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_NUMBER, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_stmt_bind_copy_text(stmt, 1, search_value, strlen(search_value));
iter->stmt = stmt;
break;
case CTS_LIST_EMAILINFOS_WITH_EMAIL:
iter->i_type = CTS_ITER_EMAILINFOS_WITH_EMAIL;
snprintf(query, sizeof(query),
"SELECT C.person_id, A.data1, A.data2, A.data3, A.data5, B.data2, C.image0, C.contact_id "
"FROM %s A, %s B, %s C "
"ON A.contact_id = C.person_id AND B.contact_id = C.contact_id "
"WHERE A.datatype = %d AND B.datatype = %d AND B.data2 LIKE ('%%' || ? || '%%') "
"ORDER BY A.data1, A.%s",
data, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, CTS_DATA_EMAIL, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_stmt_bind_copy_text(stmt, 1, search_value, strlen(search_value));
iter->stmt = stmt;
break;
case 10000: /* It is not supported. use only inhouse phone and message application */
retvm_if(CTS_SQL_MIN_LEN - 50 < strlen(search_value),
CTS_ERR_ARG_INVALID, "search_value is too long");
iter->i_type = CTS_ITER_PLOGNUMBERS_WITH_NUM;
snprintf(query, sizeof(query),
"SELECT number FROM %s WHERE number LIKE '%%%s%%' AND normal_num NOTNULL GROUP BY number",
CTS_TABLE_PHONELOGS, search_value);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
default:
ERR("Invalid parameter : The op_code(%d) is not supported", op_code);
return CTS_ERR_ARG_INVALID;
}
CTS_START_TIME_CHECK;
return CTS_SUCCESS;
}
API int contacts_svc_get_list_with_str(cts_get_list_str_op op_code,
const char *search_value, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
ret = cts_get_list_with_str(op_code, search_value, result);
if (ret) {
ERR("cts_get_list_with_str() Failed(%d)", ret);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
static inline int cts_get_list_with_int(cts_get_list_int_op op_code,
unsigned int search_value, CTSiter *iter)
{
cts_stmt stmt = NULL;
const char *display, *data;
char query[CTS_SQL_MAX_LEN] = {0};
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
iter->i_type = CTS_ITER_NONE;
iter->stmt = NULL;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
if (cts_restriction_get_permit())
data = CTS_TABLE_DATA;
else
data = CTS_TABLE_RESTRICTED_DATA_VIEW;
switch (op_code) {
case CTS_LIST_MEMBERS_OF_GROUP_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE datatype = %d AND B.contact_id IN "
"(SELECT contact_id FROM %s WHERE group_id = %d) "
"GROUP BY B.person_id "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS, CTS_DATA_NAME,
CTS_TABLE_GROUPING_INFO, search_value, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_NO_GROUP_MEMBERS_OF_ADDRESSBOOK_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE datatype = %d AND B.addrbook_id = %d AND NOT EXISTS "
"(SELECT contact_id FROM %s WHERE contact_id=B.contact_id LIMIT 1) "
"GROUP BY B.person_id "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, search_value,
CTS_TABLE_GROUPING_INFO, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_MEMBERS_OF_ADDRESSBOOK_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE datatype = %d AND B.addrbook_id = %d "
"GROUP BY B.person_id "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, search_value, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_GROUPS_OF_ADDRESSBOOK_ID:
iter->i_type = CTS_ITER_GROUPS;
snprintf(query, sizeof(query),
"SELECT group_id, %d, group_name, ringtone "
"FROM %s WHERE addrbook_id = %d "
"ORDER BY group_name COLLATE NOCASE",
search_value, CTS_TABLE_GROUPS, search_value);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_ADDRESSBOOKS_OF_ACCOUNT_ID:
iter->i_type = CTS_ITER_ADDRESSBOOKS;
snprintf(query, sizeof(query),
"SELECT addrbook_id, addrbook_name, acc_id, acc_type, mode "
"FROM %s WHERE acc_id = %d "
"ORDER BY addrbook_id",
CTS_TABLE_ADDRESSBOOKS, search_value);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_MEMBERS_OF_PERSON_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.contact_id "
"WHERE A.datatype = %d AND B.person_id = %d "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS, CTS_DATA_NAME, search_value,
CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_PLOG_OF_PERSON_ID:
iter->i_type = CTS_ITER_PLOGS_OF_PERSON_ID;
snprintf(query, sizeof(query),
"SELECT A.id, A.log_type, A.log_time, A.data1, A.data2, A.related_id, A.number "
"FROM %s A, %s B WHERE ((A.normal_num = B.data3 AND B.datatype = %d) OR "
"(A.number = B.data2 AND B.datatype = %d)) "
"AND EXISTS (SELECT contact_id from %s WHERE person_id = %d AND B.contact_id = contact_id) "
"ORDER BY A.log_time DESC",
CTS_TABLE_PHONELOGS, data, CTS_DATA_NUMBER, CTS_DATA_EMAIL,
CTS_TABLE_CONTACTS, search_value);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_NO_GROUP_MEMBERS_HAD_NUMBER_OF_ADDRESSBOOK_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE datatype = %d AND B.addrbook_id = %d AND B.default_num > 0 AND "
"NOT EXISTS (SELECT contact_id FROM %s WHERE contact_id=B.contact_id LIMIT 1) "
"GROUP BY B.person_id "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, search_value,
CTS_TABLE_GROUPING_INFO, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
case CTS_LIST_NO_GROUP_MEMBERS_HAD_EMAIL_OF_ADDRESSBOOK_ID:
iter->i_type = CTS_ITER_CONTACTS;
snprintf(query, sizeof(query),
"SELECT B.person_id, data1, data2, data3, data5, B.addrbook_id, B.image0, B.contact_id, %s "
"FROM %s A, %s B ON A.contact_id = B.person_id "
"WHERE datatype = %d AND B.addrbook_id = %d AND B.default_email > 0 AND "
"NOT EXISTS (SELECT contact_id FROM %s WHERE contact_id=B.contact_id LIMIT 1) "
"GROUP BY B.person_id "
"ORDER BY data1, %s",
display, data, CTS_TABLE_CONTACTS,
CTS_DATA_NAME, search_value,
CTS_TABLE_GROUPING_INFO, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
iter->stmt = stmt;
break;
default:
ERR("Invalid parameter : The op_code(%d) is not supported", op_code);
return CTS_ERR_ARG_INVALID;
}
return CTS_SUCCESS;
}
API int contacts_svc_get_list_with_int(cts_get_list_int_op op_code,
unsigned int search_value, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
ret = cts_get_list_with_int(op_code, search_value, result);
if (ret) {
ERR("cts_get_list_with_int() Failed(%d)", ret);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
static inline int cts_get_updated_contacts(int addressbook_id, int version,
CTSiter *iter)
{
int ret;
cts_stmt stmt = NULL;
char query[CTS_SQL_MAX_LEN] = {0};
updated_record *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retv_if(NULL == iter->info, CTS_ERR_ARG_INVALID);
iter->i_type = CTS_ITER_UPDATED_INFO_AFTER_VER;
if (0 <= addressbook_id)
{
snprintf(query, sizeof(query),
"SELECT %d, contact_id, changed_ver, created_ver, addrbook_id FROM %s "
"WHERE changed_ver > %d AND addrbook_id = %d "
"UNION "
"SELECT %d, contact_id, deleted_ver, -1, addrbook_id FROM %s "
"WHERE deleted_ver > %d AND addrbook_id = %d",
CTS_OPERATION_UPDATED, CTS_TABLE_CONTACTS, version, addressbook_id,
CTS_OPERATION_DELETED, CTS_TABLE_DELETEDS, version, addressbook_id);
}
else {
snprintf(query, sizeof(query),
"SELECT %d, contact_id, changed_ver, created_ver, addrbook_id FROM %s "
"WHERE changed_ver > %d "
"UNION "
"SELECT %d, contact_id, deleted_ver, -1, addrbook_id FROM %s "
"WHERE deleted_ver > %d ",
CTS_OPERATION_UPDATED, CTS_TABLE_CONTACTS, version,
CTS_OPERATION_DELETED, CTS_TABLE_DELETEDS, version );
}
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_TRUE != ret)
{
warn_if(CTS_SUCCESS != ret, "cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_DB_RECORD_NOT_FOUND;
}
iter->info->head = result = cts_updated_info_add_mempool();
do {
result->type = cts_stmt_get_int(stmt, 0);
result->id = cts_stmt_get_int(stmt, 1);
result->ver = cts_stmt_get_int(stmt, 2);
if (cts_stmt_get_int(stmt, 3) == result->ver || version < cts_stmt_get_int(stmt, 3))
result->type = CTS_OPERATION_INSERTED;
result->addressbook_id = cts_stmt_get_int(stmt, 4);
if (NULL == result->next)
result->next = cts_updated_info_add_mempool();
result = result->next;
}while(CTS_TRUE == cts_stmt_step(stmt));
cts_stmt_finalize(stmt);
return CTS_SUCCESS;
}
API int contacts_svc_get_updated_contacts(int addressbook_id,
int version, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retvm_if(version < 0, CTS_ERR_ARG_INVALID, "The version(%d) is invalid", version);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
result->info = calloc(1, sizeof(updated_info));
if (NULL == result->info) {
ERR("calloc() Failed");
free(result);
return CTS_ERR_OUT_OF_MEMORY;
}
ret = cts_get_updated_contacts(addressbook_id, version, result);
if (ret) {
ERR("cts_get_updated_contacts() Failed(%d)", ret);
free(result->info);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
static inline int cts_get_updated_groups(int addressbook_id, int version,
CTSiter *iter)
{
int ret;
cts_stmt stmt = NULL;
char query[CTS_SQL_MAX_LEN] = {0};
updated_record *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retv_if(NULL == iter->info, CTS_ERR_ARG_INVALID);
iter->i_type = CTS_ITER_UPDATED_INFO_AFTER_VER;
if (0 <= addressbook_id)
{
snprintf(query, sizeof(query),
"SELECT %d, group_id, changed_ver, created_ver, addrbook_id FROM %s "
"WHERE changed_ver > %d AND addrbook_id = %d "
"UNION "
"SELECT %d, group_id, deleted_ver, -1, addrbook_id FROM %s "
"WHERE deleted_ver > %d AND addrbook_id = %d",
CTS_OPERATION_UPDATED, CTS_TABLE_GROUPS, version, addressbook_id,
CTS_OPERATION_DELETED, CTS_TABLE_GROUP_DELETEDS, version, addressbook_id);
}
else {
snprintf(query, sizeof(query),
"SELECT %d, group_id, changed_ver, created_ver, addrbook_id FROM %s "
"WHERE changed_ver > %d "
"UNION "
"SELECT %d, group_id, deleted_ver, -1, addrbook_id FROM %s "
"WHERE deleted_ver > %d ",
CTS_OPERATION_UPDATED, CTS_TABLE_GROUPS, version,
CTS_OPERATION_DELETED, CTS_TABLE_GROUP_DELETEDS, version);
}
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_TRUE != ret) {
warn_if(CTS_SUCCESS != ret, "cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_DB_RECORD_NOT_FOUND;
}
iter->info->head = result = cts_updated_info_add_mempool();
do {
result->type = cts_stmt_get_int(stmt, 0);
result->id = cts_stmt_get_int(stmt, 1);
result->ver = cts_stmt_get_int(stmt, 2);
if (cts_stmt_get_int(stmt, 3) == result->ver || version < cts_stmt_get_int(stmt, 3))
result->type = CTS_OPERATION_INSERTED;
result->addressbook_id = cts_stmt_get_int(stmt, 4);
if (NULL == result->next)
result->next = cts_updated_info_add_mempool();
result = result->next;
}while (CTS_TRUE == cts_stmt_step(stmt));
cts_stmt_finalize(stmt);
return CTS_SUCCESS;
}
API int contacts_svc_get_updated_groups(int addressbook_id,
int version, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retvm_if(version < 0, CTS_ERR_ARG_INVALID, "The version(%d) is invalid", version);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
result->info = calloc(1, sizeof(updated_info));
if (NULL == result->info) {
ERR("calloc() Failed");
free(result);
return CTS_ERR_OUT_OF_MEMORY;
}
ret = cts_get_updated_groups(addressbook_id, version, result);
if (ret) {
ERR("cts_get_updated_groups() Failed(%d)", ret);
free(result->info);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
void cts_foreach_run(CTSiter *iter, cts_foreach_fn cb, void *data)
{
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int ret;
CTSvalue *value;
value = contacts_svc_iter_get_info(iter);
ret = cb(value, data);
if (CTS_SUCCESS != ret) {
ERR("cts_foreach_fn(%p) Failed(%d)", cb, ret);
contacts_svc_value_free(value);
break;
}
contacts_svc_value_free(value);
}
cts_stmt_finalize(iter->stmt);
}
API int contacts_svc_list_foreach(cts_get_list_op op_code,
cts_foreach_fn cb, void *user_data)
{
int ret;
CTSiter iter = {0};
ret = cts_get_list(op_code, &iter);
retvm_if(CTS_SUCCESS != ret, ret, "cts_get_list() Failed(%d)", ret);
cts_foreach_run(&iter, cb, user_data);
return CTS_SUCCESS;
}
API int contacts_svc_list_with_int_foreach(cts_get_list_int_op op_code,
unsigned int search_value, cts_foreach_fn cb, void *user_data)
{
int ret;
CTSiter iter = {0};
ret = cts_get_list_with_int(op_code, search_value, &iter);
retvm_if(CTS_SUCCESS != ret, ret, "cts_get_list_with_int() Failed(%d)", ret);
cts_foreach_run(&iter, cb, user_data);
return CTS_SUCCESS;
}
API int contacts_svc_list_with_str_foreach(cts_get_list_str_op op_code,
const char *search_value, cts_foreach_fn cb, void *user_data)
{
int ret;
CTSiter iter = {0};
ret = cts_get_list_with_str(op_code, search_value, &iter);
retvm_if(CTS_SUCCESS != ret, ret, "cts_get_list_with_str() Failed(%d)", ret);
cts_foreach_run(&iter, cb, user_data);
return CTS_SUCCESS;
}
// same with check_dirty_number()
static inline bool cts_is_number(const char *str)
{
int i;
for (i=0;i<strlen(str);i++)
{
switch (str[i])
{
case '0' ... '9':
case 'p':
case 'w':
case 'P':
case 'W':
case '#':
case '*':
case '+':
break;
default:
return false;
}
}
return true;
}
static inline int cts_escape_like_patten(const char *src, char *dest, int dest_size)
{
int s_pos=0, d_pos=0;
if (NULL == src) {
ERR("The parameter(src) is NULL");
dest[d_pos] = '\0';
return 0;
}
while (src[s_pos] != 0) {
if (dest_size == d_pos - 1)
break;
if ('%' == src[s_pos] || '_' == src[s_pos]) {
dest[d_pos++] = '\\';
}
dest[d_pos++] = src[s_pos++];
}
dest[d_pos] = '\0';
return d_pos;
}
API int contacts_svc_smartsearch_excl(const char *search_str, int limit, int offset,
cts_foreach_fn cb, void *user_data)
{
int ret, len;
CTSiter iter = {0};
const char *display, *data;
cts_stmt stmt = NULL;
char query[CTS_SQL_MAX_LEN];
char remake_name[CTS_SQL_MIN_LEN], escape_name[CTS_SQL_MIN_LEN];
retv_if(NULL == search_str, CTS_ERR_ARG_NULL);
retvm_if(CTS_SQL_MIN_LEN <= strlen(search_str), CTS_ERR_ARG_INVALID,
"search_str is too long");
iter.i_type = CTS_ITER_NUMBERINFOS;
if (CTS_ORDER_NAME_LASTFIRST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
display = CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP;
else
display = CTS_SCHEMA_DATA_NAME_LOOKUP;
if (cts_restriction_get_permit())
data = CTS_TABLE_DATA;
else
data = CTS_TABLE_RESTRICTED_DATA_VIEW;
if (cts_is_number(search_str)) {
len = snprintf(query, sizeof(query),
"SELECT B.person_id, A.data1, A.data2, A.data3, A.data5, C.data2, B.image0, B.contact_id "
"FROM (%s A, %s B ON A.contact_id = B.person_id AND A.datatype=%d) "
"LEFT JOIN %s C ON B.contact_id = C.contact_id AND C.datatype = %d "
"WHERE C.data2 LIKE '%%%s%%' OR A.%s LIKE ('%%' || ? || '%%') "
"ORDER BY A.data1, A.%s",
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME,
data, CTS_DATA_NUMBER,
search_str, display, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
}
else {
len = snprintf(query, sizeof(query),
"SELECT B.person_id, A.data1, A.data2, A.data3, A.data5, C.data2, B.image0, B.contact_id "
"FROM (%s A, %s B ON A.contact_id = B.person_id AND A.datatype = %d) "
"LEFT JOIN %s C ON B.default_num = C.id AND C.datatype = %d "
"WHERE A.%s LIKE ('%%' || ? || '%%') ESCAPE '\\' "
"ORDER BY A.data1, A.%s",
data, CTS_TABLE_CONTACTS, CTS_DATA_NAME,
data, CTS_DATA_NUMBER,
display, CTS_SCHEMA_DATA_NAME_SORTING_KEY);
}
if (limit)
snprintf(query+len, sizeof(query)-len, " LIMIT %d OFFSET %d", limit, offset);
ret = cts_normalize_str(search_str, remake_name, sizeof(remake_name));
retvm_if(ret < CTS_SUCCESS, ret, "cts_normalize_str() Failed(%d)", ret);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_escape_like_patten(remake_name, escape_name, sizeof(escape_name));
cts_stmt_bind_copy_text(stmt, 1, escape_name, strlen(escape_name));
iter.stmt = stmt;
cts_foreach_run(&iter, cb, user_data);
return CTS_SUCCESS;
}
static inline int cts_group_get_relation_changes(int addressbook_id, int version,
CTSiter *iter)
{
int ret;
cts_stmt stmt = NULL;
char query[CTS_SQL_MAX_LEN] = {0};
updated_record *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retv_if(NULL == iter->info, CTS_ERR_ARG_INVALID);
iter->i_type = CTS_ITER_UPDATED_INFO_AFTER_VER;
ret = snprintf(query, sizeof(query),
"SELECT group_id, type, ver, addrbook_id FROM %s, %s USING (group_id) "
"WHERE ver > %d ",
"group_relations_log", CTS_TABLE_GROUPS, version);
if (0 <= addressbook_id)
{
snprintf(query + ret , sizeof(query) -ret ,
"AND addrbook_id = %d ", addressbook_id);
}
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_TRUE != ret)
{
warn_if(CTS_SUCCESS != ret, "cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_DB_RECORD_NOT_FOUND;
}
iter->info->head = result = cts_updated_info_add_mempool();
do {
result->id = cts_stmt_get_int(stmt, 0);
result->type = cts_stmt_get_int(stmt, 1);
result->ver = cts_stmt_get_int(stmt, 2);
result->addressbook_id = cts_stmt_get_int(stmt, 3);
if (NULL == result->next)
result->next = cts_updated_info_add_mempool();
result = result->next;
}while(CTS_TRUE == cts_stmt_step(stmt));
cts_stmt_finalize(stmt);
return CTS_SUCCESS;
}
/* This function is only for OSP */
API int contacts_svc_group_get_relation_changes(int addressbook_id,
int version, CTSiter **iter)
{
int ret;
CTSiter *result;
retv_if(NULL == iter, CTS_ERR_ARG_NULL);
retvm_if(version < 0, CTS_ERR_ARG_INVALID, "The version(%d) is invalid", version);
result = calloc(1, sizeof(CTSiter));
retvm_if(NULL == result, CTS_ERR_OUT_OF_MEMORY, "calloc() Failed");
result->info = calloc(1, sizeof(updated_info));
if (NULL == result->info) {
ERR("calloc() Failed");
free(result);
return CTS_ERR_OUT_OF_MEMORY;
}
ret = cts_group_get_relation_changes(addressbook_id, version, result);
if (ret) {
ERR("cts_group_get_relation_changes() Failed(%d)", ret);
free(result->info);
free(result);
return ret;
}
*iter = (CTSiter *)result;
INFO(",CTSiter,1");
return CTS_SUCCESS;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-person.h
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CONTACTS_PERSON_H__
#define __CONTACTS_PERSON_H__
#include "cts-contact.h"
int cts_insert_person(int contact_id, int outgoing_cnt);
int cts_delete_person(int index);
int cts_person_garbagecollection(void);
int cts_person_change_primary_contact(int person_id);
enum {
CTS_LINKED_NONE,
CTS_LINKED_PRIMARY,
CTS_LINKED_SECONDARY,
};
int cts_check_linked_contact(int contact_id);
//<!--
/**
* @defgroup CONTACTS_SVC_PERSON Person
* @ingroup CONTACTS_SVC
* @addtogroup CONTACTS_SVC_PERSON
* @{
*
* This interface provides methods for linking.
*
* The person means linked contacts.\n
* If contact is not linked, the related person is same with contact.\n
* So contacts_svc_get_person() and contacts_svc_get_person_value return same value with
* contacts_svc_get_contact() and contacts_svc_get_contact_value().
*/
/**
* This function links a sub_person to base_person.
*
* @param[in] base_person_id The index of base person
* @param[in] sub_person_id The index of sub person
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_link_person(int base_person_id, int sub_person_id);
/**
* This function unlinks a contact to person.
*
* @param[in] person_id The index of person
* @param[in] contact_id The index of contact to unlink
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_unlink_person(int person_id, int contact_id);
/**
* This function gets person record which has the index from the database.
* If person has linked contacts, this function return merged record;
* Obtained person record should be freed by using contacts_svc_struct_free().
*
* @param[in] index The index of person to get
* @param[out] person Points of the person record which is returned
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @par example
* @code
void get_person(void)
{
int ret=-1;
CTSstruct *person = NULL;
CTSvalue *name;
GSList *get_list, *cursor;
ret = contacts_svc_get_person(1, &person);
if(ret < 0)
{
printf("No found record\n");
return;
}
contacts_svc_struct_get_value(person, CTS_CF_NAME_VALUE, &name);
printf("First Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_LAST_STR));
printf("Additional Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_ADDITION_STR));
printf("Display Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_DISPLAY_STR));
printf("Prefix Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_PREFIX_STR));
printf("Suffix Name : %s\n", contacts_svc_value_get_str(name, CTS_NAME_VAL_SUFFIX_STR));
get_list = NULL;
contacts_svc_struct_get_list(person, CTS_CF_NUMBER_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("number Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT));
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(person, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("email Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT));
printf("email = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
contacts_svc_struct_free(person);
}
* @endcode
*/
int contacts_svc_get_person(int person_id, CTSstruct **person);
/**
* This function gets index of person related with user_data.
* index is found by op_code with user_data related with op_code(#cts_find_op).
* @param[in] op_code #cts_find_op
* @param[in] user_data The parameter for searching
* @return index of found person on success, Negative value(#cts_error) on error
* @par example
* @code
void get_person(void)
{
int index, ret=-1;
CTSstruct *person = NULL;
index = contacts_svc_find_person_by(CTS_FIND_BY_NUMBER, "0123456789");
if(index > CTS_SUCCESS) {
ret = contacts_svc_get_person(index, &person);
if(ret < 0) {
printf("No found record\n");
return;
}
}
}
* @endcode
*/
int contacts_svc_find_person_by(cts_find_op op_code, const char *user_data);
/**
* Use for contacts_svc_get_person_value().
*/
typedef enum {
CTS_GET_PERSON_NAME_VALUE, /**< Use #NAMEVALUE */
CTS_GET_PERSON_DEFAULT_NUMBER_VALUE,/**< related with person id. Use #NUMBERVALUE */
CTS_GET_PERSON_DEFAULT_EMAIL_VALUE,/**< related with person id. Use #EMAILVALUE */
}cts_get_person_val_op;
/**
* This function can get a value data related with person_id and op_code.
* The value data is decided by op_code(#cts_get_person_val_op)
* The gotten value is readonly.
* Obtained record should be freed by using contacts_svc_value_free().
* @return #CTS_SUCCESS, Negative value(#cts_error) on error
* @param[in] op_code #cts_get_person_val_op
* @param[in] person_id The person index
* @param[out] value Points of the contacts service value(#CTSvalue) which is returned
* @par example
* @code
void get_person_default_num(int person_id)
{
int index, ret;
CTSvalue *number=NULL;
const char *default_num;
ret = contacts_svc_get_person_value(CTS_GET_PERSON_DEFAULT_NUMBER_VALUE, person_id, &number);
if(ret < CTS_SUCCESS) {
printf("contacts_svc_get_contact_value() Failed(%d)\n", ret);
return;
}
default_num = contacts_svc_value_get_str(number, CTS_NUM_VAL_NUMBER_STR);
printf("The default Number is %s\n", default_num);
contacts_svc_value_free(number);
}
* @endcode
*/
int contacts_svc_get_person_value(cts_get_person_val_op op_code, int person_id, CTSvalue **value);
/**
* This function deletes all contacts related with a person.
* It is not only deletes contact records from contact table,
* but also clears up all the info of these contacts(group relation info, favorites info and etc.).
*
* @param[in] index The index of person to delete in database.
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_delete_person(int index);
/**
* @}
*/
//-->
#endif //__CONTACTS_PERSON_H__
|
tizenorg/platform.core.pim.contacts-service
|
helper/main.c
|
/*
* Contacts Service Helper
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <glib.h>
#include <string.h>
#include <contacts-svc.h>
#include "internal.h"
#include "schema-recovery.h"
#include "helper-socket.h"
#include "utils.h"
#include "sqlite.h"
int main(int argc, char **argv)
{
int ret;
GMainLoop *cts_helper_loop = NULL;
helper_check_schema();
if (2 <= argc && !strcmp(argv[1], "schema"))
return CTS_SUCCESS;
cts_helper_loop = g_main_loop_new (NULL, FALSE);
h_retvm_if(NULL == cts_helper_loop, CTS_ERR_FAIL, "g_main_loop_new() Failed");
ret = contacts_svc_connect();
h_retvm_if(CTS_SUCCESS != ret, ret, "contacts_svc_connect() Failed(%d)", ret);
helper_socket_init();
helper_init_configuration();
g_main_loop_run(cts_helper_loop);
helper_final_configuration();
ret = contacts_svc_disconnect();
h_retvm_if(CTS_SUCCESS != ret, ret, "contacts_svc_disconnect() Failed(%d)", ret);
g_main_loop_unref(cts_helper_loop);
return CTS_SUCCESS;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-utils.h
|
<filename>src/cts-utils.h
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_UTILS_H__
#define __CTS_UTILS_H__
#include <stdbool.h>
#define CTS_IMG_PATH_SIZE_MAX 1024
#define CTS_IMAGE_LOCATION "/opt/data/contacts-svc/img"
#define CTS_VCARD_IMAGE_LOCATION "/opt/data/contacts-svc/img/vcard"
#define CTS_GROUP_IMAGE_LOCATION "/opt/data/contacts-svc/img/group"
#define CTS_MY_IMAGE_LOCATION "/opt/data/contacts-svc/img/my"
#define CTS_NOTI_CONTACT_CHANGED_DEF "/opt/data/contacts-svc/.CONTACTS_SVC_DB_CHANGED"
void cts_deregister_noti(void);
void cts_register_noti(void);
int cts_get_default_language(void);
void cts_set_contact_noti(void);
void cts_set_plog_noti(void);
void cts_set_missed_call_noti(void);
void cts_set_favor_noti(void);
void cts_set_speed_noti(void);
void cts_set_addrbook_noti(void);
void cts_set_group_noti(void);
void cts_set_group_rel_noti(void);
void cts_set_link_noti(void);
int cts_exist_file(char *path);
int cts_convert_nicknames2textlist(GSList *src, char *dest, int dest_size);
GSList* cts_convert_textlist2nicknames(char *text_list);
int cts_increase_outgoing_count(int contact_id);
int cts_get_next_ver(void);
int cts_update_contact_changed_time(int contact_id);
int cts_contact_delete_image_file(int img_type, int index);
int cts_contact_add_image_file(int img_type, int index, char *src_img, char *dest_name, int dest_size);
int cts_contact_update_image_file(int img_type, int index, char *src_img, char *dest_name, int dest_size);
char* cts_get_img(const char *dir, int index, char *dest, int dest_size);
int cts_set_img(const char *dir, int index, const char *path);
#ifndef __CONTACTS_SVC_H__
//<!--
/**
* This function starts database transaction
* If you want to handle a transaction, use it.
*
* @par Multiple inserting case
* case1 has only one DB commit. Therefore it is faster than case 2.
* And if 5th inserted contact is failed,
* case 1 insert nothing but case 2 insert 1,2,3 and 4th contacts.
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @code
* //case 1
* contacts_svc_begin_trans();
* for(i = 0; i< 20; i++) {
* if(CTS_SUCCESS != "insert api") {
* contacts_svc_end_trans(false);
* return -1;
* }
* }
* ret = contacts_svc_end_trans(true);
* if(ret < CTS_SUCCESS){
* printf("all work were rollbacked");
* return;
* }
*
* //case 2
* for(i = 0; i< 20; i++) {
* if(CTS_SUCCESS != "insert api") {
* return -1;
* }
* }
* @endcode
*/
int contacts_svc_begin_trans(void);
/**
* This function finishes database transaction of contacts service
* If you want to handle a transaction, use it.
* If returned value is error, the transaction was rollbacked.
* When transaction is success, it returns the last contacts version.
*
* @param[in] is_success true : commit, false : rollback
* @return #CTS_SUCCESS or the last contact version(when success) on success,
* Negative value(#cts_error) on error
*/
int contacts_svc_end_trans(bool is_success);
/**
* A kind of order in contacts service of contacts service
* @see contacts_svc_get_order()
*/
typedef enum{
CTS_ORDER_NAME_FIRSTLAST = 0, /**<First Name first */
CTS_ORDER_NAME_LASTFIRST = 1 /**<Last Name first */
}cts_order_type;
/**
* Use for contacts_svc_get_order().
*/
typedef enum{
CTS_ORDER_OF_SORTING, /**< Sorting Order */
CTS_ORDER_OF_DISPLAY /**< Display Order */
}cts_order_op;
/**
* This function gets the display or sorting order(Firstname first or LastName first)
*
* @param[in] op_code #cts_order_op
* @return #CTS_ORDER_NAME_FIRSTLAST or #CTS_ORDER_NAME_LASTFIRST on success,
* \n Negative value(#cts_error) on error
*/
cts_order_type contacts_svc_get_order(cts_order_op op_code);
/**
* This function sets the display or sorting order(Firstname first or LastName first)
*
* @param[in] op_code #cts_order_op
* @param[in] order order type(#cts_order_type)
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_set_order(cts_order_op op_code, cts_order_type order);
/**
* Use for contacts_svc_subscribe_change(), contacts_svc_unsubscribe_change()
*/
typedef enum{
CTS_SUBSCRIBE_CONTACT_CHANGE,
CTS_SUBSCRIBE_PLOG_CHANGE,
CTS_SUBSCRIBE_FAVORITE_CHANGE,
CTS_SUBSCRIBE_GROUP_CHANGE,
CTS_SUBSCRIBE_SPEEDDIAL_CHANGE,
CTS_SUBSCRIBE_ADDRESSBOOK_CHANGE,
CTS_SUBSCRIBE_MISSED_CALL_CHANGE,
CTS_SUBSCRIBE_LINK_CHANGE,
CTS_SUBSCRIBE_GROUP_RELATION_CHANGE /**< This is only for OSP. We cannot guarantee action for your use */
}cts_subscribe_type;
/**
* This function watchs contacts service changes.
* The notification is sent once per a transaction.
* This is handled by default context of g_main_loop.
*
* @param[in] noti_type A kind of Notification
* @param[in] cb callback function pointer
* @param[in] user_data data which is passed to callback function
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @par example
* @code
#include <stdio.h>
#include <glib.h>
#include <contacts-svc.h>
void test_callback(void *data)
{
printf("Contact data of contacts service is changed\n");
}
int main()
{
GMainLoop *loop;
contacts_svc_subscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, test_callback, NULL);
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
contacts_svc_unsubscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, test_callback);
g_main_loop_unref(loop);
return 0;
}
* @endcode
*/
int contacts_svc_subscribe_change(cts_subscribe_type noti_type,
void (*cb)(void *), void *user_data);
/**
* This function stops to watch contacts service changes.
* @param[in] noti_type A kind of Notification(#cts_subscribe_type)
* @param[in] cb callback function which is added by contacts_svc_subscribe_change()
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_unsubscribe_change(cts_subscribe_type noti_type,
void (*cb)(void *));
/**
* This function delete a callback function which is specified with user_data.
* @param[in] noti_type A kind of Notification(#cts_subscribe_type)
* @param[in] cb The callback function which is added by contacts_svc_subscribe_change()
* @param[in] user_data The user_data which is added by contacts_svc_subscribe_change()
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_unsubscribe_change_with_data(cts_subscribe_type noti_type,
void (*cb)(void *), void *user_data);
/**
* Use for contacts_svc_count()
*/
typedef enum
{
CTS_GET_ALL_CONTACT, /**< The count of contacts in the all addressbook */
CTS_GET_COUNT_SDN, /**< The count of SDN(Service Dialing Number) in SIM */
CTS_GET_ALL_PHONELOG, /**< The count of all phonelog */
CTS_GET_UNSEEN_MISSED_CALL, /**< The count of unseen missed call */
CTS_GET_INCOMING_CALL, /**< The count of incomming call */
CTS_GET_OUTGOING_CALL, /**< The count of outgoing call */
CTS_GET_MISSED_CALL, /**< The count of missed call */
CTS_GET_COUNT_ALL_GROUP, /**< The count of groups */
}cts_count_op;
/**
* This function gets count related with op_code.
*
* @param[in] op_code #cts_count_op
* @return The count number on success, Negative value(#cts_error) on error
*/
int contacts_svc_count(cts_count_op op_code);
/**
* Use for contacts_svc_count_with_int()
*/
typedef enum
{
CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, /**< The count of contacts in the addressbook related to index(search_value) */
CTS_GET_COUNT_CONTACTS_IN_GROUP, /**< The count of contacts in the group related to index(search_value) */
CTS_GET_COUNT_NO_GROUP_CONTACTS_IN_ADDRESSBOOK, /**< The count of not assigned contacts in the addressbook related to index(search_value) */
CTS_GET_COUNT_GROUPS_IN_ADDRESSBOOK /**< The count of groups in the addressbook related to index(search_value) */
}cts_count_int_op;
/**
* This function gets count related with op_code and search_value.
* \n #search_value is related with op_code. The Word after preposition is a property of search_value.
*
* @param[in] op_code #cts_count_int_op
* @param[in] search_value interger value(almost a related index) for searching
* @return The count number on success, Negative value(#cts_error) on error
*/
int contacts_svc_count_with_int(cts_count_int_op op_code, int search_value);
/**
* Use for contacts_svc_save_image()
*/
typedef enum
{
CTS_IMG_NORMAL, /**< . */
CTS_IMG_FULL, /**< . */
} cts_img_t;
/**
* This function saves image to contacts service domain.
*
* @param[in] img_type #cts_img_t
* @param[in] index index of contact
* @param[in] src_img The image path to copy(Should include extension at path)
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_save_image(cts_img_t img_type, int index, char *src_img);
/**
* This function gets image from contacts service domain.
* Usually, You can get the #CTS_IMG_NORMAL in Contacts Struct(#CTSstruct).
*
* @param[in] img_type #cts_img_t
* @param[in] index index of contact
* @param[in] img_path The pointer of getting image path(should be freed by using free())
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_get_image(cts_img_t img_type, int index, char **img_path);
/**
* This function imports sim phonebook.
*
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_import_sim(void);
/**
* This function exports sim phonebook.
* @param[in] index index of contact
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_export_sim(int index);
/**
* This function sets the outgoing count of the contact to zero.
*
* @param[in] person_id The index of person
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @see contacts_svc_get_list(), #CTS_LIST_OFTEN_USED_CONTACT
*/
int contacts_svc_reset_outgoing_count(int person_id);
//-->
#endif //#ifndef __CONTACTS_SVC_H__
#endif //__CTS_UTILS_H__
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-addressbook.c
|
<reponame>tizenorg/platform.core.pim.contacts-service<filename>src/cts-addressbook.c<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "cts-internal.h"
#include "cts-schema.h"
#include "cts-sqlite.h"
#include "cts-utils.h"
#include "cts-person.h"
#include "cts-addressbook.h"
static inline int cts_reset_internal_addressbook(void)
{
CTS_FN_CALL;
int ret;
char query[CTS_SQL_MIN_LEN];
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
snprintf(query, sizeof(query), "DELETE FROM %s WHERE addrbook_id = %d",
CTS_TABLE_CONTACTS, CTS_ADDRESSBOOK_INTERNAL);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret)
{
ERR("cts_query_exec() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
snprintf(query, sizeof(query), "DELETE FROM %s WHERE addrbook_id = %d",
CTS_TABLE_GROUPS, CTS_ADDRESSBOOK_INTERNAL);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret)
{
ERR("cts_query_exec() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
cts_set_contact_noti();
cts_set_group_noti();
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_insert_addressbook(CTSvalue *addressbook)
{
int ret, index;
cts_stmt stmt = NULL;
cts_addrbook *record = (cts_addrbook *)addressbook;
char query[CTS_SQL_MAX_LEN] = {0};
retv_if(NULL == addressbook, CTS_ERR_ARG_NULL);
retv_if(NULL == record->name, CTS_ERR_ARG_INVALID);
retvm_if(CTS_VALUE_ADDRESSBOOK != record->v_type, CTS_ERR_ARG_INVALID,
"addressbook is invalid type(%d)", record->v_type);
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
snprintf(query, sizeof(query),
"INSERT INTO %s(addrbook_name, acc_id, acc_type, mode) "
"VALUES(?, %d, %d, %d)",
CTS_TABLE_ADDRESSBOOKS, record->acc_id, record->acc_type, record->mode);
stmt = cts_query_prepare(query);
if (NULL == stmt) {
ERR("cts_query_prepare() Failed");
contacts_svc_end_trans(false);
return CTS_ERR_DB_FAILED;
}
cts_stmt_bind_text(stmt, 1, record->name);
ret = cts_stmt_step(stmt);
if (CTS_SUCCESS != ret) {
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
index = cts_db_get_last_insert_id();
cts_stmt_finalize(stmt);
cts_set_addrbook_noti();
ret = contacts_svc_end_trans(true);
retvm_if(ret < CTS_SUCCESS, ret, "contacts_svc_end_trans() Failed(%d)", ret);
return index;
}
API int contacts_svc_delete_addressbook(int addressbook_id)
{
CTS_FN_CALL;
int ret;
char query[CTS_SQL_MAX_LEN] = {0};
if (CTS_ADDRESSBOOK_INTERNAL == addressbook_id)
return cts_reset_internal_addressbook();
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
snprintf(query, sizeof(query), "DELETE FROM %s WHERE addrbook_id = %d",
CTS_TABLE_ADDRESSBOOKS, addressbook_id);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret) {
ERR("cts_query_exec() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
ret = cts_person_garbagecollection();
if (CTS_SUCCESS != ret) {
ERR("cts_person_garbagecollection() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
ret = cts_db_change();
if (0 < ret) {
cts_set_contact_noti();
cts_set_group_noti();
cts_set_addrbook_noti();
ret = contacts_svc_end_trans(true);
}
else {
contacts_svc_end_trans(false);
ret = CTS_ERR_NO_DATA;
}
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_update_addressbook(CTSvalue *addressbook)
{
int ret;
cts_stmt stmt = NULL;
char query[CTS_SQL_MIN_LEN] = {0};
cts_addrbook *record = (cts_addrbook *)addressbook;
retv_if(NULL == addressbook, CTS_ERR_ARG_NULL);
retv_if(NULL == record->name, CTS_ERR_ARG_INVALID);
retvm_if(CTS_VALUE_ADDRESSBOOK != record->v_type, CTS_ERR_ARG_INVALID,
"addressbook is invalid type(%d)", record->v_type);
snprintf(query, sizeof(query),
"UPDATE %s SET addrbook_name=?, acc_id=%d, acc_type=%d, mode=%d "
"WHERE addrbook_id=%d", CTS_TABLE_ADDRESSBOOKS,
record->acc_id, record->acc_type, record->mode, record->id);
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
stmt = cts_query_prepare(query);
if (NULL == stmt) {
ERR("cts_query_prepare() Failed");
contacts_svc_end_trans(false);
return CTS_ERR_DB_FAILED;
}
cts_stmt_bind_text(stmt, 1, record->name);
ret = cts_stmt_step(stmt);
if (CTS_SUCCESS != ret) {
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
cts_stmt_finalize(stmt);
cts_set_addrbook_noti();
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_get_addressbook(int addressbook_id, CTSvalue **ret_value)
{
int ret;
cts_addrbook *ab;
cts_stmt stmt = NULL;
char query[CTS_SQL_MAX_LEN] = {0};
retv_if(NULL == ret_value, CTS_ERR_ARG_NULL);
snprintf(query, sizeof(query),
"SELECT addrbook_id, addrbook_name, acc_id, acc_type, mode "
"FROM %s WHERE addrbook_id = %d", CTS_TABLE_ADDRESSBOOKS, addressbook_id);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_TRUE != ret) {
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_DB_RECORD_NOT_FOUND;
}
ab = (cts_addrbook *)contacts_svc_value_new(CTS_VALUE_ADDRESSBOOK);
if (ab) {
ab->embedded = true;
cts_stmt_get_addressbook(stmt, ab);
}
cts_stmt_finalize(stmt);
*ret_value = (CTSvalue *)ab;
return CTS_SUCCESS;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-restriction.c
|
<reponame>tizenorg/platform.core.pim.contacts-service
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <fcntl.h>
#include <unistd.h>
#include "cts-internal.h"
#include "cts-sqlite.h"
#include "cts-schema.h"
static const char *CTS_RESTRICTION_CHECK_FILE="/opt/data/contacts-svc/.CONTACTS_SVC_RESTRICTION_CHECK";
static int cts_restriction_permit;
int cts_restriction_init(void)
{
if (!cts_restriction_permit) {
int fd = open(CTS_RESTRICTION_CHECK_FILE, O_RDONLY);
if (0 <= fd) {
close(fd);
cts_restriction_permit = TRUE;
} else {
ERR("Restriction Mode");
}
}
if (!cts_restriction_permit) {
int ret;
const char *query;
query = "CREATE TEMP VIEW "CTS_TABLE_RESTRICTED_DATA_VIEW" AS SELECT * FROM "CTS_TABLE_DATA" WHERE is_restricted != 1";
ret = cts_query_exec(query);
retvm_if(CTS_SUCCESS != ret, ret, "cts_query_exec() Failed(%d)", ret);
}
return CTS_SUCCESS;
}
void cts_restriction_final(void)
{
cts_restriction_permit = FALSE;
}
int cts_restriction_get_permit(void)
{
return cts_restriction_permit;
}
/**
* This function make restricted contact.
* If process does not have permission for restriction, this function will be failed.
*
* @param[in] contact The contacts service struct
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
API int contacts_svc_struct_set_restriction(CTSstruct *contact)
{
contact_t *record = (contact_t *)contact;
retv_if(NULL == contact, CTS_ERR_ARG_NULL);
retv_if(FALSE == cts_restriction_permit, CTS_ERR_ENV_INVALID);
record->is_restricted = TRUE;
return CTS_SUCCESS;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/addressbook-test.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <contacts-svc.h>
int insert_addrbook(int acc_id, int acc_type, int mode, const char *group_name)
{
int ret;
CTSvalue *ab;
ab = contacts_svc_value_new(CTS_VALUE_ADDRESSBOOK);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_ACC_ID_INT, acc_id);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_ACC_TYPE_INT, acc_type);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_MODE_INT, mode);
contacts_svc_value_set_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR, group_name);
ret = contacts_svc_insert_addressbook(ab);
if (ret < CTS_SUCCESS)
printf("contacts_svc_insert_addressbook() Failed\n");
contacts_svc_value_free(ab);
return ret;
}
void get_addrbook(int addressbook_id)
{
int ret;
const char *name;
CTSvalue *ab = NULL;
ret = contacts_svc_get_addressbook(addressbook_id, &ab);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_addressbook() Failed\n");
return;
}
printf("///////////%d//////////////\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ID_INT));
printf("The related account ID : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ACC_ID_INT));
printf("The related account type : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ACC_TYPE_INT));
printf("permission : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_MODE_INT));
name = contacts_svc_value_get_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR);
if (name)
printf("Name : %s\n", name);
printf("//////////////////////////\n");
contacts_svc_value_free(ab);
}
void update_addrbook(void)
{
int ret;
CTSvalue *ab = NULL;
ret = contacts_svc_get_addressbook(2, &ab);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_addressbook() Failed\n");
return;
}
contacts_svc_value_set_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR,"Fixed-addressbook");
ret = contacts_svc_update_addressbook(ab);
if (ret < CTS_SUCCESS)
printf("contacts_svc_update_addressbook() Failed\n");
contacts_svc_value_free(ab);
}
void delete_addrbook(int addressbook_id)
{
int ret;
ret = contacts_svc_delete_addressbook(addressbook_id);
if (CTS_SUCCESS != ret)
printf("Error : contacts_svc_delete_addressbook() Failed(%d)\n", ret);
}
static int list_cb(CTSvalue *ab, void *user_data)
{
const char *name;
printf("///////////%d//////////////\n",
contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_ID_INT));
printf("The related account ID : %d\n",
contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_ACC_ID_INT));
printf("The related account type : %d\n",
contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_ACC_TYPE_INT));
printf("permission : %d\n",
contacts_svc_value_get_int(ab, CTS_LIST_ADDRESSBOOK_MODE_INT));
name = contacts_svc_value_get_str(ab, CTS_LIST_ADDRESSBOOK_NAME_STR);
if (name)
printf("Name : %s\n", name);
printf("//////////////////////////\n");
return CTS_SUCCESS;
}
void addrbook_list(void)
{
int ret;
printf("///////////0//////////////\n");
printf("Name : %s\n", "Internal Addressbook(This is logical value)");
printf("//////////////////////////\n");
ret = contacts_svc_list_foreach(CTS_LIST_ALL_ADDRESSBOOK, list_cb, NULL);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_list_foreach() Failed\n");
return;
}
}
void addrbook_list2(void)
{
int ret, count;
CTSiter *iter;
count = contacts_svc_count_with_int(CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, 0);
printf("Phone(%d)", count);
ret = contacts_svc_get_list(CTS_LIST_ALL_ADDRESSBOOK, &iter);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_list() Failed(%d)\n", ret);
return;
}
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int id;
const char *name;
CTSvalue *info;
info = contacts_svc_iter_get_info(iter);
id = contacts_svc_value_get_int(info, CTS_LIST_ADDRESSBOOK_ID_INT);
name = contacts_svc_value_get_str(info, CTS_LIST_ADDRESSBOOK_NAME_STR);
count = contacts_svc_count_with_int(CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, id);
printf("%s(%d)", name, count);
}
contacts_svc_iter_remove(iter);
}
int main()
{
int id;
contacts_svc_connect();
insert_addrbook(1, CTS_ADDRESSBOOK_TYPE_GOOGLE, CTS_ADDRESSBOOK_MODE_NONE, "test1");
insert_addrbook(1, CTS_ADDRESSBOOK_TYPE_GOOGLE, CTS_ADDRESSBOOK_MODE_NONE, "test2");
id = insert_addrbook(2, CTS_ADDRESSBOOK_TYPE_FACEBOOK, CTS_ADDRESSBOOK_MODE_READONLY,
"facebook-test");
get_addrbook(id);
addrbook_list();
update_addrbook();
addrbook_list();
delete_addrbook(id);
addrbook_list();
addrbook_list2();
contacts_svc_disconnect();
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
include/ContactsService_PG.h
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
*
* @ingroup SLP_PG
* @defgroup CONTACTS_SVC_PG Contacts Service
<h1 class="pg">Introduction</h1>
<h2 class="pg">Purpose of this document</h2>
The purpose of this document is to describe how applications can use contacts-service APIs for handling contact's information. This document gives programming guidelines to application engineers and examples of using contact data.
<h2 class="pg">Scope</h2>
The scope of this document is limited to Contacts-service API usage.
<h1 class="pg">Contacts Service Architecture</h1>
<h2 class="pg"> Overview</h2>
Contacts-service is responsible for inserting, deleting, and updating contact data in order to accommodate the needs for application's contact data.
Users can access contacts data without knowing DB schema, SQLite, relations of data
@image html SLP_ContactsService_PG_image001.PNG
<h2 class="pg">Sub-Components</h2>
Contacts-svc-helper is a process for contacts-servcie. The process wait requests of contacts-service library and respond immediately
<h1 class="pg">Contacts Service Features</h1>
- Similar to Sqlite3
- Handle information of Contact
- Handle information of Group
- Handle information of Phone log
<h2 class="pg">Similar to Sqlite3</h2>
Contacts-service API is similar to Sqlite3.
<h2 class="pg">Handle information of Contact</h2>
Contacts-service supports to insert/update/delete/get/search information of contact.
The Information of contact includes name, numbers, emails, addresses, company, messenger, events, group relation information, web sites and favorite information.
<h2 class="pg">Handle information of Group</h2>
Contacts-service supports to insert/update/delete/get information of contact.
<h2 class="pg">Handle information of Group</h2>
Contacts-service supports to insert/update/delete/get information of Phone log.
<h1 class="pg">Contacts Service API Description</h1>
you can refer @ref CONTACTS_SVC
<h1 class="pg">Sample Code</h1>
<h2 class="pg">Connect to Contact Database</h2>
Before using contact information from contacts service API, caller module should connect to the contact database, and after finishing with the contact information, should disconnect from the contact database
@code
int contacts_svc_connect(void);
int contacts_svc_disconnect(void);
@endcode
<h2 class="pg">Insert information of contact</h2>
@code
void insert_test(void)
{
CTSstruct *contact;
CTSvalue *name, *number1, *number2;
GSList *numbers=NULL;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
name = contacts_svc_value_new(CTS_VALUE_CONTACT_BASE_INFO);
if(name) {
contacts_svc_value_set_str(name, CTS_BASE_VAL_IMG_PATH_STR, "test.vcf");
}
contacts_svc_struct_store_value(contact, CTS_CF_BASE_INFO_VALUE, name);
contacts_svc_value_free(name);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if(name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "Gil-Dong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Hong");
contacts_svc_value_set_str(name, CTS_NAME_VAL_SUFFIX_STR, "engineer");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if(number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "0987654321");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT, CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
number2 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if(number2) {
contacts_svc_value_set_str(number2, CTS_NUM_VAL_NUMBER_STR, "0123456789");
contacts_svc_value_set_int(number2, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_WORK);
}
numbers = g_slist_append(numbers, number2);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
contacts_svc_value_free(number2);
g_slist_free(numbers);
contacts_svc_insert_contact(0, contact);
contacts_svc_struct_free(contact);
}
@endcode
<h2 class="pg">Get contact</h2>
@code
void get_contact(CTSstruct *contact)
{
int index=0, ret=-1;
CTSvalue *value=NULL;
GSList *get_list, *cursor;
if(!contact) {
index = contacts_svc_find_contact_by(CTS_FIND_BY_NUMBER, "0123456789");
if(index > CTS_SUCCESS)
ret = contacts_svc_get_contact(index, &contact);
if(ret < 0)
{
printf("No found record\n");
return;
}
}
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
printf("Additional Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR));
printf("Display Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR));
printf("Prefix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR));
printf("Suffix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR));
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_COMPANY_VALUE, &value);
printf("Company Name : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_NAME_STR));
printf("Company Department : %s\n", contacts_svc_value_get_str(value, CTS_COMPANY_VAL_DEPARTMENT_STR));
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("number Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT));
if(contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
if(index)
contacts_svc_insert_favorite(contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("email Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT));
printf("email = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_GROUPREL_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("group = %s:",
contacts_svc_value_get_str(cursor->data, CTS_GROUPREL_VAL_NAME_STR));
printf("%d\n",
contacts_svc_value_get_int(cursor->data, CTS_GROUPREL_VAL_ID_INT));
}
if(index)
contacts_svc_struct_free(contact);
}
@endcode
<h2 class="pg">Get contact list</h2>
@code
void get_contact_list(void)
{
CTSiter *iter = NULL;
contacts_svc_get_list(CTS_LIST_ALL_CONTACT, &iter);
while(CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *contact = NULL;
const char *first, *last, *display;
contact = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(contact, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_DISPLAY_STR);
if(display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_LAST_STR);
if(CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(contact);
}
contacts_svc_iter_remove(iter);
}
@endcode
<h2 class="pg">Delete contact </h2>
@code
void delete_test(void)
{
//get contact
int index=0, ret=-1;
CTSstruct *contact;
if(!contact) {
index = contacts_svc_find_contact_by(CTS_FIND_BY_NUMBER, "0123456789");
if(index > CTS_SUCCESS)
ret = contacts_svc_get_contact(index, &contact);
if(ret < 0)
{
printf("No found record\n");
return;
}
}
contacts_svc_delete_contact(index);
contacts_svc_struct_free(contact);
}
@endcode
<h2 class="pg">Search contacts by name </h2>
@code
void search_contacts_by_name(void)
{
int ret;
CTSiter *iter = NULL;
ret = contacts_svc_get_list_with_str(CTS_LIST_CONTACTS_WITH_NAME,
"Hong", &iter);
if(CTS_SUCCESS != ret) return;
while(CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *row_info = NULL;
const char *first, *last, *display;
row_info = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(row_info, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_DISPLAY_STR);
if(display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_LAST_STR);
if(CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(row_info, CTS_LIST_CONTACT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(row_info);
}
contacts_svc_iter_remove(iter);
}
@endcode
* @}
*/
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-struct-ext.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "cts-internal.h"
#include "cts-utils.h"
#include "cts-struct.h"
#include "cts-struct-ext.h"
#define CTS_VCARD_MOVE_TO(orig, src, check) \
do{ \
if (NULL == orig && NULL != src) { \
orig = src; \
check = true; \
src = NULL; \
} \
}while(false)
static inline int cts_merge_vcard_base(cts_ct_base *orig, cts_ct_base *addition)
{
int ret;
char dest[CTS_IMG_PATH_SIZE_MAX];
retvm_if(NULL == addition, CTS_ERR_ARG_INVALID, "Invalid addition(%p)", addition);
if (NULL == orig->img_path) {
if (orig->id && addition->img_path) {
ret = snprintf(dest, sizeof(dest), "%s/%d-%d.", CTS_IMAGE_LOCATION,
orig->id, CTS_IMG_NORMAL);
if (0 != strncmp(dest, addition->img_path, ret)) {
orig->img_path = addition->img_path;
orig->img_changed = true;
addition->img_path = NULL;
}
} else {
orig->img_path = addition->img_path;
orig->img_changed = true;
addition->img_path = NULL;
}
}
if (NULL == orig->full_img_path) {
if (orig->id && addition->full_img_path) {
ret = snprintf(dest, sizeof(dest), "%s/%d-%d.", CTS_IMAGE_LOCATION,
orig->id, CTS_IMG_FULL);
if (0 != strncmp(dest, addition->full_img_path, ret)) {
orig->full_img_path = addition->full_img_path;
orig->full_img_changed = true;
addition->full_img_path = NULL;
}
} else {
orig->full_img_path = addition->full_img_path;
orig->full_img_changed = true;
addition->full_img_path = NULL;
}
}
CTS_VCARD_MOVE_TO(orig->uid, addition->uid, orig->uid_changed);
CTS_VCARD_MOVE_TO(orig->note, addition->note, orig->note_changed);
CTS_VCARD_MOVE_TO(orig->ringtone_path, addition->ringtone_path, orig->ringtone_changed);
if (NULL == orig->vcard_img_path) {
orig->vcard_img_path = addition->vcard_img_path;
addition->vcard_img_path = NULL;
}
return CTS_SUCCESS;
}
static inline int cts_merge_vcard_name(cts_name *orig, cts_name *addition)
{
retvm_if(NULL == addition, CTS_ERR_ARG_INVALID, "Invalid addition(%p)", addition);
if (NULL == orig->first && NULL == orig->last) {
CTS_VCARD_MOVE_TO(orig->first, addition->first, orig->is_changed);
CTS_VCARD_MOVE_TO(orig->last, addition->last, orig->is_changed);
}
CTS_VCARD_MOVE_TO(orig->addition, addition->addition, orig->is_changed);
CTS_VCARD_MOVE_TO(orig->display, addition->display, orig->is_changed);
CTS_VCARD_MOVE_TO(orig->prefix, addition->prefix, orig->is_changed);
CTS_VCARD_MOVE_TO(orig->suffix, addition->suffix, orig->is_changed);
return CTS_SUCCESS;
}
static inline GSList* cts_merge_vcard_numbers(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_number *addition = i->data;
if (NULL == addition->number) continue;
for (j=orig;j;j=j->next) {
cts_number *org = j->data;
if (org->deleted) continue;
if (addition->number && org->number
&& 0 == strcmp(addition->number, org->number))
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_emails(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_email *addition = i->data;
if (NULL == addition->email_addr) continue;
for (j=orig;j;j=j->next) {
cts_email *org = j->data;
if (org->deleted) continue;
if (addition->email_addr && org->email_addr
&& 0 == strcmp(addition->email_addr, org->email_addr))
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_events(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_event *addition = i->data;
for (j=orig;j;j=j->next) {
cts_event *org = j->data;
if (org->deleted) continue;
if (addition->date == org->date)
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_postals(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_postal *addition = i->data;
for (j=orig;j;j=j->next) {
cts_postal *org = j->data;
if (org->deleted) continue;
char *s1, *s2;
s1 = addition->pobox;
s2 = org->pobox;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->postalcode;
s2 = org->postalcode;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->region;
s2 = org->region;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->locality;
s2 = org->locality;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->street;
s2 = org->street;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->extended;
s2 = org->extended;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
s1 = addition->country;
s2 = org->country;
if (s1 == s2 || (s1 && s2 && 0 == strcmp(s1, s2))) {
break;
}
}
}
}
}
}
}
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_webs(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_web *addition = i->data;
if (NULL == addition->url) continue;
for (j=orig;j;j=j->next) {
cts_web *org = j->data;
if (org->deleted) continue;
if (addition->url && org->url
&& 0 == strcmp(addition->url, org->url))
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_nicknames(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_nickname *addition = i->data;
if (NULL == addition->nick) continue;
for (j=orig;j;j=j->next) {
cts_nickname *org = j->data;
if (org->deleted) continue;
if (addition->nick && org->nick
&& 0 == strcmp(addition->nick, org->nick))
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
static inline GSList* cts_merge_vcard_extends(GSList *orig, GSList *addition)
{
GSList *d, *t;
cts_extend *orig_val, *addition_val;
for (d=addition;d;d=d->next) {
addition_val = d->data;
for (t=orig;t;t=t->next) {
orig_val = t->data;
if (orig_val->deleted) continue;
if (addition_val->type == orig_val->type)
break;
}
if (NULL == t) {
orig = g_slist_append(orig, addition_val);
d->data = NULL;
}
}
return orig;
}
static inline int cts_merge_vcard_company(cts_company *orig, cts_company *addition)
{
bool temp;
retvm_if(NULL == addition, CTS_ERR_ARG_INVALID, "Invalid addition(%p)", addition);
CTS_VCARD_MOVE_TO(orig->name, addition->name, temp);
CTS_VCARD_MOVE_TO(orig->department, addition->department, temp);
CTS_VCARD_MOVE_TO(orig->jot_title, addition->jot_title, temp);
CTS_VCARD_MOVE_TO(orig->role, addition->role, temp);
CTS_VCARD_MOVE_TO(orig->assistant_name, addition->assistant_name, temp);
return CTS_SUCCESS;
}
static inline GSList* cts_merge_vcard_grouprel(GSList *orig, GSList *addition)
{
GSList *i, *j;
for (i=addition;i;i=i->next) {
cts_group *addition = i->data;
if (0 == addition->id) continue;
for (j=orig;j;j=j->next) {
cts_group *org = j->data;
if (org->deleted) continue;
if (addition->id == org->id)
break;
}
if (NULL == j) {
orig = g_slist_append(orig, addition);
i->data = NULL;
}
}
return orig;
}
API int contacts_svc_struct_merge(CTSstruct *s1, CTSstruct *s2)
{
contact_t *orig, *addition;
retv_if(NULL == s1, CTS_ERR_ARG_NULL);
retv_if(NULL == s2, CTS_ERR_ARG_NULL);
orig = (contact_t *)s1;
addition = (contact_t *)s2;
if (orig->base) {
cts_merge_vcard_base(orig->base, addition->base);
} else {
orig->base = addition->base;
addition->base = NULL;
}
if (orig->name) {
cts_merge_vcard_name(orig->name, addition->name);
} else {
orig->name = addition->name;
addition->name = NULL;
}
if (orig->numbers) {
orig->numbers =
cts_merge_vcard_numbers(orig->numbers, addition->numbers);
} else {
orig->numbers = addition->numbers;
addition->numbers = NULL;
}
if (orig->emails) {
orig->emails =
cts_merge_vcard_emails(orig->emails, addition->emails);
} else {
orig->emails = addition->emails;
addition->emails = NULL;
}
//orig->grouprelations does not support.
if (orig->events) {
orig->events =
cts_merge_vcard_events(orig->events, addition->events);
} else {
orig->events = addition->events;
addition->events = NULL;
}
//orig->messengers does not support.
if (orig->postal_addrs) {
orig->postal_addrs =
cts_merge_vcard_postals(orig->postal_addrs, addition->postal_addrs);
} else {
orig->postal_addrs = addition->postal_addrs;
addition->postal_addrs = NULL;
}
if (orig->web_addrs) {
orig->web_addrs =
cts_merge_vcard_webs(orig->web_addrs, addition->web_addrs);
} else {
orig->web_addrs = addition->web_addrs;
addition->web_addrs = NULL;
}
if (orig->nicknames) {
orig->nicknames =
cts_merge_vcard_nicknames(orig->nicknames, addition->nicknames);
} else {
orig->nicknames = addition->nicknames;
addition->nicknames = NULL;
}
if (orig->company) {
cts_merge_vcard_company(orig->company, addition->company);
} else {
orig->company = addition->company;
addition->company = NULL;
}
if (orig->grouprelations) {
cts_merge_vcard_grouprel(orig->grouprelations, addition->grouprelations);
} else {
orig->grouprelations = addition->grouprelations;
addition->grouprelations = NULL;
}
if (orig->extended_values) {
orig->extended_values =
cts_merge_vcard_extends(orig->extended_values, addition->extended_values);
} else {
orig->extended_values = addition->extended_values;
addition->extended_values = NULL;
}
return CTS_SUCCESS;
}
static inline cts_ct_base* cts_struct_dup_base(const cts_ct_base *src)
{
cts_ct_base *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_ct_base));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_ct_base));
if (src->uid)
result->uid = strdup(src->uid);
if (src->img_path)
result->img_path = strdup(src->img_path);
if (src->full_img_path)
result->full_img_path = strdup(src->full_img_path);
if (src->ringtone_path)
result->ringtone_path = strdup(src->ringtone_path);
if (src->note)
result->note = strdup(src->note);
if (src->vcard_img_path)
result->vcard_img_path = strdup(src->vcard_img_path);
}
return result;
}
static inline cts_name* cts_struct_dup_name(const cts_name *src)
{
cts_name *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_name));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_name));
if (src->first)
result->first = strdup(src->first);
if (src->last)
result->last = strdup(src->last);
if (src->addition)
result->addition = strdup(src->addition);
if (src->display)
result->display = strdup(src->display);
if (src->prefix)
result->prefix = strdup(src->prefix);
if (src->suffix)
result->suffix = strdup(src->suffix);
}
return result;
}
static inline cts_number* cts_struct_dup_number(const cts_number *src)
{
cts_number *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_number));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_number));
if (src->number)
result->number = strdup(src->number);
}
return result;
}
static inline cts_email* cts_struct_dup_email(const cts_email *src)
{
cts_email *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_email));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_email));
if (src->email_addr)
result->email_addr = strdup(src->email_addr);
}
return result;
}
static inline cts_web* cts_struct_dup_web(const cts_web *src)
{
cts_web *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_web));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_web));
if (src->url)
result->url = strdup(src->url);
}
return result;
}
static inline cts_postal* cts_struct_dup_postal(const cts_postal *src)
{
cts_postal *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_postal));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_postal));
if (src->pobox)
result->pobox = strdup(src->pobox);
if (src->postalcode)
result->postalcode = strdup(src->postalcode);
if (src->region)
result->region = strdup(src->region);
if (src->locality)
result->locality = strdup(src->locality);
if (src->street)
result->street = strdup(src->street);
if (src->extended)
result->extended = strdup(src->extended);
if (src->country)
result->country = strdup(src->country);
}
return result;
}
static inline cts_event* cts_struct_dup_event(const cts_event *src)
{
cts_event *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_event));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_event));
}
return result;
}
static inline cts_messenger* cts_struct_dup_messenger(const cts_messenger *src)
{
cts_messenger *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_messenger));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_messenger));
if (src->im_id)
result->im_id = strdup(src->im_id);
if (src->svc_name)
result->svc_name = strdup(src->svc_name);
if (src->svc_op)
result->svc_op = strdup(src->svc_op);
}
return result;
}
static inline cts_group* cts_struct_dup_grouprel(const cts_group *src)
{
cts_group *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_group));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_group));
if (src->name)
result->name = strdup(src->name);
if (src->ringtone_path)
result->ringtone_path = strdup(src->ringtone_path);
if (src->img_path)
result->img_path = strdup(src->img_path);
}
return result;
}
static inline cts_extend* cts_struct_dup_extend(const cts_extend *src)
{
cts_extend *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_extend));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_extend));
if (src->data2)
result->data2 = strdup(src->data2);
if (src->data3)
result->data3 = strdup(src->data3);
if (src->data4)
result->data4 = strdup(src->data4);
if (src->data5)
result->data5 = strdup(src->data5);
if (src->data6)
result->data6 = strdup(src->data6);
if (src->data7)
result->data7 = strdup(src->data7);
if (src->data8)
result->data8 = strdup(src->data8);
if (src->data9)
result->data9 = strdup(src->data9);
if (src->data10)
result->data10 = strdup(src->data10);
}
return result;
}
static inline cts_nickname* cts_struct_dup_nick(const cts_nickname *src)
{
cts_nickname *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_nickname));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_nickname));
if (src->nick)
result->nick = strdup(src->nick);
}
return result;
}
static inline GSList* cts_struct_dup_list(int type, GSList *src)
{
GSList *cur, *result = NULL;
if (src) {
result = g_slist_copy(src);
for (cur=result;cur;cur=cur->next) {
switch (type) {
case CTS_VALUE_NUMBER:
cur->data = cts_struct_dup_number(cur->data);
break;
case CTS_VALUE_EMAIL:
cur->data = cts_struct_dup_email(cur->data);
break;
case CTS_VALUE_WEB:
cur->data = cts_struct_dup_web(cur->data);
break;
case CTS_VALUE_POSTAL:
cur->data = cts_struct_dup_postal(cur->data);
break;
case CTS_VALUE_EVENT:
cur->data = cts_struct_dup_event(cur->data);
break;
case CTS_VALUE_MESSENGER:
cur->data = cts_struct_dup_messenger(cur->data);
break;
case CTS_VALUE_GROUP_RELATION:
cur->data = cts_struct_dup_grouprel(cur->data);
break;
case CTS_VALUE_EXTEND:
cur->data = cts_struct_dup_extend(cur->data);
break;
case CTS_VALUE_NICKNAME:
cur->data = cts_struct_dup_nick(cur->data);
break;
default:
ERR("invalid type(%d)", type);
break;
}
}
}
return result;
}
static inline cts_company* cts_struct_dup_company(const cts_company *src)
{
cts_company *result = NULL;
if (src) {
result = calloc(1, sizeof(cts_company));
retvm_if(NULL == result, NULL, "calloc() Failed");
memcpy(result, src, sizeof(cts_company));
if (src->name)
result->name = strdup(src->name);
if (src->department)
result->department = strdup(src->department);
if (src->jot_title)
result->jot_title = strdup(src->jot_title);
if (src->role)
result->role = strdup(src->role);
if (src->assistant_name)
result->assistant_name = strdup(src->assistant_name);
}
return result;
}
API CTSstruct* contacts_svc_struct_duplicate(const CTSstruct *contact)
{
contact_t *src, *result = NULL;
retvm_if(NULL == contact, NULL, "contact is NULL");
src = (contact_t *)contact;
result = (contact_t *)contacts_svc_struct_new(CTS_STRUCT_CONTACT);
retvm_if(NULL == result, NULL, "contacts_svc_struct_new() Failed");
result->base = cts_struct_dup_base(src->base);
result->name = cts_struct_dup_name(src->name);
result->numbers = cts_struct_dup_list(CTS_VALUE_NUMBER, src->numbers);
result->emails = cts_struct_dup_list(CTS_VALUE_EMAIL, src->emails);
result->web_addrs = cts_struct_dup_list(CTS_VALUE_WEB, src->web_addrs);
result->postal_addrs = cts_struct_dup_list(CTS_VALUE_POSTAL, src->postal_addrs);
result->events = cts_struct_dup_list(CTS_VALUE_EVENT, src->events);
result->messengers = cts_struct_dup_list(CTS_VALUE_MESSENGER, src->messengers);
result->grouprelations = cts_struct_dup_list(CTS_VALUE_GROUP_RELATION, src->grouprelations);
result->company = cts_struct_dup_company(src->company);
result->extended_values = cts_struct_dup_list(CTS_VALUE_EXTEND, src->extended_values);
result->nicknames = cts_struct_dup_list(CTS_VALUE_NICKNAME, src->nicknames);
result->default_num = src->default_num;
result->default_email = src->default_email;
return (CTSstruct *)result;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-socket.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "cts-internal.h"
#include "cts-normalize.h"
#include "cts-socket.h"
static int cts_csockfd = -1;
static inline int cts_safe_write(int fd, const char *buf, int buf_size)
{
int ret, writed=0;
while (buf_size) {
ret = write(fd, buf+writed, buf_size);
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return ret;
}
writed += ret;
buf_size -= ret;
}
return writed;
}
static inline int cts_safe_read(int fd, char *buf, int buf_size)
{
int ret, read_size=0;
while (buf_size) {
ret = read(fd, buf+read_size, buf_size);
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return ret;
}
read_size += ret;
buf_size -= ret;
}
return read_size;
}
static int cts_socket_handle_return(int fd, cts_socket_msg *msg)
{
CTS_FN_CALL;
int ret;
ret = cts_safe_read(fd, (char *)msg, sizeof(cts_socket_msg));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_read() Failed(errno = %d)", errno);
warn_if(CTS_REQUEST_RETURN_VALUE != msg->type,
"Unknown Type(%d), ret=%d, attach_num= %d,"
"attach1 = %d, attach2 = %d, attach3 = %d, attach4 = %d",
msg->type, msg->val, msg->attach_num,
msg->attach_sizes[0],msg->attach_sizes[1],msg->attach_sizes[2],
msg->attach_sizes[3]);
retvm_if(CTS_REQUEST_MAX_ATTACH < msg->attach_num, CTS_ERR_SOCKET_FAILED,
"Invalid msg(attach_num = %d)", msg->attach_num);
return CTS_SUCCESS;
}
static void cts_remove_invalid_msg(int fd, int size)
{
int ret;
char dummy[CTS_SOCKET_MSG_SIZE];
while (size) {
if (sizeof(dummy) < size) {
ret = read(fd, dummy, sizeof(dummy));
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return;
}
size -= ret;
}
else {
ret = read(fd, dummy, size);
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return;
}
size -= ret;
}
}
}
int cts_request_sim_import(void)
{
int i, ret;
cts_socket_msg msg={0};
retvm_if(-1 == cts_csockfd, CTS_ERR_ENV_INVALID, "socket is not connected");
msg.type = CTS_REQUEST_IMPORT_SIM;
ret = cts_safe_write(cts_csockfd, (char *)&msg, sizeof(msg));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_socket_handle_return(cts_csockfd, &msg);
retvm_if(CTS_SUCCESS != ret, ret, "cts_socket_handle_return() Failed(%d)", ret);
CTS_DBG("attach_num = %d", msg.attach_num);
for (i=0;i<msg.attach_num;i++)
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[i]);
return msg.val;
}
int cts_request_sim_export(int index)
{
int i, ret;
cts_socket_msg msg={0};
char src[64] = {0};
retvm_if(-1 == cts_csockfd, CTS_ERR_ENV_INVALID, "socket is not connected");
snprintf(src, sizeof(src), "%d", index);
msg.type = CTS_REQUEST_EXPORT_SIM;
msg.attach_num = 1;
msg.attach_sizes[0] = strlen(src);
ret = cts_safe_write(cts_csockfd, (char *)&msg, sizeof(msg));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_safe_write(cts_csockfd, src, msg.attach_sizes[0]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_socket_handle_return(cts_csockfd, &msg);
retvm_if(CTS_SUCCESS != ret, ret, "cts_socket_handle_return() Failed(%d)", ret);
CTS_DBG("attach_num = %d", msg.attach_num);
for (i=0;i<msg.attach_num;i++)
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[i]);
return msg.val;
}
int cts_request_normalize_str(const char *src, char *dest, int dest_size)
{
int i, ret;
cts_socket_msg msg={0};
retvm_if(-1 == cts_csockfd, CTS_ERR_ENV_INVALID, "socket is not connected");
msg.type = CTS_REQUEST_NORMALIZE_STR;
msg.attach_num = CTS_NS_ATTACH_NUM;
msg.attach_sizes[0] = strlen(src);
if (0 == msg.attach_sizes[0]) {
ERR("The parameter(src) is empty string");
dest[0] = '\0';
return CTS_SUCCESS;
}
ret = cts_safe_write(cts_csockfd, (char *)&msg, sizeof(msg));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_safe_write(cts_csockfd, src, msg.attach_sizes[0]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
CTS_DBG("Send message : %s(%d)", src, msg.attach_sizes[0]);
ret = cts_socket_handle_return(cts_csockfd, &msg);
retvm_if(CTS_SUCCESS != ret, ret, "cts_socket_handle_return() Failed(%d)", ret);
warn_if(CTS_NS_ATTACH_NUM != msg.attach_num,
"Invalid attachments(attach_num = %d)", msg.attach_num);
if (dest_size <= msg.attach_sizes[0]) {
ret = cts_safe_read(cts_csockfd, dest, dest_size);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_read() Failed(errno = %d)", errno);
msg.attach_sizes[0] -= ret;
dest[dest_size-1] = '\0';
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[0]);
}
else {
ret = cts_safe_read(cts_csockfd, dest, msg.attach_sizes[0]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_read() Failed(errno = %d)", errno);
dest[msg.attach_sizes[0]] = '\0';
}
for (i=CTS_NS_ATTACH_NUM;i<msg.attach_num;i++)
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[i]);
return msg.val;
}
int cts_request_normalize_name(char dest[][CTS_SQL_MAX_LEN])
{
int i, ret;
cts_socket_msg msg={0};
retvm_if(-1 == cts_csockfd, CTS_ERR_ENV_INVALID, "socket is not connected");
msg.type = CTS_REQUEST_NORMALIZE_NAME;
msg.attach_num = CTS_NN_ATTACH_NUM;
msg.attach_sizes[CTS_NN_FIRST] = strlen(dest[CTS_NN_FIRST]);
msg.attach_sizes[CTS_NN_LAST] = strlen(dest[CTS_NN_LAST]);
msg.attach_sizes[CTS_NN_SORTKEY] = strlen(dest[CTS_NN_SORTKEY]);
if (!msg.attach_sizes[CTS_NN_FIRST] && !msg.attach_sizes[CTS_NN_LAST]){
return CTS_SUCCESS;
}
ret = cts_safe_write(cts_csockfd, (char *)&msg, sizeof(msg));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_safe_write(cts_csockfd, dest[CTS_NN_FIRST], msg.attach_sizes[CTS_NN_FIRST]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_safe_write(cts_csockfd, dest[CTS_NN_LAST], msg.attach_sizes[CTS_NN_LAST]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
ret = cts_safe_write(cts_csockfd, dest[CTS_NN_SORTKEY], msg.attach_sizes[CTS_NN_SORTKEY]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_write() Failed(errno = %d)", errno);
CTS_DBG("request_first = %s(%d), request_last = %s(%d), request_sortkey = %s(%d)",
dest[CTS_NN_FIRST], msg.attach_sizes[CTS_NN_FIRST],
dest[CTS_NN_LAST], msg.attach_sizes[CTS_NN_LAST],
dest[CTS_NN_SORTKEY], msg.attach_sizes[CTS_NN_SORTKEY]);
ret = cts_socket_handle_return(cts_csockfd, &msg);
retvm_if(CTS_SUCCESS != ret, ret, "cts_socket_handle_return() Failed(%d)", ret);
if (CTS_NN_MAX < msg.attach_num) {
ERR("Invalid attachments(attach_num = %d)", msg.attach_num);
for (i=0;i<msg.attach_num;i++)
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[i]);
return CTS_ERR_MSG_INVALID;
}
for (i=0;i<msg.attach_num;i++)
{
CTS_DBG("msg_size = %d", msg.attach_sizes[i]);
if (CTS_SQL_MAX_LEN <= msg.attach_sizes[i])
{
ret = cts_safe_read(cts_csockfd, dest[i], sizeof(dest[i]));
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_read() Failed(errno = %d)", errno);
msg.attach_sizes[i] -= ret;
dest[i][CTS_SQL_MAX_LEN-1] = '\0';
cts_remove_invalid_msg(cts_csockfd, msg.attach_sizes[i]);
}
else {
ret = cts_safe_read(cts_csockfd, dest[i], msg.attach_sizes[i]);
retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "cts_safe_read() Failed(errno = %d)", errno);
dest[i][msg.attach_sizes[i]] = '\0';
}
}
return msg.val;
}
int cts_socket_init(void)
{
int ret;
struct sockaddr_un caddr;
bzero(&caddr, sizeof(caddr));
caddr.sun_family = AF_UNIX;
snprintf(caddr.sun_path, sizeof(caddr.sun_path), "%s", CTS_SOCKET_PATH);
cts_csockfd = socket(PF_UNIX, SOCK_STREAM, 0);
retvm_if(-1 == cts_csockfd, CTS_ERR_SOCKET_FAILED,
"socket() Failed(errno = %d)", errno);
ret = connect(cts_csockfd, (struct sockaddr *)&caddr, sizeof(caddr));
if (-1 == ret) {
ERR("connect() Failed(errno = %d)", errno);
close(cts_csockfd);
cts_csockfd = -1;
return CTS_ERR_SOCKET_FAILED;
}
return CTS_SUCCESS;
}
void cts_socket_final(void)
{
close(cts_csockfd);
cts_csockfd = -1;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-normalize.h
|
<filename>src/cts-normalize.h
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_NORMALIZE_H__
#define __CTS_NORMALIZE_H__
#include "cts-sqlite.h"
#define CTS_COMPARE_BETWEEN(left_range, value, right_range) (((left_range) <= (value)) && ((value) <= (right_range)))
#define CTS_VCONF_DEFAULT_LANGUAGE "file/private/contacts-service/default_lang"
/**
* Language Type
*/
enum LANGTYPE{
CTS_LANG_NUMBER = 0,
CTS_LANG_DEFAULT = 1,
CTS_LANG_SYMBOL = 2,
CTS_LANG_ENGLISH = 3,
CTS_LANG_KOREAN = 4, /* always last-first */
CTS_LANG_CHINESE = 5,
CTS_LANG_JAPANESE = 6,
CTS_LANG_FRENCH = 7,
CTS_LANG_GERMAN = 8,
CTS_LANG_ITALIAN = 9,
CTS_LANG_RUSSIAN = 10,
CTS_LANG_DUTCH = 11,
CTS_LANG_PORTUGUESE = 12,
CTS_LANG_TURKISH = 13,
CTS_LANG_GREEK = 14,
CTS_LANG_SPANISH = 15,
CTS_LANG_OTHERS = 16,
};
enum{
CTS_NN_FIRST,
CTS_NN_LAST,
CTS_NN_SORTKEY,
CTS_NN_MAX,
};
int cts_normalize_str(const char *src, char *dest, int dest_size);
int cts_normalize_name(cts_name *src, char dest[][CTS_SQL_MAX_LEN], bool is_display);
void cts_set_extra_normalize_fn(int (*fn)(char dest[][CTS_SQL_MAX_LEN]));
const char* cts_normalize_number(const char *src);
int cts_clean_number(const char *src, char *dest, int dest_size);
#endif //__CTS_NORMALIZE_H__
|
tizenorg/platform.core.pim.contacts-service
|
test/person-test.c
|
<reponame>tizenorg/platform.core.pim.contacts-service
/*
* Contacts Service
*
* Copyright (c) 2010 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <contacts-svc.h>
static int make_preconditon(const char *first, const char *last, const char *num)
{
int ret;
CTSstruct *contact;
CTSvalue *name, *number1, *base;
GSList *numbers;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if (name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, first);
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, last);
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
numbers = NULL;
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, num);
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT,
CTS_NUM_TYPE_CELL);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
g_slist_free(numbers);
contacts_svc_insert_contact(0, contact);
contacts_svc_struct_get_value(contact, CTS_CF_BASE_INFO_VALUE, &base);
ret = contacts_svc_value_get_int(base, CTS_BASE_VAL_PERSON_ID_INT);
contacts_svc_struct_free(contact);
return ret;
}
static void get_person(int id)
{
int index=0, ret=-1;
CTSstruct *person;
CTSvalue *value=NULL;
GSList *get_list, *cursor;
ret = contacts_svc_get_person(id, &person);
if (ret < 0) {
printf("No found record\n");
return;
}
contacts_svc_struct_get_value(person, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
//printf("Additional Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_ADDITION_STR));
//printf("Display Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_DISPLAY_STR));
//printf("Prefix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_PREFIX_STR));
//printf("Suffix Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_SUFFIX_STR));
get_list = NULL;
contacts_svc_struct_get_list(person, CTS_CF_NUMBER_LIST, &get_list);
for (cursor=get_list;cursor;cursor=g_slist_next(cursor))
{
int type;
type = contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT);
printf("number Type = %d ", type);
if (contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
if (index)
contacts_svc_set_favorite(CTS_FAVOR_NUMBER,
contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_ID_INT));
}
get_list = NULL;
contacts_svc_struct_get_list(person, CTS_CF_EMAIL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("email Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_EMAIL_VAL_TYPE_INT));
printf("email = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_EMAIL_VAL_ADDR_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(person, CTS_CF_GROUPREL_LIST, &get_list);
cursor = get_list;
for (;cursor;cursor=g_slist_next(cursor))
{
printf("group = %s:",
contacts_svc_value_get_str(cursor->data, CTS_GROUPREL_VAL_NAME_STR));
printf("%d\n",
contacts_svc_value_get_int(cursor->data, CTS_GROUPREL_VAL_ID_INT));
}
contacts_svc_struct_free(person);
}
static void get_person_list(void)
{
CTSiter *iter = NULL;
printf("Phone contact NUM = %d\n",
contacts_svc_count(CTS_GET_ALL_CONTACT));
contacts_svc_get_list(CTS_LIST_ALL_CONTACT, &iter);
while (CTS_SUCCESS == contacts_svc_iter_next(iter))
{
CTSvalue *contact = NULL;
const char *first, *last, *display;
contact = contacts_svc_iter_get_info(iter);
printf("(%8d)", contacts_svc_value_get_int(contact, CTS_LIST_CONTACT_ID_INT));
display = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_DISPLAY_STR);
if (display)
printf("%s :", display);
else
{
first = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_FIRST_STR);
last = contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_LAST_STR);
if (CTS_ORDER_NAME_FIRSTLAST == contacts_svc_get_order(CTS_ORDER_OF_DISPLAY))
printf("%s %s :", first, last);
else
printf("%s %s :", last, first);
}
printf("%s", contacts_svc_value_get_str(contact, CTS_LIST_CONTACT_IMG_PATH_STR));
printf("\n");
contacts_svc_value_free(contact);
}
contacts_svc_iter_remove(iter);
}
int main(int argc, char **argv)
{
int person1, person2;
contacts_svc_connect();
person1 = make_preconditon("111", "111", "11111111");
person2 = make_preconditon("222", "222", "22222222");
get_person_list();
contacts_svc_link_person(person1, person2);
get_person(person1);
get_person_list();
contacts_svc_unlink_person(person1, person2);
get_person_list();
contacts_svc_disconnect();
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-favorite.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "cts-internal.h"
#include "cts-schema.h"
#include "cts-sqlite.h"
#include "cts-utils.h"
#include "cts-restriction.h"
#include "cts-favorite.h"
API int contacts_svc_set_favorite(cts_favor_type op, int related_id)
{
int ret;
double prio = 0.0;
cts_stmt stmt;
char query[CTS_SQL_MAX_LEN] = {0};
retvm_if(CTS_FAVOR_PERSON != op && CTS_FAVOR_NUMBER != op, CTS_ERR_ARG_INVALID,
"op(%d) is invalid", op);
snprintf(query, sizeof(query),
"SELECT MAX(favorite_prio) FROM %s", CTS_TABLE_FAVORITES);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
ret = cts_stmt_step(stmt);
if (CTS_TRUE == ret) {
prio = cts_stmt_get_dbl(stmt, 0);
}
else if (CTS_SUCCESS != ret) {
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
cts_stmt_finalize(stmt);
prio = prio + 1.0;
snprintf(query, sizeof(query),
"INSERT INTO %s SELECT NULL, %d, contact_id, %f FROM %s WHERE person_id = %d",
CTS_TABLE_FAVORITES, op, prio, CTS_TABLE_CONTACTS, related_id);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret)
{
ERR("cts_query_exec() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
cts_set_favor_noti();
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_unset_favorite(cts_favor_type op, int related_id)
{
int ret;
cts_stmt stmt;
char query[CTS_SQL_MIN_LEN] = {0};
if (CTS_FAVOR_PERSON == op) {
snprintf(query, sizeof(query), "DELETE FROM %s WHERE type = %d AND related_id IN "
"(SELECT contact_id FROM %s WHERE person_id = %d)",
CTS_TABLE_FAVORITES, CTS_FAVOR_PERSON, CTS_TABLE_CONTACTS, related_id);
} else if (CTS_FAVOR_NUMBER == op) {
snprintf(query, sizeof(query), "DELETE FROM %s WHERE type = %d AND related_id = %d",
CTS_TABLE_FAVORITES, CTS_FAVOR_NUMBER, related_id);
} else {
ERR("op(%d) is invalid", op);
return CTS_ERR_ARG_INVALID;
}
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = contacts_svc_begin_trans();
if (ret) {
cts_stmt_finalize(stmt);
ERR("contacts_svc_begin_trans() Failed(%d)", ret);
return ret;
}
ret = cts_stmt_step(stmt);
if (CTS_SUCCESS != ret)
{
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
ret = cts_db_change();
cts_stmt_finalize(stmt);
if (0 < ret) {
cts_set_favor_noti();
ret = contacts_svc_end_trans(true);
}
else {
contacts_svc_end_trans(false);
ret = CTS_ERR_NO_DATA;
}
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_delete_favorite(int favorite_id)
{
int ret;
cts_stmt stmt;
char query[CTS_SQL_MIN_LEN] = {0};
snprintf(query, sizeof(query), "DELETE FROM %s WHERE id = %d",
CTS_TABLE_FAVORITES, favorite_id);
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_SUCCESS != ret)
{
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
ret = cts_db_change();
cts_stmt_finalize(stmt);
if (0 < ret) {
cts_set_favor_noti();
ret = contacts_svc_end_trans(true);
}
else {
contacts_svc_end_trans(false);
ret = CTS_ERR_NO_DATA;
}
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
static inline int cts_modify_favorite_prio(int favorite_id, int front, int back)
{
int ret;
cts_stmt stmt;
double front_prio=0.0, back_prio=0.0, prio;
char query[CTS_SQL_MIN_LEN] = {0};
snprintf(query, sizeof(query), "SELECT favorite_prio FROM %s WHERE id = ?",
CTS_TABLE_FAVORITES);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
cts_stmt_bind_int(stmt, 1, front);
ret = cts_stmt_step(stmt);
if (CTS_TRUE == ret)
front_prio = cts_stmt_get_dbl(stmt, 0);
cts_stmt_reset(stmt);
cts_stmt_bind_int(stmt, 1, back);
ret = cts_stmt_step(stmt);
if (CTS_TRUE == ret)
back_prio = cts_stmt_get_dbl(stmt, 0);
cts_stmt_finalize(stmt);
retvm_if(0.0 == front_prio && 0.0 == back_prio, CTS_ERR_ARG_INVALID,
"The indexes for front and back are invalid.");
if (0.0 == back_prio)
prio = front_prio + 1;
else
prio = (front_prio + back_prio) / 2;
snprintf(query, sizeof(query),
"UPDATE %s SET favorite_prio = %f WHERE id = %d",
CTS_TABLE_FAVORITES, prio, favorite_id);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret)
{
ERR("cts_query_exec() Failed(%d)", ret);
return ret;
}
return CTS_SUCCESS;
}
API int contacts_svc_favorite_order(int favorite_id,
int front_favorite_id, int back_favorite_id)
{
int ret;
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
ret = cts_modify_favorite_prio(favorite_id, front_favorite_id, back_favorite_id);
if (CTS_SUCCESS != ret)
{
ERR("cts_modify_favorite_prio() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
cts_set_favor_noti();
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_set_speeddial(int speed_num, int number_id)
{
int ret;
char query[CTS_SQL_MAX_LEN] = {0};
ret = contacts_svc_begin_trans();
retvm_if(ret, ret, "contacts_svc_begin_trans() Failed(%d)", ret);
snprintf(query, sizeof(query),
"INSERT INTO %s(speed_num, number_id) VALUES(%d, %d)",
CTS_TABLE_SPEEDDIALS, speed_num, number_id);
ret = cts_query_exec(query);
if (CTS_SUCCESS != ret) {
ERR("cts_query_exec() Failed(%d)", ret);
contacts_svc_end_trans(false);
return ret;
}
cts_set_speed_noti();
ret = contacts_svc_end_trans(true);
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_unset_speeddial(int speed_num)
{
int ret;
cts_stmt stmt;
char query[CTS_SQL_MIN_LEN] = {0};
snprintf(query, sizeof(query), "DELETE FROM %s WHERE speed_num = %d",
CTS_TABLE_SPEEDDIALS, speed_num);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = contacts_svc_begin_trans();
if (ret) {
cts_stmt_finalize(stmt);
ERR("contacts_svc_begin_trans() Failed(%d)", ret);
return ret;
}
ret = cts_stmt_step(stmt);
if (CTS_SUCCESS != ret) {
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
contacts_svc_end_trans(false);
return ret;
}
ret = cts_db_change();
cts_stmt_finalize(stmt);
if (0 < ret) {
cts_set_speed_noti();
ret = contacts_svc_end_trans(true);
}
else {
contacts_svc_end_trans(false);
ret = CTS_ERR_NO_DATA;
}
if (ret < CTS_SUCCESS)
return ret;
else
return CTS_SUCCESS;
}
API int contacts_svc_get_speeddial(int speed_num, CTSvalue **value)
{
int ret;
cts_stmt stmt;
const char *data;
cts_number *number;
char query[CTS_SQL_MAX_LEN] = {0};
if (cts_restriction_get_permit())
data = CTS_TABLE_DATA;
else
data = CTS_TABLE_RESTRICTED_DATA_VIEW;
snprintf(query, sizeof(query),
"SELECT A.id, A.data1, A.data2, A.contact_id FROM %s A, %s B "
"WHERE A.datatype = %d AND B.speed_num = %d AND A.id = B.number_id",
data, CTS_TABLE_SPEEDDIALS, CTS_DATA_NUMBER, speed_num);
stmt = cts_query_prepare(query);
retvm_if(NULL == stmt, CTS_ERR_DB_FAILED, "cts_query_prepare() Failed");
ret = cts_stmt_step(stmt);
if (CTS_TRUE != ret)
{
ERR("cts_stmt_step() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_DB_RECORD_NOT_FOUND;
}
number = (cts_number *)contacts_svc_value_new(CTS_VALUE_NUMBER);
if (number) {
ret = CTS_SUCCESS;
number->v_type = CTS_VALUE_RDONLY_NUMBER;
number->embedded = true;
number->id = cts_stmt_get_int(stmt, 0);
number->type = cts_stmt_get_int(stmt, 1);
number->number = SAFE_STRDUP(cts_stmt_get_text(stmt, 2));
ret = cts_stmt_get_int(stmt, 3);
*value = (CTSvalue*) number;
cts_stmt_finalize(stmt);
return ret;
}
else {
ERR("contacts_svc_value_new() Failed(%d)", ret);
cts_stmt_finalize(stmt);
return CTS_ERR_OUT_OF_MEMORY;
}
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-internal.h
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_INTERNAL_H__
#define __CTS_INTERNAL_H__
#include <stdio.h>
#include "cts-errors.h"
#include "cts-struct.h"
#ifndef API
#define API __attribute__ ((visibility("default")))
#endif
#define SAFE_STR(src) (src)?src:""
#define CTS_DLOG_OUT
//#define CTS_DEBUGGING
//#define CTS_TIMECHECK
#ifdef CTS_DLOG_OUT
#define LOG_TAG "CONTACTS_SVC"
#include <dlog.h>
#define DLOG(prio, fmt, arg...) \
do { SLOG(prio, LOG_TAG, fmt, ##arg); } while (0)
#define INFO(fmt, arg...) SLOGI(fmt, ##arg)
#define ERR(fmt, arg...) SLOGE("%s(%d): " fmt, __FUNCTION__, __LINE__, ##arg)
#define DBG(fmt, arg...) SLOGD("%s:" fmt, __FUNCTION__, ##arg)
#else
#include <unistd.h>
#define PRT(prio, fmt, arg...) \
do { fprintf((prio?stderr:stdout),"[Contacts-service]" fmt"\n", ##arg); } while (0)
#define INFO(fmt, arg...) PRT(0, fmt, ##arg)
#define ERR(fmt, arg...) PRT(1,"%s(%d): " fmt, __FUNCTION__, __LINE__, ##arg)
#define DBG(fmt, arg...) \
do { \
printf("\x1b[105;37m[%d]\x1b[0m(%s)" fmt "\n", getpid(), __FUNCTION__, ##arg); \
} while (0)
#endif
#ifdef CTS_DEBUGGING
#define CTS_FN_CALL DBG(">>>>>>>> called")
#define CTS_FN_END DBG("<<<<<<<< ended")
#define CTS_DBG(fmt, arg...) DBG("(%d) " fmt, __LINE__, ##arg)
#else /* CTS_DEBUGGING */
#define CTS_FN_CALL
#define CTS_FN_END
#define CTS_DBG(fmt, arg...)
#endif /* CTS_DEBUGGING */
#define warn_if(expr, fmt, arg...) do { \
if (expr) { \
ERR(fmt, ##arg); \
} \
} while (0)
#define ret_if(expr) do { \
if (expr) { \
ERR("(%s)", #expr); \
return; \
} \
} while (0)
#define retv_if(expr, val) do { \
if (expr) { \
ERR("(%s)", #expr); \
return (val); \
} \
} while (0)
#define retm_if(expr, fmt, arg...) do { \
if (expr) { \
ERR(fmt, ##arg); \
return; \
} \
} while (0)
#define retvm_if(expr, val, fmt, arg...) do { \
if (expr) { \
ERR(fmt, ##arg); \
return (val); \
} \
} while (0)
/************** TimeCheck ***************/
#ifdef CTS_TIMECHECK
double correction, startT;
double cts_set_start_time(void);
double cts_exec_time(double start);
int cts_init_time(void);
#define CTS_START_TIME_CHECK \
cts_init_time();\
startT = cts_set_start_time()
#define CTS_END_TIME_CHECK(fmt, arg...) \
DBG(fmt" time = %f ms\n", ##arg, cts_exec_time(startT))
#else /* CTS_TIMECHECK */
#define CTS_START_TIME_CHECK
#define CTS_END_TIME_CHECK(arg)
#endif /* CTS_TIMECHECK */
#endif /* __CTS_INTERNAL_H__ */
|
tizenorg/platform.core.pim.contacts-service
|
helper/localize.c
|
/*
* Contacts Service Helper
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "internal.h"
#include "cts-normalize.h"
#include "localize.h"
/* korean -Hangul Jamo extended A*/
#define CTS_JAMO_A_START (UChar)0xA960
#define CTS_JAMO_A_END (UChar)0xA97F
/* korean -Hangul Jamo extended B*/
#define CTS_JAMO_B_START (UChar)0xD7B0
#define CTS_JAMO_B_END (UChar)0xD7FF
/* korean -Hangul Compatability */
#define CTS_HAN_C_START (UChar)0x3130
#define CTS_HAN_C_END (UChar)0x318F
/* korean -Hangul halfwidth */
#define CTS_HAN_HALF_START (UChar)0xFFA0
#define CTS_HAN_HALF_END (UChar)0xFFDC
static const char hangul_compatibility_choseong[] = {
0x31, 0x32, 0x34, 0x37, 0x38, 0x39, 0x40, 0x41,
0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x65, 0x66, 0x6E,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80,
0x81, 0x84, 0x85, 0x86, 0x00};
static const unsigned char hangul_jamo_choseong[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x1A, 0x06, 0x07, // to choseong 0x1100~0x115F
0x08, 0x21, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x14, 0x15, 0x1C, 0x1D, 0x1E, 0x20,
0x22, 0x23, 0x27, 0x29, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x32, 0x36, 0x40, 0x47, 0x4C, 0x57, 0x58, 0x59, 0x00};
static const char hangul_compatibility_jungseong[] = {
0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E,
0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x87, 0x88,
0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x00};
static const unsigned char hangul_jamo_jungseong[] = {
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, // to jungseong 0x1160~0x11A7
0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x60, 0x84, 0x85, 0x88, 0x91, 0x92,
0x94, 0x9E, 0xA1, 0x00};
static const char hangul_compatibility_jongseong[] = {
0x33, 0x35, 0x36, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E,
0x3F, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D,
0x6F, 0x70, 0x82, 0x83, 0x00};
static const unsigned char hangul_jamo_jongseong[] = {
0xAA, 0xAC, 0xAD, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, // to jongseong 0x11A8~0x11FF
0xC7, 0xC8, 0xCC, 0xCE, 0xD3, 0xD7, 0xD9, 0xDF, 0xF1, 0xF2, 0x00};
static inline bool is_hangul(UChar src)
{
if ((0x1100 == (src & 0xFF00)) /* korean -Hangul Jamo*/
|| CTS_COMPARE_BETWEEN(CTS_JAMO_A_START, src, CTS_JAMO_A_END)
|| CTS_COMPARE_BETWEEN(CTS_JAMO_B_START, src, CTS_JAMO_B_END)
|| CTS_COMPARE_BETWEEN(CTS_HAN_C_START, src, CTS_HAN_C_END)
|| CTS_COMPARE_BETWEEN(CTS_HAN_HALF_START, src, CTS_HAN_HALF_END))
return true;
else
return FALSE;
}
static inline void hangul_compatibility2jamo(UChar *src)
{
int unicode_value1 = 0;
int unicode_value2 = 0;
unicode_value1 = (0xFF00 & (*src)) >> 8;
unicode_value2 = (0xFF & (*src));
/* korean -Hangul Jamo halfwidth*/
if (CTS_COMPARE_BETWEEN(CTS_HAN_HALF_START, *src, CTS_HAN_HALF_END)) {
unicode_value1 = 0x31;
if (unicode_value2 < 0xBF)
unicode_value2 -= 0x70;
else if (unicode_value2 < 0xC8)
unicode_value2 -= 0x73;
else if (unicode_value2 < 0xD0)
unicode_value2 -= 0x75;
else if (unicode_value2 < 0xD8)
unicode_value2 -= 0x77;
else
unicode_value2 -= 0x79;
(*src) = unicode_value1 << 8 | unicode_value2;
}
if (CTS_COMPARE_BETWEEN(CTS_HAN_C_START, *src, CTS_HAN_C_END))
{
char *pos;
if (NULL != (pos = strchr(hangul_compatibility_choseong, unicode_value2)))
{
unicode_value1 = 0x11;
unicode_value2 = hangul_jamo_choseong[pos - hangul_compatibility_choseong];
(*src) = unicode_value1 << 8 | unicode_value2;
}
else if (NULL != (pos = strchr(hangul_compatibility_jungseong, unicode_value2)))
{
unicode_value1 = 0x11;
unicode_value2 = hangul_jamo_jungseong[pos - hangul_compatibility_jungseong];
(*src) = unicode_value1 << 8 | unicode_value2;
}
else if (NULL != (pos = strchr(hangul_compatibility_jongseong, unicode_value2)))
{
unicode_value1 = 0x11;
unicode_value2 = hangul_jamo_jongseong[pos - hangul_compatibility_jongseong];
(*src) = unicode_value1 << 8 | unicode_value2;
}
}
}
int helper_check_language(UChar *word)
{
int type;
if (CTS_COMPARE_BETWEEN('0', word[0], '9')) {
type = CTS_LANG_NUMBER;
}
else if (CTS_COMPARE_BETWEEN(0x41, word[0], 0x7A)) { /* english */
type = CTS_LANG_ENGLISH;
}
else if (is_hangul(word[0])){
type = CTS_LANG_KOREAN;
}
else
type = CTS_LANG_OTHERS;
return type;
}
void helper_extra_normalize(UChar *word, int32_t word_size)
{
int i;
for (i=0;i<word_size;i++) {
if (is_hangul(word[i])) {
hangul_compatibility2jamo(&word[i]);
}
}
}
int helper_get_language_type(const char *system_lang)
{
int type;
h_retv_if(NULL == system_lang, CTS_LANG_OTHERS);
if (!strncmp(system_lang, "ko", sizeof("ko") - 1))
type = CTS_LANG_KOREAN;
else if (!strncmp(system_lang, "en", sizeof("en") - 1))
type = CTS_LANG_ENGLISH;
else
type = CTS_LANG_OTHERS;
return type;
}
|
tizenorg/platform.core.pim.contacts-service
|
test/timetest.c
|
<filename>test/timetest.c
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include "timetest.h"
FILE *outfp;
double correction;
double set_start_time(void)
{
// DEBUG_FUNC_START;
struct timeval tv;
double curtime;
gettimeofday(&tv, NULL);
curtime = tv.tv_sec * 1000 + (double)tv.tv_usec/1000;
return curtime;
}
double exec_time(double start)
{
// DEBUG_FUNC_START;
double end = set_start_time();
return (end - start - correction);
}
int init_time(void)
{
// DEBUG_FUNC_START;
double temp_t;
temp_t = set_start_time();
correction = exec_time(temp_t);
return 0;
}
int print_time(char *prn_args, double time)
{
DEBUG_FUNC_START;
#ifdef USE_STD_OUT
printf("%200s =\t", prn_args);
printf("%f \n", time);
#else
fprintf(outfp, "%.50s\t", prn_args);
fprintf(outfp, "%f \n", time);
#endif
return 0;
}
int print_argument(char *prn_args)
{
DEBUG_FUNC_START;
#ifdef USE_STD_OUT
printf("%s", prn_args);
#else
fprintf(outfp, "%s\n", prn_args);
#endif
return 0;
}
int print_milestone(char *prn_args, int level)
{
DEBUG_FUNC_START;
int i;
if (level > 1) {
for (i=0;i<level;i++)
printf("\n##################################################################\n");
printf("\n%s =\n", prn_args);
for (i=0;i<level;i++)
printf("\n##################################################################\n");
}
#ifdef USE_STD_OUT
if (1 == level)
printf("\n##################################################################\n");
printf("\n%s =\n", prn_args);
printf("\n##################################################################\n");
#else
for (i=0;i<level;i++)
fprintf(outfp, "\n##################################################################\n");
fprintf(outfp, "%s \n", prn_args);
for (i=0;i<level;i++)
fprintf(outfp, "\n##################################################################\n");
#endif
return 0;
}
int std_output(char *prn_args, double time)
{
DEBUG_FUNC_START;
printf("%.50s =\t", prn_args);
printf("%f \n", time);
return 0;
}
int file_print_init(char *filename)
{
DEBUG_FUNC_START;
outfp = fopen(filename, "w"); //"aw"
TEST_ERR_PRN_TREAT(NULL == outfp , ("(%s) Open Error \n", filename),
{return -1;});
return 0;
}
|
tizenorg/platform.core.pim.contacts-service
|
helper/normalize.c
|
/*
* Contacts Service Helper
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string.h>
#include <unicode/ustring.h>
#include <unicode/unorm.h>
#include <unicode/ucol.h>
#include <contacts-svc.h>
#include <vconf.h>
#include <vconf-keys.h>
#include "internal.h"
#include "cts-sqlite.h"
#include "localize.h"
#include "normalize.h"
#include "utils.h"
#define array_sizeof(a) (sizeof(a) / sizeof(a[0]))
int helper_unicode_to_utf8(char *src, int src_len, char *dest, int dest_size)
{
int32_t size = 0;
UErrorCode status = 0;
UChar *unicode_src = (UChar *)src;
u_strToUTF8(dest, dest_size, &size, unicode_src, -1, &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"u_strToUTF8() Failed(%s)", u_errorName(status));
dest[size]='\0';
return CTS_SUCCESS;
}
static inline int check_utf8(char c)
{
if ((c & 0xff) < (128 & 0xff))
return 1;
else if ((c & (char)0xe0) == (char)0xc0)
return 2;
else if ((c & (char)0xf0) == (char)0xe0)
return 3;
else if ((c & (char)0xf8) == (char)0xf0)
return 4;
else if ((c & (char)0xfc) == (char)0xf8)
return 5;
else if ((c & (char)0xfe) == (char)0xfc)
return 6;
else
return CTS_ERR_FAIL;
}
int helper_normalize_str(const char *src, char *dest, int dest_size)
{
int type = CTS_LANG_OTHERS;
int32_t size;
UErrorCode status = 0;
UChar tmp_result[CTS_SQL_MAX_LEN*2];
UChar result[CTS_SQL_MAX_LEN*2];
int i = 0;
int j = 0;
int str_len = strlen(src);
int char_len = 0;
for (i=0;i<str_len;i+=char_len) {
char char_src[10];
char_len = check_utf8(src[i]);
memcpy(char_src, &src[i], char_len);
char_src[char_len] = '\0';
u_strFromUTF8(tmp_result, array_sizeof(tmp_result), NULL, char_src, -1, &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"u_strFromUTF8() Failed(%s)", u_errorName(status));
u_strToLower(tmp_result, array_sizeof(tmp_result), tmp_result, -1, NULL, &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"u_strToLower() Failed(%s)", u_errorName(status));
size = unorm_normalize(tmp_result, -1, UNORM_NFD, 0,
(UChar *)result, array_sizeof(result), &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"unorm_normalize(%s) Failed(%s)", char_src, u_errorName(status));
if (0 == i)
type = helper_check_language(result);
helper_extra_normalize(result, size);
u_strToUTF8(&dest[j], dest_size-j, &size, result, -1, &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"u_strToUTF8() Failed(%s)", u_errorName(status));
j += size;
dest[j++] = 0x01;
}
dest[j]='\0';
HELPER_DBG("src(%s) is transformed(%s)", src, dest);
return type;
}
int helper_collation_str(const char *src, char *dest, int dest_size)
{
HELPER_FN_CALL;
int32_t size = 0;
UErrorCode status = 0;
UChar tmp_result[CTS_SQL_MAX_LEN];
UCollator *collator;
const char *region;
region = vconf_get_str(VCONFKEY_REGIONFORMAT);
HELPER_DBG("region %s", region);
collator = ucol_open(region, &status);
h_retvm_if(U_FAILURE(status), CTS_ERR_ICU_FAILED,
"ucol_open() Failed(%s)", u_errorName(status));
if (U_FAILURE(status)){
ERR("ucol_setAttribute Failed(%s)", u_errorName(status));
ucol_close(collator);
return CTS_ERR_ICU_FAILED;
}
u_strFromUTF8(tmp_result, array_sizeof(tmp_result), NULL, src, -1, &status);
if (U_FAILURE(status)){
ERR("u_strFromUTF8 Failed(%s)", u_errorName(status));
ucol_close(collator);
return CTS_ERR_ICU_FAILED;
}
size = ucol_getSortKey(collator, tmp_result, -1, (uint8_t *)dest, dest_size);
ucol_close(collator);
dest[size]='\0';
return CTS_SUCCESS;
}
API int cts_helper_normalize_name(char dest[][CTS_SQL_MAX_LEN])
{
int lang_type=0;
int ret=CTS_ERR_NO_DATA;
int sizes[CTS_NN_MAX]={0};
char normalized_first[CTS_SQL_MAX_LEN];
char normalized_last[CTS_SQL_MAX_LEN];
sizes[CTS_NN_FIRST] = strlen(dest[CTS_NN_FIRST]);
sizes[CTS_NN_LAST] = strlen(dest[CTS_NN_LAST]);
if (sizes[CTS_NN_FIRST]) {
ret = helper_normalize_str(dest[CTS_NN_FIRST], normalized_first,
sizeof(normalized_first));
h_retvm_if(ret < CTS_SUCCESS, ret, "helper_normalize_str() Failed(%d)", ret);
lang_type = ret;
sizes[CTS_NN_FIRST] = strlen(normalized_first);
}
if (sizes[CTS_NN_LAST]) {
ret = helper_normalize_str(dest[CTS_NN_LAST], normalized_last,
sizeof(normalized_first));
h_retvm_if(ret < CTS_SUCCESS, ret, "helper_normalize_str() Failed(%d)", ret);
if (lang_type < ret) lang_type = ret;
sizes[CTS_NN_LAST] = strlen(normalized_last);
}
if (sizes[CTS_NN_FIRST])
snprintf(dest[CTS_NN_FIRST], sizeof(dest[CTS_NN_FIRST]), "%s", normalized_first);
if (sizes[CTS_NN_LAST])
snprintf(dest[CTS_NN_LAST], sizeof(dest[CTS_NN_LAST]), "%s", normalized_last);
return lang_type;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-types.h
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_TYPES_H__
#define __CTS_TYPES_H__
//<!--
/**
* @defgroup CONTACTS_SVC_TYPES Types
* @ingroup CONTACTS_SVC
* @addtogroup CONTACTS_SVC_TYPES
* @{
*
* It is Types of Number, E-mail, Web address, Address, Event, Phone Log, etc.
* And this interface provides methods to handle custom types.
*
*/
/**
* The Number can be made with a set of values by specifying one or more values.
* \n Example : CTS_NUM_TYPE_HOME|CTS_NUM_TYPE_VOICE
* \n Exceptionally, CTS_NUM_TYPE_CUSTOM is exclusive.
* CTS_NUM_TYPE_CUSTOM should be handled earlier.
*/
enum NUMBERTYPE{
CTS_NUM_TYPE_NONE = 0,
CTS_NUM_TYPE_HOME = 1<<0,/**< a telephone number associated with a residence */
CTS_NUM_TYPE_WORK = 1<<1,/**< a telephone number associated with a place of work */
CTS_NUM_TYPE_VOICE = 1<<2,/**< a voice telephone number */
CTS_NUM_TYPE_FAX = 1<<3,/**< a facsimile telephone number */
CTS_NUM_TYPE_MSG = 1<<4,/**< the telephone number has voice messaging support */
CTS_NUM_TYPE_CELL = 1<<5,/**< a cellular telephone number */
CTS_NUM_TYPE_PAGER = 1<<6,/**< a paging device telephone number */
CTS_NUM_TYPE_BBS = 1<<7,/**< a bulletin board system telephone number */
CTS_NUM_TYPE_MODEM = 1<<8,/**< a MODEM connected telephone number */
CTS_NUM_TYPE_CAR = 1<<9,/**< a car-phone telephone number */
CTS_NUM_TYPE_ISDN = 1<<10,/**< an ISDN service telephone number */
CTS_NUM_TYPE_VIDEO = 1<<11,/**< a video conferencing telephone number */
CTS_NUM_TYPE_PCS = 1<<12,/**< a personal communication services telephone number */
CTS_NUM_TYPE_ASSISTANT = 1<<30,/**< a additional type for assistant */
CTS_NUM_TYPE_CUSTOM = 1<<31,/**< Custom number type */
};
enum EMAILTYPE{
CTS_EMAIL_TYPE_NONE = 0,/**< Other */
CTS_EMAIL_TYPE_HOME = 1<<0,/**< . */
CTS_EMAIL_TYPE_WORK = 1<<1,/**< . */
};
enum ADDRESSTYPE{
CTS_ADDR_TYPE_NONE = 0,/**< . */
CTS_ADDR_TYPE_HOME = 1<<0,/**< a delivery address for a residence */
CTS_ADDR_TYPE_WORK = 1<<1,/**< a delivery address for a place of work */
CTS_ADDR_TYPE_DOM = 1<<2,/**< a domestic delivery address */
CTS_ADDR_TYPE_INTL = 1<<3,/**< an international delivery address */
CTS_ADDR_TYPE_POSTAL = 1<<4,/**< a postal delivery address */
CTS_ADDR_TYPE_PARCEL = 1<<5,/**< a parcel delivery address */
};
enum WEBTYPE{
CTS_WEB_TYPE_NONE,/**< Other */
CTS_WEB_TYPE_HOME,/**< . */
CTS_WEB_TYPE_WORK,/**< . */
};
enum PLOGTYPE{
CTS_PLOG_TYPE_NONE,
CTS_PLOG_TYPE_VOICE_INCOMMING = 1,/**< . */
CTS_PLOG_TYPE_VOICE_OUTGOING = 2,/**< . */
CTS_PLOG_TYPE_VIDEO_INCOMMING = 3,/**< . */
CTS_PLOG_TYPE_VIDEO_OUTGOING = 4,/**< . */
CTS_PLOG_TYPE_VOICE_INCOMMING_UNSEEN = 5,/**< Not confirmed missed call */
CTS_PLOG_TYPE_VOICE_INCOMMING_SEEN = 6,/**< Confirmed missed call */
CTS_PLOG_TYPE_VIDEO_INCOMMING_UNSEEN = 7,/**< Not confirmed missed video call */
CTS_PLOG_TYPE_VIDEO_INCOMMING_SEEN = 8,/**< Confirmed missed video call */
CTS_PLOG_TYPE_VOICE_REJECT = 9,/**< . */
CTS_PLOG_TYPE_VIDEO_REJECT = 10,/**< . */
CTS_PLOG_TYPE_VOICE_BLOCKED = 11,/**< . */
CTS_PLOG_TYPE_VIDEO_BLOCKED = 12,/**< . */
CTS_PLOG_TYPE_MMS_INCOMMING = 101,/**< . */
CTS_PLOG_TYPE_MMS_OUTGOING = 102,/**< . */
CTS_PLOG_TYPE_SMS_INCOMMING = 103,/**< . */
CTS_PLOG_TYPE_SMS_OUTGOING = 104,/**< . */
CTS_PLOG_TYPE_SMS_BLOCKED = 105,/**< . */
CTS_PLOG_TYPE_MMS_BLOCKED = 106,/**< . */
CTS_PLOG_TYPE_EMAIL_RECEIVED = 201,/**<.*/
CTS_PLOG_TYPE_EMAIL_SENT = 202,/**<.*/
CTS_PLOG_TYPE_MAX
};
enum EVENTTYPE{
CTS_EVENT_TYPE_BIRTH,/**< . */
CTS_EVENT_TYPE_ANNIVERSARY/**< . */
};
enum ADDRESSBOOKTYPE{
CTS_ADDRESSBOOK_TYPE_INTERNAL, /**< . */
CTS_ADDRESSBOOK_TYPE_EXCHANGE, /**< . */
CTS_ADDRESSBOOK_TYPE_GOOGLE, /**< . */
CTS_ADDRESSBOOK_TYPE_YAHOO, /**< . */
CTS_ADDRESSBOOK_TYPE_FACEBOOK, /**< . */
CTS_ADDRESSBOOK_TYPE_OTHER, /**< . */
};
/**
* Use for contacts_svc_insert_custom_type(),
* contacts_svc_delete_custom_type(), contacts_svc_find_custom_type().
*/
typedef enum {
CTS_TYPE_CLASS_EXTEND_DATA=0,/**< Extend Data type(@ref CONTACTS_SVC_EXTEND) */
CTS_TYPE_CLASS_NUM=1,/**< Custom Number type */
}cts_custom_type_class;
/**
* This function inserts a User defined type into database.
* This api assigns a index of the group automatically.
* \n The returned index is unique & non-reusable.
*
* @param[in] type_class #cts_custom_type_class
* @param[in] type_name Name of Custom Type
* @return the index of the inserted custom type on success, Negative value(#cts_error) on error
*/
int contacts_svc_insert_custom_type(cts_custom_type_class type_class, char *type_name);
/**
* This function deletes a user defined type in database.
*
* @param[in] type_class #cts_custom_type_class
* @param[in] index The index of User defined type to delete in database.
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_delete_custom_type(cts_custom_type_class type_class, int index);
/**
* This function gets name of custom type.
* Obtained string should be free using by free().
* @param[in] type_class #cts_custom_type_class
* @param[in] index The index of User defined type.
* @return The gotten information, or NULL if no value is obtained or error
*/
char* contacts_svc_get_custom_type(cts_custom_type_class type_class, int index);
/**
* This function gets index of user defined type of #name.
*
* @param[in] type_class #cts_custom_type_class
* @param[in] type_name The name of type for searching
* @return index of found Custom type on success, Negative value(#cts_error) on error
*/
int contacts_svc_find_custom_type(cts_custom_type_class type_class, char *type_name);
/*
* @}
*/
/**
* @defgroup CONTACTS_SVC_EXTEND Using the Extend Data for Contact
* @ingroup CONTACTS_SVC
* @addtogroup CONTACTS_SVC_EXTEND
* @{
*
* This is description of usages of extend data related with a contact.
*
* @section extend_sec1 Properties
* - The extend data is contacts service value(#CTSvalue).
* - The extend data only exist for contact struct(#CTSstruct).
* - The type of extend data is defined
* by contacts_svc_insert_custom_type() with #CTS_TYPE_CLASS_EXTEND_DATA.
* - The extend data is stored to contact by contacts_svc_struct_store_value().
* - Extend data can be stored only one at each type in contacts.
* - The index of custom type is used as the field parameter of contacts_svc_struct_store_value().
* - The composition of the extend data(#EXTENDVALUE)
* -# #CTS_EXTEND_VAL_DATA1_INT
* -# #CTS_EXTEND_VAL_DATA2_STR
* -# #CTS_EXTEND_VAL_DATA3_STR
* -# #CTS_EXTEND_VAL_DATA4_STR
* -# #CTS_EXTEND_VAL_DATA5_STR
* -# #CTS_EXTEND_VAL_DATA6_STR
* -# #CTS_EXTEND_VAL_DATA7_STR
* -# #CTS_EXTEND_VAL_DATA8_STR
* -# #CTS_EXTEND_VAL_DATA9_STR
* -# #CTS_EXTEND_VAL_DATA10_STR
*
* @section extend_sec2 Usages
* - Notice
* \n The extend data has values of fixed type.
* \n Therefore if you want to save values of the other types, convert to string.
* \n This mechanism is a supplementary mechanism. Do not abuse.
* - example
* @code
#include <stdio.h>
#include <glib.h>
#include <contacts-svc.h>
static void print_extend_contact(CTSstruct *contact)
{
int ret;
CTSvalue *value;
GSList *get_list, *cursor;
value = NULL;
contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &value);
printf("First Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_FIRST_STR));
printf("Last Name : %s\n", contacts_svc_value_get_str(value, CTS_NAME_VAL_LAST_STR));
value = NULL;
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
ret = contacts_svc_struct_get_value(contact, ret, &value);
if(CTS_SUCCESS == ret) {
printf("extend1 data2 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA2_STR));
printf("extend1 data3 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA3_STR));
printf("extend1 data4 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA4_STR));
}
value = NULL;
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
ret = contacts_svc_struct_get_value(contact, ret, &value);
if(CTS_SUCCESS == ret) {
printf("extend2 data2 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA2_STR));
printf("extend2 data3 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA3_STR));
printf("extend2 data4 : %s\n", contacts_svc_value_get_str(value, CTS_EXTEND_VAL_DATA4_STR));
}
get_list = NULL;
contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
cursor = get_list;
for(;cursor;cursor=g_slist_next(cursor))
{
printf("number Type = %d",
contacts_svc_value_get_int(cursor->data, CTS_NUM_VAL_TYPE_INT));
if(contacts_svc_value_get_bool(cursor->data, CTS_NUM_VAL_FAVORITE_BOOL))
printf("(favorite)");
printf("Number = %s\n",
contacts_svc_value_get_str(cursor->data, CTS_NUM_VAL_NUMBER_STR));
}
}
void extend_data_test(void)
{
int ret, index;
CTSstruct *contact;
CTSvalue *name, *number1, *extend_value;
GSList *numbers=NULL;
contact = contacts_svc_struct_new(CTS_STRUCT_CONTACT);
name = contacts_svc_value_new(CTS_VALUE_NAME);
if(name) {
contacts_svc_value_set_str(name, CTS_NAME_VAL_FIRST_STR, "People");
contacts_svc_value_set_str(name, CTS_NAME_VAL_LAST_STR, "Japan");
}
contacts_svc_struct_store_value(contact, CTS_CF_NAME_VALUE, name);
contacts_svc_value_free(name);
number1 = contacts_svc_value_new(CTS_VALUE_NUMBER);
if(number1) {
contacts_svc_value_set_str(number1, CTS_NUM_VAL_NUMBER_STR, "0333333333");
contacts_svc_value_set_int(number1, CTS_NUM_VAL_TYPE_INT, CTS_NUM_TYPE_MOBILE);
contacts_svc_value_set_bool(number1, CTS_NUM_VAL_DEFAULT_BOOL, true);
}
numbers = g_slist_append(numbers, number1);
contacts_svc_struct_store_list(contact, CTS_CF_NUMBER_LIST, numbers);
contacts_svc_value_free(number1);
g_slist_free(numbers);
extend_value = contacts_svc_value_new(CTS_VALUE_EXTEND);
if(extend_value) {
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "YomiFirstName");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA3_STR, "YomiLastName");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA4_STR, "YomiCompanyName");
}
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
if(CTS_ERR_DB_RECORD_NOT_FOUND == ret)
ret = contacts_svc_insert_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "YomiName");
contacts_svc_struct_store_value(contact, ret, extend_value);
contacts_svc_value_free(extend_value);
extend_value = contacts_svc_value_new(CTS_VALUE_EXTEND);
if(extend_value) {
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "Children1");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA3_STR, "Children2");
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA4_STR, "Children3");
}
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
if(CTS_ERR_DB_RECORD_NOT_FOUND == ret)
ret = contacts_svc_insert_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
contacts_svc_struct_store_value(contact, ret, extend_value);
contacts_svc_value_free(extend_value);
index = contacts_svc_insert_contact(0, contact);
contacts_svc_struct_free(contact);
contact = NULL;
ret = contacts_svc_get_contact(index, &contact);
if(ret < 0)
{
printf("No found record\n");
return;
}
print_extend_contact(contact);
//update test
extend_value = NULL;
ret = contacts_svc_find_custom_type(CTS_TYPE_CLASS_EXTEND_DATA, "Family");
ret = contacts_svc_struct_get_value(contact, ret, &extend_value);
if(CTS_SUCCESS == ret)
contacts_svc_value_set_str(extend_value, CTS_EXTEND_VAL_DATA2_STR, "Children4");
contacts_svc_struct_store_value(contact, ret, extend_value);
contacts_svc_update_contact(contact);
contacts_svc_struct_free(contact);
contact = NULL;
ret = contacts_svc_get_contact(index, &contact);
if(ret < 0)
{
printf("No found record\n");
return;
}
print_extend_contact(contact);
contacts_svc_struct_free(contact);
}
int main()
{
contacts_svc_connect();
extend_data_test();
contacts_svc_disconnect();
return 0;
}
* @endcode
*
* @}
*/
//-->
#endif //__CTS_TYPES_H__
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-schema.h
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_SCHEMA_H__
#define __CTS_SCHEMA_H__
#define CTS_DB_PATH "/opt/dbspace/.contacts-svc.db"
#define CTS_DB_JOURNAL_PATH "/opt/dbspace/.contacts-svc.db-journal"
// For Security
#define CTS_SECURITY_FILE_GROUP 6005
#define CTS_SECURITY_DEFAULT_PERMISSION 0660
#define CTS_SECURITY_DIR_DEFAULT_PERMISSION 0770
#define CTS_SCHEMA_TABLE_TOTAL 10
// Tables
#define CTS_TABLE_PERSONS "persons"
#define CTS_TABLE_CONTACTS "contacts"
#define CTS_TABLE_GROUPS "groups"
#define CTS_TABLE_ADDRESSBOOKS "addressbooks"
#define CTS_TABLE_DATA "data" // This is the data table for contact all fields
#define CTS_TABLE_FAVORITES "favorites"
#define CTS_TABLE_PHONELOGS "phonelogs"
#define CTS_TABLE_PHONELOG_ACC "phonelog_accumulation"
#define CTS_TABLE_GROUPING_INFO "group_relations"
#define CTS_TABLE_DELETEDS "deleteds"
#define CTS_TABLE_GROUP_DELETEDS "group_deleteds"
#define CTS_TABLE_CUSTOM_TYPES "custom_types"
#define CTS_TABLE_SIM_SERVICES "sim_services"
#define CTS_TABLE_SPEEDDIALS "speeddials"
#define CTS_TABLE_VERSION "cts_version"
#define CTS_TABLE_MY_PROFILES "my_profiles"
#define CTS_TABLE_RESTRICTED_DATA_VIEW "restricted_data"
#define CTS_SCHEMA_DATA_NAME_LANG_INFO "data1"
#define CTS_SCHEMA_DATA_NAME_LOOKUP "data8"
#define CTS_SCHEMA_DATA_NAME_REVERSE_LOOKUP "data9"
#define CTS_SCHEMA_DATA_NAME_SORTING_KEY "data10"
#define CTS_SCHEMA_SQLITE_SEQ "sqlite_sequence"
#endif /* __CTS_SCHEMA_H__ */
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-addressbook.h
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_ADDRESSBOOK_H__
#define __CTS_ADDRESSBOOK_H__
/**
* system addressbook id
*/
enum ADDRESSBOOK{
CTS_ADDRESSBOOK_INTERNAL,
CTS_ADDRESSBOOK_START,
};
#ifndef __CONTACTS_SVC_H__
//<!--
/**
* @defgroup CONTACTS_SVC_ADDRESSBOOK Addressbook Modification
* @ingroup CONTACTS_SVC
* @addtogroup CONTACTS_SVC_ADDRESSBOOK
* @{
*
* This interface provides methods to insert/update/delete the addressbook.
* Addressbook supports groups and contacts. Several addressbooks can be included in the same account_id.
*
* If the ID of an addressbook is 'zero', it means it is the internal addressbook of a phone.
* It needs additional management because it is not included in database(physical storage).
*
* - getting all addressbook (0 is logical value for internal addressbook)
* @code
void addrbook_list(void)
{
int ret, count;
CTSiter *iter;
count = contacts_svc_count_with_int(CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, 0);
printf("Phone(%d)", count);
ret = contacts_svc_get_list(CTS_LIST_ALL_ADDRESSBOOK, &iter);
if (CTS_SUCCESS != ret) {
printf("contacts_svc_get_list() Failed(%d)\n", ret);
return;
}
while (CTS_SUCCESS == contacts_svc_iter_next(iter)) {
int id;
const char *name;
CTSvalue *info;
info = contacts_svc_iter_get_info(iter);
id = contacts_svc_value_get_int(info, CTS_LIST_ADDRESSBOOK_ID_INT);
name = contacts_svc_value_get_str(info, CTS_LIST_ADDRESSBOOK_NAME_STR);
count = contacts_svc_count_with_int(CTS_GET_COUNT_CONTACTS_IN_ADDRESSBOOK, id);
printf("%s(%d)", name, count);
}
contacts_svc_iter_remove(iter);
}
* @endcode
*
*/
/**
* addressbook permission
*/
enum ADDRESSBOOKPERMISSION {
CTS_ADDRESSBOOK_MODE_NONE, /**< .*/
CTS_ADDRESSBOOK_MODE_READONLY, /**< .*/
};
/**
* This function inserts a addressbook information into database.
* The implementation assigns an index number of the addressbook automatically.
* \n The returned index is unique and non-reusable.
*
* @param[in] addressbook A addressbook information of #CTSvalue created by contacts_svc_value_new(CTS_VALUE_ADDRESSBOOK).
* @return the index of contact on success, Negative value(#cts_error) on error
* @par example
* @code
int insert_addrbook(void)
{
int ret;
CTSvalue *ab;
ab = contacts_svc_value_new(CTS_VALUE_ADDRESSBOOK);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_ACC_ID_INT, 1);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_ACC_TYPE_INT, CTS_ADDRESSBOOK_TYPE_GOOGLE);
contacts_svc_value_set_int(ab, CTS_ADDRESSBOOK_VAL_MODE_INT, CTS_ADDRESSBOOK_MODE_NONE);
contacts_svc_value_set_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR, "test1");
ret = contacts_svc_insert_addressbook(ab);
if(ret < CTS_SUCCESS)
printf("contacts_svc_insert_addressbook() Failed\n");
contacts_svc_value_free(ab);
return ret;
}
* @endcode
*/
int contacts_svc_insert_addressbook(CTSvalue *addressbook);
/**
* This function deletes the addressbook information related to addressbook_id.
* Also, the related contacts and groups are deleted.
* @param[in] addressbook_id index of addressbook
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
*/
int contacts_svc_delete_addressbook(int addressbook_id);
/**
* This function updates a addressbook information into database.
*
* @param[in] addressbook A addressbook information of #CTSvalue created by contacts_svc_get_addressbook().
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @par example
* @code
void update_addrbook(void)
{
int ret;
CTSvalue *ab = NULL;
ret = contacts_svc_get_addressbook(2, &ab);
if(CTS_SUCCESS != ret) {
printf("contacts_svc_get_addressbook() Failed\n");
return;
}
contacts_svc_value_set_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR,"Fixed-addressbook");
ret = contacts_svc_update_addressbook(ab);
if(ret < CTS_SUCCESS)
printf("contacts_svc_update_addressbook() Failed\n");
contacts_svc_value_free(ab);
}
* @endcode
*/
int contacts_svc_update_addressbook(CTSvalue *addressbook);
/**
* This function gets a addressbook record which has the index from the database.
* Obtained addressbook record should be free using by contacts_svc_value_free().
* @param[in] addressbook_id The index of addressbook to get
* @param[out] ret_value Points of the addressbook record which is returned
* @return #CTS_SUCCESS on success, Negative value(#cts_error) on error
* @par example
* @code
void get_addrbook(int addressbook_id)
{
int ret;
const char *name;
CTSvalue *ab = NULL;
ret = contacts_svc_get_addressbook(addressbook_id, &ab);
if(CTS_SUCCESS != ret) {
printf("contacts_svc_get_addressbook() Failed\n");
return;
}
printf("///////////%d//////////////\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ID_INT));
printf("The related account ID : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ACC_ID_INT));
printf("The related account type : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_ACC_TYPE_INT));
printf("permission : %d\n",
contacts_svc_value_get_int(ab, CTS_ADDRESSBOOK_VAL_MODE_INT));
name = contacts_svc_value_get_str(ab, CTS_ADDRESSBOOK_VAL_NAME_STR);
if(name)
printf("Name : %s\n", name);
printf("//////////////////////////\n");
contacts_svc_value_free(ab);
}
* @endcode
*/
int contacts_svc_get_addressbook(int addressbook_id, CTSvalue **ret_value);
/**
* @}
*/
//-->
#endif //__CONTACTS_SVC_H__
#endif //__CTS_ADDRESSBOOK_H__
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-socket.h
|
<gh_stars>0
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_SOCKET_H__
#define __CTS_SOCKET_H__
#include "cts-struct.h"
#include "cts-sqlite.h"
#define CTS_SOCKET_PATH "/opt/data/contacts-svc/.contacts-svc.sock"
#define CTS_SOCKET_MSG_SIZE 128
//Message TYPE
enum{
CTS_REQUEST_RETURN_VALUE,
CTS_REQUEST_IMPORT_SIM,
CTS_REQUEST_NORMALIZE_STR,
CTS_REQUEST_NORMALIZE_NAME,
CTS_REQUEST_EXPORT_SIM,
};
//#define CTS_REQUEST_IMPORT_SIM "cts_request_import_sim"
//#define CTS_REQUEST_NORMALIZE_STR "cts_request_normalize_str"
//#define CTS_REQUEST_RETURN_VALUE "cts_request_return_value"
#define CTS_REQUEST_MAX_ATTACH 5
#define CTS_NS_ATTACH_NUM 1 //NS = Normalize String
#define CTS_NN_ATTACH_NUM 3 //NN = Normalize Name
typedef struct{
int type;
int val;
int attach_num;
int attach_sizes[CTS_REQUEST_MAX_ATTACH];
}cts_socket_msg;
int cts_socket_init(void);
int cts_request_normalize_name(char dest[][CTS_SQL_MAX_LEN]);
int cts_request_normalize_str(const char * src, char * dest, int dest_size);
int cts_request_sim_import(void);
int cts_request_sim_export(int index);
void cts_socket_final(void);
#endif //__CTS_SOCKET_H__
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-sqlite.c
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string.h>
#include <db-util.h>
#include "cts-internal.h"
#include "cts-schema.h"
#include "cts-im.h"
#include "cts-sqlite.h"
static sqlite3 *cts_db;
int cts_db_open(void)
{
CTS_FN_CALL;
int ret;
if (!cts_db) {
ret = db_util_open(CTS_DB_PATH, &cts_db, 0);
retvm_if(SQLITE_OK != ret, CTS_ERR_DB_NOT_OPENED,
"db_util_open() Failed(%d)", ret);
}
return CTS_SUCCESS;
}
int cts_db_close(void)
{
int ret = 0;
if (cts_db) {
ret = db_util_close(cts_db);
warn_if(SQLITE_OK != ret, "db_util_close() Failed(%d)", ret);
cts_db = NULL;
CTS_DBG("The database disconnected really.");
}
return CTS_SUCCESS;
}
int cts_db_change(void)
{
return sqlite3_changes(cts_db);
}
int cts_db_get_last_insert_id(void)
{
return sqlite3_last_insert_rowid(cts_db);
}
int cts_db_get_next_id(const char *table)
{
int ret;
char query[CTS_SQL_MAX_LEN] = {0};
snprintf(query, sizeof(query), "SELECT seq FROM %s WHERE name = '%s'",
CTS_SCHEMA_SQLITE_SEQ, table);
ret = cts_query_get_first_int_result(query);
if (ret < CTS_SUCCESS) {
if (CTS_ERR_DB_RECORD_NOT_FOUND == ret)
return 1;
else
return ret;
} else {
return (1 + ret);
}
}
int cts_query_get_first_int_result(const char *query)
{
int ret;
cts_stmt stmt = NULL;
retvm_if(NULL == cts_db, CTS_ERR_DB_NOT_OPENED, "Database is not opended");
ret = sqlite3_prepare_v2(cts_db, query, strlen(query), &stmt, NULL);
retvm_if(SQLITE_OK != ret, CTS_ERR_DB_FAILED,
"sqlite3_prepare_v2(%s) Failed(%s)", query, sqlite3_errmsg(cts_db));
ret = sqlite3_step(stmt);
if (SQLITE_ROW != ret) {
ERR("sqlite3_step() Failed(%d, %s)", ret, sqlite3_errmsg(cts_db));
sqlite3_finalize(stmt);
if (SQLITE_DONE == ret) return CTS_ERR_DB_RECORD_NOT_FOUND;
return CTS_ERR_DB_FAILED;
}
ret = sqlite3_column_int(stmt, 0);
sqlite3_finalize(stmt);
return ret;
}
int cts_query_exec(const char *query)
{
int ret;
char *err_msg = NULL;
retvm_if(NULL == cts_db, CTS_ERR_DB_NOT_OPENED, "Database is not opended");
CTS_DBG("query : %s", query);
ret = sqlite3_exec(cts_db, query, NULL, NULL, &err_msg);
if (SQLITE_OK != ret) {
ERR("sqlite3_exec(%s) Failed(%d, %s)", query, ret, err_msg);
sqlite3_free(err_msg);
switch (ret) {
case SQLITE_BUSY:
case SQLITE_LOCKED:
return CTS_ERR_DB_LOCK;
case SQLITE_IOERR:
return CTS_ERR_IO_ERR;
case SQLITE_FULL:
return CTS_ERR_NO_SPACE;
default:
return CTS_ERR_DB_FAILED;
}
}
return CTS_SUCCESS;
}
cts_stmt cts_query_prepare(char *query)
{
int ret = -1;
cts_stmt stmt = NULL;
retvm_if(NULL == cts_db, NULL, "Database is not opended");
CTS_DBG("prepare query : %s", query);
ret = sqlite3_prepare_v2(cts_db, query, strlen(query), &stmt, NULL);
retvm_if(SQLITE_OK != ret, NULL,
"sqlite3_prepare_v2(%s) Failed(%s)", query, sqlite3_errmsg(cts_db));
return stmt;
}
int cts_stmt_get_first_int_result(cts_stmt stmt)
{
int ret;
retvm_if(NULL == cts_db, CTS_ERR_DB_NOT_OPENED, "Database is not opended");
ret = sqlite3_step(stmt);
if (SQLITE_ROW != ret) {
ERR("sqlite3_step() Failed(%d, %s)", ret, sqlite3_errmsg(cts_db));
sqlite3_finalize(stmt);
if (SQLITE_DONE == ret) return CTS_ERR_DB_RECORD_NOT_FOUND;
return CTS_ERR_DB_FAILED;
}
ret = sqlite3_column_int(stmt, 0);
sqlite3_finalize(stmt);
return ret;
}
int cts_stmt_step(cts_stmt stmt)
{
int ret;
ret = sqlite3_step(stmt);
switch (ret) {
case SQLITE_BUSY:
case SQLITE_LOCKED:
ret = CTS_ERR_DB_LOCK;
break;
case SQLITE_IOERR:
ret = CTS_ERR_IO_ERR;
break;
case SQLITE_FULL:
ret = CTS_ERR_NO_SPACE;
break;
case SQLITE_CONSTRAINT:
ret = CTS_ERR_ALREADY_EXIST;
break;
case SQLITE_ROW:
ret = CTS_TRUE;
break;
case SQLITE_DONE:
ret = CTS_SUCCESS;
break;
default:
ERR("sqlite3_step() Failed(%d)", ret);
ret = CTS_ERR_DB_FAILED;
break;
}
return ret;
}
void cts_stmt_reset(cts_stmt stmt)
{
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
}
void cts_stmt_finalize(cts_stmt stmt)
{
int ret;
if (NULL == stmt)
return;
ret = sqlite3_finalize(stmt);
warn_if(ret != SQLITE_OK,
"sqlite3_finalize Failed(%d, %s)", ret, sqlite3_errmsg(cts_db));
}
int cts_stmt_bind_name(cts_stmt stmt, int start_cnt, cts_name *name_struct)
{
if (name_struct->first)
sqlite3_bind_text(stmt, start_cnt+1, name_struct->first,
strlen(name_struct->first), SQLITE_STATIC);
if (name_struct->last)
sqlite3_bind_text(stmt, start_cnt+2, name_struct->last,
strlen(name_struct->last), SQLITE_STATIC);
if (name_struct->addition)
sqlite3_bind_text(stmt, start_cnt+3, name_struct->addition,
strlen(name_struct->addition), SQLITE_STATIC);
if (name_struct->display)
sqlite3_bind_text(stmt, start_cnt+4, name_struct->display,
strlen(name_struct->display), SQLITE_STATIC);
if (name_struct->prefix)
sqlite3_bind_text(stmt, start_cnt+5, name_struct->prefix,
strlen(name_struct->prefix), SQLITE_STATIC);
if (name_struct->suffix)
sqlite3_bind_text(stmt, start_cnt+6, name_struct->suffix,
strlen(name_struct->suffix), SQLITE_STATIC);
return start_cnt+7;
}
int cts_stmt_bind_event(cts_stmt stmt, int start_cnt, cts_event *event_struct)
{
sqlite3_bind_int(stmt, start_cnt++, event_struct->type);
sqlite3_bind_int(stmt, start_cnt++, event_struct->date);
return CTS_SUCCESS;
}
int cts_stmt_bind_messenger(cts_stmt stmt, int start_cnt, cts_messenger *im_struct)
{
sqlite3_bind_int(stmt, start_cnt, im_struct->type);
if (im_struct->im_id)
sqlite3_bind_text(stmt, start_cnt+1, im_struct->im_id,
strlen(im_struct->im_id), SQLITE_STATIC);
if (CTS_IM_TYPE_NONE == im_struct->type) {
if (im_struct->svc_name)
sqlite3_bind_text(stmt, start_cnt+2, im_struct->svc_name,
strlen(im_struct->svc_name), SQLITE_STATIC);
if (im_struct->svc_op)
sqlite3_bind_text(stmt, start_cnt+3, im_struct->svc_op,
strlen(im_struct->svc_op), SQLITE_STATIC);
}
return CTS_SUCCESS;
}
int cts_stmt_bind_postal(cts_stmt stmt, int start_cnt, cts_postal *postal_struct)
{
sqlite3_bind_int(stmt, start_cnt, postal_struct->type);
if (postal_struct->pobox)
sqlite3_bind_text(stmt, start_cnt+1, postal_struct->pobox,
strlen(postal_struct->pobox), SQLITE_STATIC);
if (postal_struct->postalcode)
sqlite3_bind_text(stmt, start_cnt+2, postal_struct->postalcode,
strlen(postal_struct->postalcode), SQLITE_STATIC);
if (postal_struct->region)
sqlite3_bind_text(stmt, start_cnt+3, postal_struct->region,
strlen(postal_struct->region), SQLITE_STATIC);
if (postal_struct->locality)
sqlite3_bind_text(stmt, start_cnt+4, postal_struct->locality,
strlen(postal_struct->locality), SQLITE_STATIC);
if (postal_struct->street)
sqlite3_bind_text(stmt, start_cnt+5, postal_struct->street,
strlen(postal_struct->street), SQLITE_STATIC);
if (postal_struct->extended)
sqlite3_bind_text(stmt, start_cnt+6, postal_struct->extended,
strlen(postal_struct->extended), SQLITE_STATIC);
if (postal_struct->country)
sqlite3_bind_text(stmt, start_cnt+7, postal_struct->country,
strlen(postal_struct->country), SQLITE_STATIC);
return CTS_SUCCESS;
}
int cts_stmt_bind_company(cts_stmt stmt, int start_cnt, cts_company *company_struct)
{
if (company_struct->name)
sqlite3_bind_text(stmt, start_cnt+1, company_struct->name,
strlen(company_struct->name), SQLITE_STATIC);
if (company_struct->department)
sqlite3_bind_text(stmt, start_cnt+2, company_struct->department,
strlen(company_struct->department), SQLITE_STATIC);
if (company_struct->jot_title)
sqlite3_bind_text(stmt, start_cnt+3, company_struct->jot_title,
strlen(company_struct->jot_title), SQLITE_STATIC);
if (company_struct->role)
sqlite3_bind_text(stmt, start_cnt+4, company_struct->role,
strlen(company_struct->role), SQLITE_STATIC);
if (company_struct->assistant_name)
sqlite3_bind_text(stmt, start_cnt+5, company_struct->assistant_name,
strlen(company_struct->assistant_name), SQLITE_STATIC);
return CTS_SUCCESS;
}
int cts_stmt_bind_web(cts_stmt stmt, int start_cnt, cts_web *web_struct)
{
sqlite3_bind_int(stmt, start_cnt++, web_struct->type);
if (web_struct->url)
sqlite3_bind_text(stmt, start_cnt++, web_struct->url,
strlen(web_struct->url), SQLITE_STATIC);
return CTS_SUCCESS;
}
int cts_stmt_bind_extend(cts_stmt stmt, int start_cnt, cts_extend *extend_struct)
{
sqlite3_bind_int(stmt, start_cnt, extend_struct->data1);
if (extend_struct->data2)
sqlite3_bind_text(stmt, start_cnt+1, extend_struct->data2,
strlen(extend_struct->data2), SQLITE_STATIC);
if (extend_struct->data3)
sqlite3_bind_text(stmt, start_cnt+2, extend_struct->data3,
strlen(extend_struct->data3), SQLITE_STATIC);
if (extend_struct->data4)
sqlite3_bind_text(stmt, start_cnt+3, extend_struct->data4,
strlen(extend_struct->data4), SQLITE_STATIC);
if (extend_struct->data5)
sqlite3_bind_text(stmt, start_cnt+4, extend_struct->data5,
strlen(extend_struct->data5), SQLITE_STATIC);
if (extend_struct->data6)
sqlite3_bind_text(stmt, start_cnt+5, extend_struct->data6,
strlen(extend_struct->data6), SQLITE_STATIC);
if (extend_struct->data7)
sqlite3_bind_text(stmt, start_cnt+6, extend_struct->data7,
strlen(extend_struct->data7), SQLITE_STATIC);
if (extend_struct->data8)
sqlite3_bind_text(stmt, start_cnt+7, extend_struct->data8,
strlen(extend_struct->data8), SQLITE_STATIC);
if (extend_struct->data9)
sqlite3_bind_text(stmt, start_cnt+8, extend_struct->data9,
strlen(extend_struct->data9), SQLITE_STATIC);
if (extend_struct->data10)
sqlite3_bind_text(stmt, start_cnt+9, extend_struct->data10,
strlen(extend_struct->data10), SQLITE_STATIC);
return CTS_SUCCESS;
}
int cts_stmt_get_addressbook(cts_stmt stmt, cts_addrbook *ab)
{
int cnt = 0;
char *temp;
ab->id = cts_stmt_get_int(stmt, cnt++);
temp = cts_stmt_get_text(stmt, cnt++);
ab->name = SAFE_STRDUP(temp);
ab->acc_id = cts_stmt_get_int(stmt, cnt++);
ab->acc_type = cts_stmt_get_int(stmt, cnt++);
ab->mode = cts_stmt_get_int(stmt, cnt++);
return CTS_SUCCESS;
}
int cts_stmt_get_number(cts_stmt stmt, cts_number *result, int start_cnt)
{
char *temp;
result->id = cts_stmt_get_int(stmt, start_cnt++);
result->type = cts_stmt_get_int(stmt, start_cnt++);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->number = SAFE_STRDUP(temp);
return start_cnt;
}
int cts_stmt_get_email(cts_stmt stmt, cts_email *result, int start_cnt)
{
char *temp;
result->id = cts_stmt_get_int(stmt, start_cnt++);
result->type = cts_stmt_get_int(stmt, start_cnt++);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->email_addr = SAFE_STRDUP(temp);
return start_cnt;
}
int cts_stmt_get_name(cts_stmt stmt, cts_name *result, int start_cnt)
{
char *temp;
result->id = cts_stmt_get_int(stmt, start_cnt++);
result->lang_type = cts_stmt_get_int(stmt, start_cnt++);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->first = SAFE_STRDUP(temp);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->last = SAFE_STRDUP(temp);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->addition = SAFE_STRDUP(temp);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->display = SAFE_STRDUP(temp);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->prefix = SAFE_STRDUP(temp);
temp = cts_stmt_get_text(stmt, start_cnt++);
result->suffix = SAFE_STRDUP(temp);
return CTS_SUCCESS;
}
|
tizenorg/platform.core.pim.contacts-service
|
src/cts-sqlite.h
|
/*
* Contacts Service
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __CTS_SQLITE_H__
#define __CTS_SQLITE_H__
#include <sqlite3.h>
#include "cts-struct.h"
#define CTS_SQL_MAX_LEN 2048 //normal string length
#define CTS_SQL_MIN_LEN 1024 //short sql string length
typedef sqlite3_stmt* cts_stmt;
int cts_db_open(void);
int cts_db_close(void);
int cts_db_change();
int cts_db_get_last_insert_id(void);
int cts_db_get_next_id(const char *table);
int cts_query_get_first_int_result(const char *query);
int cts_query_exec(const char *query);
cts_stmt cts_query_prepare(char *query);
int cts_stmt_step(cts_stmt stmt);
void cts_stmt_reset(cts_stmt stmt);
void cts_stmt_finalize(cts_stmt stmt);
int cts_stmt_get_first_int_result(cts_stmt stmt);
static inline int cts_stmt_bind_int(cts_stmt stmt, int pos, int num) {
return sqlite3_bind_int(stmt, pos, num);
}
static inline int cts_stmt_bind_text(cts_stmt stmt, int pos, const char *str) {
return sqlite3_bind_text(stmt, pos, str, strlen(str), SQLITE_STATIC);
}
static inline int cts_stmt_bind_copy_text(cts_stmt stmt, int pos,
const char *str, int strlen){
return sqlite3_bind_text(stmt, pos, str, strlen, SQLITE_TRANSIENT);
}
int cts_stmt_bind_copy_text(cts_stmt stmt, int pos, const char *str, int strlen);
int cts_stmt_bind_name(cts_stmt stmt, int start_cnt, cts_name *name_struct);
int cts_stmt_bind_postal(cts_stmt stmt, int start_cnt, cts_postal *postal_struct);
int cts_stmt_bind_company(cts_stmt stmt, int start_cnt, cts_company *company_struct);
int cts_stmt_bind_web(cts_stmt stmt, int start_cnt, cts_web *web_struct);
int cts_stmt_bind_messenger(cts_stmt stmt, int start_cnt, cts_messenger *im_struct);
int cts_stmt_bind_event(cts_stmt stmt, int start_cnt, cts_event *event_struct);
int cts_stmt_bind_extend(cts_stmt stmt, int start_cnt, cts_extend *extend_struct);
static inline double cts_stmt_get_dbl(cts_stmt stmt, int pos) {
return sqlite3_column_double(stmt, pos);
}
static inline int cts_stmt_get_int(cts_stmt stmt, int pos) {
return sqlite3_column_int(stmt, pos);
}
static inline char* cts_stmt_get_text(cts_stmt stmt, int pos) {
return (char *)sqlite3_column_text(stmt, pos);
}
int cts_stmt_get_addressbook(cts_stmt stmt, cts_addrbook *ab);
int cts_stmt_get_number(cts_stmt stmt, cts_number *result, int start_cnt);
int cts_stmt_get_email(cts_stmt stmt, cts_email *result, int start_cnt);
int cts_stmt_get_name(cts_stmt stmt, cts_name *result, int start_cnt);
#endif //__CTS_SQLITE_H__
|
tizenorg/platform.core.pim.contacts-service
|
helper/helper-socket.c
|
<filename>helper/helper-socket.c<gh_stars>0
/*
* Contacts Service Helper
*
* Copyright (c) 2010 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact: <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <unistd.h>
#include <stdlib.h>
#include <glib.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <contacts-svc.h>
#include <sd-daemon.h>
#include "internal.h"
#include "cts-schema.h"
#include "cts-sqlite.h"
#include "cts-socket.h"
#include "helper-socket.h"
#include "sim.h"
#include "normalize.h"
#include "utils.h"
static inline int helper_safe_write(int fd, char *buf, int buf_size)
{
int ret, writed=0;
while (buf_size) {
ret = write(fd, buf+writed, buf_size);
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return ret;
}
writed += ret;
buf_size -= ret;
}
return writed;
}
static inline int helper_safe_read(int fd, char *buf, int buf_size)
{
int ret, read_size=0;
while (buf_size) {
ret = read(fd, buf+read_size, buf_size);
if (-1 == ret) {
if (EINTR == errno)
continue;
else
return ret;
}
read_size += ret;
buf_size -= ret;
}
return read_size;
}
static void helper_discard_msg(GIOChannel *src, int size)
{
gsize len;
GError *gerr = NULL;
char dummy[CTS_SQL_MAX_LEN];
while (size) {
if (sizeof(dummy) < size) {
g_io_channel_read_chars(src, dummy, sizeof(dummy), &len, &gerr);
if (gerr) {
ERR("g_io_channel_read_chars() Failed(%s)", gerr->message);
g_error_free(gerr);
return;
}
size -= len;
}
else {
g_io_channel_read_chars(src, dummy, size, &len, &gerr);
if (gerr) {
ERR("g_io_channel_read_chars() Failed(%s)", gerr->message);
g_error_free(gerr);
return;
}
size -= len;
}
}
}
int helper_socket_return(GIOChannel *src, int value, int attach_num, int *attach_size)
{
int ret;
cts_socket_msg msg={0};
h_retvm_if(CTS_ERR_SOCKET_FAILED == value, value, "Socket has problems");
h_retvm_if(CTS_REQUEST_MAX_ATTACH < attach_num, CTS_ERR_ARG_INVALID,
"Invalid msg(attach_num = %d)", attach_num);
msg.type = CTS_REQUEST_RETURN_VALUE;
msg.val = value;
msg.attach_num = attach_num;
memcpy(msg.attach_sizes, attach_size, attach_num * sizeof(int));
HELPER_DBG("fd = %d, MSG_TYPE=%d, MSG_VAL=%d, MSG_ATTACH_NUM=%d,"
"MSG_ATTACH1=%d, MSG_ATTACH2=%d, MSG_ATTACH3=%d, MSG_ATTACH4=%d",
g_io_channel_unix_get_fd(src), msg.type, msg.val, msg.attach_num,
msg.attach_sizes[0], msg.attach_sizes[1], msg.attach_sizes[2],
msg.attach_sizes[3]);
ret = helper_safe_write(g_io_channel_unix_get_fd(src), (char *)&msg, sizeof(msg));
h_retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED,
"helper_safe_write() Failed(errno = %d)", errno);
return CTS_SUCCESS;
}
static void helper_handle_import_sim(GIOChannel *src)
{
int ret;
ret = helper_sim_read_pb_record(src);
if (CTS_SUCCESS != ret) {
ERR("helper_sim_read_pb_record() Failed(%d)", ret);
helper_socket_return(src, ret, 0, NULL);
}
}
static void helper_handle_export_sim(GIOChannel *src, int size)
{
int ret;
gsize len;
GError *gerr = NULL;
char receiver[CTS_SQL_MAX_LEN];
g_io_channel_read_chars(src, receiver, size, &len, &gerr);
if (gerr) {
ERR("g_io_channel_read_chars() Failed(%s)", gerr->message);
g_error_free(gerr);
return;
}
HELPER_DBG("Receiver = %s(%d), read_size = %d", receiver, len, size);
if (len) {
receiver[len] = '\0';
HELPER_DBG("export contact %d", atoi(receiver));
ret = helper_sim_write_pb_record(src, atoi(receiver));
if (CTS_SUCCESS != ret) {
ERR("helper_sim_write_pb_record() Failed(%d)", ret);
helper_socket_return(src, ret, 0, NULL);
}
}
}
static int helper_normalize(GIOChannel *src, int read_size,
char *dest, int dest_size)
{
int ret=CTS_SUCCESS;
gsize len;
GError *gerr = NULL;
char receiver[CTS_SQL_MAX_LEN];
g_io_channel_read_chars(src, receiver, read_size, &len, &gerr);
if (gerr) {
ERR("g_io_channel_read_chars() Failed(%s)", gerr->message);
g_error_free(gerr);
return CTS_ERR_SOCKET_FAILED;
}
HELPER_DBG("Receiver = %s(%d), read_size = %d", receiver, len, read_size);
if (len) {
receiver[len] = '\0';
ret = helper_normalize_str(receiver, dest, dest_size);
h_retvm_if(ret < CTS_SUCCESS, ret, "helper_normalize_str() Failed(%d)", ret);
HELPER_DBG("Normalized text of %s = %s(%d)", receiver, dest, strlen(dest));
}
return ret;
}
static int helper_collation(GIOChannel *src, int read_size,
char *dest, int dest_size)
{
int ret = CTS_SUCCESS;
gsize len;
GError *gerr = NULL;
char receiver[CTS_SQL_MAX_LEN];
g_io_channel_read_chars(src, receiver, read_size, &len, &gerr);
if (gerr) {
ERR("g_io_channel_read_chars() Failed(%s)", gerr->message);
g_error_free(gerr);
return CTS_ERR_SOCKET_FAILED;
}
HELPER_DBG("Receiver = %s(%d), read_size = %d", receiver, len, read_size);
if (len) {
receiver[len] = '\0';
ret = helper_collation_str(receiver, dest, dest_size);
h_retvm_if(ret < CTS_SUCCESS, ret, "helper_collation_str() Failed(%d)", ret);
HELPER_DBG("Sortkey of %s : %s, %d", receiver, dest, strlen(dest));
}
return ret;
}
static void helper_handle_normalize_str(GIOChannel *src, int size)
{
HELPER_FN_CALL;
int str_len, ret;
char normalized_str[CTS_SQL_MAX_LEN];
ret = helper_normalize(src, size, normalized_str, sizeof(normalized_str));
if (ret < CTS_SUCCESS) {
ERR("helper_normalize() Failed(%d)", ret);
helper_socket_return(src, ret, 0, NULL);
return;
}
str_len = strlen(normalized_str);
ret = helper_socket_return(src, CTS_SUCCESS, 1, &str_len);
h_retm_if(CTS_SUCCESS != ret, "helper_socket_return() Failed(%d)", ret);
ret = helper_safe_write(g_io_channel_unix_get_fd(src), normalized_str, str_len);
h_retm_if(-1 == ret, "helper_safe_write() Failed(errno = %d)", errno);
}
static void helper_handle_normalize_name(GIOChannel *src, int* sizes)
{
HELPER_FN_CALL;
int fd, ret;
int lang_type = 0;
int msg_size_buf[CTS_REQUEST_MAX_ATTACH]={0};
char normalized_first[CTS_SQL_MAX_LEN], normalized_last[CTS_SQL_MAX_LEN];
char sortkey[CTS_SQL_MAX_LEN];
if (sizes[CTS_NN_FIRST])
{
ret = helper_normalize(src, sizes[CTS_NN_FIRST], normalized_first,
sizeof(normalized_first));
if (ret < CTS_SUCCESS) {
ERR("helper_normalize() Failed(%d)", ret);
helper_discard_msg(src, sizes[CTS_NN_LAST] + sizes[CTS_NN_SORTKEY]);
helper_socket_return(src, ret, 0, NULL);
return;
}
lang_type = ret;
msg_size_buf[CTS_NN_FIRST] = strlen(normalized_first);
}
if (sizes[CTS_NN_LAST])
{
ret = helper_normalize(src, sizes[CTS_NN_LAST], normalized_last,
sizeof(normalized_last));
if (ret < CTS_SUCCESS) {
ERR("helper_normalize() Failed(%d)", ret);
helper_discard_msg(src, sizes[CTS_NN_SORTKEY]);
helper_socket_return(src, ret, 0, NULL);
return;
}
if (lang_type < ret) lang_type = ret;
msg_size_buf[CTS_NN_LAST] = strlen(normalized_last);
}
if (sizes[CTS_NN_SORTKEY])
{
ret = helper_collation(src, sizes[CTS_NN_SORTKEY], sortkey, sizeof(sortkey));
if (ret < CTS_SUCCESS) {
ERR("helper_collation() Failed(%d)", ret);
helper_socket_return(src, ret, 0, NULL);
}
msg_size_buf[CTS_NN_SORTKEY] = strlen(sortkey);
}
ret = helper_socket_return(src, lang_type, 3, msg_size_buf);
h_retm_if(CTS_SUCCESS != ret, "helper_socket_return() Failed(%d)", ret);
fd = g_io_channel_unix_get_fd(src);
ret = helper_safe_write(fd, normalized_first, msg_size_buf[0]);
h_retm_if(-1 == ret, "helper_safe_write() Failed(errno = %d)", errno);
ret = helper_safe_write(fd, normalized_last, msg_size_buf[1]);
h_retm_if(-1 == ret, "helper_safe_write() Failed(errno = %d)", errno);
ret = helper_safe_write(fd, sortkey, msg_size_buf[2]);
h_retm_if(-1 == ret, "helper_safe_write() Failed(errno = %d)", errno);
}
static gboolean request_handler(GIOChannel *src, GIOCondition condition,
gpointer data)
{
int ret;
cts_socket_msg msg={0};
HELPER_FN_CALL;
if (G_IO_HUP & condition) {
close(g_io_channel_unix_get_fd(src));
return FALSE;
}
ret = helper_safe_read(g_io_channel_unix_get_fd(src), (char *)&msg, sizeof(msg));
h_retvm_if(-1 == ret, TRUE, "helper_safe_read() Failed(errno = %d)", errno);
HELPER_DBG("attach number = %d, attach1 = %d, attach2 = %d, attach3 = %d",
msg.attach_num, msg.attach_sizes[CTS_NN_FIRST],
msg.attach_sizes[CTS_NN_LAST], msg.attach_sizes[CTS_NN_SORTKEY]);
switch (msg.type)
{
case CTS_REQUEST_IMPORT_SIM:
helper_handle_import_sim(src);
break;
case CTS_REQUEST_EXPORT_SIM:
helper_handle_export_sim(src, msg.attach_sizes[0]);
break;
case CTS_REQUEST_NORMALIZE_STR:
if (CTS_NS_ATTACH_NUM != msg.attach_num) {
ERR("Invalid CTS_NS_ATTACH_NUM = %d", msg.attach_num);
helper_socket_return(src, CTS_ERR_MSG_INVALID, 0, NULL);
}
else
helper_handle_normalize_str(src, msg.attach_sizes[0]);
break;
case CTS_REQUEST_NORMALIZE_NAME:
if (CTS_NN_ATTACH_NUM != msg.attach_num) {
ERR("Invalid CTS_NN_ATTACH_NUM = %d", msg.attach_num);
helper_socket_return(src, CTS_ERR_MSG_INVALID, 0, NULL);
}else if (!msg.attach_sizes[CTS_NN_FIRST] && !msg.attach_sizes[CTS_NN_LAST]) {
ERR("No attach names(CTS_NN_FIRST size = %d, CTS_NN_LAST size = %d ",
msg.attach_sizes[CTS_NN_FIRST], msg.attach_sizes[CTS_NN_LAST]);
helper_socket_return(src, CTS_ERR_MSG_INVALID, 0, NULL);
}
else
helper_handle_normalize_name(src, msg.attach_sizes);
break;
default:
ERR("Unknown request type(%d)", msg.type);
break;
}
return TRUE;
}
static gboolean socket_handler(GIOChannel *src,
GIOCondition condition, gpointer data)
{
GIOChannel *channel;
int client_sockfd, sockfd = (int)data;
struct sockaddr_un clientaddr;
socklen_t client_len = sizeof(clientaddr);
HELPER_FN_CALL;
client_sockfd = accept(sockfd, (struct sockaddr *)&clientaddr, &client_len);
h_retvm_if(-1 == client_sockfd, TRUE, "accept() Failed(errno = %d)", errno);
channel = g_io_channel_unix_new(client_sockfd);
g_io_add_watch(channel, G_IO_IN|G_IO_HUP, request_handler, NULL);
g_io_channel_unref(channel);
return TRUE;
}
int helper_socket_init(void)
{
int sockfd, ret;
struct sockaddr_un addr;
GIOChannel *gio;
if (sd_listen_fds(1) == 1 && sd_is_socket_unix(SD_LISTEN_FDS_START, SOCK_STREAM, -1, CTS_SOCKET_PATH, 0) > 0) {
sockfd = SD_LISTEN_FDS_START;
} else {
unlink(CTS_SOCKET_PATH);
bzero(&addr, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", CTS_SOCKET_PATH);
sockfd = socket(PF_UNIX, SOCK_STREAM, 0);
h_retvm_if(-1 == sockfd, CTS_ERR_SOCKET_FAILED, "socket() Failed(errno = %d)", errno);
ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
h_retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "bind() Failed(errno = %d)", errno);
chown(CTS_SOCKET_PATH, getuid(), CTS_SECURITY_FILE_GROUP);
chmod(CTS_SOCKET_PATH, CTS_SECURITY_DEFAULT_PERMISSION);
ret = listen(sockfd, 30);
h_retvm_if(-1 == ret, CTS_ERR_SOCKET_FAILED, "listen() Failed(errno = %d)", errno);
}
gio = g_io_channel_unix_new(sockfd);
g_io_add_watch(gio, G_IO_IN, socket_handler, (gpointer)sockfd);
return CTS_SUCCESS;
}
|
danielbrodi/WatchDog
|
watchdog.h
|
/*********************************FILE__HEADER*********************************\
* File: watchdog.h
* Author: <NAME>
* Date: 11-July-2021
* Version: 1.0
* Description: Watchdog program implementation API.
\******************************************************************************/
#ifndef __WATCHDOG_H__
#define __WATCHDOG_H__
#include <stddef.h> /* size_t */
/* Creates a Watch Dog program that will watch your program and restart it
* if it gets stuck or terminates.
* signal_intervals is necessary to determine the time that wait time between
* signals sending. num_allowed_misses is the amount of signals that the
* Watch Dog will not recevie before deciding that the other side is down,
* and will restart it. */
void KeepMeAlive(int argc, char *argv[], size_t signal_intervals,
size_t num_allowed_misses);
/* DNR - Do not resuscitate.
* Used to stop the Watch Dog from watching the program.
* Returns '0' if DNR request succeeded and WD won't watch the program anymore.
* Returns '1' if failed. */
int DNR(void);
#endif /* __WATCHDOG_H__ */
|
danielbrodi/WatchDog
|
wd_internal.h
|
/*********************************FILE__HEADER*********************************\
* File: watchdog.h
* Author: <NAME>
* Date: 14-July-2021
* Version: 1.0
* Description: Watchdog's program internal functions API.
--Not available or visible to the client--
\******************************************************************************/
#ifndef __WD_INTERNAL_H__
#define __WD_INTERNAL_H__
#include "scheduler.h" /* oper_ret_ty */
#ifdef NDEBUG
#define DEBUG if(0)
#else
#define DEBUG if(1)
#endif
/* a struct that contains all relevant and needed data to start a program */
typedef struct info
{
char **argv_for_wd;
size_t num_allowed_misses;
size_t signal_intervals;
int i_am_wd; /* 0 if the caller is the user app, 1 if its the WD program */
sem_t *is_process_ready; /* indicates if the process is ready to receive signals */
}info_ty;
/* Creates a new process and runs through it the Watch Dog program or the
* user's main program.
* The decesion is made by which of the two got terminated and needs to restart.
*/
int StartWDProcess(info_ty *info);
/* Manages the Watch Dog operation of scheduling sending signals and checking
* whether the other side is responding or not.
* Uses a scheduler's program to synchornize the tasks. */
void *WDThreadSchedulerIMP(void *info);
int WDManageSchedulerIMP(info_ty *info);
/* Scheduler's task which sends SIGUSR1 to the needed process each preiod of
* time */
oper_ret_ty OnIntervalSendSignalIMP(void *unused);
/* Scheduler's task which checks if the maximum number of missed signals has
* been reached. If too many signals are missed - restarts the other program */
oper_ret_ty OnIntervalCheckIfMissIMP(void *info);
/* Scheduler's task which regulary checks if a DNR request has been made and
* stops the WatchDog if needed */
oper_ret_ty OnIntervalCheckIfDNR_IMP(void *scheduler_to_stop);
/* Sets a user defined function as a signal handler of a given signal */
void SetSignalHandler(int signal, void(*handler_func)(int));
/* Signal handler for SIGUSR1 - resets the missed signals counter */
void handler_ResetErrorsCounter(int sig_id);
/* Signal handler for SIGUSR2 - raises the DNR flag */
void handler_SetOnDNR(int sig_id);
/* Terminates a process and returns 0 if successfully terminated.
* A failure to terminate the process returns 1 */
int TerminateProcessIMP(pid_t process_to_kill);
/* Sets a process to be signaled */
void SetProcessToSignalIMP(pid_t pid);
pid_t GetProcessToSignalIMP();
#endif /* __WD_INTERNAL_H__ */
|
danielbrodi/WatchDog
|
wd_internal.c
|
/*********************************FILE__HEADER*********************************\
* File: watchdog.c
* Author: <NAME>
* Date: 12-July-2021
* Pseudocode Reviewer: <NAME>
* Code Reviewer: <NAME>
* Version: 1.5
* Description: Watchdog's program internal functions.
\***********************************s*******************************************/
/******************************** Header Files ********************************/
#define _POSIX_C_SOURCE 199506L /* sigaction struct */
#define _XOPEN_SOURCE
#include <assert.h> /* assert */
#include <errno.h> /* errno */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, time() */
#include <string.h>
#include <semaphore.h> /* sem_wait */
#include <signal.h> /* signals functions */
#include <unistd.h> /* fork, getppid, sleep */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* pid_t */
#include "utils.h" /* print colors, UNUSED, ExitIfError, ReturnIfError */
#include "wd_internal.h"
#include "scheduler.h" /* scheduler's API functions */
/***************************** Global Definitions *****************************/
/* determines if the scheduler should stop, which means the WD should stop */
static volatile sig_atomic_t g_scheduler_should_stop = 0;
/* counts amount of times that the WD did not receive a life signal */
static volatile sig_atomic_t g_counter_missed_signals = 0;
/* ID of the process which should to be signaled */
static volatile pid_t g_process_to_signal = 0;
/**************************** Forward Declarations ****************************/
/* Creates a new process and runs through it the Watch Dog program or the
* user's main program.
* The decesion is made by which of the two got terminated and needs to restart.
* Returns '0' if process was started successfully, otherwise returns '1'.
*/
int StartWDProcess(info_ty *info);
/* Manages the Watch Dog operation of scheduling sending signals and checking
* whether the other side is responding or not.
* Uses a scheduler's program to synchornize the tasks. */
void *WDThreadSchedulerIMP(void *info);
int WDManageSchedulerIMP(info_ty *info);
/* Scheduler's task which sends SIGUSR1 to the needed process each preiod of
* time */
oper_ret_ty OnIntervalSendSignalIMP(void *unused);
/* Scheduler's task which checks if the maximum number of missed signals has
* been reached. If too many signals are missed - restarts the other program */
oper_ret_ty OnIntervalCheckIfMissIMP(void *info);
/* Scheduler's task which regulary checks if a DNR request has been made and
* stops the WatchDog if needed */
oper_ret_ty OnIntervalCheckIfDNR_IMP(void *scheduler_to_stop);
/* Sets a user defined function as a signal handler of a given signal */
void SetSignalHandler(int signal, void(*handler_func)(int));
/* Signal handler for SIGUSR1 - resets the missed signals counter */
void handler_ResetErrorsCounter(int sig_id);
/* Signal handler for SIGUSR2 - raises the DNR flag */
void handler_SetOnDNR(int sig_id);
/* Terminates a process and returns 0 if successfully terminated.
* A failure to terminate the process returns 1 */
int TerminateProcessIMP(pid_t process_to_kill);
/* Sets a process to be signaled */
void SetProcessToSignalIMP(pid_t pid);
/* Returns PID Of the process to be signaled */
pid_t GetProcessToSignalIMP();
/************************* Functions Implementations *************************/
/* for improved readabillity */
enum {CHILD = 0};
/* WDPCreate function - start */
int StartWDProcess(info_ty *info)
{
pid_t pid = 0;
char *program_to_run = NULL;
char **argv_to_run = NULL;
/* asserts */
assert(info);
/* check if the caller of the function is the Watch Dog or the user
* program. */
if (info->i_am_wd)
{
DEBUG printf(CYAN "%120s[wd %d] Trying to Fork and run User_APP\n" NORMAL, "",
getpid());
program_to_run = info->argv_for_wd[0];
}
else
{
DEBUG printf(CYAN "[app %d] Trying to Fork and Run WD\n" NORMAL, getpid());
program_to_run = "./watchdog";
}
/* fork: */
pid = fork();
/* check if process was successfully created and return error otherwise */
ReturnIfError(pid < 0, "Failed to fork a WD process\n", FAILURE);
/*---------------------------------*/
/* if child: */
if (CHILD == pid)
{
/* execv needed program */
argv_to_run = info->argv_for_wd;
execvp(program_to_run, argv_to_run);
/* return (1) if any errors */
ReturnIfError(1, "Failed to execute the WatchDog program\n", FAILURE);
}
/* end child */
/*---------------------------------*/
/*---------------------------------*/
/* if parent: */
else
{
/* wait until the created process will be ready to receive signals */
sem_wait(info->is_process_ready);
/* updates communicator process id as the child's pid */
SetProcessToSignalIMP(pid);
return (SUCCESS);
/* end parent */
}
/*---------------------------------*/
return (FAILURE);
}
/******************************************************************************/
/* manages WD scheduler - sends and checks for signals */
void *WDThreadSchedulerIMP(void *info)
{
sigset_t signal_set = {0};
assert(info);
sigemptyset(&signal_set);
sigaddset(&signal_set, SIGUSR1);
/* unblock SIGUSR1 to be able to receive signals from the Watch Dog */
pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
WDManageSchedulerIMP(info);
/* when scheduelr is done start cleaning up memory */
sem_unlink("PROCESS_IS_READY");
sem_close(((info_ty *)info)->is_process_ready);
free(((info_ty *)info)->argv_for_wd);
memset(info, 0, sizeof(info_ty));
free((info_ty *)info);
info = NULL;
return (NULL);
}
/*----------------------------------------------------------------------------*/
int WDManageSchedulerIMP(info_ty *info)
{
int ret_status = 0;
size_t signal_intervals = 0;
scheduler_ty *wd_scheduler = NULL;
assert(info);
signal_intervals = info->signal_intervals;
assert(signal_intervals);
/* create scheduler */
wd_scheduler = SchedulerCreate();
ReturnIfError(!wd_scheduler, "Failed to create a WatchDog Scheduler!\n",
FAILURE);
/* add a scheduler task that sends signals */
SchedulerAdd(wd_scheduler, OnIntervalSendSignalIMP, signal_intervals, info);
/* add a scheduler task that checks if there are signals from the process */
SchedulerAdd(wd_scheduler, OnIntervalCheckIfMissIMP, signal_intervals, info);
/* add a scheduler task that checks the DNR status and stops scheduler
* if needed */
SchedulerAdd(wd_scheduler, OnIntervalCheckIfDNR_IMP, 1, wd_scheduler);
/* scheduler run and check its return status */
ret_status = SchedulerRun(wd_scheduler);
/* scheduler destroy */
SchedulerDestroy(wd_scheduler);
/* return if scheduler has successfully finished */
return (SUCCESS == ret_status ? SUCCESS : FAILURE);
}
/******************************************************************************/
oper_ret_ty OnIntervalSendSignalIMP(void *info)
{
/* send SIGUSR1 to process_to_signal and handle errors if any */
if (kill(g_process_to_signal, SIGUSR1))
{
if (ESRCH == errno)
{
fprintf(stderr, "%60s|[pid:%d] the target process"
" does not exist|", "", getpid());
}
else if (EPERM == errno)
{
fprintf(stderr, "%60s[pid:%d] has no permission to send SIGUSR1 signal",
"", getpid());
}
}
else
{
if (((info_ty *)info)->i_am_wd)
{
DEBUG printf(GREEN "%120sWatchDog[pid:%d] ", "", getpid());
}
else
{
DEBUG printf(GREEN "\nUserApp[pid:%d] ", getpid());
}
DEBUG printf("Sending signal to [pid:%d]\n" NORMAL, g_process_to_signal);
}
/* keep signaling */
return (NOT_DONE);
}
/******************************************************************************/
oper_ret_ty OnIntervalCheckIfMissIMP(void *info)
{
sig_atomic_t num_allowed_misses = 0;
assert(info);
num_allowed_misses = ((info_ty *)info)->num_allowed_misses;
assert(num_allowed_misses);
/* increment missed signals counter */
__sync_fetch_and_add(&g_counter_missed_signals, 1);
if (((info_ty *)info)->i_am_wd)
{
DEBUG printf(RED "%120s[wd %d] ", "", getpid());
}
else
{
DEBUG printf(RED "[app %d] ", getpid());
}
DEBUG printf("[restart check] num of misses: %d\n" NORMAL,
g_counter_missed_signals);
/* if num_missed_signals equals num_allowed_fails : */
if (num_allowed_misses == g_counter_missed_signals)
{
DEBUG printf(CYAN "%60s|-|Restarting process %d|-|\n" NORMAL, "",
g_process_to_signal);
/* restart process_to_watch using its original argv parameters */
if (FAILURE == TerminateProcessIMP(g_process_to_signal))
{
return (OPER_FAILURE);
}
if (FAILURE == StartWDProcess(info))
{
return (OPER_FAILURE);
}
/* resets the missed signals counter */
__sync_fetch_and_xor(&g_counter_missed_signals, g_counter_missed_signals);
}
/* end if reached num_allowed_fails */
/* keep checking */
return (NOT_DONE);
}
/******************************************************************************/
oper_ret_ty OnIntervalCheckIfDNR_IMP(void *scheduler_to_stop)
{
assert(scheduler_to_stop);
/* if DNR flag is on - stop the scheduler */
if (g_scheduler_should_stop)
{
SchedulerStop((scheduler_ty *)scheduler_to_stop);
}
/* keep checking */
return (NOT_DONE);
}
/******************************************************************************/
int TerminateProcessIMP(pid_t process_to_kill)
{
int status = 0;
assert(process_to_kill);
DEBUG printf(YELLOW "%60sTrying to kill %d\n:", "", process_to_kill);
/*---------------------------------------------------------*/
/* terminate process_to_kill */
if (kill(process_to_kill, SIGTERM))
{
waitpid(process_to_kill, &status, 0);
if (!WIFEXITED(status))
{
fprintf(stderr, "Process exited abnormally!\n");
}
DEBUG printf(WHITE "%d was successfully terminated!\n" NORMAL,
process_to_kill);
return(SUCCESS);
}
else
{
waitpid(process_to_kill, &status, 0);
if (!WIFEXITED(status))
{
fprintf(stderr, "Process exited abnormally!\n");
}
if (-1 == kill(process_to_kill, SIGKILL))
{
if (ESRCH == errno)
{
DEBUG printf(WHITE "%d was successfully terminated!\n" NORMAL,
process_to_kill);
return (SUCCESS);
}
}
}
/*---------------------------------------------------------*/
DEBUG printf(WHITE "%60s%d was not successfully killed!\n", "", process_to_kill);
return (FAILURE);
}
/******************************************************************************/
void SetSignalHandler(int signal, void(*handler_func)(int))
{
struct sigaction signal_action = {0};
/* clean the set of signals that aren’t permitted to
* interrupt execution of this handler. */
ExitIfError(-1 == sigemptyset(&signal_action.sa_mask),
"Error: Could not empty set of signals\n", 1);
signal_action.sa_flags = 0;
/* set the signal handler as the parameter given fuction */
signal_action.sa_handler = handler_func;
/* register the user defined signal handler to handle the signal */
/* handle errors if any */
ExitIfError(sigaction(signal, &signal_action, NULL) < 0,
"Error: Could not set register a sigaction handler\n", 1);
}
/******************************************************************************/
void handler_ResetErrorsCounter(int sig_id)
{
UNUSED(sig_id);
DEBUG printf(BLUE "%60s|[pid:%d] received SIGUSR1 signal|\n" NORMAL, "", getpid());
/* reset counter of missed signals by XOR counter with itself */
__sync_fetch_and_xor(&g_counter_missed_signals, g_counter_missed_signals);
return;
}
/******************************************************************************/
void handler_SetOnDNR(int sig_id)
{
UNUSED(sig_id);
/* set DNR flag as 1 */
__sync_fetch_and_add(&g_scheduler_should_stop, 1);
return;
}
/******************************************************************************/
void SetProcessToSignalIMP(pid_t pid)
{
assert(pid);
/* set global variable of process to signal as a given pid */
__sync_val_compare_and_swap(&g_process_to_signal, g_process_to_signal, pid);
return;
}
/******************************************************************************/
pid_t GetProcessToSignalIMP()
{
/* returns PID Of the process to be signaled */
return (g_process_to_signal);
}
/******************************************************************************/
|
danielbrodi/WatchDog
|
user_app.c
|
<reponame>danielbrodi/WatchDog
/*********************************FILE__HEADER*********************************\
* File: watchdog.c
* Author: <NAME>
* Date: 12-July-2021
* Pseudocode Reviewer: <NAME>
* Code Reviewer: <NAME>
* Version: 1.0
* Description: Sample of a user app that runs a Watch Dog program.
\******************************************************************************/
#include <stdio.h> /* printf */
#include <time.h> /* time_t, time() */
#include <unistd.h>
#include <signal.h>
#include "utils.h"
#include "watchdog.h"
int main(int argc, char *argv[])
{
size_t num_allowed_fails = 5;
size_t num_seconds_between_checks = 2;
time_t start_time = time(0);
time_t time_to_wait = 10; /* in seconds */
time_t end_time = start_time + time_to_wait;
printf(GREEN "[app %d] USER APP STARTED RUNNING|\n", getpid());
KeepMeAlive(argc, argv, num_seconds_between_checks, num_allowed_fails);
while(time(0) < end_time)
{
printf("\n%60s|Program[pid:%d] is running . . .|\n"
"%60s|Waiting for a signal . . .%9s|\n", "",getpid(), "", "");
sleep(1);
}
printf(WHITE "\n%60s|*USER APP IS DONE*: EXITING . . .|\n" NORMAL, "");
/* dnr */
DNR();
return (0);
}
|
danielbrodi/WatchDog
|
watchdog_main.c
|
/*********************************FILE__HEADER*********************************\
* File: watchdog_main.c
* Author: <NAME>
* Date: 12-July-2021
* Pseudocode Reviewer: <NAME>
* Code Reviewer: <NAME>
* Version: 1.5
* Description: Main function of the Watch Dog program.
\******************************************************************************/
/******************************** Header Files ********************************/
#define _POSIX_C_SOURCE 199506L /* setenv, getenv */
#define _DEFAULT_SOURCE /* setenv, getenv */
#include <assert.h> /* assert */
#include <stddef.h> /* size_t, NULL */
#include <stdio.h> /* sprintf */
#include <stdlib.h> /* putenv, getenv */
#include <string.h> /* atol */
#include <fcntl.h> /* O_CREAT */
#include <pthread.h> /* pthread_create, pthread_t */
#include <semaphore.h> /* sem_open, sem_post */
#include <signal.h> /* signals functions */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* getppid */
#include "utils.h" /* ReturnIfError, print colors */
#include "wd_internal.h" /* WDManageSchedulerIMP, SetSignalHandler,info_ty*/
/************************* Functions Implementations *************************/
/* start main function */
int main(int argc, char *argv[])
{
size_t signal_intervals = 0;
size_t num_allowed_misses = 0;
info_ty *wd_info = (info_ty *)malloc(sizeof(info_ty));
ExitIfError(NULL == wd_info, "Failed to allocate memory for info struct!\n"
,-1);
assert(argv);
/* set signal handlers to deal SIGUSR1 & SIGUSR2 */
SetSignalHandler(SIGUSR1, handler_ResetErrorsCounter);
SetSignalHandler(SIGUSR2, handler_SetOnDNR);
UNUSED(argc);
/* add itself to env variable to indicate there is a running watch dog */
/* handle errors */
setenv("WD_IS_ON", "1", 1);
DEBUG printf(GREEN "%100s[wd %d] WD STARTED RUNNING\n", "", getpid());
signal_intervals = atol(getenv("SIGNAL_INTERVAL"));
num_allowed_misses = atol(getenv("NUM_ALLOWED_MISSES"));
/* set info struct to be transfered to the scheduler function with all
* the needede information */
wd_info->argv_for_wd = argv + 1;
wd_info->num_allowed_misses = num_allowed_misses;
wd_info->signal_intervals = signal_intervals;
wd_info->i_am_wd = 1;
wd_info->is_process_ready = sem_open("PROCESS_IS_READY", O_CREAT, 0666, 0);
SetProcessToSignalIMP(getppid());
/* set the process as ready and setted up to receive signals */
sem_post(wd_info->is_process_ready);
/* WDManageScheduler and start watching the app */
WDManageSchedulerIMP(wd_info);
/* free struct's memory */
memset(wd_info, 0, sizeof(info_ty));
free(wd_info);
wd_info = NULL;
/* return */
return (0);
}
/******************************************************************************/
|
danielbrodi/WatchDog
|
utils.h
|
/****************************** File Header ***********************************\
* File Name: utils.h
* Author: <NAME>
* Description: Utilities for different programs.
\******************************************************************************/
#ifndef __UTILS_H__
#define __UTILS_H__
#include "stdio.h" /* printf, fprintf */
#include "stdlib.h" /* exit */
#define UNUSED(x) ((void)(x))
#define DEAD_MEM(type) ((type)0xdeadbeef)
/* escape keys for printf to color output for stodout */
#define NORMAL "\x1B[0m"
#define BLACK "\x1B[30m"
#define RED "\x1B[31m"
#define GREEN "\x1B[32m"
#define YELLOW "\x1B[33m"
#define BLUE "\x1B[34m"
#define PURPLE "\x1B[35m"
#define CYAN "\x1B[36m"
#define WHITE "\x1B[37m"
/* print colored output of SUCCESS and FAILURE */
#define PRINT_SUCCESS printf (GREEN "SUCCESS\n" NORMAL)
#define PRINT_FAILURE printf (RED "FAILURE\n" NORMAL)
/* exits the program with the given 'ret status' if 'is_bad' is true */
void ExitIfError(int is_bad, char *msg_to_print, int ret_stat)
{
if (is_bad)
{
printf(RED "%s\n" NORMAL, msg_to_print);
exit(ret_stat);
}
}
/* return the program with the given 'ret status' if 'is_bad' is true */
int ReturnIfError(int is_bad, char *msg_to_print, int ret_stat)
{
if (is_bad)
{
fprintf(stderr, RED "%s\n" NORMAL, msg_to_print);
return (ret_stat);
}
return(0);
}
/******************************************************************************/
typedef enum
{
FALSE,
TRUE
} boolean_ty;
/******************************************************************************/
typedef enum
{
SUCCESS,
FAILURE
} status_ty;
/******************************************************************************/
#endif /* __UTILS_H__ */
|
danielbrodi/WatchDog
|
watchdog.c
|
<filename>watchdog.c
/*********************************FILE__HEADER*********************************\
* File: watchdog.c
* Author: <NAME>
* Date: 11-July-2021
* Pseudocode Reviewer: <NAME>
* Code Reviewer: <NAME>
* Version: 1.5
* Description: Watchdog's program creator.
Watchdog should protect a client's program from being
terminated and restart it if needed.
The client's program should also protect the watchdog
program from being terminated and also
restart it if needed.
\******************************************************************************/
/******************************** Header Files ********************************/
#define _POSIX_C_SOURCE 199506L /* setenv, getenv */
#define _DEFAULT_SOURCE /* setenv, getenv */
#include <assert.h> /* assert */
#include <stddef.h> /* size_t, NULL */
#include <stdio.h> /* sprintf */
#include <stdlib.h> /* setenv, getenv */
#include <string.h> /* memcpy */
#include <fcntl.h> /* O_CREAT */
#include <semaphore.h> /* sem_open */
#include <pthread.h> /* pthread_create, pthread_t */
#include <signal.h> /* signals functions */
#include <unistd.h>
#include <sys/types.h> /* pid_t */
#include "utils.h" /* ReturnIfError */
#include "wd_internal.h"
#include "watchdog.h"
/***************************** Global Definitions *****************************/
/* A thread is used as a communicator between the user's app and the
* Watch Dog program. */
static pthread_t g_wd_thread = 0;
/************************* Functions Implementations *************************/
void KeepMeAlive(int argc, char *argv[], size_t signal_intervals,
size_t num_allowed_misses)
{
sigset_t signal_set = {0};
/* stores values of num_allowed_misses and signal_intervals as env vars */
char env_num_allowed_misses[120] = {'\0'};
char env_signal_intervals[120] = {'\0'};
info_ty *wd_info = (info_ty *)malloc(sizeof(info_ty));
ReturnIfError(NULL == wd_info, "Failed to allocate memory for info struct!\n"
,-1);
/* asserts */
assert(signal_intervals);
assert(num_allowed_misses);
/* register SIGUSR1 signal handler to manage received signals status */
SetSignalHandler(SIGUSR1, handler_ResetErrorsCounter);
sigemptyset(&signal_set);
sigaddset(&signal_set, SIGUSR1);
/* set ENV variables of num_allowed_misses and signal_intervals */
sprintf(env_signal_intervals, "%ld", signal_intervals);
setenv("SIGNAL_INTERVAL", env_signal_intervals, 1);
sprintf(env_num_allowed_misses, "%ld", num_allowed_misses);
setenv("NUM_ALLOWED_MISSES", env_num_allowed_misses, 1);
/* set info struct to be transfered to the scheduler function with all
* the needede information */
/* allocate memory for new arguments to run with the Watch Dog program */
/* extra 2 spaces for NULL and for the WD program name */
wd_info->argv_for_wd = (char **)(calloc(argc + 2, sizeof(char *)));
/* copy argv and attach wd_app_name to the beginning */
wd_info->argv_for_wd[0] = "./watchdog";
memcpy(wd_info->argv_for_wd+1, argv, argc * sizeof(char *));
wd_info->num_allowed_misses = num_allowed_misses;
wd_info->signal_intervals = signal_intervals;
wd_info->i_am_wd = 0;
wd_info->is_process_ready = sem_open("PROCESS_IS_READY", O_CREAT, 0666, 0);
/* check if there is already a watch dog (by an env variable): */
/* if yes - get its pid and mark it as the WD */
/* if no - create a new process and run WD and get its pid */
if (getenv("WD_IS_ON"))
{
DEBUG printf(RED "[app %d] WD already exists, no need to create a new one!\n"
NORMAL, getpid());
SetProcessToSignalIMP(getppid());
}
else
{
DEBUG printf(RED "\n[app %d] WD DOES NOT EXIST - CREATING WD . . .\n" NORMAL,
getpid() );
ReturnIfError(FAILURE == StartWDProcess(wd_info),
"[app] Failed to create WD process!\n", -1);
}
DEBUG printf(YELLOW "[app %d] WatchDog PID: %d\n" NORMAL, getpid(),
GetProcessToSignalIMP());
ReturnIfError(GetProcessToSignalIMP() <= 0,
"[app] PID of new created WD process is invalid!\n", -1);
sem_post(wd_info->is_process_ready);
/* block SIGUSR1 in the current main user's app thread so only the
* communicator thread will be able to receive SIGUSR1 from the Watchdog */
pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
/* create a thread that will use a scheduler
* to communicate with the Watch Dog process */
/* handle errors*/
ReturnIfError(pthread_create(&g_wd_thread, NULL, WDThreadSchedulerIMP,
wd_info),"[app] Failed to create a WD thread\n", -1);
/* return success */
return;
}
/******************************************************************************/
/* DNR function - start */
int DNR(void)
{
/* set DNR flag as 1 */
DEBUG printf(YELLOW "\n\n%60sSENDING DNR . . . \n\n" NORMAL, "");
kill(GetProcessToSignalIMP(), SIGUSR2);
handler_SetOnDNR(0);
/* verify the watch dog is terminated */
TerminateProcessIMP(GetProcessToSignalIMP());
if (pthread_join(g_wd_thread, NULL))
{
fprintf(stderr, "[app] Failed to finish WD thread\n");
return (FAILURE);
}
return (SUCCESS);
/* DNR function - end */
}
/******************************************************************************/
|
skyshivy/PopTest
|
ProtoFramework.xcframework/ios-arm64_x86_64-simulator/ProtoFramework.framework/Headers/ProtoFramework.h
|
//
// ProtoFramework.h
// ProtoFramework
//
// Created by SKY on 29/05/21.
//
#import <Foundation/Foundation.h>
//! Project version number for ProtoFramework.
FOUNDATION_EXPORT double ProtoFrameworkVersionNumber;
//! Project version string for ProtoFramework.
FOUNDATION_EXPORT const unsigned char ProtoFrameworkVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ProtoFramework/PublicHeader.h>
|
skyshivy/PopTest
|
Popup.xcframework/ios-arm64_i386_x86_64-simulator/Popup.framework/Headers/ShakeAndWin.h
|
<reponame>skyshivy/PopTest
//
// ShakeAndWin.h
// ShakeAndWin
//
// Created by SKY on 29/12/20.
//
#import <Foundation/Foundation.h>
//! Project version number for ShakeAndWin.
FOUNDATION_EXPORT double ShakeAndWinVersionNumber;
//! Project version string for ShakeAndWin.
FOUNDATION_EXPORT const unsigned char ShakeAndWinVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <ShakeAndWin/PublicHeader.h>
|
kumpera/binaryen
|
src/ir/effects.h
|
<filename>src/ir/effects.h
/*
* Copyright 2017 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef wasm_ir_effects_h
#define wasm_ir_effects_h
namespace wasm {
// Look for side effects, including control flow
// TODO: optimize
struct EffectAnalyzer : public PostWalker<EffectAnalyzer> {
EffectAnalyzer(PassOptions& passOptions, Expression *ast = nullptr) {
ignoreImplicitTraps = passOptions.ignoreImplicitTraps;
debugInfo = passOptions.debugInfo;
if (ast) analyze(ast);
}
bool ignoreImplicitTraps;
bool debugInfo;
void analyze(Expression *ast) {
breakNames.clear();
walk(ast);
// if we are left with breaks, they are external
if (breakNames.size() > 0) branches = true;
}
// Core effect tracking
bool branches = false; // branches out of this expression, returns, infinite loops, etc
bool calls = false;
std::set<Index> localsRead;
std::set<Index> localsWritten;
std::set<Name> globalsRead;
std::set<Name> globalsWritten;
bool readsMemory = false;
bool writesMemory = false;
bool implicitTrap = false; // a load or div/rem, which may trap. we ignore trap
// differences, so it is ok to reorder these, but we can't
// remove them, as they count as side effects, and we
// can't move them in a way that would cause other noticeable
// (global) side effects
bool isAtomic = false; // An atomic load/store/RMW/Cmpxchg or an operator that
// has a defined ordering wrt atomics (e.g. grow_memory)
// Helper functions to check for various effect types
bool accessesLocal() { return localsRead.size() + localsWritten.size() > 0; }
bool accessesGlobal() { return globalsRead.size() + globalsWritten.size() > 0; }
bool accessesMemory() { return calls || readsMemory || writesMemory; }
bool hasGlobalSideEffects() { return calls || globalsWritten.size() > 0 || writesMemory || isAtomic; }
bool hasSideEffects() { return hasGlobalSideEffects() || localsWritten.size() > 0 || branches || implicitTrap; }
bool hasAnything() { return branches || calls || accessesLocal() || readsMemory || writesMemory || accessesGlobal() || implicitTrap || isAtomic; }
bool noticesGlobalSideEffects() { return calls || readsMemory || isAtomic || globalsRead.size(); }
// check if we break to anything external from ourselves
bool hasExternalBreakTargets() { return !breakNames.empty(); }
// checks if these effects would invalidate another set (e.g., if we write, we invalidate someone that reads, they can't be moved past us)
bool invalidates(EffectAnalyzer& other) {
if (branches || other.branches
|| ((writesMemory || calls) && other.accessesMemory())
|| (accessesMemory() && (other.writesMemory || other.calls))) {
return true;
}
// All atomics are sequentially consistent for now, and ordered wrt other
// memory references.
if ((isAtomic && other.accessesMemory()) ||
(other.isAtomic && accessesMemory())) {
return true;
}
for (auto local : localsWritten) {
if (other.localsWritten.count(local) || other.localsRead.count(local)) {
return true;
}
}
for (auto local : localsRead) {
if (other.localsWritten.count(local)) return true;
}
if ((accessesGlobal() && other.calls) || (other.accessesGlobal() && calls)) {
return true;
}
for (auto global : globalsWritten) {
if (other.globalsWritten.count(global) || other.globalsRead.count(global)) {
return true;
}
}
for (auto global : globalsRead) {
if (other.globalsWritten.count(global)) return true;
}
// we are ok to reorder implicit traps, but not conditionalize them
if ((implicitTrap && other.branches) || (other.implicitTrap && branches)) {
return true;
}
// we can't reorder an implicit trap in a way that alters global state
if ((implicitTrap && other.hasGlobalSideEffects()) || (other.implicitTrap && hasGlobalSideEffects())) {
return true;
}
return false;
}
void mergeIn(EffectAnalyzer& other) {
branches = branches || other.branches;
calls = calls || other.calls;
readsMemory = readsMemory || other.readsMemory;
writesMemory = writesMemory || other.writesMemory;
implicitTrap = implicitTrap || other.implicitTrap;
isAtomic = isAtomic || other.isAtomic;
for (auto i : other.localsRead) localsRead.insert(i);
for (auto i : other.localsWritten) localsWritten.insert(i);
for (auto i : other.globalsRead) globalsRead.insert(i);
for (auto i : other.globalsWritten) globalsWritten.insert(i);
}
// the checks above happen after the node's children were processed, in the order of execution
// we must also check for control flow that happens before the children, i.e., loops
bool checkPre(Expression* curr) {
if (curr->is<Loop>()) {
branches = true;
return true;
}
return false;
}
bool checkPost(Expression* curr) {
visit(curr);
if (curr->is<Loop>()) {
branches = true;
}
return hasAnything();
}
std::set<Name> breakNames;
void visitBreak(Break *curr) {
breakNames.insert(curr->name);
}
void visitSwitch(Switch *curr) {
for (auto name : curr->targets) {
breakNames.insert(name);
}
breakNames.insert(curr->default_);
}
void visitBlock(Block* curr) {
if (curr->name.is()) breakNames.erase(curr->name); // these were internal breaks
}
void visitLoop(Loop* curr) {
if (curr->name.is()) breakNames.erase(curr->name); // these were internal breaks
// if the loop is unreachable, then there is branching control flow:
// (1) if the body is unreachable because of a (return), uncaught (br) etc., then we
// already noted branching, so it is ok to mark it again (if we have *caught*
// (br)s, then they did not lead to the loop body being unreachable).
// (same logic applies to blocks)
// (2) if the loop is unreachable because it only has branches up to the loop
// top, but no way to get out, then it is an infinite loop, and we consider
// that a branching side effect (note how the same logic does not apply to
// blocks).
if (curr->type == unreachable) {
branches = true;
}
}
void visitCall(Call *curr) { calls = true; }
void visitCallImport(CallImport *curr) {
calls = true;
if (debugInfo) {
// debugInfo call imports must be preserved very strongly, do not
// move code around them
branches = true; // !
}
}
void visitCallIndirect(CallIndirect *curr) { calls = true; }
void visitGetLocal(GetLocal *curr) {
localsRead.insert(curr->index);
}
void visitSetLocal(SetLocal *curr) {
localsWritten.insert(curr->index);
}
void visitGetGlobal(GetGlobal *curr) {
globalsRead.insert(curr->name);
}
void visitSetGlobal(SetGlobal *curr) {
globalsWritten.insert(curr->name);
}
void visitLoad(Load *curr) {
readsMemory = true;
isAtomic |= curr->isAtomic;
if (!ignoreImplicitTraps) implicitTrap = true;
}
void visitStore(Store *curr) {
writesMemory = true;
isAtomic |= curr->isAtomic;
if (!ignoreImplicitTraps) implicitTrap = true;
}
void visitAtomicRMW(AtomicRMW* curr) {
readsMemory = true;
writesMemory = true;
isAtomic = true;
if (!ignoreImplicitTraps) implicitTrap = true;
}
void visitAtomicCmpxchg(AtomicCmpxchg* curr) {
readsMemory = true;
writesMemory = true;
isAtomic = true;
if (!ignoreImplicitTraps) implicitTrap = true;
}
void visitAtomicWait(AtomicWait* curr) {
readsMemory = true;
// AtomicWait doesn't strictly write memory, but it does modify the waiters
// list associated with the specified address, which we can think of as a
// write.
writesMemory = true;
isAtomic = true;
if (!ignoreImplicitTraps) implicitTrap = true;
}
void visitAtomicWake(AtomicWake* curr) {
// AtomicWake doesn't strictly write memory, but it does modify the waiters
// list associated with the specified address, which we can think of as a
// write.
readsMemory = true;
writesMemory = true;
isAtomic = true;
if (!ignoreImplicitTraps) implicitTrap = true;
};
void visitUnary(Unary *curr) {
if (!ignoreImplicitTraps) {
switch (curr->op) {
case TruncSFloat32ToInt32:
case TruncSFloat32ToInt64:
case TruncUFloat32ToInt32:
case TruncUFloat32ToInt64:
case TruncSFloat64ToInt32:
case TruncSFloat64ToInt64:
case TruncUFloat64ToInt32:
case TruncUFloat64ToInt64: {
implicitTrap = true;
break;
}
default: {}
}
}
}
void visitBinary(Binary *curr) {
if (!ignoreImplicitTraps) {
switch (curr->op) {
case DivSInt32:
case DivUInt32:
case RemSInt32:
case RemUInt32:
case DivSInt64:
case DivUInt64:
case RemSInt64:
case RemUInt64: {
implicitTrap = true;
break;
}
default: {}
}
}
}
void visitReturn(Return *curr) { branches = true; }
void visitHost(Host *curr) {
calls = true;
// grow_memory modifies the set of valid addresses, and thus can be modeled as modifying memory
writesMemory = true;
// Atomics are also sequentially consistent with grow_memory.
isAtomic = true;
}
void visitUnreachable(Unreachable *curr) { branches = true; }
};
} // namespace wasm
#endif // wasm_ir_effects_h
|
kumpera/binaryen
|
src/wasm-stack.h
|
/*
* Copyright 2018 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef wasm_stack_h
#define wasm_stack_h
#include "wasm.h"
#include "wasm-binary.h"
#include "wasm-traversal.h"
#include "ir/branch-utils.h"
#include "pass.h"
namespace wasm {
// Stack IR: an IR that represents code at the wasm binary format level,
// that is, a stack machine. Binaryen IR is *almost* identical to this,
// but as documented in README.md, there are a few differences, intended
// to make Binaryen IR fast and flexible for maximal optimization. Stack
// IR, on the other hand, is designed to optimize a few final things that
// can only really be done when modeling the stack machine format precisely.
// Currently the benefits of Stack IR are minor, less than 1% reduction in
// code size. For that reason it is just a secondary IR, run optionally
// after the main IR has been optimized. However, if we improve Stack IR
// optimizations to a point where they have a significant impact, it's
// possible that could motivate investigating replacing the main IR with Stack
// IR (so that we have just a single IR).
// A StackIR instance (see wasm.h) contains a linear sequence of
// stack instructions. This representation is very simple: just a single vector of
// all instructions, in order.
// * nullptr is allowed in the vector, representing something to skip.
// This is useful as a common thing optimizations do is remove instructions,
// so this way we can do so without compacting the vector all the time.
// A Stack IR instruction. Most just directly reflect a Binaryen IR node,
// but we need extra ones for certain things.
class StackInst {
public:
StackInst(MixedArena&) {}
enum Op {
Basic, // an instruction directly corresponding to a non-control-flow
// Binaryen IR node
BlockBegin, // the beginning of a block
BlockEnd, // the ending of a block
IfBegin, // the beginning of a if
IfElse, // the else of a if
IfEnd, // the ending of a if
LoopBegin, // the beginning of a loop
LoopEnd, // the ending of a loop
} op;
Expression* origin; // the expression this originates from
Type type; // the type - usually identical to the origin type, but
// e.g. wasm has no unreachable blocks, they must be none
};
//
// StackWriter: Writes out binary format stack machine code for a Binaryen IR expression
//
// A stack writer has one of three modes:
// * Binaryen2Binary: directly writes the expression to wasm binary
// * Binaryen2Stack: queues the expressions linearly, in Stack IR (SIR)
// * Stack2Binary: emits SIR to wasm binary
//
// Direct writing, in Binaryen2Binary, is fast. Otherwise, Binaryen2Stack
// lets you optimize the Stack IR before running Stack2Binary (but the cost
// is that the extra IR in the middle makes things 20% slower than direct
// Binaryen2Binary).
//
// To reduce the amount of boilerplate code here, we implement all 3 in
// a single class, templated on the mode. This allows compilers to trivially
// optimize out irrelevant code paths, and there should be no runtime
// downside.
//
enum class StackWriterMode {
Binaryen2Binary, Binaryen2Stack, Stack2Binary
};
template<StackWriterMode Mode, typename Parent>
class StackWriter : public Visitor<StackWriter<Mode, Parent>> {
public:
StackWriter(Parent& parent, BufferWithRandomAccess& o, bool sourceMap=false, bool debug=false)
: parent(parent), o(o), sourceMap(sourceMap), debug(debug), allocator(parent.getModule()->allocator) {}
StackIR stackIR; // filled in Binaryen2Stack, read in Stack2Binary
std::map<Type, size_t> numLocalsByType; // type => number of locals of that type in the compact form
// visits a node, emitting the proper code for it
void visit(Expression* curr);
// emits a node, but if it is a block with no name, emit a list of its contents
void visitPossibleBlockContents(Expression* curr);
// visits a child node. (in some modes we may not want to visit children,
// that logic is handled here)
void visitChild(Expression* curr);
void visitBlock(Block* curr);
void visitBlockEnd(Block* curr);
void visitIf(If* curr);
void visitIfElse(If* curr);
void visitIfEnd(If* curr);
void visitLoop(Loop* curr);
void visitLoopEnd(Loop* curr);
void visitBreak(Break* curr);
void visitSwitch(Switch* curr);
void visitCall(Call* curr);
void visitCallImport(CallImport* curr);
void visitCallIndirect(CallIndirect* curr);
void visitGetLocal(GetLocal* curr);
void visitSetLocal(SetLocal* curr);
void visitGetGlobal(GetGlobal* curr);
void visitSetGlobal(SetGlobal* curr);
void visitLoad(Load* curr);
void visitStore(Store* curr);
void visitAtomicRMW(AtomicRMW* curr);
void visitAtomicCmpxchg(AtomicCmpxchg* curr);
void visitAtomicWait(AtomicWait* curr);
void visitAtomicWake(AtomicWake* curr);
void visitConst(Const* curr);
void visitUnary(Unary* curr);
void visitBinary(Binary* curr);
void visitSelect(Select* curr);
void visitReturn(Return* curr);
void visitHost(Host* curr);
void visitNop(Nop* curr);
void visitUnreachable(Unreachable* curr);
void visitDrop(Drop* curr);
// We need to emit extra unreachable opcodes in some cases
void emitExtraUnreachable();
// If we are in Binaryen2Stack, then this adds the item to the
// stack IR and returns true, which is all we need to do for
// non-control flow expressions.
bool justAddToStack(Expression* curr);
void setFunction(Function* funcInit) {
func = funcInit;
}
void mapLocalsAndEmitHeader();
protected:
Parent& parent;
BufferWithRandomAccess& o;
bool sourceMap;
bool debug;
MixedArena& allocator;
Function* func;
std::map<Index, size_t> mappedLocals; // local index => index in compact form of [all int32s][all int64s]etc
std::vector<Name> breakStack;
int32_t getBreakIndex(Name name);
void emitMemoryAccess(size_t alignment, size_t bytes, uint32_t offset);
void finishFunctionBody();
StackInst* makeStackInst(StackInst::Op op, Expression* origin);
StackInst* makeStackInst(Expression* origin) {
return makeStackInst(StackInst::Basic, origin);
}
};
// Write out a single expression, such as an offset for a global segment.
template<typename Parent>
class ExpressionStackWriter : StackWriter<StackWriterMode::Binaryen2Binary, Parent> {
public:
ExpressionStackWriter(Expression* curr, Parent& parent, BufferWithRandomAccess& o, bool debug=false) :
StackWriter<StackWriterMode::Binaryen2Binary, Parent>(parent, o, /* sourceMap= */ false, debug) {
this->visit(curr);
}
};
// Write out a function body, including the local header info.
template<typename Parent>
class FunctionStackWriter : StackWriter<StackWriterMode::Binaryen2Binary, Parent> {
public:
FunctionStackWriter(Function* funcInit, Parent& parent, BufferWithRandomAccess& o, bool sourceMap=false, bool debug=false) :
StackWriter<StackWriterMode::Binaryen2Binary, Parent>(parent, o, sourceMap, debug) {
this->setFunction(funcInit);
this->mapLocalsAndEmitHeader();
this->visitPossibleBlockContents(this->func->body);
this->finishFunctionBody();
}
};
// Use Stack IR to write the function body
template<typename Parent>
class StackIRFunctionStackWriter : StackWriter<StackWriterMode::Stack2Binary, Parent> {
public:
StackIRFunctionStackWriter(Function* funcInit, Parent& parent, BufferWithRandomAccess& o, bool debug=false) :
StackWriter<StackWriterMode::Stack2Binary, Parent>(parent, o, false, debug) {
this->setFunction(funcInit);
this->mapLocalsAndEmitHeader();
for (auto* inst : *funcInit->stackIR) {
if (!inst) continue; // a nullptr is just something we can skip
switch (inst->op) {
case StackInst::Basic:
case StackInst::BlockBegin:
case StackInst::IfBegin:
case StackInst::LoopBegin: {
this->visit(inst->origin);
break;
}
case StackInst::BlockEnd: {
this->visitBlockEnd(inst->origin->template cast<Block>());
break;
}
case StackInst::IfElse: {
this->visitIfElse(inst->origin->template cast<If>());
break;
}
case StackInst::IfEnd: {
this->visitIfEnd(inst->origin->template cast<If>());
break;
}
case StackInst::LoopEnd: {
this->visitLoopEnd(inst->origin->template cast<Loop>());
break;
}
default: WASM_UNREACHABLE();
}
}
this->finishFunctionBody();
}
};
//
// Implementations
//
// StackWriter
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::mapLocalsAndEmitHeader() {
// Map them
for (Index i = 0; i < func->getNumParams(); i++) {
size_t curr = mappedLocals.size();
mappedLocals[i] = curr;
}
for (auto type : func->vars) {
numLocalsByType[type]++;
}
std::map<Type, size_t> currLocalsByType;
for (Index i = func->getVarIndexBase(); i < func->getNumLocals(); i++) {
size_t index = func->getVarIndexBase();
Type type = func->getLocalType(i);
currLocalsByType[type]++; // increment now for simplicity, must decrement it in returns
if (type == i32) {
mappedLocals[i] = index + currLocalsByType[i32] - 1;
continue;
}
index += numLocalsByType[i32];
if (type == i64) {
mappedLocals[i] = index + currLocalsByType[i64] - 1;
continue;
}
index += numLocalsByType[i64];
if (type == f32) {
mappedLocals[i] = index + currLocalsByType[f32] - 1;
continue;
}
index += numLocalsByType[f32];
if (type == f64) {
mappedLocals[i] = index + currLocalsByType[f64] - 1;
continue;
}
WASM_UNREACHABLE();
}
// Emit them.
o << U32LEB(
(numLocalsByType[i32] ? 1 : 0) +
(numLocalsByType[i64] ? 1 : 0) +
(numLocalsByType[f32] ? 1 : 0) +
(numLocalsByType[f64] ? 1 : 0)
);
if (numLocalsByType[i32]) o << U32LEB(numLocalsByType[i32]) << binaryType(i32);
if (numLocalsByType[i64]) o << U32LEB(numLocalsByType[i64]) << binaryType(i64);
if (numLocalsByType[f32]) o << U32LEB(numLocalsByType[f32]) << binaryType(f32);
if (numLocalsByType[f64]) o << U32LEB(numLocalsByType[f64]) << binaryType(f64);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visit(Expression* curr) {
if (Mode == StackWriterMode::Binaryen2Binary && sourceMap) {
parent.writeDebugLocation(curr, func);
}
Visitor<StackWriter>::visit(curr);
}
// emits a node, but if it is a block with no name, emit a list of its contents
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitPossibleBlockContents(Expression* curr) {
auto* block = curr->dynCast<Block>();
if (!block || BranchUtils::BranchSeeker::hasNamed(block, block->name)) {
visitChild(curr);
return;
}
for (auto* child : block->list) {
visitChild(child);
}
if (block->type == unreachable && block->list.back()->type != unreachable) {
// similar to in visitBlock, here we could skip emitting the block itself,
// but must still end the 'block' (the contents, really) with an unreachable
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitChild(Expression* curr) {
// In stack => binary, we don't need to visit child nodes, everything
// is already in the linear stream.
if (Mode != StackWriterMode::Stack2Binary) {
visit(curr);
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBlock(Block* curr) {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::BlockBegin, curr));
} else {
if (debug) std::cerr << "zz node: Block" << std::endl;
o << int8_t(BinaryConsts::Block);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(curr->name); // TODO: we don't need to do this in Binaryen2Stack
Index i = 0;
for (auto* child : curr->list) {
if (debug) std::cerr << " " << size_t(curr) << "\n zz Block element " << i++ << std::endl;
visitChild(child);
}
// in Stack2Binary the block ending is in the stream later on
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
visitBlockEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBlockEnd(Block* curr) {
if (curr->type == unreachable) {
// an unreachable block is one that cannot be exited. We cannot encode this directly
// in wasm, where blocks must be none,i32,i64,f32,f64. Since the block cannot be
// exited, we can emit an unreachable at the end, and that will always be valid,
// and then the block is ok as a none
emitExtraUnreachable();
}
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::BlockEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
assert(!breakStack.empty());
breakStack.pop_back();
if (curr->type == unreachable) {
// and emit an unreachable *outside* the block too, so later things can pop anything
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIf(If* curr) {
if (debug) std::cerr << "zz node: If" << std::endl;
if (curr->condition->type == unreachable) {
// this if-else is unreachable because of the condition, i.e., the condition
// does not exit. So don't emit the if, but do consume the condition
visitChild(curr->condition);
emitExtraUnreachable();
return;
}
visitChild(curr->condition);
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfBegin, curr));
} else {
o << int8_t(BinaryConsts::If);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(IMPOSSIBLE_CONTINUE); // the binary format requires this; we have a block if we need one
// TODO: optimize this in Stack IR (if child is a block, we
// may break to this instead)
visitPossibleBlockContents(curr->ifTrue); // TODO: emit block contents directly, if possible
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
if (curr->ifFalse) {
visitIfElse(curr);
}
visitIfEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIfElse(If* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfElse, curr));
} else {
o << int8_t(BinaryConsts::Else);
}
breakStack.push_back(IMPOSSIBLE_CONTINUE); // TODO ditto
visitPossibleBlockContents(curr->ifFalse);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIfEnd(If* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
if (curr->type == unreachable) {
// we already handled the case of the condition being unreachable. otherwise,
// we may still be unreachable, if we are an if-else with both sides unreachable.
// wasm does not allow this to be emitted directly, so we must do something more. we could do
// better, but for now we emit an extra unreachable instruction after the if, so it is not consumed itself,
assert(curr->ifFalse);
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoop(Loop* curr) {
if (debug) std::cerr << "zz node: Loop" << std::endl;
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::LoopBegin, curr));
} else {
o << int8_t(BinaryConsts::Loop);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(curr->name);
visitPossibleBlockContents(curr->body);
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
visitLoopEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoopEnd(Loop* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (curr->type == unreachable) {
// we emitted a loop without a return type, and the body might be
// block contents, so ensure it is not consumed
emitExtraUnreachable();
}
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::LoopEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
if (curr->type == unreachable) {
// we emitted a loop without a return type, so it must not be consumed
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBreak(Break* curr) {
if (debug) std::cerr << "zz node: Break" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
if (curr->condition) visitChild(curr->condition);
if (!justAddToStack(curr)) {
o << int8_t(curr->condition ? BinaryConsts::BrIf : BinaryConsts::Br)
<< U32LEB(getBreakIndex(curr->name));
}
if (curr->condition && curr->type == unreachable) {
// a br_if is normally none or emits a value. if it is unreachable,
// then either the condition or the value is unreachable, which is
// extremely rare, and may require us to make the stack polymorphic
// (if the block we branch to has a value, we may lack one as we
// are not a reachable branch; the wasm spec on the other hand does
// presume the br_if emits a value of the right type, even if it
// popped unreachable)
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSwitch(Switch* curr) {
if (debug) std::cerr << "zz node: Switch" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
visitChild(curr->condition);
if (!BranchUtils::isBranchReachable(curr)) {
// if the branch is not reachable, then it's dangerous to emit it, as
// wasm type checking rules are different, especially in unreachable
// code. so just don't emit that unreachable code.
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::TableSwitch) << U32LEB(curr->targets.size());
for (auto target : curr->targets) {
o << U32LEB(getBreakIndex(target));
}
o << U32LEB(getBreakIndex(curr->default_));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCall(Call* curr) {
if (debug) std::cerr << "zz node: Call" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
if (!justAddToStack(curr)) {
o << int8_t(BinaryConsts::CallFunction) << U32LEB(parent.getFunctionIndex(curr->target));
}
if (curr->type == unreachable) { // TODO FIXME: this and similar can be removed
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCallImport(CallImport* curr) {
if (debug) std::cerr << "zz node: CallImport" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::CallFunction) << U32LEB(parent.getFunctionIndex(curr->target));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCallIndirect(CallIndirect* curr) {
if (debug) std::cerr << "zz node: CallIndirect" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
visitChild(curr->target);
if (!justAddToStack(curr)) {
o << int8_t(BinaryConsts::CallIndirect)
<< U32LEB(parent.getFunctionTypeIndex(curr->fullType))
<< U32LEB(0); // Reserved flags field
}
if (curr->type == unreachable) {
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitGetLocal(GetLocal* curr) {
if (debug) std::cerr << "zz node: GetLocal " << (o.size() + 1) << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::GetLocal) << U32LEB(mappedLocals[curr->index]);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSetLocal(SetLocal* curr) {
if (debug) std::cerr << "zz node: Set|TeeLocal" << std::endl;
visitChild(curr->value);
if (!justAddToStack(curr)) {
o << int8_t(curr->isTee() ? BinaryConsts::TeeLocal : BinaryConsts::SetLocal) << U32LEB(mappedLocals[curr->index]);
}
if (curr->type == unreachable) {
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitGetGlobal(GetGlobal* curr) {
if (debug) std::cerr << "zz node: GetGlobal " << (o.size() + 1) << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::GetGlobal) << U32LEB(parent.getGlobalIndex(curr->name));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSetGlobal(SetGlobal* curr) {
if (debug) std::cerr << "zz node: SetGlobal" << std::endl;
visitChild(curr->value);
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::SetGlobal) << U32LEB(parent.getGlobalIndex(curr->name));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoad(Load* curr) {
if (debug) std::cerr << "zz node: Load" << std::endl;
visitChild(curr->ptr);
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
if (!curr->isAtomic) {
switch (curr->type) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(curr->signed_ ? BinaryConsts::I32LoadMem8S : BinaryConsts::I32LoadMem8U); break;
case 2: o << int8_t(curr->signed_ ? BinaryConsts::I32LoadMem16S : BinaryConsts::I32LoadMem16U); break;
case 4: o << int8_t(BinaryConsts::I32LoadMem); break;
default: abort();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem8S : BinaryConsts::I64LoadMem8U); break;
case 2: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem16S : BinaryConsts::I64LoadMem16U); break;
case 4: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem32S : BinaryConsts::I64LoadMem32U); break;
case 8: o << int8_t(BinaryConsts::I64LoadMem); break;
default: abort();
}
break;
}
case f32: o << int8_t(BinaryConsts::F32LoadMem); break;
case f64: o << int8_t(BinaryConsts::F64LoadMem); break;
case unreachable: return; // the pointer is unreachable, so we are never reached; just don't emit a load
default: WASM_UNREACHABLE();
}
} else {
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->type) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicLoad8U); break;
case 2: o << int8_t(BinaryConsts::I32AtomicLoad16U); break;
case 4: o << int8_t(BinaryConsts::I32AtomicLoad); break;
default: WASM_UNREACHABLE();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicLoad8U); break;
case 2: o << int8_t(BinaryConsts::I64AtomicLoad16U); break;
case 4: o << int8_t(BinaryConsts::I64AtomicLoad32U); break;
case 8: o << int8_t(BinaryConsts::I64AtomicLoad); break;
default: WASM_UNREACHABLE();
}
break;
}
case unreachable: return;
default: WASM_UNREACHABLE();
}
}
emitMemoryAccess(curr->align, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitStore(Store* curr) {
if (debug) std::cerr << "zz node: Store" << std::endl;
visitChild(curr->ptr);
visitChild(curr->value);
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
if (!curr->isAtomic) {
switch (curr->valueType) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32StoreMem8); break;
case 2: o << int8_t(BinaryConsts::I32StoreMem16); break;
case 4: o << int8_t(BinaryConsts::I32StoreMem); break;
default: abort();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64StoreMem8); break;
case 2: o << int8_t(BinaryConsts::I64StoreMem16); break;
case 4: o << int8_t(BinaryConsts::I64StoreMem32); break;
case 8: o << int8_t(BinaryConsts::I64StoreMem); break;
default: abort();
}
break;
}
case f32: o << int8_t(BinaryConsts::F32StoreMem); break;
case f64: o << int8_t(BinaryConsts::F64StoreMem); break;
default: abort();
}
} else {
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->valueType) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicStore8); break;
case 2: o << int8_t(BinaryConsts::I32AtomicStore16); break;
case 4: o << int8_t(BinaryConsts::I32AtomicStore); break;
default: WASM_UNREACHABLE();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicStore8); break;
case 2: o << int8_t(BinaryConsts::I64AtomicStore16); break;
case 4: o << int8_t(BinaryConsts::I64AtomicStore32); break;
case 8: o << int8_t(BinaryConsts::I64AtomicStore); break;
default: WASM_UNREACHABLE();
}
break;
}
default: WASM_UNREACHABLE();
}
}
emitMemoryAccess(curr->align, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicRMW(AtomicRMW* curr) {
if (debug) std::cerr << "zz node: AtomicRMW" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->value);
if (curr->value->type == unreachable) return;
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
#define CASE_FOR_OP(Op) \
case Op: \
switch (curr->type) { \
case i32: \
switch (curr->bytes) { \
case 1: o << int8_t(BinaryConsts::I32AtomicRMW##Op##8U); break; \
case 2: o << int8_t(BinaryConsts::I32AtomicRMW##Op##16U); break; \
case 4: o << int8_t(BinaryConsts::I32AtomicRMW##Op); break; \
default: WASM_UNREACHABLE(); \
} \
break; \
case i64: \
switch (curr->bytes) { \
case 1: o << int8_t(BinaryConsts::I64AtomicRMW##Op##8U); break; \
case 2: o << int8_t(BinaryConsts::I64AtomicRMW##Op##16U); break; \
case 4: o << int8_t(BinaryConsts::I64AtomicRMW##Op##32U); break; \
case 8: o << int8_t(BinaryConsts::I64AtomicRMW##Op); break; \
default: WASM_UNREACHABLE(); \
} \
break; \
default: WASM_UNREACHABLE(); \
} \
break
switch(curr->op) {
CASE_FOR_OP(Add);
CASE_FOR_OP(Sub);
CASE_FOR_OP(And);
CASE_FOR_OP(Or);
CASE_FOR_OP(Xor);
CASE_FOR_OP(Xchg);
default: WASM_UNREACHABLE();
}
#undef CASE_FOR_OP
emitMemoryAccess(curr->bytes, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicCmpxchg(AtomicCmpxchg* curr) {
if (debug) std::cerr << "zz node: AtomicCmpxchg" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->expected);
if (curr->expected->type == unreachable) return;
visitChild(curr->replacement);
if (curr->replacement->type == unreachable) return;
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->type) {
case i32:
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicCmpxchg8U); break;
case 2: o << int8_t(BinaryConsts::I32AtomicCmpxchg16U); break;
case 4: o << int8_t(BinaryConsts::I32AtomicCmpxchg); break;
default: WASM_UNREACHABLE();
}
break;
case i64:
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicCmpxchg8U); break;
case 2: o << int8_t(BinaryConsts::I64AtomicCmpxchg16U); break;
case 4: o << int8_t(BinaryConsts::I64AtomicCmpxchg32U); break;
case 8: o << int8_t(BinaryConsts::I64AtomicCmpxchg); break;
default: WASM_UNREACHABLE();
}
break;
default: WASM_UNREACHABLE();
}
emitMemoryAccess(curr->bytes, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicWait(AtomicWait* curr) {
if (debug) std::cerr << "zz node: AtomicWait" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->expected);
if (curr->expected->type == unreachable) return;
visitChild(curr->timeout);
if (curr->timeout->type == unreachable) return;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->expectedType) {
case i32: {
o << int8_t(BinaryConsts::I32AtomicWait);
emitMemoryAccess(4, 4, 0);
break;
}
case i64: {
o << int8_t(BinaryConsts::I64AtomicWait);
emitMemoryAccess(8, 8, 0);
break;
}
default: WASM_UNREACHABLE();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicWake(AtomicWake* curr) {
if (debug) std::cerr << "zz node: AtomicWake" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->wakeCount);
if (curr->wakeCount->type == unreachable) return;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix) << int8_t(BinaryConsts::AtomicWake);
emitMemoryAccess(4, 4, 0);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitConst(Const* curr) {
if (debug) std::cerr << "zz node: Const" << curr << " : " << curr->type << std::endl;
if (justAddToStack(curr)) return;
switch (curr->type) {
case i32: {
o << int8_t(BinaryConsts::I32Const) << S32LEB(curr->value.geti32());
break;
}
case i64: {
o << int8_t(BinaryConsts::I64Const) << S64LEB(curr->value.geti64());
break;
}
case f32: {
o << int8_t(BinaryConsts::F32Const) << curr->value.reinterpreti32();
break;
}
case f64: {
o << int8_t(BinaryConsts::F64Const) << curr->value.reinterpreti64();
break;
}
default: abort();
}
if (debug) std::cerr << "zz const node done.\n";
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitUnary(Unary* curr) {
if (debug) std::cerr << "zz node: Unary" << std::endl;
visitChild(curr->value);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case ClzInt32: o << int8_t(BinaryConsts::I32Clz); break;
case CtzInt32: o << int8_t(BinaryConsts::I32Ctz); break;
case PopcntInt32: o << int8_t(BinaryConsts::I32Popcnt); break;
case EqZInt32: o << int8_t(BinaryConsts::I32EqZ); break;
case ClzInt64: o << int8_t(BinaryConsts::I64Clz); break;
case CtzInt64: o << int8_t(BinaryConsts::I64Ctz); break;
case PopcntInt64: o << int8_t(BinaryConsts::I64Popcnt); break;
case EqZInt64: o << int8_t(BinaryConsts::I64EqZ); break;
case NegFloat32: o << int8_t(BinaryConsts::F32Neg); break;
case AbsFloat32: o << int8_t(BinaryConsts::F32Abs); break;
case CeilFloat32: o << int8_t(BinaryConsts::F32Ceil); break;
case FloorFloat32: o << int8_t(BinaryConsts::F32Floor); break;
case TruncFloat32: o << int8_t(BinaryConsts::F32Trunc); break;
case NearestFloat32: o << int8_t(BinaryConsts::F32NearestInt); break;
case SqrtFloat32: o << int8_t(BinaryConsts::F32Sqrt); break;
case NegFloat64: o << int8_t(BinaryConsts::F64Neg); break;
case AbsFloat64: o << int8_t(BinaryConsts::F64Abs); break;
case CeilFloat64: o << int8_t(BinaryConsts::F64Ceil); break;
case FloorFloat64: o << int8_t(BinaryConsts::F64Floor); break;
case TruncFloat64: o << int8_t(BinaryConsts::F64Trunc); break;
case NearestFloat64: o << int8_t(BinaryConsts::F64NearestInt); break;
case SqrtFloat64: o << int8_t(BinaryConsts::F64Sqrt); break;
case ExtendSInt32: o << int8_t(BinaryConsts::I64STruncI32); break;
case ExtendUInt32: o << int8_t(BinaryConsts::I64UTruncI32); break;
case WrapInt64: o << int8_t(BinaryConsts::I32ConvertI64); break;
case TruncUFloat32ToInt32: o << int8_t(BinaryConsts::I32UTruncF32); break;
case TruncUFloat32ToInt64: o << int8_t(BinaryConsts::I64UTruncF32); break;
case TruncSFloat32ToInt32: o << int8_t(BinaryConsts::I32STruncF32); break;
case TruncSFloat32ToInt64: o << int8_t(BinaryConsts::I64STruncF32); break;
case TruncUFloat64ToInt32: o << int8_t(BinaryConsts::I32UTruncF64); break;
case TruncUFloat64ToInt64: o << int8_t(BinaryConsts::I64UTruncF64); break;
case TruncSFloat64ToInt32: o << int8_t(BinaryConsts::I32STruncF64); break;
case TruncSFloat64ToInt64: o << int8_t(BinaryConsts::I64STruncF64); break;
case ConvertUInt32ToFloat32: o << int8_t(BinaryConsts::F32UConvertI32); break;
case ConvertUInt32ToFloat64: o << int8_t(BinaryConsts::F64UConvertI32); break;
case ConvertSInt32ToFloat32: o << int8_t(BinaryConsts::F32SConvertI32); break;
case ConvertSInt32ToFloat64: o << int8_t(BinaryConsts::F64SConvertI32); break;
case ConvertUInt64ToFloat32: o << int8_t(BinaryConsts::F32UConvertI64); break;
case ConvertUInt64ToFloat64: o << int8_t(BinaryConsts::F64UConvertI64); break;
case ConvertSInt64ToFloat32: o << int8_t(BinaryConsts::F32SConvertI64); break;
case ConvertSInt64ToFloat64: o << int8_t(BinaryConsts::F64SConvertI64); break;
case DemoteFloat64: o << int8_t(BinaryConsts::F32ConvertF64); break;
case PromoteFloat32: o << int8_t(BinaryConsts::F64ConvertF32); break;
case ReinterpretFloat32: o << int8_t(BinaryConsts::I32ReinterpretF32); break;
case ReinterpretFloat64: o << int8_t(BinaryConsts::I64ReinterpretF64); break;
case ReinterpretInt32: o << int8_t(BinaryConsts::F32ReinterpretI32); break;
case ReinterpretInt64: o << int8_t(BinaryConsts::F64ReinterpretI64); break;
case ExtendS8Int32: o << int8_t(BinaryConsts::I32ExtendS8); break;
case ExtendS16Int32: o << int8_t(BinaryConsts::I32ExtendS16); break;
case ExtendS8Int64: o << int8_t(BinaryConsts::I64ExtendS8); break;
case ExtendS16Int64: o << int8_t(BinaryConsts::I64ExtendS16); break;
case ExtendS32Int64: o << int8_t(BinaryConsts::I64ExtendS32); break;
default: abort();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBinary(Binary* curr) {
if (debug) std::cerr << "zz node: Binary" << std::endl;
visitChild(curr->left);
visitChild(curr->right);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case AddInt32: o << int8_t(BinaryConsts::I32Add); break;
case SubInt32: o << int8_t(BinaryConsts::I32Sub); break;
case MulInt32: o << int8_t(BinaryConsts::I32Mul); break;
case DivSInt32: o << int8_t(BinaryConsts::I32DivS); break;
case DivUInt32: o << int8_t(BinaryConsts::I32DivU); break;
case RemSInt32: o << int8_t(BinaryConsts::I32RemS); break;
case RemUInt32: o << int8_t(BinaryConsts::I32RemU); break;
case AndInt32: o << int8_t(BinaryConsts::I32And); break;
case OrInt32: o << int8_t(BinaryConsts::I32Or); break;
case XorInt32: o << int8_t(BinaryConsts::I32Xor); break;
case ShlInt32: o << int8_t(BinaryConsts::I32Shl); break;
case ShrUInt32: o << int8_t(BinaryConsts::I32ShrU); break;
case ShrSInt32: o << int8_t(BinaryConsts::I32ShrS); break;
case RotLInt32: o << int8_t(BinaryConsts::I32RotL); break;
case RotRInt32: o << int8_t(BinaryConsts::I32RotR); break;
case EqInt32: o << int8_t(BinaryConsts::I32Eq); break;
case NeInt32: o << int8_t(BinaryConsts::I32Ne); break;
case LtSInt32: o << int8_t(BinaryConsts::I32LtS); break;
case LtUInt32: o << int8_t(BinaryConsts::I32LtU); break;
case LeSInt32: o << int8_t(BinaryConsts::I32LeS); break;
case LeUInt32: o << int8_t(BinaryConsts::I32LeU); break;
case GtSInt32: o << int8_t(BinaryConsts::I32GtS); break;
case GtUInt32: o << int8_t(BinaryConsts::I32GtU); break;
case GeSInt32: o << int8_t(BinaryConsts::I32GeS); break;
case GeUInt32: o << int8_t(BinaryConsts::I32GeU); break;
case AddInt64: o << int8_t(BinaryConsts::I64Add); break;
case SubInt64: o << int8_t(BinaryConsts::I64Sub); break;
case MulInt64: o << int8_t(BinaryConsts::I64Mul); break;
case DivSInt64: o << int8_t(BinaryConsts::I64DivS); break;
case DivUInt64: o << int8_t(BinaryConsts::I64DivU); break;
case RemSInt64: o << int8_t(BinaryConsts::I64RemS); break;
case RemUInt64: o << int8_t(BinaryConsts::I64RemU); break;
case AndInt64: o << int8_t(BinaryConsts::I64And); break;
case OrInt64: o << int8_t(BinaryConsts::I64Or); break;
case XorInt64: o << int8_t(BinaryConsts::I64Xor); break;
case ShlInt64: o << int8_t(BinaryConsts::I64Shl); break;
case ShrUInt64: o << int8_t(BinaryConsts::I64ShrU); break;
case ShrSInt64: o << int8_t(BinaryConsts::I64ShrS); break;
case RotLInt64: o << int8_t(BinaryConsts::I64RotL); break;
case RotRInt64: o << int8_t(BinaryConsts::I64RotR); break;
case EqInt64: o << int8_t(BinaryConsts::I64Eq); break;
case NeInt64: o << int8_t(BinaryConsts::I64Ne); break;
case LtSInt64: o << int8_t(BinaryConsts::I64LtS); break;
case LtUInt64: o << int8_t(BinaryConsts::I64LtU); break;
case LeSInt64: o << int8_t(BinaryConsts::I64LeS); break;
case LeUInt64: o << int8_t(BinaryConsts::I64LeU); break;
case GtSInt64: o << int8_t(BinaryConsts::I64GtS); break;
case GtUInt64: o << int8_t(BinaryConsts::I64GtU); break;
case GeSInt64: o << int8_t(BinaryConsts::I64GeS); break;
case GeUInt64: o << int8_t(BinaryConsts::I64GeU); break;
case AddFloat32: o << int8_t(BinaryConsts::F32Add); break;
case SubFloat32: o << int8_t(BinaryConsts::F32Sub); break;
case MulFloat32: o << int8_t(BinaryConsts::F32Mul); break;
case DivFloat32: o << int8_t(BinaryConsts::F32Div); break;
case CopySignFloat32: o << int8_t(BinaryConsts::F32CopySign);break;
case MinFloat32: o << int8_t(BinaryConsts::F32Min); break;
case MaxFloat32: o << int8_t(BinaryConsts::F32Max); break;
case EqFloat32: o << int8_t(BinaryConsts::F32Eq); break;
case NeFloat32: o << int8_t(BinaryConsts::F32Ne); break;
case LtFloat32: o << int8_t(BinaryConsts::F32Lt); break;
case LeFloat32: o << int8_t(BinaryConsts::F32Le); break;
case GtFloat32: o << int8_t(BinaryConsts::F32Gt); break;
case GeFloat32: o << int8_t(BinaryConsts::F32Ge); break;
case AddFloat64: o << int8_t(BinaryConsts::F64Add); break;
case SubFloat64: o << int8_t(BinaryConsts::F64Sub); break;
case MulFloat64: o << int8_t(BinaryConsts::F64Mul); break;
case DivFloat64: o << int8_t(BinaryConsts::F64Div); break;
case CopySignFloat64: o << int8_t(BinaryConsts::F64CopySign);break;
case MinFloat64: o << int8_t(BinaryConsts::F64Min); break;
case MaxFloat64: o << int8_t(BinaryConsts::F64Max); break;
case EqFloat64: o << int8_t(BinaryConsts::F64Eq); break;
case NeFloat64: o << int8_t(BinaryConsts::F64Ne); break;
case LtFloat64: o << int8_t(BinaryConsts::F64Lt); break;
case LeFloat64: o << int8_t(BinaryConsts::F64Le); break;
case GtFloat64: o << int8_t(BinaryConsts::F64Gt); break;
case GeFloat64: o << int8_t(BinaryConsts::F64Ge); break;
default: abort();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSelect(Select* curr) {
if (debug) std::cerr << "zz node: Select" << std::endl;
visitChild(curr->ifTrue);
visitChild(curr->ifFalse);
visitChild(curr->condition);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Select);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitReturn(Return* curr) {
if (debug) std::cerr << "zz node: Return" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Return);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitHost(Host* curr) {
if (debug) std::cerr << "zz node: Host" << std::endl;
switch (curr->op) {
case CurrentMemory: {
break;
}
case GrowMemory: {
visitChild(curr->operands[0]);
break;
}
default: WASM_UNREACHABLE();
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case CurrentMemory: {
o << int8_t(BinaryConsts::CurrentMemory);
break;
}
case GrowMemory: {
o << int8_t(BinaryConsts::GrowMemory);
break;
}
default: WASM_UNREACHABLE();
}
o << U32LEB(0); // Reserved flags field
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitNop(Nop* curr) {
if (debug) std::cerr << "zz node: Nop" << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Nop);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitUnreachable(Unreachable* curr) {
if (debug) std::cerr << "zz node: Unreachable" << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Unreachable);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitDrop(Drop* curr) {
if (debug) std::cerr << "zz node: Drop" << std::endl;
visitChild(curr->value);
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Drop);
}
template<StackWriterMode Mode, typename Parent>
int32_t StackWriter<Mode, Parent>::getBreakIndex(Name name) { // -1 if not found
for (int i = breakStack.size() - 1; i >= 0; i--) {
if (breakStack[i] == name) {
return breakStack.size() - 1 - i;
}
}
WASM_UNREACHABLE();
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::emitMemoryAccess(size_t alignment, size_t bytes, uint32_t offset) {
o << U32LEB(Log2(alignment ? alignment : bytes));
o << U32LEB(offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::emitExtraUnreachable() {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(Builder(allocator).makeUnreachable()));
} else if (Mode == StackWriterMode::Binaryen2Binary) {
o << int8_t(BinaryConsts::Unreachable);
}
}
template<StackWriterMode Mode, typename Parent>
bool StackWriter<Mode, Parent>::justAddToStack(Expression* curr) {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(curr));
return true;
}
return false;
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::finishFunctionBody() {
o << int8_t(BinaryConsts::End);
}
template<StackWriterMode Mode, typename Parent>
StackInst* StackWriter<Mode, Parent>::makeStackInst(StackInst::Op op, Expression* origin) {
auto* ret = allocator.alloc<StackInst>();
ret->op = op;
ret->origin = origin;
auto stackType = origin->type;
if (origin->is<Block>() || origin->is<Loop>() || origin->is<If>()) {
if (stackType == unreachable) {
// There are no unreachable blocks, loops, or ifs. we emit extra unreachables
// to fix that up, so that they are valid as having none type.
stackType = none;
} else if (op != StackInst::BlockEnd &&
op != StackInst::IfEnd &&
op != StackInst::LoopEnd) {
// If a concrete type is returned, we mark the end of the construct has
// having that type (as it is pushed to the value stack at that point),
// other parts are marked as none).
stackType = none;
}
}
ret->type = stackType;
return ret;
}
} // namespace wasm
#endif // wasm_stack_h
|
kumpera/binaryen
|
src/ir/function-utils.h
|
/*
* Copyright 2018 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef wasm_ir_function_h
#define wasm_ir_function_h
#include "wasm.h"
#include "ir/utils.h"
namespace wasm {
namespace FunctionUtils {
// Checks if two functions are equal in all functional aspects,
// everything but their name (which can't be the same, in the same
// module!) - same params, vars, body, result, etc.
inline bool equal(Function* left, Function* right) {
if (left->getNumParams() != right->getNumParams()) return false;
if (left->getNumVars() != right->getNumVars()) return false;
for (Index i = 0; i < left->getNumLocals(); i++) {
if (left->getLocalType(i) != right->getLocalType(i)) return false;
}
if (left->result != right->result) return false;
if (left->type != right->type) return false;
return ExpressionAnalyzer::equal(left->body, right->body);
}
} // namespace FunctionUtils
} // namespace wasm
#endif // wasm_ir_function_h
|
kylewray/librbr
|
librbr/include/core/observation_transitions/observation_transitions_array.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef OBSERVATION_TRANSITIONS_ARRAY_H
#define OBSERVATION_TRANSITIONS_ARRAY_H
#include "observation_transitions.h"
#include "../observations/observations.h"
#include "../observations/observations_map.h"
#include "../observations/observation.h"
#include "../observations/indexed_observation.h"
#include "../states/state.h"
#include "../states/indexed_state.h"
#include "../actions/action.h"
#include "../actions/indexed_action.h"
/**
* A class for finite observation transitions in an MDP-like object. Informally, there are two basic ways to
* store finite observation transitions: a table lookup mapping observation-action-state triples to real values,
* or a generator function based on one of these triples. In both cases, we require that any class with
* finite observation transitions provide certain get functions so that any generic solver can handle both cases.
*
* If you want to create a generator function-based ObservationTransitionsArray class, please create a child
* class which implements the function in the virtual functions described below. You will likely ignore
* the internal observationTrantions vector variable here.
*
* This class requires that states and actions be of types IndexedState and IndexedAction, respectively.
*/
class ObservationTransitionsArray : virtual public ObservationTransitions {
public:
/**
* The default constructor for the ObservationTransitionsArray class. This requires the
* number of states, actions, and observations to be specified.
* @param numStates The number of states.
* @param numActions The number of actions.
* @param numObservations The number of observations.
*/
ObservationTransitionsArray(unsigned int numStates, unsigned int numActions, unsigned int numObservations);
/**
* The default deconstructor for the ObservationTransitionsArray class.
*/
virtual ~ObservationTransitionsArray();
/**
* Set a observation transition from a particular observation-action-state triple to a probability.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @param observation The next observation to which we assign a probability.
* @param probability The probability of the observation given we took the action and landed
* in the state given.
* @throw ObservationTransitionException Either the state, action, or observation was invalid.
*/
virtual void set(Action *previousAction, State *state, Observation *observation, double probability);
/**
* The probability of a transition following the observation-action-state triple provided.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @param observation The next observation to which we assign a probability.
* @throw ObservationTransitionException Either the state, action, or observation was invalid.
* @return The probability of the observation given we took the action and landed in the state given.
*/
virtual double get(Action *previousAction, State *state, Observation *observation);
/**
* Add an available observation.
* @param previousAction The previous action taken at the previous state.
* @param state The resultant state.
* @param availableObservation The available observation.
* @throw ObservationTransitionException The action-state pair could not be found.
*/
void add_available(Action *previousAction, State *state, Observation *availableObservation);
/**
* Return a list of the observations available given a previous state and the action taken there.
* @param Z A set of observations.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @return The list of available observations.
*/
virtual const std::vector<Observation *> &available(Observations *Z, Action *previousAction, State *state);
/**
* Set the entire 3-dimensional array with the one provided. This only performs a copy.
* @param O A pointer to the new 3-d array of raw observations transitions data. This must be
* an array of size m x n x z.
*/
virtual void set_observation_transitions(const float *O);
/**
* Get the memory location of the 3-dimensional array.
* @return A pointer to the raw observation transitions data.
*/
virtual float *get_observation_transitions();
/**
* Get the number of states used for the observation transitions array.
* @return The number of states.
*/
virtual unsigned int get_num_states() const;
/**
* Get the number of actions used for the observation transitions array.
* @return The number of actions.
*/
virtual unsigned int get_num_actions() const;
/**
* Get the number of observations used for the observation transitions array.
* @return The number of observations.
*/
virtual unsigned int get_num_observations() const;
/**
* Reset the observation transitions by assigning all probabilities to zero. This does not free memory.
*/
virtual void reset();
private:
/**
* Compute the available observations for the action and state pair provided, then store the result
* in availableObservations.
* @param Z The finite set of observations.
* @param a The current action.
* @param sp The next state.
*/
virtual void compute_available(ObservationsMap *Z, IndexedAction *a, IndexedState *sp);
/**
* The 3-dimensional array of all action-state-observation transitions. Internally,
* these are floats to improve speed.
*/
float *observationTransitions;
/**
* The number of states in the state transitions second dimension.
*/
unsigned int states;
/**
* The number of actions in the state transitions first dimension.
*/
unsigned int actions;
/**
* The number of observations in the state transitions third dimension.
*/
unsigned int observations;
/**
* A mapping from action-state pairs to a vector of available observations.
*/
std::vector<Observation *> *availableObservations;
};
#endif // OBSERVATION_TRANSITIONS_ARRAY_H
|
kylewray/librbr
|
librbr/include/pomdp/pomdp_value_iteration.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POMDP_VALUE_ITERATION_H
#define POMDP_VALUE_ITERATION_H
#include "pomdp.h"
#include "../core/policy/policy_alpha_vectors.h"
#include "../core/policy/policy_alpha_vector.h"
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/observations/observations_map.h"
#include "../core/state_transitions/state_transitions_map.h"
#include "../core/observation_transitions/observation_transitions_map.h"
//#include "../core/rewards/s_rewards.h"
#include "../core/rewards/sa_rewards.h"
#include "../core/rewards/sas_rewards.h"
#include "../core/rewards/saso_rewards.h"
#include "../core/horizon.h"
/**
* Solve an POMDP via value iteration (finite or infinite horizon). This solver has the
* following requirements:
* - POMDP states must be of type FiniteStates.
* - POMDP actions must be of type FiniteActions.
* - POMDP observations must be of type FiniteObservations.
* - POMDP state transitions must be of type FiniteStateTransitions.
* - POMDP observation transitions must be of type FiniteObservationTransitions.
* - POMDP rewards must be of type SASRewards.
*/
class POMDPValueIteration {
public:
/**
* The default constructor for the POMDPValueIteration class. Default number of iterations
* for infinite horizon POMDPs is 1.
*/
POMDPValueIteration();
/**
* A constructor for the POMDPValueIteration class which allows for the specification
* of the number of iterations to run for infinite horizon. Default is 1.
* @param numIterations The number of iterations to run for infinite horizon POMDPs.
*/
POMDPValueIteration(unsigned int numIterations);
/**
* The deconstructor for the POMDPValueIteration class.
*/
virtual ~POMDPValueIteration();
/**
* Set the number of iterations to run for infinite horizon POMDPs.
* @param numIterations The number of iterations to run for infinite horizon POMDPs.
*/
void set_num_iterations(unsigned int numIterations);
/**
* Get the number of iterations to run for infinite horizon POMDPs.
* @return The number of iterations to run for infinite horizon POMDPs.
*/
unsigned int get_num_iterations();
/**
* Compute the optimal number of iterations to run for infinite horizon POMDPs, given
* the desired tolerance, requiring knowledge of the reward function.
* @param pomdp The partially observable Markov decision process to use.
* @param epsilon The desired tolerance between value functions to check for convergence.
* @throw RewardException The POMDP did not have a SARewards rewards object.
*/
void compute_num_iterations(POMDP *pomdp, double epsilon);
/**
* Solve the POMDP provided using value iteration.
* @param pomdp The partially observable Markov decision process to solve.
* @throw CoreException The POMDP was null.
* @throw StateException The POMDP did not have a FiniteStates states object.
* @throw ActionException The POMDP did not have a FiniteActions actions object.
* @throw ObservationException The POMDP did not have a FiniteObservations observations object.
* @throw StateTransitionsException The POMDP did not have a FiniteStateTransitions state transitions object.
* @throw ObservationTransitionsException The POMDP did not have a FiniteObservationTransitions observation transitions object.
* @throw RewardException The POMDP did not have a SARewards rewards object.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a finite state controller (infinite horizon) or tree (finite horizon).
*/
PolicyAlphaVectors *solve(POMDP *pomdp);
private:
/**
* Solve a finite horizon POMDP using value iteration.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param R The state-action-state-observation rewards (or other children types).
* @param h The horizon.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a collection of alpha vectors.
*/
PolicyAlphaVectors *solve_finite_horizon(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitionsMap *T, ObservationTransitionsMap *O, Rewards *R,
Horizon *h);
/**
* Solve an infinite horizon POMDP using value iteration.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param R The state-action-state-observation rewards (or other children types).
* @param h The horizon.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a collection of alpha vectors.
*/
PolicyAlphaVectors *solve_infinite_horizon(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitionsMap *T, ObservationTransitionsMap *O, Rewards *R,
Horizon *h);
/**
* The number of iterations until the solver stops for infinite horizon POMDPs.
*/
unsigned int iterations;
};
#endif // POMDP_VALUE_ITERATION_H
|
kylewray/librbr
|
librbr/include/core/states/belief_state.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BELIEF_STATE_H
#define BELIEF_STATE_H
#include <map>
#include <vector>
#include "state.h"
/**
* A belief over a set of states.
*/
class BeliefState {
public:
/**
* The default constructor of the BeliefState object.
*/
BeliefState();
/**
* The copy constructor of the BeliefState object.
* @param other The belief state to copy.
*/
BeliefState(const BeliefState &other);
/**
* The default deconstructor of the BeliefState object.
*/
virtual ~BeliefState();
/**
* Set the probability of a state.
* @param state The state to set a belief over.
* @param probability The probability of the state.
*/
void set(State *state, double probability);
/**
* Get the probability of a state.
* @param state The state to get a belief over.
* @return The belief probability of the state.
*/
double get(State *state) const;
/**
* Get the set of states with non-zero belief probability. Note: This set may change
* if you have nested for loops, so be sure to correctly use this function.
* @return The set of states with non-zero belief probability.
*/
const std::vector<State *> &get_states();
/**
* Overload the equals operator to set this belief state equal to the belief state provided.
* @param other The belief state to copy.
* @return The new version of this belief state.
*/
BeliefState &operator=(const BeliefState &other);
/**
* Reset the belief state.
*/
void reset();
private:
/**
* The belief over the states. If a state is not mapped, then it
* is assumed that the probability for that state is 0.
*/
std::map<State *, double> belief;
/**
* The set of states corresponding to this belief state which are non-zero.
*/
std::vector<State *> states;
};
#endif // BELIEF_STATE_H
|
kylewray/librbr
|
librbr/include/core/policy/policy_map.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POLICY_MAP_H
#define POLICY_MAP_H
#include <vector>
#include <string>
#include <map>
#include "policy.h"
#include "../states/state.h"
#include "../states/states_map.h"
#include "../actions/action.h"
#include "../actions/actions_map.h"
#include "../horizon.h"
/**
* A simple map policy which works for MDPs and Dec-MDPs; each actual state
* deterministically maps to a single action. This will likely be used
* exclusively for MDPs and Dec-MDPs.
*
* Additionally, the class supports finite horizon solutions, too. By default
* it assumes infinite horizon.
*/
class PolicyMap : virtual public Policy {
public:
/**
* The default constructor for a PolicyMap object. It defaults to a horizon of 1.
*/
PolicyMap();
/**
* A constructor for a PolicyMap object which specifies the horizon.
* @param horizon The horizon of the problem; 0 represents infinite horizon.
*/
PolicyMap(unsigned int horizon);
/**
* A constructor for a PolicyMap object which specifies the horizon.
* @param horizon The horizon object from the MDP-like object.
*/
PolicyMap(Horizon *horizon);
/**
* A virtual deconstructor to prevent errors upon the deletion of a child object.
*/
virtual ~PolicyMap();
/**
* Set the mapping from a state to an action. For finite horizon, it assumes 0 by default.
* @param state The state to define.
* @param action The action which should be taken at the state.
*/
void set(State *state, Action *action);
/**
* Set the mapping from a state to an action, allowing the explicit specification of the horizon.
* @param horizon The horizon to set.
* @param state The state to define.
* @param action The action which should be taken at the state.
* @throw PolicyException The horizon was invalid.
*/
void set(unsigned int horizon, State *state, Action *action);
/**
* Get the action for a given state. For finite horizon, it assumes 0 by default.
* @param state The state to retrieve a mapping.
* @throw PolicyException The policy was not defined for this state.
* @return The action to take at the given state.
*/
Action *get(State *state);
/**
* Get the action for a given state, allowing the explicit specification of the horizon.
* @param horizon The horizon to set.
* @param state The state to retrieve a mapping.
* @throw PolicyException The policy was not defined for this state, or horizon was invalid.
* @return The action to take at the given state.
*/
Action *get(unsigned int horizon, State *state);
/**
* A function which must load a policy file.
* @param filename The name and path of the file to load.
* @param states The states object which contains the actual state objects to be mapped.
* @param actions The actions object which contains the actual action objects to be mapped.
* @param horizon The horizons object to ensure valid policy creation.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool load(std::string filename, StatesMap *states, ActionsMap *actions, Horizon *horizon);
/**
* A function which must save a policy file.
* @param filename The name and path of the file to save.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool save(std::string filename);
/**
* Reset the policy mapping.
*/
virtual void reset();
private:
/**
* Defines the policy itself; it's the internal mapping from states to actions. There is
* one of these mappings for each horizon.
*/
std::vector<std::map<State *, Action *> > policy;
};
#endif // POLICY_MAP_H
|
kylewray/librbr
|
librbr/include/management/pomdp_file.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POMDP_FILE_H
#define POMDP_FILE_H
#include "../mdp/mdp.h"
#include "../pomdp/pomdp.h"
#include "../dec_pomdp/dec_pomdp.h"
#include "../core/states/belief_state.h"
#include <fstream>
/**
* A class which provides functionality save a Cassandra POMDP file into a array-based Markovian object.
*/
class POMDPFile {
public:
/**
* The default constructor for a POMDPFile object.
*/
POMDPFile();
/**
* The default deconstructor for a POMDPFile object.
*/
virtual ~POMDPFile();
/**
* A method which simply saves *any* MDP object as a Cassandra MDP file.
* @param mdp The MDP object to save.
* @param filename The name of the output file.
* @throw CoreException An error arose trying to save the MDP object. This could be
* an invalid mdp was provided, or the filename was invalid.
* ToDo: Implement saving pomdp files.
*/
// void save_mdp(MDP *mdp, std::string filename);
/**
* A method which simply saves *any* POMDP object as a Cassandra POMDP file.
* @param pomdp The POMDP object to save.
* @param filename The name of the output file.
* @param start The starting belief state.
* @throw CoreException An error arose trying to save the POMDP object. This could
* be an invalid mdp was provided, or the filename was invalid.
*/
void save_pomdp(POMDP *pomdp, std::string filename, BeliefState *start);
/**
* A method which simply saves *any* Dec-POMDP object as a raw Dec-POMDP file.
* @param decpomdp The Dec-POMDP object to save.
* @param filename The name of the output file.
* @throw CoreException An error arose trying to save the Dec-POMDP object. This could
* be an invalid mdp was provided, or the filename was invalid.
* ToDo: Implement saving dec-pomdp files.
*/
// void save_decpomdp(DecPOMDP *decpomdp, std::string filename);
};
#endif // POMDP_FILE_H
|
kylewray/librbr
|
librbr/include/management/raw_file.h
|
<filename>librbr/include/management/raw_file.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef RAW_FILE_H
#define RAW_FILE_H
#include "../mdp/mdp.h"
#include "../pomdp/pomdp.h"
#include "../dec_pomdp/dec_pomdp.h"
#include <fstream>
/**
* An enumeration for the types of rewards that are possible.
*/
enum RawFileRewardsType {
RawFileSRewards,
RawFileSARewards,
RawFileSASRewards,
RawFileSASORewards,
NumRawFileRewardsTypes
};
/**
* A class which provides functionality load a raw Markovian file into a array-based Markovian object,
* as well as save *any* Markovian object as a the appropriate raw Markovian file.
*/
class RawFile {
public:
/**
* The default constructor for a RawFile object.
*/
RawFile();
/**
* The default deconstructor for a RawFile object.
*/
virtual ~RawFile();
/**
* A method which simply loads a raw MDP file into an array-based MDP object.
* @param filename The name of the input file.
* @throw CoreException An error arose trying to save the MDP object. This is
* either due to an error within the file, or the file itself
* was not able to be loaded.
*/
MDP *load_raw_mdp(std::string filename);
/**
* A method which simply saves *any* MDP object as a raw MDP file.
* @param mdp The MDP object to save.
* @param filename The name of the output file.
* @throw CoreException An error arose trying to save the MDP object. This could be
* an invalid mdp was provided, or the filename was invalid.
*/
void save_raw_mdp(MDP *mdp, std::string filename);
/**
* A method which simply loads a raw MDP file into an array-based MDP object.
* @param filename The name of the input file.
* @throw CoreException An error arose trying to save the POMDP object. This is
* either due to an error within the file, or the file itself
* was not able to be loaded.
* ToDo: Implement loading raw pomdp files.
*/
// POMDP *load_raw_pomdp(std::string filename);
/**
* A method which simply saves *any* POMDP object as a raw POMDP file.
* @param pomdp The POMDP object to save.
* @param filename The name of the output file.
* @throw CoreException An error arose trying to save the POMDP object. This could
* be an invalid mdp was provided, or the filename was invalid.
* ToDo: Implement saving raw pomdp files.
*/
// void save_raw_pomdp(POMDP *pomdp, std::string filename);
/**
* A method which simply loads a raw MDP file into an array-based MDP object.
* @param filename The name of the input file.
* @throw CoreException An error arose trying to save the Dec-POMDP object. This is
* either due to an error within the file, or the file itself
* was not able to be loaded.
* ToDo: Implement loading raw dec-pomdp files.
*/
// DecPOMDP *load_raw_decpomdp(std::string filename);
/**
* A method which simply saves *any* Dec-POMDP object as a raw Dec-POMDP file.
* @param decpomdp The Dec-POMDP object to save.
* @param filename The name of the output file.
* @throw CoreException An error arose trying to save the Dec-POMDP object. This could
* be an invalid mdp was provided, or the filename was invalid.
* ToDo: Implement saving raw dec-pomdp files.
*/
// void save_raw_decpomdp(DecPOMDP *decpomdp, std::string filename);
private:
/**
* Load a matrix of data to into the 1-d array provided, given the offset provided.
* @param file The file stream.
* @param rows The number of rows to read.
* @param cols The number of columns to read for each row.
* @param array The array to modify.
* @param offset The offset from the start of the array.
* @throw CoreException Either ran out of lines, or a parsing error arose.
*/
void load_data(std::ifstream &file, unsigned int rows, unsigned int cols, float *array, unsigned int offset);
};
#endif // RAW_FILE_H
|
kylewray/librbr
|
librbr/include/core/rewards/factored_rewards.h
|
<filename>librbr/include/core/rewards/factored_rewards.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FACTORED_REWARDS_H
#define FACTORED_REWARDS_H
#include "rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
#include "../observations/observation.h"
#include <vector>
/**
* A class for factored rewards in an MDP-like object, i.e., multi-objective MDPs (MOMDPs). This
* class stores a fixed set of reward functions, each a Rewards child object in-and-of-itself.
*/
class FactoredRewards : virtual public Rewards {
public:
/**
* The default constructor for the FactoredRewards class.
*/
FactoredRewards();
/**
* The constructor for the FactoredRewards class which allows the specification
* of the number of rewards.
* @param numRewards The number of rewards in the multi-rewards vector, minimum of 1.
*/
FactoredRewards(unsigned int numRewards);
/**
* The default deconstructor for the FactoredRewards class.
*/
virtual ~FactoredRewards();
/**
* Add a new rewards factor to the vector of available rewards. This relinquishes control of the
* new rewards factor to this object.
* @param newRewardsFactor The new rewards factor to include in the vector of available rewards.
* @throw RewardException The new rewards factor was null.
*/
virtual void add_factor(Rewards *newRewardsFactor);
/**
* Set the particular rewards element in the multi-rewards vector. This frees memory.
* @param factorIndex The index of the factor to add the rewards factor to.
* @param newRewardsFactor The new rewards factor for this index.
* @throw RewardException The index was invalid.
*/
virtual void set(unsigned int factorIndex, Rewards *newRewardsFactor);
/**
* Get the particular rewards element in the factored rewards vector.
* @param factorIndex The index of the factor to add the rewards factor to.
* @throw RewardException The index was invalid.
* @return The rewards for this index.
*/
virtual Rewards *get(unsigned int factorIndex);
/**
* Get the number of rewards, i.e., the dimension of the factored rewards vector.
* @return The number of rewards.
*/
virtual unsigned int get_num_rewards() const;
/**
* Reset the rewards, freeing all the memory allocated by each object in the vector.
*/
virtual void reset();
protected:
/**
* The vector of modifiable reward objects.
*/
std::vector<Rewards *> rewards;
};
#endif // FACTORED_REWARDS_H
|
kylewray/librbr
|
librbr/include/core/actions/actions_map.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ACTIONS_MAP_H
#define ACTIONS_MAP_H
#include <unordered_map>
#include <vector>
#include "action.h"
#include "actions.h"
#include "../states/state.h"
/**
* A class for finite sets of actions in an MDP-like object. Informally, there are two basic ways to
* store finite actions: a vector of actions or a generator function based on a state. In both cases,
* we require that any class with finite actions provide certain get functions so that any generic
* solver can handle both cases.
*
* If you want to create a generator function-based FiniteActions class, please create a child class
* which implements the function in the virtual functions described below. You will likely ignore the
* internal actions vector variable here.
*/
class ActionsMap : virtual public Actions {
public:
/**
* The default constructor for the FiniteActions class.
*/
ActionsMap();
/**
* The constructor for the FiniteActions class which allows the specification of an initial set of actions.
* @param actions The initial vector of actions.
*/
ActionsMap(const std::vector<Action *> &actions);
/**
* The default deconstructor for the FiniteActions class.
*/
virtual ~ActionsMap();
/**
* Add an action to the set of available actions.
* @param newAction The new action to include in the set of available actions.
*/
void add(Action *newAction);
/**
* Remove an action to the set of available actions. This frees the memory.
* @param removeAction The action to remove from the set of available actions.
* @throw ActionException The action was not found in the actions list.
*/
void remove(Action *removeAction);
/**
* Set the internal actions list given another list, performing a deep copy. This resets
* the current list of states and frees the memory.
* @param newActions The vector of new actions to use.
*/
void set(const std::vector<Action *> &newActions);
/**
* Check if this action has already been created or not.
* @param action The action to check if it is created or not.
* @return Returns @code{true} if the action exists in the actions hash; @code{false} otherwise.
*/
bool exists(Action *action) const;
/**
* Get an action with a particular hash value.
* @param hash The hash of the action.
* @throw ActionException There are no actions with the hash value specified.
* @return The action with the particular hash value specified.
*/
Action *get(unsigned int hash);
/**
* Return the number of actions.
* @return The number of actions.
*/
unsigned int get_num_actions() const;
/**
* Return a list of the actions available given a state.
* @param state The current state.
* @return Return a list of available actions.
*/
virtual std::unordered_map<unsigned int, Action *> available(State *state);
/**
* Reset the actions, clearing the internal list.
*/
virtual void reset();
/**
* To facilitate easy iteration, return a constant beginning of the actions vector.
* @return The iterator which points to a constant beginning of the actions vector.
*/
std::unordered_map<unsigned int, Action *>::iterator begin();
/**
* To facilitate easy iteration, return a constant end of the actions vector.
* @return The iterator which points to a constant end of the actions vector.
*/
std::unordered_map<unsigned int, Action *>::iterator end();
protected:
/**
* The mapping of actions hash values to states. This is the main container of states.
*/
std::unordered_map<unsigned int, Action *> actions;
};
/**
* Get the action pointer of an action iterator.
* @param actionIterator The action iterator to retrieve the action pointer from.
*/
Action *resolve(std::unordered_map<unsigned int, Action *>::value_type &actionIterator);
/**
* Get the hash of an action iterator.
* @param actionIterator The action iterator to retrieve the hash value from.
*/
unsigned int hash_value(std::unordered_map<unsigned int, Action *>::value_type &actionIterator);
#endif // ACTIONS_MAP_H
|
kylewray/librbr
|
librbr/include/utilities/string_manipulation.h
|
<filename>librbr/include/utilities/string_manipulation.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STRING_MANIPULATION_H
#define STRING_MANIPULATION_H
#include <sstream>
#include <string>
#include <vector>
/**
* Trim the left and right sides of a string, removing the whitespace.
* @param item The string to trim.
*/
void trim_whitespace(std::string &item);
/**
* Remove all white space from a string.
* @param item The string to remove white space from.
* @return The resulting item without any white spaces.
*/
void remove_whitespace(std::string &item);
/**
* Split a string delimited by spaces ' ' into a vector of strings. If this
* string happens to represent joint actions, joint observations, or
* factored states, then it will split on spaces surrounding '<...>' instead.
* @param item The string to split which is delimited by spaces ' '.
* @return The resulting vector of items.
*/
std::vector<std::string> split_string_by_space(std::string item);
/**
* Split a string delimited by colons ':' into a vector of strings. This
* trims whitespace around each element.
* @param item The string to split which is delimited by colons ':'.
* @return The resulting vector of items.
*/
std::vector<std::string> split_string_by_colon(std::string item);
#endif // STRING_MANIPULATION_H
|
kylewray/librbr
|
librbr/include/mdp/mdp.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MDP_H
#define MDP_H
#include "../core/states/states.h"
#include "../core/actions/actions.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/rewards/rewards.h"
#include "../core/initial.h"
#include "../core/horizon.h"
/**
* A Markov Decision Process (MDP).
*/
class MDP {
public:
/**
* The default constructor for the MDP class.
*/
MDP();
/**
* A constructor for the MDP class.
* @param S The states.
* @param A The actions.
* @param T The state transitions, which uses the states and actions parameters.
* @param R The rewards, which uses the states and actions parameters.
* @param h The horizon.
*/
MDP(States *S, Actions *A, StateTransitions *T, Rewards *R, Horizon *h);
/**
* A deconstructor for the MDP class.
*/
virtual ~MDP();
/**
* Get the states object.
* @return The states object.
*/
States *get_states();
/**
* Get the actions object.
* @return The actions object.
*/
Actions *get_actions();
/**
* Get the state transitions object.
* @return The state transitions object.
*/
StateTransitions *get_state_transitions();
/**
* Get the rewards object.
* @return The rewards object.
*/
Rewards *get_rewards();
/**
* Get the horizon object.
* @return The horizon object.
*/
Horizon *get_horizon();
protected:
/**
* The states in the MDP; e.g., an array of strings.
*/
States *states;
/**
* The actions in the MDP; e.g., an array of strings.
*/
Actions *actions;
/**
* The state transition function in the MDP; e.g., a three-dimensional array mapping to a double.
*/
StateTransitions *stateTransitions;
/**
* The reward function in the MDP; e.g., a two-dimensional array mapping to a double.
*/
Rewards *rewards;
/**
* The horizon, either a finite time or a discount factor.
*/
Horizon *horizon;
};
#endif // MDP_H
|
kylewray/librbr
|
librbr/include/core/actions/action.h
|
<filename>librbr/include/core/actions/action.h<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ACTION_H
#define ACTION_H
#include <string>
/**
* An abstract action object.
*/
class Action {
public:
/**
* The default constructor of the Action object.
*/
Action();
/**
* The copy constructor of the Action object. Required by use as a map key.
* @param other The action to copy.
*/
Action(const Action &other);
/**
* The default deconstructor of the Action object.
*/
virtual ~Action();
/**
* Overload the equals operator to set this action equal to the action provided.
* @param other The action to copy.
* @return The new version of this action.
*/
virtual Action &operator=(const Action &other);
/**
* Overload the equality comparison operator.
* @param other The action to compare.
* @return Returns @code{true} if this action is equal to the other; @code{false} otherwise.
*/
virtual bool operator==(const Action &other) const;
/**
* Overload the less than operator for comparison.
* @param other The action to compare.
* @return Returns @code{true} if this action is less than the other; @code{false} otherwise.
*/
virtual bool operator<(const Action &other) const;
/**
* Returns a string representation of this action.
* @return Returns the string representing this action.
*/
virtual std::string to_string() const = 0;
/**
* Returns a hash value used to quickly identify this action in a collection of actions.
* @return Returns the hash value of this action.
*/
virtual unsigned int hash_value() const = 0;
};
#endif // ACTION_H
|
kylewray/librbr
|
librbr/include/pomdp/pomdp_pbvi.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POMDP_PBVI_H
#define POMDP_PBVI_H
#include "pomdp.h"
#include "../core/policy/policy_alpha_vectors.h"
#include "../core/policy/policy_alpha_vector.h"
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/observations/observations_map.h"
#include "../core/state_transitions/state_transitions_map.h"
#include "../core/observation_transitions/observation_transitions_map.h"
#include "../core/rewards/saso_rewards.h"
#include "../core/horizon.h"
/**
* List the possible expansion rules available while using PBVI.
*/
enum POMDPPBVIExpansionRule {
NONE,
RANDOM_BELIEF_SELECTION,
STOCHASTIC_SIMULATION_RANDOM_ACTION,
STOCHASTIC_SIMULATION_GREEDY_ACTION,
STOCHASTIC_SIMULATION_EXPLORATORY_ACTION,
GREEDY_ERROR_REDUCTION,
NUM_EXPANSION_RULES
};
/**
* Solve an POMDP via Point-Based Value Iteration (PBVI) (finite or infinite horizon). This
* solver has the following requirements:
* - POMDP states must be of type FiniteStates.
* - POMDP actions must be of type FiniteActions.
* - POMDP observations must be of type FiniteObservations.
* - POMDP state transitions must be of type FiniteStateTransitions.
* - POMDP observation transitions must be of type FiniteObservationTransitions.
* - POMDP rewards must be of type SASRewards.
*/
class POMDPPBVI {
public:
/**
* The default constructor for the POMDPPBVI class. Default number of iterations for infinite
* horizon POMDPs is 1. The default expansion rule is Random Belief Selection.
*/
POMDPPBVI();
/**
* A constructor for the POMDPPBVI class which allows for the specification of the expansion rule,
* and the number of iterations (both updates and expansions) to run for infinite horizon.
* The default is 1 for both.
* @param expansionRule The expansion rule to use.
* @param updateIterations The number of update iterations to run for infinite horizon POMDPs.
* @param expansionIterations The number of expansion iterations to run for infinite horizon POMDPs.
*/
POMDPPBVI(POMDPPBVIExpansionRule expansionRule, unsigned int updateIterations, unsigned int expansionIterations);
/**
* The deconstructor for the POMDPPBVI class. This method frees all the belief state memory.
*/
virtual ~POMDPPBVI();
/**
* Add an initial belief state which is used to seed the belief states before computing the optimal policy.
* Note: This relinquishes control of the belief state's memory management to this class.
* @param b The initial set of belief states before calling 'solve'.
*/
virtual void add_initial_belief_state(BeliefState *b);
/**
* Set the initial set of belief states which are used to seed the belief states before computing
* the optimal policy. Note: This relinquishes control of the belief states' memory management to this class.
* @param initialBeliefStates The initial set of belief states before calling 'solve'.
*/
virtual void set_initial_belief_states(const std::vector<BeliefState *> &initialBeliefStates);
/**
* Set the expansion rule to add belief points.
* @param expansionRule The expansion rule to use.
*/
virtual void set_expansion_rule(POMDPPBVIExpansionRule expansionRule);
/**
* Set the number of update iterations to run for infinite horizon POMDPs.
* @param iterations The number of update iterations to run for infinite horizon POMDPs.
*/
virtual void set_num_update_iterations(unsigned int iterations);
/**
* Set the number of expansion iterations to run for infinite horizon POMDPs.
* @param iterations The number of expansion iterations to run for infinite horizon POMDPs.
*/
virtual void set_num_expansion_iterations(unsigned int iterations);
/**
* Get the initial set of belief states which are used to seed the belief states before computing
* the optimal policy.
* @return The initial set of belief states before calling 'solve'.
*/
virtual std::vector<BeliefState *> &get_initial_belief_states();
/**
* Get the set of belief states which were used to compute the optimal policy. This vector is only
* populated after calling 'solve'.
* @return The final set of belief states after calling 'solve'.
*/
virtual std::vector<BeliefState *> &get_belief_states();
/**
* Set the expansion rule to add belief points.
* @param expansionRule The expansion rule to use.
*/
virtual POMDPPBVIExpansionRule get_expansion_rule() const;
/**
* Get the number of update iterations to run for infinite horizon POMDPs.
* @return The number of update iterations to run for infinite horizon POMDPs.
*/
virtual unsigned int get_num_update_iterations() const;
/**
* Get the number of expansion iterations to run for infinite horizon POMDPs.
* @return The number of expansion iterations to run for infinite horizon POMDPs.
*/
virtual unsigned int get_num_expansion_iterations() const;
/**
* Compute the optimal number of update iterations to run for infinite horizon POMDPs, given
* the desired tolerance, requiring knowledge of the reward function.
* @param pomdp The partially observable Markov decision process to use.
* @param epsilon The desired tolerance between value functions to check for convergence.
* @throw RewardException The POMDP did not have a SARewards rewards object.
*/
virtual void compute_num_update_iterations(POMDP *pomdp, double epsilon);
/**
* Solve the POMDP provided using point-based value iteration.
* @param pomdp The partially observable Markov decision process to solve.
* @throw CoreException The POMDP was null.
* @throw StateException The POMDP did not have a FiniteStates states object.
* @throw ActionException The POMDP did not have a FiniteActions actions object.
* @throw ObservationException The POMDP did not have a FiniteObservations observations object.
* @throw StateTransitionsException The POMDP did not have a FiniteStateTransitions state transitions object.
* @throw ObservationTransitionsException The POMDP did not have a FiniteObservationTransitions observation transitions object.
* @throw RewardException The POMDP did not have a SASRewards rewards object.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a finite state controller (infinite horizon) or tree (finite horizon).
*/
virtual PolicyAlphaVectors *solve(POMDP *pomdp);
/**
* Reset this POMDP PBVI solver. This method frees all the belief state memory.
*/
virtual void reset();
protected:
/**
* Solve a finite horizon POMDP using point-based value iteration.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param R The state-action-state-observation rewards.
* @param h The horizon.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a collection of alpha vectors.
*/
virtual PolicyAlphaVectors *solve_finite_horizon(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O, Rewards *R,
Horizon *h);
/**
* Solve an infinite horizon POMDP using point-based value iteration.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param R The state-action rewards.
* @param h The horizon.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy as a collection of alpha vectors.
*/
virtual PolicyAlphaVectors *solve_infinite_horizon(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O, Rewards *R,
Horizon *h);
/**
* Expand the set of beliefs following Random Belief Selection. This works by randomly selecting a set of new
* belief points at each expansion. One new point is selected for each current belief point, doubling the total
* quantity each time.
* @param S The finite states.
*/
virtual void expand_random_belief_selection(StatesMap *S);
/**
* Expand the set of beliefs following Stochastic Simulation with Random Actions. "Stochastic Simulation" means it
* generates belief points which are reachable given the initial set of belief points, i.e., it traverses the belief
* tree. In this case, for each belief point it randomly selects a state, proportional to the belief, then randomly
* selects an action (uniformly), then randomly selects a next state and next observation. The result is a new belief
* point.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
*/
virtual void expand_stochastic_simulation_random_actions(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O);
/**
* Expand the set of beliefs following Stochastic Simulation with Greedy Action. "Stochastic Simulation" means it
* generates belief points which are reachable given the initial set of belief points, i.e., it traverses the belief
* tree. In this case, for each belief point it randomly selects a state, proportional to the belief, then randomly
* rolls a die. If it is less than some epsilon, it randomly selects an action (uniformly); otherwise, it selects the
* optimal action. Next, it randomly selects a next state and next observation. The result is a new belief point.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param gamma The current set of alpha vectors.
*/
virtual void expand_stochastic_simulation_greedy_action(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O, std::vector<PolicyAlphaVector *> &gamma);
/**
* Expand the set of beliefs following Stochastic Simulation with Exploratory Action. "Stochastic Simulation" means it
* generates belief points which are reachable given the initial set of belief points, i.e., it traverses the belief
* tree. In this case, for each belief point it adds a new belief point which maximizes over the actions, given a randomly
* selected next belief point following this action, selecting the point which is farthest away from the closest belief point.
* @param S The finite states.
* @param A The finite actions.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
*/
virtual void expand_stochastic_simulation_exploratory_action(StatesMap *S, ActionsMap *A, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O);
/**
* Expand the set of beliefs following Greedy Error Reduction. TODO: Implement.
*/
virtual void expand_greedy_error_reduction();
/**
* The expansion rule to use which adds belief points.
*/
POMDPPBVIExpansionRule rule;
/**
* The number of update iterations until the solver stops for infinite horizon POMDPs.
*/
unsigned int updates;
/**
* The number of expansion iterations until the solver stops for infinite horizon POMDPs.
*/
unsigned int expansions;
/**
* The initial set of belief points.
*/
std::vector<BeliefState *> initialB;
/**
* The final set of belief points after the solver's iterations.
*/
std::vector<BeliefState *> B;
};
#endif // POMDP_PBVI_H
|
kylewray/librbr
|
librbr/include/core/policy/policy_tree.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POLICY_TREE_H
#define POLICY_TREE_H
#include <vector>
#include <string>
#include <map>
#include <fstream>
#include "policy.h"
#include "../states/state.h"
#include "../states/states_map.h"
#include "../actions/action.h"
#include "../actions/actions_map.h"
#include "../observations/observation.h"
#include "../observations/observations_map.h"
#include "../horizon.h"
/**
* A small structure for a policy tree's node.
*/
struct PolicyTreeNode {
/**
* The default constructor for the PolicyTreeNode class. It defaults to a null action.
*/
PolicyTreeNode();
/**
* A constructor for the PolicyTreeNode class which allows the specification of the action.
* @param a The corresponding action at this node.
*/
PolicyTreeNode(Action *a);
/**
* The current node's action.
*/
Action *action;
/**
* A pointer to each of the children following a given observation.
* If next is empty, then we are at a leaf.
*/
std::map<Observation *, PolicyTreeNode *> next;
};
/**
* A policy tree for POMDPs (and possibly Dec-POMDPs). Each node represents an
* action to take, and each edge represents an observation made at the time step.
* It is likely that this will only be used for finite horizon scenarios.
*
* This requires a finite observations object. The reason being that the set of
* observations is the branching factor for the tree.
*/
class PolicyTree : public Policy {
public:
/**
* The default constructor for a PolicyTree object. It defaults to a horizon of 0, which
* is a single action.
*/
PolicyTree();
/**
* A constructor for a PolicyTree object which specifies the horizon. If the horizon
* is zero, then it will create an empty tree (no nodes).
* @param observations The finite set of observations.
* @param horizon The horizon of the problem.
*/
PolicyTree(ObservationsMap *observations, unsigned int horizon);
/**
* A constructor for a MapPolicy object which specifies the horizon.
* @param observations The finite set of observations.
* @param horizon The horizon object from the MDP-like object.
*/
PolicyTree(ObservationsMap *observations, Horizon *horizon);
/**
* A virtual deconstructor to prevent errors upon the deletion of a child object.
*/
virtual ~PolicyTree();
/**
* Set the action given a history of observations.
* @param history The history of observations.
* @param action The action to take after this history of observations.
* @throw PolicyException The policy was not defined for this history.
*/
void set(const std::vector<Observation *> &history, Action *action);
/**
* Get the action given a history of observations.
* @param history The history of observations.
* @throw PolicyException The policy was not defined for this history.
* @return The action to take given the history of observations provided.
*/
Action *get(const std::vector<Observation *> &history);
/**
* A function which must load a policy file.
* @param filename The name and path of the file to load.
* @param actions The actions object which contains the actual action objects to be mapped.
* @param observations The observations object which contains the actual observation objects to be mapped.
* @param horizon The horizons object to ensure valid policy creation.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool load(std::string filename, ActionsMap *actions, ObservationsMap *observations, Horizon *horizon);
/**
* A function which must save a policy file.
* @param filename The name and path of the file to save.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool save(std::string filename);
/**
* A function which follows the defined policy, having the current state stored internally,
* and returns the action to select next.
* @throw PolicyException The horizon has already been reached; no more planning has been done.
*/
virtual Action *next(Observation *observation);
/**
* Reset the policy, clearing the entire tree.
*/
virtual void reset();
private:
/**
* Generate the policy tree recursively.
* @param observations The finite set of observations (branching factor).
* @param horizon The remaining horizon value; once zero, recursion terminates.
* @return The root of this node's subtree.
*/
PolicyTreeNode *generate_tree(ObservationsMap *observations, unsigned int horizon);
/**
* Traverse the tree following the history provided.
* @param history The history of observations.
* @throw PolicyException The policy was not defined for this history.
* @return The final node after following the history.
*/
PolicyTreeNode *traverse(const std::vector<Observation *> &history);
/**
* Save the policy tree recursively.
* @param file The handle to the output file.
* @param node The current node.
* @param history The history of observations so far.
*/
void save_tree(std::ofstream &file, PolicyTreeNode *node, std::vector<Observation *> history);
/**
* Defines the policy itself; it's the internal mapping from states to actions. There is
* one of these mappings for each level.
*/
std::vector<PolicyTreeNode *> nodes;
/**
* The root node of the policy tree.
*/
PolicyTreeNode *root;
/**
* The current node in the tree.
*/
PolicyTreeNode *current;
};
#endif // POLICY_TREE_H
|
kylewray/librbr
|
librbr/include/ssp/ssp.h
|
<filename>librbr/include/ssp/ssp.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SSP_H
#define SSP_H
#include "../mdp/mdp.h"
#include "../core/states/states.h"
#include "../core/actions/actions.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/rewards/rewards.h"
#include "../core/initial.h"
#include "../core/horizon.h"
#include <vector>
/**
* A Stochastic Control Process (SSP), which is a more general form of an MDP.
*/
class SSP : public MDP {
public:
/**
* The default constructor for the SSP class.
*/
SSP();
/**
* A constructor for the SSP class.
* @param S The states.
* @param A The actions.
* @param T The state transitions, which uses the states and actions parameters.
* @param R The rewards, which uses the states and actions parameters.
* @param h The horizon.
*/
SSP(States *S, Actions *A, StateTransitions *T, Rewards *R, Horizon *h, State *s0, std::vector<State *> G);
/**
* A deconstructor for the SSP class.
*/
virtual ~SSP();
/**
* Get the initial state object.
* @return The initial state object.
*/
State *get_initial_state();
/**
* Get the goal states.
* @return The goal states as a vector.
*/
std::vector<State *> get_goal_states();
protected:
/**
* The initial state of the SSP.
*/
State *initialState;
/**
* The set of goal states of the SSP.
*/
std::vector<State *> goalStates;
};
#endif // SSP_H
|
kylewray/librbr
|
librbr/include/core/policy/policy_alpha_vectors.h
|
<reponame>kylewray/librbr<filename>librbr/include/core/policy/policy_alpha_vectors.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POLICY_ALPHA_VECTORS_H
#define POLICY_ALPHA_VECTORS_H
#include <vector>
#include <string>
#include <map>
#include "policy.h"
#include "policy_alpha_vector.h"
#include "../states/state.h"
#include "../states/states_map.h"
#include "../actions/action.h"
#include "../actions/actions_map.h"
#include "../observations/observation.h"
#include "../observations/observations_map.h"
#include "../horizon.h"
/**
* A policy for a set of alpha vectors, which supports finite or infinite horizon. It allows
* for the resultant action given a belief point (which can be updated externally).
*
* Importantly, this class manages all alpha vectors once provided a list of them. All methods
* which set alpha vectors automatically assume the user has relinquished control of memory
* management once passed into the method.
*/
class PolicyAlphaVectors : virtual public Policy {
public:
/**
* The default constructor for a PolicyAlphaVectors object. It defaults to a horizon of 1.
*/
PolicyAlphaVectors();
/**
* A constructor for a PolicyAlphaVectors object which specifies the horizon.
* @param horizon The horizon of the problem; 0 represents infinite horizon.
*/
PolicyAlphaVectors(unsigned int horizon);
/**
* A constructor for a PolicyAlphaVectors object which specifies the horizon.
* @param horizon The horizon object from the MDP-like object.
*/
PolicyAlphaVectors(Horizon *horizon);
/**
* A constructor for a PolicyAlphaVectors object which specifies the alpha vectors.
* It defaults to a horizon of 1 in this case.
* @param alphas The set of alpha vectors.
*/
PolicyAlphaVectors(std::vector<PolicyAlphaVector *> &alphas);
/**
* A constructor for a PolicyAlphaVectors object which specifies the alpha vectors.
* It defaults to a horizon of 1 in this case.
* @param alphas The set of alpha vectors at each horizon.
*/
PolicyAlphaVectors(std::vector<std::vector<PolicyAlphaVector *> > &alphas);
/**
* A virtual deconstructor to prevent errors upon the deletion of a child object.
*/
virtual ~PolicyAlphaVectors();
/**
* Set the alpha vectors. For finite horizon, it assumes 0 by default. This frees the memory of
* previous alpha vectors.
* @param alphas The set of alpha vectors.
*/
virtual void set(std::vector<PolicyAlphaVector *> &alphas);
/**
* Set the alpha vectors, allowing the explicit specification of the horizon. This frees
* the memory of previous alpha vectors.
* @param horizon The horizon to set.
* @param alphas The set of alpha vectors.
* @throw PolicyException The horizon was invalid.
*/
virtual void set(unsigned int horizon, std::vector<PolicyAlphaVector *> &alphas);
/**
* Get the action for a given belief state. For finite horizon, it assumes 0 by default.
* @param belief The belief state to retrieve a mapping.
* @throw PolicyException The policy was not defined for this state.
* @return The action to take at the given belief state.
*/
virtual Action *get(BeliefState *belief);
/**
* Get the action for a given belief state, allowing the explicit specification of the horizon.
* @param horizon The horizon to set.
* @param belief The belief state to retrieve a mapping.
* @throw PolicyException The policy was not defined for this belief state, or horizon was invalid.
* @return The action to take at the given belief state.
*/
virtual Action *get(unsigned int horizon, BeliefState *belief);
/**
* Get the set of actions at a given belief state, up to the specified "deviation" away from optimal.
* For finite horizon, it assumes 0 by default.
* @param belief The belief state to retrieve a mapping.
* @param deviation The deviation from the optimal value.
* @param A The return set of actions up to the deviation. This will be modified.
* @throw PolicyException The policy was not defined for this state.
* @return The action to take at the given belief state.
*/
virtual void get(BeliefState *belief, double deviation, std::vector<Action *> &A);
/**
* Get the set of actions at a given belief state, up to the specified "deviation" away from optimal,
* allowing the explicit specification of the horizon.
* @param horizon The horizon to set.
* @param belief The belief state to retrieve a mapping.
* @param deviation The deviation from the optimal value.
* @param A The return set of actions up to the deviation. This will be modified.
* @throw PolicyException The policy was not defined for this belief state, or horizon was invalid.
* @return The action to take at the given belief state.
*/
virtual void get(unsigned int horizon, BeliefState *belief, double deviation, std::vector<Action *> &A);
/**
* Compute the value of the belief state by computing: max_{alpha} dot(beta, alpha).
* For finite horizon, it assumes 0 by default.
* @param belief The belief state 'beta' vector.
* @return The value of the belief state provided.
*/
virtual double compute_value(BeliefState *belief);
/**
* Compute the value of the belief state by computing: max_{alpha} dot(beta, alpha), allowing the
* explicit specification of the horizon.
* @param horizon The horizon to set.
* @param belief The belief state 'beta' vector.
* @return The value of the belief state provided.
*/
virtual double compute_value(unsigned int horizon, BeliefState *belief);
/**
* A function which must load a policy file.
* @param filename The name and path of the file to load.
* @param states The states object which contains the actual state objects to be mapped.
* @param actions The actions object which contains the actual action objects to be mapped.
* @param observations The observations object which contains the actual observation objects to be mapped.
* @param horizon The horizons object to ensure valid policy creation.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool load(std::string filename, StatesMap *states, ActionsMap *actions,
ObservationsMap *observations, Horizon *horizon);
/**
* A function which must save a policy file.
* @param filename The name and path of the file to save.
* @param states The states object which contains the actual state objects to be mapped.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
virtual bool save(std::string filename, StatesMap *states);
/**
* Reset the alpha vectors, freeing the memory.
*/
virtual void reset();
/**
* Print the alpha vectors to the screen.
*/
virtual void print() const;
/**
* A static method to prune a set of alpha vectors. This will free the memory of the alpha vectors inside 'alphas',
* for those alpha vectors which are pruned.
* @param S The finite set of states.
* @param alphas The set of alpha vectors for which dominated ones will be pruned in place.
* @throws PolicyException The states were invalid, there were zero alpha vectors, or the first alpha vector is null.
*/
static void prune_dominated(StatesMap *S, std::vector<PolicyAlphaVector *> &alphas);
private:
/**
* Defines the policy itself; it's the internal mapping from states to actions. There is
* one of these mappings for each horizon.
*/
std::vector<std::vector<PolicyAlphaVector *> > alphaVectors;
};
#endif // POLICY_ALPHA_VECTORS_H
|
kylewray/librbr
|
librbr/include/utilities/log.h
|
<filename>librbr/include/utilities/log.h<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LOG_H
#define LOG_H
#include <string>
#include <iostream>
#define LOG_STREAM std::cerr
//#define LOG_STREAM std::cout
/**
* Log a normal message or error to a stream, e.g., std::cerr or std::cout.
* Note: This is *not* to be used in any classes within "core." It is exclusively for the MDP-like objects
* and the various utilities provided.
* @param msg The message to output along with the error.
* @param error The detailed error message.
*/
void log_message(const std::string &classFunctionName, const std::string &message);
#endif // LOG_H
|
kylewray/librbr
|
librbr/include/mdp/mdp_policy_iteration.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MDP_POLICY_ITERATION_H
#define MDP_POLICY_ITERATION_H
#include "mdp.h"
#include "../core/policy/policy_map.h"
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/state_transitions/state_transitions_map.h"
#include "../core/rewards/sas_rewards.h"
#include "../core/horizon.h"
/**
* Solve an MDP via policy iteration (infinite horizon) with either the exact or modified
* version. This solver has the following requirements:
* - MDP states must be of type FiniteStates.
* - MDP actions must be of type FiniteActions.
* - MDP state transitions must be of type FiniteStateTransitions.
* - MDP rewards must be of type SASRewards.
*/
class MDPPolicyIteration {
public:
/**
* The default constructor for the PolicyIteration class. It uses the exact
* version of policy iteration by default.
*/
MDPPolicyIteration();
/**
* A constructor for the PolicyIteration class. It uses the modified version of
* policy iteration with a given k value.
* @param k The number of iterations to compute an approximate set of value functions.
*/
MDPPolicyIteration(unsigned int k);
/**
* The deconstructor for the PolicyIteration class.
*/
virtual ~MDPPolicyIteration();
/**
* Solve the MDP provided using policy iteration.
* @param mdp The Markov decision process to solve.
* @throw StateException The MDP did not have a FiniteStates states object.
* @throw ActionException The MDP did not have a FiniteActions actions object.
* @throw StateTransitionsException The MDP did not have a FiniteStateTransitions state transitions object.
* @throw RewardException The MDP did not have a SASRewards rewards object.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy.
*/
PolicyMap *solve(MDP *mdp);
private:
/**
* Solve an infinite horizon MDP using exact policy iteration.
* @param S The finite states.
* @param A The finite actions.
* @param T The finite state transition function.
* @param R The state-action-state rewards.
* @param h The horizon.
* @throw PolicyException An error occurred computing the policy.
* @return Return the optimal policy.
*/
PolicyMap *solve_exact(StatesMap *S, ActionsMap *A, StateTransitionsMap *T,
SASRewards *R, Horizon *h);
/**
* Solve an infinite horizon MDP using modified policy iteration.
* @param S The finite states.
* @param A The finite actions.
* @param T The finite state transition function.
* @param R The state-action-state rewards.
* @param h The horizon.
* @throws PolicyException An error occurred computing the policy.
* @return Return the optimal policy.
*/
PolicyMap *solve_modified(StatesMap *S, ActionsMap *A, StateTransitionsMap *T,
SASRewards *R, Horizon *h);
/**
* The number of times to iterate in the modified version. Disable the modified version of
* policy iteration by setting k = 0.
*/
unsigned int modifiedK;
};
#endif // MDP_POLICY_ITERATION_H
|
kylewray/librbr
|
librbr/include/core/state_transitions/state_transitions_array.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATE_TRANSITIONS_ARRAY_H
#define STATE_TRANSITIONS_ARRAY_H
#include "state_transitions.h"
#include "../states/states.h"
#include "../states/states_map.h"
#include "../states/state.h"
#include "../states/indexed_state.h"
#include "../actions/action.h"
#include "../actions/indexed_action.h"
/**
* A class for finite state transitions in an MDP-like object. Informally, there are two basic ways to
* store finite state transitions: a table lookup mapping state-action-state triples to real values,
* or a generator function based on one of these triples. In both cases, we require that any class with
* finite state transitions provide certain get functions so that any generic solver can handle both cases.
*
* If you want to create a generator function-based StateTransitionsArray class, please create a child
* class which implements the function in the virtual functions described below. You will likely ignore
* the internal stateTrantions vector variable here.
*
* This class requires that states and actions be of types IndexedState and IndexedAction, respectively.
*/
class StateTransitionsArray : virtual public StateTransitions {
public:
/**
* The default constructor for the StateTransitionsArray class. This requires the
* number of states and actions to be specified.
* @param numStates The number of states.
* @param numActions The number of actions.
*/
StateTransitionsArray(unsigned int numStates, unsigned int numActions);
/**
* The default deconstructor for the StateTransitionsArray class.
*/
virtual ~StateTransitionsArray();
/**
* Set a state transition from a particular state-action-state triple to a probability.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @param probability The probability of going from the state, taking the action, then
* moving to the nextState.
* @throw StateTransitionException Either one of the states or the action was invalid.
*/
virtual void set(State *state, Action *action, State *nextState, double probability);
/**
* The probability of a transition following the state-action-state triple provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @throw StateTransitionException Either one of the states or the action was invalid.
* @return The probability of going from the state, taking the action, then moving to the nextState.
*/
virtual double get(State *state, Action *action, State *nextState);
/**
* Add a successor to a particular state.
* @param state The previous state.
* @param action The action taken at the previous state.
* @param successorState The previous state.
* @throw StateTransitionException The state-action pair was invalid.
*/
virtual void add_successor(State *state, Action *action, State *successorState);
/**
* Return a list of the states available given a previous state and the action taken there.
* Note: This list may change (continual planning) if nested inside loops incorrectly. To be safe,
* just call it once unless you know what you are doing.
* @param S The set of states.
* @param state The previous state.
* @param action The action taken at the previous state.
* @throw StateTransitionException An error occurred. Please see child class definitions for specifics.
* @return successors A reference to the list of successor states.
*/
virtual const std::vector<State *> &successors(States *S, State *state, Action *action);
/**
* Set the entire 3-dimensional array with the one provided. This only performs a copy.
* @param T A pointer to the new 3-d array of raw state transitions data. This must be
* an array of size n x m x n.
*/
virtual void set_state_transitions(const float *T);
/**
* Get the memory location of the 3-dimensional array.
* @return A pointer to the raw state transitions data.
*/
virtual float *get_state_transitions();
/**
* Get the number of states used for the state transitions array.
* @return The number of states.
*/
virtual unsigned int get_num_states() const;
/**
* Get the number of actions used for the state transitions array.
* @return The number of actions.
*/
virtual unsigned int get_num_actions() const;
/**
* Reset the state transitions by assigning all probabilities to zero. This does not free memory.
*/
virtual void reset();
private:
/**
* Compute the successor states for the state and action pair provided, then store the result
* in successorStates.
* @param S The finite set of states.
* @param s The current state.
* @param a The current action.
*/
virtual void compute_successors(StatesMap *S, IndexedState *s, IndexedAction *a);
/**
* The 3-dimensional array of all state-action-state transitions. Internally,
* these are floats to improve speed.
*/
float *stateTransitions;
/**
* The number of states in the state transitions first and third dimensions.
*/
unsigned int states;
/**
* The number of actions in the state transitions second dimension.
*/
unsigned int actions;
/**
* A mapping from state-action pairs to a vector of successor states.
*/
std::vector<State *> *successorStates;
};
#endif // STATE_TRANSITIONS_ARRAY_H
|
kylewray/librbr
|
librbr/include/core/states/state.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATE_H
#define STATE_H
#include <string>
/**
* An abstract state object.
*/
class State {
public:
/**
* The default constructor of the State object.
*/
State();
/**
* The copy constructor of the State object.
* @param other The state to copy.
*/
State(const State &other);
/**
* The default deconstructor of the State object.
*/
virtual ~State();
/**
* Overload the equals operator to set this state equal to the state provided.
* @param other The state to copy.
* @return The new version of this state.
*/
virtual State &operator=(const State &other);
/**
* Overload the equality comparison operator.
* @param other The state to compare.
* @return Returns @code{true} if this state is equal to the other; @code{false} otherwise.
*/
virtual bool operator==(const State &other) const;
/**
* Overload the less than operator for comparison.
* @param other The state to compare.
* @return Returns @code{true} if this state is less than the other; @code{false} otherwise.
*/
virtual bool operator<(const State &other) const;
/**
* Returns a string representation of this state.
* @return Returns the string representing this state.
*/
virtual std::string to_string() const = 0;
/**
* Returns a hash value used to quickly identify this state in a collection of states.
* @return Returns the hash value of this state.
*/
virtual unsigned int hash_value() const = 0;
};
#endif // STATE_H
|
kylewray/librbr
|
librbr/include/core/observations/indexed_observation.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INDEXED_OBSERVATION_H
#define INDEXED_OBSERVATION_H
#include <string>
#include "observation.h"
/**
* A observation object identified by a unique index which is determined using a static variable,
* incremented each time a new IndexedObservation is created.
*/
class IndexedObservation : public Observation {
public:
/**
* The default constructor of the IndexedObservation object.
*/
IndexedObservation();
/**
* The copy constructor of the IndexedObservation object.
* @param other The observation to copy.
*/
IndexedObservation(const IndexedObservation &other);
/**
* The default deconstructor of the IndexedObservation object.
*/
virtual ~IndexedObservation();
/**
* Get the index of this observation.
* @return The index of this observation.
*/
virtual unsigned int get_index() const;
/**
* Overload the equals operator to set this observation equal to the observation provided.
* @param other The observation to copy.
* @return The new version of this observation.
*/
virtual Observation &operator=(const Observation &other);
/**
* Returns a string representation of this observation.
* @return Returns the string representing this observation.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this observation in a collection of observations.
* @return Returns the hash value of this observation.
*/
virtual unsigned int hash_value() const;
/**
* Get the number of observations which have been created. This is the value of the indexer.
* @return The number of observations which have been created.
*/
static unsigned int get_num_observations();
/**
* Reset the internal static variable which assigns indexes (called the indexer).
*/
static void reset_indexer();
protected:
/**
* All indexed observations have an integer for their index. This is also used as their hash.
*/
unsigned int index;
/**
* A static variable which assigns indexes to the observations. This defaults to zero.
*/
static unsigned int indexer;
};
#endif // INDEXED_OBSERVATION_H
|
kylewray/librbr
|
librbr/include/mdp/mdp_utilities.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MDP_UTILITIES_H
#define MDP_UTILITIES_H
#include <unordered_map>
#include <vector>
#include "../core/states/state.h"
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/rewards/sas_rewards.h"
#include "../core/rewards/factored_rewards.h"
#include "../core/horizon.h"
#include "../core/policy/policy_map.h"
/**
* Compute the Bellman update/backup for a given state and compute the action which achieves the
* highest Q(s, a), and store the value and action in the variables provided.
* @param S The finite states.
* @param A The finite actions.
* @param T The finite state transition function.
* @param R The state-action-state rewards.
* @param h The horizon.
* @param s The current state being examined, i.e., V(s).
* @param V The current Bellman backup, mapping states to expected rewards. This will be updated.
* @param aBest The action which produced the maximum V(s) value. This will be updated.
*/
void bellman_update(StatesMap *S, ActionsMap *A, StateTransitions *T,
SASRewards *R, Horizon *h, State *s,
std::unordered_map<State *, double> &V, Action *&aBest);
/**
* Compute the value of states (V^\pi), following the Bellman's equation, given a policy. This assumes
* a single reward function.
* @param S The finite states.
* @param A The finite actions.
* @param T The finite state transition function.
* @param R The state-action-state rewards.
* @param h The horizon.
* @param epsilon The tolerance for convergence.
* @param pi The policy mapping states to actions.
* @param V The resultant values, mapping states to expected rewards. This will be updated.
*/
void compute_V_pi(StatesMap *S, ActionsMap *A, StateTransitions *T, SASRewards *R, Horizon *h,
double epsilon, PolicyMap *pi, std::unordered_map<State *, double> &V);
/**
* Compute the value of states (V^\pi), following the Bellman's equation, given a policy. This assumes
* a factored reward function, eaching having a SASReward.
* @param S The finite states.
* @param A The finite actions.
* @param T The finite state transition function.
* @param R The factored rewards, each being a state-action-state reward.
* @param h The horizon.
* @param epsilon The tolerance for convergence.
* @param pi The policy mapping states to actions.
* @param V The resultant values, mapping states to expected rewards. This will be updated.
*/
void compute_V_pi(StatesMap *S, ActionsMap *A, StateTransitions *T, FactoredRewards *R, Horizon *h,
double epsilon, PolicyMap *pi, std::vector<std::unordered_map<State *, double> > &V);
#endif // MDP_UTILITIES_H
|
kylewray/librbr
|
librbr/include/core/observations/observations_map.h
|
<reponame>kylewray/librbr<filename>librbr/include/core/observations/observations_map.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef OBSERVATIONS_MAP_H
#define OBSERVATIONS_MAP_H
#include <unordered_map>
#include <vector>
#include "observation.h"
#include "observations.h"
#include "../states/state.h"
#include "../actions/action.h"
/**
* A class for finite sets of observations in an MDP-like object. Informally, there are two basic ways to
* store finite observations: a vector of observations or a generator function based on a state and action.
* In both cases, we require that any class with finite observations provide certain get functions so that
* any generic solver can handle both cases.
*
* If you want to create a generator function-based FiniteObservations class, please create a child class which
* implements the function in the virtual functions described below. You will likely ignore the internal
* observations vector variable here.
*/
class ObservationsMap : public Observations {
public:
/**
* The default constructor for the FiniteObservations class.
*/
ObservationsMap();
/**
* The constructor for the FiniteObservations class which allows the specification of an initial set of observations.
* @param observations The initial vector of observations.
*/
ObservationsMap(const std::vector<Observation *> &observations);
/**
* The default deconstructor for the FiniteObservations class.
*/
virtual ~ObservationsMap();
/**
* Add a observation to the set of available observations.
* @param newObservation The new observation to include in the set of available states.
*/
void add(Observation *newObservation);
/**
* Remove a observation to the set of available observations. This frees the memory.
* @param removeObservation The state to remove from the set of available observations.
* @throw ObservationException The observation was not found in the observations list.
*/
void remove(Observation *removeObservation);
/**
* Set the internal observations list given another list, performing a deep copy. This resets
* the current list of observations and frees the memory.
* @param newObservations The vector of new observations to use.
*/
void set(const std::vector<Observation *> &newObservations);
/**
* Check if this observation has already been created or not.
* @param observation The observation to check if it is created or not.
* @return Returns @code{true} if the observation exists in the observations hash; @code{false} otherwise.
*/
bool exists(Observation *observation);
/**
* Get an observation with a particular hash value.
* @param hash The hash of the observation.
* @throw ObservationException There are no observations with the hash value specified.
* @return The observation with the particular hash value specified.
*/
Observation *get(unsigned int hash);
/**
* Return the number of observations.
* @return The number of observations.
*/
unsigned int get_num_observations() const;
/**
* Reset the observations, clearing the internal list and freeing the memory.
*/
void reset();
/**
* To facilitate easy iteration, return a constant beginning of the observations vector.
* @return The iterator which points to a constant beginning of the observations vector.
*/
std::unordered_map<unsigned int, Observation *>::iterator begin();
/**
* To facilitate easy iteration, return a constant end of the observations vector.
* @return The iterator which points to a constant end of the observations vector.
*/
std::unordered_map<unsigned int, Observation *>::iterator end();
protected:
/**
* The mapping of observation hash values to observations. This is the main
* container of observations.
*/
std::unordered_map<unsigned int, Observation *> observations;
};
/**
* Get the observation pointer of a observation iterator.
* @param observationIterator The observation iterator to retrieve the observation pointer from.
*/
Observation *resolve(std::unordered_map<unsigned int, Observation *>::value_type &observationIterator);
/**
* Get the hash of a observation iterator.
* @param observationIterator The observation iterator to retrieve the hash value from.
*/
unsigned int hash_value(std::unordered_map<unsigned int, Observation *>::value_type &observationIterator);
#endif // OBSERVATIONS_MAP_H
|
kylewray/librbr
|
librbr/include/core/rewards/sa_rewards_array.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SA_REWARDS_ARRAY_H
#define SA_REWARDS_ARRAY_H
#include "sa_rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
/**
* A class for state-action rewards in an MDP-like object, internally storing
* the rewards as an array.
*/
class SARewardsArray : virtual public SARewards {
public:
/**
* The default constructor for the SARewardsArray class. This requires the number of states,
* actions, and observations.
* @param numStates The number of states.
* @param numActions The number of actions.
*/
SARewardsArray(unsigned int numStates, unsigned int numActions);
/**
* The default deconstructor for the SARewardsArray class.
*/
virtual ~SARewardsArray();
/**
* Set a state transition from a particular state-action pair to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param reward The reward from the provided state-action-state triple.
*/
virtual void set(State *state, Action *action, double reward);
/**
* Set a state transition from a particular state-action-state triple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param reward The reward from the provided state-action-state triple.
*/
virtual void set(State *state, Action *action, State *nextState, double reward);
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @param reward The reward from the provided state-action-state-observation quadruple.
*/
virtual void set(State *state, Action *action, State *nextState,
Observation *observation, double reward);
/**
* The probability of a transition following the state-action pair provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action);
/**
* The probability of a transition following the state-action-state triple provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the reward.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState);
/**
* The probability of a transition following the state-action-state-observation quadruple provided.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState,
Observation *observation);
/**
* Set the entire 2-dimensional array with the one provided. This only performs a copy.
* @param R A pointer to the new 2-d array of raw rewards data. This must be
* an array of size n x m.
*/
virtual void set_rewards(const float *R);
/**
* Get the memory location of the 2-dimensional array.
* @return A pointer to the raw rewards data.
*/
virtual float *get_rewards();
/**
* Get the number of states used for the rewards array.
* @return The number of states.
*/
virtual unsigned int get_num_states() const;
/**
* Get the number of actions used for the rewards array.
* @return The number of actions.
*/
virtual unsigned int get_num_actions() const;
/**
* Get the minimal R-value.
* @return The minimal R-value.
*/
virtual double get_min() const;
/**
* Get the maximal R-value.
* @return The maximal R-value.
*/
virtual double get_max() const;
/**
* Reset the rewards, clearing the internal mapping.
*/
virtual void reset();
private:
/**
* The 2-dimensional array mapping state-action to floats. Floats were
* used to improve speed.
*/
float *rewards;
/**
* The number of states, which is the first dimension of the rewards array.
*/
unsigned int states;
/**
* The number of actions, which is the second dimension of the rewards array.
*/
unsigned int actions;
/**
* The minimum R-value.
*/
double Rmin;
/**
* The maximum R-value.
*/
double Rmax;
};
#endif // SA_REWARDS_ARRAY_H
|
kylewray/librbr
|
librbr/include/core/policy/policy_alpha_vector.h
|
<filename>librbr/include/core/policy/policy_alpha_vector.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POLICY_ALPHA_VECTOR_H
#define POLICY_ALPHA_VECTOR_H
#include "../actions/action.h"
#include "../states/belief_state.h"
#include <vector>
/**
* A small class to manipulate alpha vectors for POMDPs and Dec-POMDPs. This stores an
* action to take should this alpha vector define the maximal value of the belief state
* following equation: dot(beta, alpha) = V(b), where beta = <b(s_1), ..., b(s_n)>.
*/
class PolicyAlphaVector {
public:
/**
* The default constructor for the PolicyAlphaVector class.
*/
PolicyAlphaVector();
/**
* A constructor for the PolicyAlphaVector class which specifies the initial action.
* @param action The action to take if this is the maximal alpha vector.
*/
PolicyAlphaVector(Action *action);
/**
* The copy constructor for the PolicyAlphaVector class.
* @param other The other alpha vector to copy.
*/
PolicyAlphaVector(PolicyAlphaVector &other);
/**
* A deconstructor for the PolicyAlphaVector class.
*/
virtual ~PolicyAlphaVector();
/**
* Set the value of a state. Unset alpha values are assumed to be 0.
* @param state Set the value of this state.
* @param value The alpha value of the state.
*/
virtual void set(State *state, double value);
/**
* Get the value of a state. Unset alpha values are assumed to be 0.
* @param state Get the value of this state.
* @return The alpha vector's value of the state.
*/
virtual double get(State *state);
/**
* Set the action to take if this alpha vector is optimal for a belief state.
*/
virtual void set_action(Action *action);
/**
* Get the action to take at this alpha vector.
* @return The action to take if this alpha vector is optimal for a belief state.
*/
virtual Action *get_action();
/**
* Get the dimension of this alpha vector (which is the number of states).
* @return The dimension of this alpha vector.
*/
virtual int get_dimension() const;
/**
* Compute the value of the belief state by computing: dot(beta, alpha).
* @param belief The belief state 'beta' vector.
* @return The value of the belief state provided.
*/
virtual double compute_value(BeliefState *belief);
/**
* Overload the equals operator to set this alpha vector equal to the alpha vector provided.
* @param other The alpha vector to copy.
* @return The new version of this alpha vector.
*/
virtual PolicyAlphaVector &operator=(PolicyAlphaVector &other);
/**
* Overload the plus operator to return the summation of all elements in the vectors.
* @param other The alpha vector to add to this one.
* @return The resultant alpha vector from the sum of this one and the other one provided.
*/
virtual PolicyAlphaVector operator+(PolicyAlphaVector &other);
/**
* Overload the plus-equals operator to return the summation of all elements in the vectors.
* @param other The alpha vector to add to this one.
* @return The resultant alpha vector from the sum of this one and the other one provided.
*/
virtual PolicyAlphaVector &operator+=(PolicyAlphaVector &other);
/**
* Overload the minus operator to return the subtraction of all elements in the vectors.
* @param other The alpha vector to subtract to this one.
* @return The resultant alpha vector from the element-wise subtraction of this one and the other one provided.
*/
virtual PolicyAlphaVector operator-(PolicyAlphaVector &other);
/**
* Overload the minus-equals operator to return the subtraction of all elements in the vectors.
* @param other The alpha vector to subtract to this one.
* @return The resultant alpha vector from the element-wise subtraction of this one and the other one provided.
*/
virtual PolicyAlphaVector &operator-=(PolicyAlphaVector &other);
/**
* Reset the alpha vector.
*/
virtual void reset();
/**
* Print the alpha vector as a row of belief values. This will omit undefined alpha vector values.
*/
virtual void print();
/**
* Print the alpha vector as a row of belief values in the order of the states vector provided. This will
* also only print the values of the states specified.
*/
virtual void print(const std::vector<State *> &states);
/**
* Compute the cross-sum (Minkowski sum) of two alpha vectors. This creates new PolicyAlphaVector in memory.
* @param A The left set of alpha vectors.
* @param B The right set of alpha vectors.
* @return The result from performing the cross-sum on the two sets of alpha vectors.
*/
static std::vector<PolicyAlphaVector *> cross_sum(std::vector<PolicyAlphaVector *> &A, std::vector<PolicyAlphaVector *> &B);
private:
/**
* The alpha vector values: alpha = <V(s_1), ..., V(s_n)>. Unset alpha values are
* assumed to be 0.
*/
std::map<State *, double> alphaVector;
/**
* The action to take if this alpha vector is optimal for a belief state.
*/
Action *alphaVectorAction;
};
#endif // POLICY_ALPHA_VECTOR_H
|
kylewray/librbr
|
librbr/include/core/horizon.h
|
<filename>librbr/include/core/horizon.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef HORIZON_H
#define HORIZON_H
/**
* The horizon of all MDP-like objects can be either finite or infinite. In the
* finite horizon case, a number of stages must be specified. In the infinite
* horizon case, a discount factor must be specified. The discount factor is
* optional in the finite horizon case.
*/
class Horizon {
public:
/**
* The constructor for the Horizon class.
*/
Horizon();
/**
* The constructor for the Horizon class which defines a finite horizon.
* @param h The positive horizon to use.
*/
Horizon(unsigned int h);
/**
* The constructor for the Horizon class which defines an infinite horizon.
* @param d The discount factor (gamma) value in [0, 1).
*/
Horizon(double d);
/**
* The deconstructor for the Horizon class.
*/
virtual ~Horizon();
/**
* Return true if the horizon is finite; false if it is infinite.
* @return Return @code{true} if the horizon is infinite; @code{false} otherwise.
*/
bool is_finite() const;
/**
* Get the horizon.
* @return The horizon.
*/
unsigned int get_horizon() const;
/**
* Return the discount factor gamma.
* @return The discount factor gamma in [0, 1].
*/
double get_discount_factor() const;
/**
* Set the horizon.
* @param h The non-negative horizon to use. A horizon of 0 means infinite horizon.
*/
void set_horizon(unsigned int h);
/**
* Set the discount factor.
* @param d The discount factor (gamma) value in [0, 1).
*/
void set_discount_factor(double d);
/**
* Reset the horizon to a default horizon of 1 (finite) with 1.0 discount factor.
*/
void reset();
private:
/**
* The horizon. A horizon of 0 means infinite horizon.
*/
unsigned int horizon;
/**
* The discount factor in the range of [0, 1].
*/
double discountFactor;
};
#endif // HORIZON_H
|
kylewray/librbr
|
librbr/include/core/states/state_utilities.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATE_UTILITIES_H
#define STATE_UTILITIES_H
#include "states_map.h"
#include "named_state.h"
/**
* Find a particular state given the name in a set of states.
* @param S The finite set of states.
* @param stateName The name of the state.
* @throw StateException The name was invalid, or a state was not a NamedState.
* @return The state with the corresponding name provided.
*/
State *find_state(StatesMap *S, std::string stateName);
#endif // STATE_UTILITIES_H
|
kylewray/librbr
|
librbr/include/core/observations/observation.h
|
<filename>librbr/include/core/observations/observation.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef OBSERVATION_H
#define OBSERVATION_H
#include <string>
/**
* An abstract observation object.
*/
class Observation {
public:
/**
* The default constructor of the Observation object.
*/
Observation();
/**
* The copy constructor of the Observation object.
* @param other The observation to copy.
*/
Observation(const Observation &other);
/**
* The default deconstructor of the Observation object.
*/
virtual ~Observation();
/**
* Overload the equals operator to set this observation equal to the observation provided.
* @param other The observation to copy.
* @return The new version of this observation.
*/
virtual Observation &operator=(const Observation &other);
/**
* Overload the equality comparison operator.
* @param other The observation to compare.
* @return Returns @code{true} if this observation is equal to the other; @code{false} otherwise.
*/
virtual bool operator==(const Observation &other) const;
/**
* Overload the less than operator for comparison.
* @param other The observation to compare.
* @return Returns @code{true} if this observation is less than the other; @code{false} otherwise.
*/
virtual bool operator<(const Observation &other) const;
/**
* Returns a string representation of this observation.
* @return Returns the string representing this observation.
*/
virtual std::string to_string() const = 0;
/**
* Returns a hash value used to quickly identify this observation in a collection of observations.
* @return Returns the hash value of this observation.
*/
virtual unsigned int hash_value() const = 0;
};
#endif // OBSERVATION_H
|
kylewray/librbr
|
librbr/include/core/rewards/rewards.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef REWARDS_H
#define REWARDS_H
/**
* An abstract class which defines how to interact with a rewards object.
* This general structure should work for any implementation of rewards,
* such as a full table lookup, a partial table lookup with 'wildcard' capability,
* a function, etc. This should be able to map any state, state-action pair, or
* state-action-state triple to a real value, or a distribution over possible next
* states for continuous states and/or actions.
*
* This high level class allows for a single definition of each MDP-like object, instead
* of one for every kind of combination of actions, states, etc.
*/
class Rewards {
public:
/**
* The deconstructor for the Rewards class, which ensures that children
* classes properly deconstruct themselves.
*/
virtual ~Rewards();
};
#endif // REWARDS_H
|
kylewray/librbr
|
librbr/include/core/observations/joint_observation.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JOINT_OBSERVATION_H
#define JOINT_OBSERVATION_H
#include <string>
#include <vector>
#include "observation.h"
/**
* An abstract observation object. Typically, this will just be a string; however, by abstracting
* the observations, we are able to have observations that are classes in-and-of-themselves.
*/
class JointObservation : public Observation {
public:
/**
* The constructor of the JointObservation object which allows initial specification of the
* number of joint states.
* @param numJointStates The number of joint states in the tuple.
*/
JointObservation(int numJointObservations);
/**
* The constructor of the JointObservation object which allows initial specification of the
* actual joint observation tuple (vector).
* @param jointObservation The list of states which define this joint observation.
*/
JointObservation(const std::vector<Observation *> &jointObservation);
/**
* The copy constructor of the JointObservation object.
* @param other The observation to copy.
*/
JointObservation(JointObservation &other);
/**
* The default deconstructor of the JointObservation object.
*/
virtual ~JointObservation();
/**
* Set the joint observation given a list of observations.
* @param jointObservation The list of observations which define this joint observation.
*/
virtual void set(const std::vector<Observation *> &jointObservation);
/**
* Get the joint observation.
* @return The list of observations.
*/
virtual std::vector<Observation *> &get();
/**
* Get a particular observation at a index.
* @param index The index to retrieve the observation.
* @throw ObservationException The index is not valid.
* @return The observation at the index provided.
*/
virtual Observation *get(unsigned int index);
/**
* Get the number of observations within the joint observation.
* @return The number of observations within the joint observation.
*/
virtual int get_num_observations() const;
/**
* Overload the equals operator to set this joint observation equal to the observation provided.
* @param other The joint observation to copy.
* @return The new version of this observation.
*/
virtual Observation &operator=(Observation &other);
/**
* Returns a string representation of this action.
* @return Returns the string representing this action.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this action in a collection of actions.
* @return Returns the hash value of this action.
*/
virtual unsigned int hash_value() const;
protected:
/**
* The joint observation is defined as a tuple of observations. To remain general, this is a vector, but
* should remain a fixed size. This class will manage the memory of these observation objects.
*/
std::vector<Observation *> observations;
};
#endif // JOINT_OBSERVATION_H
|
kylewray/librbr
|
librbr/include/ssp/ssp_uct.h
|
<reponame>kylewray/librbr<filename>librbr/include/ssp/ssp_uct.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SSP_UCT_H
#define SSP_UCT_H
#include "ssp.h"
#include "../core/states/states.h"
#include "../core/actions/actions.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/rewards/rewards.h"
#include "../core/initial.h"
#include "../core/horizon.h"
#include <unordered_map>
///**
// * Solve an SSP via UCT. This solver has the following requirements:
// * - SSP states must be of type FiniteStates.
// * - SSP actions must be of type FiniteActions.
// * - SSP state transitions must be of type FiniteStateTransitions.
// * - SSP rewards must be of type SASRewards.
// */
//class SSPUCT {
//public:
// /**
// * The default constructor for the SSPUCT class. The default tolerance is 0.001.
// */
// SSPUCT();
//
// /**
// * A constructor for the SSPUCT class which allows for the specification
// * of the convergence criterion (tolerance).
// * @param tolerance The tolerance which determines convergence of UCT.
// */
// SSPUCT(double tolerance);
//
// /**
// * The deconstructor for the SSPUCT class.
// */
// virtual ~SSPUCT();
//
// /**
// * Solve the MDP provided using value iteration.
// * @param ssp The stochastic shortest path to solve.
// * @throw StateException The SSP did not have a StatesMap states object.
// * @throw ActionException The SSP did not have a ActionsMap actions object.
// * @throw StateTransitionsException The SSP did not have a FiniteStateTransitions state transitions object.
// * @throw RewardException The SSP did not have a SASRewards rewards object.
// * @throw PolicyException An error occurred computing the policy.
// * @return Return the optimal policy.
// */
// PolicyMap *solve(SSP *ssp);
//
// /**
// * Get the values of the states' mapping.
// * @return The mapping from states to values.
// */
// const std::unordered_map<State *, double> &get_V() const;
//
//private:
// /**
// * Solve a finite horizon SSP using value iteration.
// * @param S The finite states.
// * @param A The finite actions.
// * @param T The finite state transition function.
// * @param R The state-action-state rewards.
// * @param h The horizon.
// * @throw PolicyException An error occurred computing the policy.
// * @return Return the optimal policy.
// */
// PolicyMap *solve_finite_horizon(StatesMap *S, ActionsMap *A, StateTransitions *T,
// SASRewards *R, Horizon *h);
//
// /**
// * Solve an infinite horizon SSP using value iteration.
// * @param S The finite states.
// * @param A The finite actions.
// * @param T The finite state transition function.
// * @param R The state-action-state rewards.
// * @param h The horizon.
// * @throw PolicyException An error occurred computing the policy.
// * @return Return the optimal policy.
// */
// PolicyMap *solve_infinite_horizon(StatesMap *S, ActionsMap *A, StateTransitions *T,
// SASRewards *R, Horizon *h);
//
// /**
// * The value of a states and state's actions.
// */
// std::unordered_map<State *, double> V;
//
// /**
// * The tolerance convergence criterion.
// */
// double epsilon;
//
//};
#endif // SSP_UCT_H
|
kylewray/librbr
|
librbr/include/utilities/a_star.h
|
<filename>librbr/include/utilities/a_star.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef A_STAR_H
#define A_STAR_H
#include <vector>
#include <map>
/**
* An implementation of the A* search algorithm.
*/
template <typename T>
class AStar {
public:
/**
* The default constructor for the AStar class. It requires the specification of all
* relevant variables.
* @param heuristic The heuristic function estimating the distance from a node to the goal.
* @param cost The cost from the immediate transition from one node to another.
* @param successors Generate the list of successors nodes.
*/
AStar(double (*heuristic)(T node, T goal), double (*cost)(T n1, T n2), std::vector<T> (*successors)(T node));
/**
* The deconstructor for the AStar class.
*/
virtual ~AStar();
/**
* Solve the search problem given a starting node.
* @param start The initial node.
* @param goal The goal node.
* @throw UtilityException Either there is no path from the start to goal, or path reconstruction failed.
*/
void solve(T start, T goal);
/**
* Get the solution path which was computed from the last call of solve.
* @return The solution path from the start node to the goal node.
*/
const std::vector<T> &get_path();
/**
* Get the number of nodes expanded from the last call of solve.
* @return The number of nodes expanded.
*/
int get_num_nodes_expanded();
private:
/**
* Reconstruct the path given a collection of maps nodes to parents and store it internally.
* @param start The initial node.
* @param goal The goal node.
* @param trace The trace of all expanded nodes to their parents.
* @throw UtilityException The trace of the route was corrupt.
*/
void reconstruct_path(T start, T goal, std::map<T, T> &trace);
/**
* The heuristic function estimating the distance from a node to the goal.
*/
double (*heuristic)(T node, T goal);
/**
* The cost from the immediate transition from one node to another.
*/
double (*cost)(T n1, T n2);
/**
* Generate the list of successors nodes.
*/
std::vector<T> (*successors)(T node);
/**
* The optimal path from the last call of solve.
*/
std::vector<T> path;
/**
* The number of nodes expanded from the last call of solve.
*/
unsigned int numNodesExpanded;
};
#include "../../src/utilities/a_star.tpp"
#endif // A_STAR_H
|
kylewray/librbr
|
librbr/include/core/actions/joint_actions_map.h
|
<reponame>kylewray/librbr<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JOINT_ACTIONS_MAP_H
#define JOINT_ACTIONS_MAP_H
#include <vector>
#include "action.h"
#include "actions.h"
#include "actions_map.h"
/**
* A class for finite sets of joint actions in an MDP-like object. Informally, there are two basic ways to
* store finite actions: a vector of actions or a generator function based on a state and action. In both
* cases, we require that any class with finite actions provide certain get functions so that any generic
* solver can handle both cases.
*
* If you want to create a generator function-based FiniteJointActions class, please create a child class which
* implements the function in the virtual functions described below. You will likely ignore the internal
* states vector variable here.
*
* Note: The protected "states" variable implicitly must only store JointState objects, not State objects.
*/
class JointActionsMap : virtual public ActionsMap {
public:
/**
* The default constructor for the FiniteJointActions class which requires that you
* specify the number of factors.
* @param numFactors The number of action factors, minimum of 1.
*/
JointActionsMap(unsigned int numFactors);
/**
* The default deconstructor for the FiniteJointActions class.
*/
virtual ~JointActionsMap();
/**
* Add a action to the set of available actions in a factor. This does *not* update the
* actions list; please call update() once all factors have been set.
* @param factorIndex The index of the factor to add the actions to.
* @param newAction The new actions to include in the set of available actions.
* @throw ActionException The index was invalid.
*/
void add(unsigned int factorIndex, Action *newAction);
/**
* Remove an action to the set of available actions in a factor. This frees the memory. This does *not*
* update the actions list; please call update() once all factors have been set.
* @param factorIndex The index of the factor to add the actions to.
* @param removeAction The action to remove from the set of available actions.
* @throw ActionException The index was invalid, or the action was not found in the actions list.
*/
void remove(unsigned int factorIndex, Action *removeAction);
/**
* Set the internal actions list for a factor given another list, performing a deep copy. This resets
* the current list of actions and frees the memory. This does *not* update the states list; please
* call update() once all factors have been set.
* @param factorIndex The index of the factor to add the actions to.
* @param newActions The vector of new actions to use.
* @throw ActionException The index was invalid, or newActions was empty.
*/
void set(unsigned int factorIndex, const std::vector<Action *> &newActions);
/**
* Get the action at the corresponding index, given the particular factor. The factor index
* is defined by the agent, and an action's index is defined by the order in which they are
* added and removed.
* @param factorIndex The index of the factor.
* @param actionIndex The index of the action.
* @throw ActionException The index was invalid.
* @return The action at the corresponding index.
*/
Action *get(unsigned int factorIndex, unsigned int actionIndex);
/**
* Update the internal actions list which holds all permutations of joint actions in an efficient structure.
* Note: This *must* be called after sequences of add(), remove(), and/or set() calls.
* @throw ActionException If a action factor has not been defined.
*/
void update();
/**
* Get the number of factored actions.
* @return The number of factored actions.
*/
unsigned int get_num_factors();
/**
* Reset the joint actions, clearing the internal list and freeing the memory.
*/
virtual void reset();
protected:
/**
* The list of all available actions for each action factor.
*/
std::vector<std::vector<Action *> > factoredActions;
private:
/**
* A helper function for updating the internal "actions" variable as part of the update() function.
* @param currentJointAction The current (incomplete) joint action as a vector of actions.
* @param currentFactorIndex The current factor index.
*/
void update_step(std::vector<Action *> currentJointAction, unsigned int currentFactorIndex);
};
#endif // JOINT_ACTIONS_MAP_H
|
kylewray/librbr
|
librbr/include/core/policy/policy.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POLICY_H
#define POLICY_H
#include <string>
#include "../actions/action.h"
/**
* An abstract class for all policies of MDP-like objects.
*/
class Policy {
public:
/**
* A virtual deconstructor to prevent errors upon the deletion of a child object.
*/
virtual ~Policy();
};
#endif // POLICY_H
|
kylewray/librbr
|
librbr/include/core/state_transitions/state_transitions_map.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATE_TRANSITIONS_MAP_H
#define STATE_TRANSITIONS_MAP_H
#include <unordered_map>
#include "state_transitions.h"
#include "../states/states.h"
#include "../states/states_map.h"
#include "../states/state.h"
#include "../actions/action.h"
/**
* A class for finite state transitions in an MDP-like object. Informally, there are two basic ways to
* store finite state transitions: a table lookup mapping state-action-state triples to real values,
* or a generator function based on one of these triples. In both cases, we require that any class with
* finite state transitions provide certain get functions so that any generic solver can handle both cases.
*
* If you want to create a generator function-based StateTransitionsMap class, please create a child
* class which implements the function in the virtual functions described below. You will likely ignore
* the internal stateTrantions vector variable here.
*/
class StateTransitionsMap : virtual public StateTransitions {
public:
/**
* The default constructor for the StateTransitionsMap class.
*/
StateTransitionsMap();
/**
* The default deconstructor for the StateTransitionsMap class.
*/
virtual ~StateTransitionsMap();
/**
* Set a state transition from a particular state-action-state triple to a probability.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @param probability The probability of going from the state, taking the action, then
* moving to the nextState.
*/
virtual void set(State *state, Action *action, State *nextState, double probability);
/**
* The probability of a transition following the state-action-state triple provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @return The probability of going from the state, taking the action, then moving to the nextState.
*/
virtual double get(State *state, Action *action, State *nextState);
/**
* Add a successor to a particular state.
* @param state The previous state.
* @param action The action taken at the previous state.
* @param successorState The previous state.
* @throw StateTransitionException The state-action pair could not be found.
*/
virtual void add_successor(State *state, Action *action, State *successorState);
/**
* Return a list of the states available given a previous state and the action taken there.
* Note: This list may change (continual planning) if nested inside loops incorrectly. To be safe,
* just call it once unless you know what you are doing.
* @param S The set of states.
* @param state The previous state.
* @param action The action taken at the previous state.
* @throw StateTransitionException The state-action pair could not be found.
* @return successors A reference to the list of successor states.
*/
virtual const std::vector<State *> &successors(States *S, State *state, Action *action);
/**
* Reset the state transitions, clearing the internal mapping.
*/
virtual void reset();
private:
/**
* The actual get function which returns a value. This will throw an error if the value is undefined.
* It is used as a helper function for the public get function.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the reward.
* @throw StateTransitionException The state transition was not defined.
* @return The probability of going from the state, taking the action, then moving to the nextState.
*/
virtual double get_value(State *state, Action *action, State *nextState);
/**
* Compute the successor states for the state and action pair provided, then store the result
* in successorStates via the 'succ' parameter.
* @param S The finite set of states.
* @param s The current state.
* @param a The current action.
* @param succ The reference to the successors vector.
*/
virtual void compute_successors(StatesMap *S, State *s, Action *a, std::vector<State *> &succ);
/**
* The list of all state-action-state transitions.
*/
std::unordered_map<State *,
std::unordered_map<Action *,
std::unordered_map<State *, double> > > stateTransitions;
/**
* A special state (implicitly constant) referring to a state wildcard.
*/
State *stateWildcard;
/**
* A special action (implicitly constant) referring to an action wildcard.
*/
Action *actionWildcard;
/**
* A mapping from state-action pairs to a vector of successor states.
*/
std::unordered_map<State *, std::unordered_map<Action *, std::vector<State *> > > successorStates;
};
#endif // STATE_TRANSITIONS_MAP_H
|
kylewray/librbr
|
librbr/include/core/initial.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INITIAL_STATE_H
#define INITIAL_STATE_H
#include <map>
#include "states/state.h"
#include "states/belief_state.h"
/**
* A class which defines the initial state of an MDP-like object. In fully observable models,
* the initial state is simply a state. In partially observable models, the initial state
* consists of a true initial state and an initial belief over states.
*/
class Initial {
public:
/**
* The constructor for the Initial class.
*/
Initial();
/**
* The constructor for the Initial class, specifying the true initial state.
* @param state The true initial state.
*/
Initial(State *state);
/**
* The constructor for the Initial class, specifying the belief over the states.
* @param belief The belief over the states.
*/
Initial(BeliefState &belief);
/**
* The deconstructor for the Initial class.
*/
virtual ~Initial();
/**
* Set the true initial state.
* @param state The true initial state.
*/
void set_initial_state(State *state);
/**
* Set the initial belief over states.
* @param belief The belief over the states.
*/
void set_initial_belief(BeliefState &belief);
/**
* Set the probability of a particular state, assuming the belief has been created.
* @param state The state to which the probability will be assigned.
* @param probability The probability of that the initial state is the state given.
*/
void set_initial_belief(State *state, double probability);
/**
* Get the true initial state.
* @return The true initial state.
*/
State *get_initial_state();
/**
* Get the probability of a particular state.
* @param state The state to which the probability will be assigned.
* @return The probability of that the initial state is the state given.
*/
BeliefState &get_initial_belief();
/**
* Reset the initial state and the initial belief.
*/
void reset();
private:
/**
* The true initial state.
*/
State *initialState;
/**
* The belief over the states.
*/
BeliefState initialBelief;
};
#endif // INITIAL_STATE_H
|
kylewray/librbr
|
librbr/include/core/actions/indexed_action.h
|
<filename>librbr/include/core/actions/indexed_action.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INDEXED_ACTION_H
#define INDEXED_ACTION_H
#include <string>
#include "action.h"
/**
* An action object identified by a unique index which is determined using a static variable,
* incremented each time a new IndexedAction is created.
*/
class IndexedAction : virtual public Action {
public:
/**
* The default constructor of the IndexedAction object.
*/
IndexedAction();
/**
* The copy constructor of the IndexedAction object.
* @param other The action to copy.
*/
IndexedAction(const IndexedAction &other);
/**
* The default deconstructor of the IndexedAction object.
*/
virtual ~IndexedAction();
/**
* Get the index of this action.
* @return The index of this action.
*/
virtual unsigned int get_index() const;
/**
* Overload the equals operator to set this action equal to the action provided.
* @param other The action to copy.
* @param ActionException The other action is not a IndexedAction.
* @return The new version of this action.
*/
virtual Action &operator=(const Action &other);
/**
* Returns a string representation of this action.
* @return Returns the string representing this action.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this action in a collection of actions.
* @return Returns the hash value of this action.
*/
virtual unsigned int hash_value() const;
/**
* Get the number of actions which have been created. This is the value of the indexer.
* @return The number of actions which have been created.
*/
static unsigned int get_num_actions();
/**
* Reset the internal static variable which assigns indexes (called the indexer).
*/
static void reset_indexer();
protected:
/**
* All indexed actions have an integer for their index. This is also used as their hash.
*/
unsigned int index;
/**
* A static variable which assigns indexes to the actions. This defaults to zero.
*/
static unsigned int indexer;
};
#endif // INDEXED_ACTION_H
|
kylewray/librbr
|
librbr_tests/include/perform_tests.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef PERFORM_TESTS_H
#define PERFORM_TESTS_H
#define NUM_AGENT_TESTS 8
#define NUM_STATE_TESTS 22
#define NUM_ACTION_TESTS 22
#define NUM_OBSERVATION_TESTS 22
#define NUM_REWARD_TESTS 17
#define NUM_STATE_TRANSITION_TESTS 6
#define NUM_OBSERVATION_TRANSITION_TESTS 6
#define NUM_POLICY_TESTS 19
#define NUM_UNIFIED_FILE_TESTS 20
#define NUM_UTILITIES_TESTS 1
#define NUM_MDP_TESTS 6
#define NUM_POMDP_TESTS 6
/**
* Test the agents objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_agents();
/**
* Test the states objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_states();
/**
* Test the actions objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_actions();
/**
* Test the observation objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_observations();
/**
* Test the reward objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_rewards();
/**
* Test the state transition objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_state_transitions();
/**
* Test the observation transition objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_observation_transitions();
/**
* Test the policy objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_policy();
/**
* Test the UnifiedFile object. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_unified_file();
/**
* Test the utilities objects. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_utilities();
/**
* Test the MDP solvers. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_mdp();
/**
* Test the POMDP solvers. Output the success or failure for each test.
* @return The number of successes during execution.
*/
int test_pomdp();
#endif // PERFORM_TESTS_H
|
kylewray/librbr
|
librbr/include/pomdp/pomdp.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POMDP_H
#define POMDP_H
#include "../core/states/states.h"
#include "../core/actions/actions.h"
#include "../core/observations/observations.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/observation_transitions/observation_transitions.h"
#include "../core/rewards/rewards.h"
#include "../core/initial.h"
#include "../core/horizon.h"
#include "../mdp/mdp.h"
/**
* A Partially Observable Markov Decision Process (POMDP).
*/
class POMDP : public MDP {
public:
/**
* The default constructor for the POMDP class.
*/
POMDP();
/**
* A constructor for the POMDP class.
* @param S The states.
* @param A The actions.
* @param Z The observations.
* @param T The state transitions, which uses the states and actions parameters.
* @param O The observation transitions, which uses the states, actions, and observations parameters.
* @param R The rewards, which uses the states and actions parameters.
* @param h The horizon.
*/
POMDP(States *S, Actions *A, Observations *Z, StateTransitions *T, ObservationTransitions *O,
Rewards *R, Horizon *h);
/**
* A deconstructor for the POMDP class.
*/
virtual ~POMDP();
/**
* Get the observations object.
* @return The observations object.
*/
Observations *get_observations();
/**
* Get the observation transitions object.
* @return The observation transitions object.
*/
ObservationTransitions *get_observation_transitions();
protected:
/**
* The observations in the POMDP; e.g., factored vectors of strings.
*/
Observations *observations;
/**
* The observation transition function in the POMDP; e.g., a three-dimensional array mapping to a double.
*/
ObservationTransitions *observationTransitions;
};
#endif // POMDP_H
|
kylewray/librbr
|
librbr/include/core/agents/agent.h
|
<reponame>kylewray/librbr
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AGENT_H
#define AGENT_H
#include <string>
/**
* An abstract agent object. Typically, this will just be a string; however, by abstracting
* the agents, we are able to have agents that are classes in-and-of-themselves.
*/
class Agent {
public:
/**
* The default constructor of the Agent object.
*/
Agent();
/**
* The constructor of the Agent object which allows initial specification of the unique name.
* @param initialName The unique name of the state.
*/
Agent(std::string initialName);
/**
* The copy constructor of the Agent object.
* @param other The agent to copy.
*/
Agent(const Agent &other);
/**
* The default deconstructor of the Agent object.
*/
virtual ~Agent();
/**
* Set the name.
* @param newName The new name.
*/
virtual void set_name(std::string newName);
/**
* Get the name.
* @return The current name.
*/
virtual std::string get_name() const;
/**
* Overload the equals operator to set this agent equal to the agent provided.
* @param other The agent to copy.
* @return The new version of this agent.
*/
virtual Agent &operator=(const Agent &other);
/**
* Overload the equality comparison operator.
* @param other The agent to compare.
* @return Returns @code{true} if this agent is equal to the other; @code{false} otherwise.
*/
virtual bool operator==(const Agent &other) const;
/**
* Overload the less than operator for comparison.
* @param other The agent to compare.
* @return Returns @code{true} if this agent is less than the other; @code{false} otherwise.
*/
virtual bool operator<(const Agent &other) const;
/**
* Returns a string representation of this agent.
* @return Returns the string representing this agent.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this action in a collection of agent.
* @return Returns the hash value of this agent.
*/
virtual unsigned int hash_value() const;
protected:
/**
* All agents must have the ability to convert the internal representation to a string.
* For most policy solvers, this must be unique.
*/
std::string name;
};
#endif // AGENT_H
|
kylewray/librbr
|
librbr/include/core/rewards/saso_rewards_map.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SASO_REWARDS_MAP_H
#define SASO_REWARDS_MAP_H
#include <unordered_map>
#include "saso_rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
#include "../observations/observation.h"
/**
* A class for state-action-state-observation rewards in an MDP-like object, internally storing
* the rewards as a map.
*/
class SASORewardsMap : virtual public SASORewards {
public:
/**
* The default constructor for the SASORewardsMap class.
*/
SASORewardsMap();
/**
* The default deconstructor for the SASORewardsMap class.
*/
virtual ~SASORewardsMap();
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @param reward The reward from the provided state-action-state-observation quadruple.
*/
virtual void set(State *state, Action *action, State *nextState,
Observation *observation, double reward);
/**
* The probability of a transition following the state-action-state-observation quadruple provided.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState,
Observation *observation);
/**
* Get the minimal R-value.
* @return The minimal R-value.
*/
virtual double get_min() const;
/**
* Get the maximal R-value.
* @return The maximal R-value.
*/
virtual double get_max() const;
/**
* Reset the rewards, clearing the internal mapping.
*/
virtual void reset();
private:
/**
* The actual get function which returns a value. This will throw an error if the value is undefined.
* It is used as a helper function for the public get function.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @throw RewardException The reward was not defined.
* @return The reward from taking the given action in the given state.
*/
virtual double get_value(State *state, Action *action, State *nextState,
Observation *observation);
/**
* The list of all state-action-state-observation rewards.
*/
std::unordered_map<State *,
std::unordered_map<Action *,
std::unordered_map<State *,
std::unordered_map<Observation *, double> > > > rewards;
/**
* A special state (implicitly constant) referring to a state wildcard.
*/
State *stateWildcard;
/**
* A special action (implicitly constant) referring to an action wildcard.
*/
Action *actionWildcard;
/**
* A special observation (implicitly constant) referring to an observation wildcard.
*/
Observation *observationWildcard;
/**
* The minimum R-value.
*/
double Rmin;
/**
* The maximum R-value.
*/
double Rmax;
};
#endif // SASO_REWARDS_MAP_H
|
kylewray/librbr
|
librbr/include/core/state_transitions/state_transitions.h
|
<reponame>kylewray/librbr<filename>librbr/include/core/state_transitions/state_transitions.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATE_TRANSITIONS_H
#define STATE_TRANSITIONS_H
#include <vector>
#include "../states/state.h"
#include "../states/states.h"
#include "../actions/action.h"
/**
* An abstract class which defines how to interact with a state transitions object.
* This general structure should work for any implementation of state transitions,
* such as a full table lookup, a partial table lookup with 'wildcard' capability,
* a function, etc. This should be able to map any state-action-state triple to a
* real value, or a distribution over possible next states for continuous states
* and/or actions.
*
* This high level class allows for a single definition of each MDP-like object, instead
* of one for every kind of combination of actions, states, etc.
*/
class StateTransitions {
public:
/**
* The deconstructor for the StateTransitions class, which ensures that children
* classes properly deconstruct themselves.
*/
virtual ~StateTransitions();
/**
* Set a state transition from a particular state-action-state triple to a probability.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @param probability The probability of going from the state, taking the action, then
* moving to the nextState.
* @throw StateTransitionException An error occurred. Please see child class definitions for specifics.
*/
virtual void set(State *state, Action *action, State *nextState, double probability) = 0;
/**
* The probability of a transition following the state-action-state triple provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the probability.
* @throw StateTransitionException An error occurred. Please see child class definitions for specifics.
* @return The probability of going from the state, taking the action, then moving to the nextState.
*/
virtual double get(State *state, Action *action, State *nextState) = 0;
/**
* Return a list of the states available given a previous state and the action taken there.
* Note: This list may change (continual planning) if nested inside loops incorrectly. To be safe,
* just call it once unless you know what you are doing.
* @param S The set of states.
* @param state The previous state.
* @param action The action taken at the previous state.
* @throw StateTransitionException An error occurred. Please see child class definitions for specifics.
* @return successors A reference to the list of successor states.
*/
virtual const std::vector<State *> &successors(States *S, State *state, Action *action) = 0;
};
#endif // STATE_TRANSITIONS_H
|
kylewray/librbr
|
librbr/include/core/observations/named_observation.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef NAMED_OBSERVATION_H
#define NAMED_OBSERVATION_H
#include <string>
#include "observation.h"
/**
* An observation object identified by a unique name.
*/
class NamedObservation : public Observation {
public:
/**
* The default constructor of the NamedObservation object.
*/
NamedObservation();
/**
* The constructor of the NamedObservation object which allows initial specification of the unique name.
* @param initialName The unique name of the state.
*/
NamedObservation(std::string initialName);
/**
* The copy constructor of the NamedObservation object.
* @param other The observation to copy.
*/
NamedObservation(const NamedObservation &other);
/**
* The default deconstructor of the NamedObservation object.
*/
virtual ~NamedObservation();
/**
* Set the name.
* @param newName The new name.
*/
virtual void set_name(std::string newName);
/**
* Get the name.
* @return The current name.
*/
virtual std::string get_name() const;
/**
* Overload the equals operator to set this observation equal to the observation provided.
* @param other The observation to copy.
* @return The new version of this observation.
*/
virtual Observation &operator=(const Observation &other);
/**
* Returns a string representation of this observation.
* @return Returns the string representing this observation.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this observation in a collection of observations.
* @return Returns the hash value of this observation.
*/
virtual unsigned int hash_value() const;
/**
* Create a hash value for use in searching based on the name specified.
* @param nameToHash The name to convert to a hash value.
*/
static unsigned int hash_value(std::string nameToHash);
protected:
/**
* All observations must have the ability to convert the internal representation to a string.
* For most policy solvers, this must be unique; however, this need not always be the case,
* e.g., continuous observations.
*/
std::string name;
};
#endif // NAMED_OBSERVATION_H
|
kylewray/librbr
|
librbr/include/core/rewards/factored_weighted_rewards.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FACTORED_WEIGHTED_REWARDS_H
#define FACTORED_WEIGHTED_REWARDS_H
#include "factored_rewards.h"
#include "sa_rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
#include "../observations/observation.h"
#include <vector>
/**
* A class for factored rewards in an MDP-like object, i.e., multi-objective MDPs (MOMDPs).
* This differs from FactoredRewards due to the inclusion of a weight vector used to weigh
* the components evenly.
*
* The class does not re-implement all of the FactoredRewards methods; however, since
* SASORewards is the most 'ancestral' of the rewards objects, and is abstract, we define
* those methods.
*
* TODO: Inherit from SRewards, once created. Then, implement the missing 'get' and 'set' methods.
*/
class FactoredWeightedRewards : virtual public FactoredRewards, virtual public SARewards {
public:
/**
* The default constructor for the FactoredWeightedRewards class.
*/
FactoredWeightedRewards();
/**
* The constructor for the FactoredWeightedRewards class which allows the specification
* of the number of rewards.
* @param numRewards The number of rewards in the multi-rewards vector, minimum of 1.
* @param weights The weight vector, with dimension equal to numRewards, on the simplex.
* @throw RewardException The weight dimension is not equal to the number of rewards.
*/
FactoredWeightedRewards(unsigned int numRewards, std::vector<double> &weights);
/**
* The default deconstructor for the FactoredWeightedRewards class.
*/
virtual ~FactoredWeightedRewards();
/**
* Add a new rewards factor to the vector of available rewards. This relinquishes control of the
* new rewards factor to this object. This places the additional requirement that the newRewardsFactor
* must be of type SASORewards.
* @param newRewardsFactor The new rewards factor to include in the vector of available rewards.
* @throw RewardException The new rewards factor was null.
*/
virtual void add_factor(Rewards *newRewardsFactor);
/**
* Set the particular rewards element in the multi-rewards vector. This frees memory. This places the
* additional requirement that the newRewardsFactor must be of type S***Rewards.
* @param factorIndex The index of the factor to add the rewards factor to.
* @param newRewardsFactor The new rewards factor for this index.
* @throw RewardException The index was invalid.
*/
virtual void set(unsigned int factorIndex, Rewards *newRewardsFactor);
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* In the case of FactoredWeightedRewards, all factors will be set to the reward, so that the sum of
* the weighted rewards equals the reward defined here. This method is defined for SARewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param reward The reward from the provided state-action-state-observation quadruple.
* @throw RewardException A reward was found which was not of type SARewards.
*/
virtual void set(State *state, Action *action, double reward);
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* In the case of FactoredWeightedRewards, all factors will be set to the reward, so that the sum of
* the weighted rewards equals the reward defined here. This method is defined for SARewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param reward The reward from the provided state-action-state-observation quadruple.
* @throw RewardException A reward was found which was not of type SASRewards.
*/
virtual void set(State *state, Action *action, State *nextState, double reward);
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* In the case of FactoredWeightedRewards, all factors will be set to the reward, so that the sum of
* the weighted rewards equals the reward defined here. This method is defined for SARewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @param reward The reward from the provided state-action-state-observation quadruple.
* @throw RewardException A reward was found which was not of type SASORewards.
*/
virtual void set(State *state, Action *action, State *nextState,
Observation *observation, double reward);
/**
* The probability of a transition following the state-action pair provided.
* This method is defined for SARewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @throw RewardException A reward was found which was not of type SARewards.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action);
/**
* The probability of a transition following the state-action-state triple provided.
* This method is defined for SASRewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @throw RewardException A reward was found which was not of type SASRewards.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState);
/**
* The probability of a transition following the state-action-state-observation quadruple provided.
* This method is defined for SASORewards.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @throw RewardException A reward was found which was not of type SASORewards.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState,
Observation *observation);
/**
* Set the weights for the factored weighted rewards.
* @param weights The new weight vector.
*/
void set_weights(const std::vector<double> &weights);
/**
* Get the weights for the factored weighted rewards.
* @return The weight vector.
*/
const std::vector<double> &get_weights() const;
/**
* Get the minimal R-value. This method is defined for SASORewards.
* @return The minimal R-value.
*/
virtual double get_min() const;
/**
* Get the maximal R-value. This method is defined for SASORewards.
* @return The maximal R-value.
*/
virtual double get_max() const;
/**
* Reset the rewards, clearing the internal mapping. This method is defined for
* SASORewards. It calls both FactoredRewards' reset method as well as all factors'
* reset methods.
*/
virtual void reset();
protected:
/**
* The weight vector used to combine each of the factors into a single value.
*/
std::vector<double> w;
};
#endif // FACTORED_WEIGHTED_REWARDS_H
|
kylewray/librbr
|
librbr/include/core/actions/action_utilities.h
|
<filename>librbr/include/core/actions/action_utilities.h<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ACTION_UTILITIES_H
#define ACTION_UTILITIES_H
#include "actions_map.h"
#include "named_action.h"
/**
* Find a particular action given the name in a set of actions.
* @param A The finite set of actions.
* @param actionName The name of the action.
* @throw ActionException The name was invalid, or an action was not a NamedAction.
* @return The action with the corresponding name provided.
*/
Action *find_action(ActionsMap *A, std::string actionName);
#endif // ACTION_UTILITIES_H
|
kylewray/librbr
|
librbr/include/core/agents/agents.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AGENTS_H
#define AGENTS_H
#include "agent.h"
#include <vector>
#include <algorithm>
/**
* A class for finite sets of agents in an MDP-like object. The base assumption is that the set of
* agents is always finite. Also, if this class is used, then it will be for the decentralized
* MDP and POMDP classes.
*/
class Agents {
public:
/**
* The default constructor for the Agents class.
*/
Agents();
/**
* The default deconstructor for the Agents class.
*/
virtual ~Agents();
/**
* Add an agent to the set of available agents.
* @param newAgent The new agent to include in the set of available agents.
*/
void add(Agent *newAgent);
/**
* Remove an agent to the set of available agents. This frees the memory.
* @param removeAgent The agent to remove from the set of available agents.
* @throw AgentException The agent was not found in the agents list.
*/
void remove(Agent *removeAgent);
/**
* Set the internal actions list given another list, performing a deep copy. This resets
* the current list of states and frees the memory.
* @param newActions The vector of new actions to use.
*/
void set(const std::vector<Agent *> &newAgents);
/**
* Get an agent at a particular index. The index is determined by the order in which
* agents were added.
* @param agentIndex The index of the agent.
* @throw AgentException The index was invalid.
* @return The agent at the corresponding index.
*/
Agent *get(unsigned int agentIndex);
/**
* Return the number of agents.
* @return The number of agents.
*/
unsigned int get_num_agents() const;
/**
* Get a particular agent given the name.
* @param agentName The name of the agent.
* @throw AgentException The name was invalid.
* @return The agent with the corresponding name provided.
*/
virtual Agent *find(std::string agentName);
/**
* Reset the agents, clearing the internal list and freeing the memory.
*/
void reset();
/**
* To facilitate easy iteration, return a constant beginning of the agents vector.
* @return The iterator which points to a constant beginning of the agents vector.
*/
std::vector<Agent *>::iterator begin();
/**
* To facilitate easy iteration, return a constant end of the agents vector.
* @return The iterator which points to a constant end of the agents vector.
*/
std::vector<Agent *>::iterator end();
protected:
/**
* The list of all agents.
*/
std::vector<Agent *> agents;
};
#endif // AGENTS_H
|
kylewray/librbr
|
librbr/include/core/observations/joint_observations_map.h
|
<filename>librbr/include/core/observations/joint_observations_map.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JOINT_OBSERVATIONS_MAP_H
#define JOINT_OBSERVATIONS_MAP_H
#include <vector>
#include "observation.h"
#include "observations.h"
#include "observations_map.h"
/**
* A class for finite sets of observations in an MDP-like object. Informally, there are two basic ways to
* store finite observations: a vector of observations or a generator function based on a state and action.
* In both cases, we require that any class with finite observations provide certain get functions so that
* any generic solver can handle both cases.
*
* If you want to create a generator function-based FiniteJointObservations class, please create a child
* class which implements the function in the virtual functions described below. You will likely ignore the
* internal observations vector variable here.
*
* Note: The protected "observations" variable implicitly must only store JointObservation objects, not
* Observation objects.
*/
class JointObservationsMap : public ObservationsMap {
public:
/**
* The default constructor for the FiniteJointObservations class which requires that you
* specify the number of factors.
* @param numFactors The number of observation factors, minimum of 1.
*/
JointObservationsMap(unsigned int numFactors);
/**
* The default deconstructor for the FiniteJointObservations class.
*/
virtual ~JointObservationsMap();
/**
* Add an observation to the set of available observations in a factor. This does *not* update the
* observations list; please call update() once all factors have been set.
* @param factorIndex The index of the factor to add the observation to.
* @param newObservation The new observation to include in the set of available observations.
* @throw ObservationException The index was invalid.
*/
void add(unsigned int factorIndex, Observation *newObservation);
/**
* Remove an observation to the set of available observations in a factor. This frees the memory. This
* does *not* update the observations list; please call update() once all factors have been set.
* @param factorIndex The index of the factor to add the observations to.
* @param removeObservation The observation to remove from the set of available observations.
* @throw ObservationException The index was invalid, or the observation was not found in the observations list.
*/
void remove(unsigned int factorIndex, Observation *removeObservation);
/**
* Set the internal observations list for a factor given another list, performing a deep copy. This resets
* the current list of observations and frees the memory. This does *not* update the observations list; please
* call update() once all factors have been set.
* @param factorIndex The index of the factor to add the observation to.
* @param newObservations The vector of new observations to use.
* @throw ObservationException The index was invalid, or newObservations was empty.
*/
void set(unsigned int factorIndex, const std::vector<Observation *> &newObservations);
/**
* Get the observation at the corresponding index, given the particular factor. The factor index
* is defined by the agent, and an observation's index is defined by the order in which they are
* added and removed.
* @param factorIndex The index of the factor.
* @param observationIndex The index of the observation.
* @throw ObservationException The index was invalid.
* @return The observation at the corresponding index.
*/
Observation *get(unsigned int factorIndex, unsigned int observationIndex);
/**
* Update the internal observations list which holds all permutations of joint observations in an efficient structure.
* Note: This *must* be called after sequences of add(), remove(), and/or set() calls.
* @throw ObservationException A state factor has not been defined.
*/
void update();
/**
* Get the number of factored observations.
*/
unsigned int get_num_factors();
/**
* Reset the joint observations, clearing the internal list and freeing the memory.
*/
virtual void reset();
protected:
/**
* The list of all available observations for each observation factor.
*/
std::vector<std::vector<Observation *> > factoredObservations;
private:
/**
* A helper function for updating the internal "observations" variable as part of the update() function.
* @param currentJointObservation The current (incomplete) joint observation as a vector of observations.
* @param currentFactorIndex The current factor index.
*/
void update_step(std::vector<Observation *> currentJointObservation, unsigned int currentFactorIndex);
};
#endif // JOINT_OBSERVATIONS_MAP_H
|
kylewray/librbr
|
librbr/include/core/states/factored_state.h
|
<filename>librbr/include/core/states/factored_state.h<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FACTORED_STATE_H
#define FACTORED_STATE_H
#include <string>
#include <vector>
#include "state.h"
/**
* A factored state object. This is essentially a list of states, each state being a state object itself.
* Note: This class does *not* manage the memory of the states provided. Memory should be managed in
* a class such as FiniteFactoredStates.
*/
class FactoredState : virtual public State {
public:
/**
* The constructor of the FactoredState object which allows initial specification of the
* number of factored states.
* @param numFactoredStates The number of factored states in the tuple.
*/
FactoredState(int numFactoredStates);
/**
* The constructor of the FactoredState object which allows initial specification of the
* actual factored state tuple (vector).
* @param factoredState The list of states which define this factored state.
*/
FactoredState(const std::vector<State *> &factoredState);
/**
* The copy constructor of the FactoredState object.
* @param other The factored state to copy.
*/
FactoredState(FactoredState &other);
/**
* The default deconstructor of the FactoredState object.
*/
virtual ~FactoredState();
/**
* Set the factored state given a list of states.
* @param factoredState The list of states which define this factored state.
*/
virtual void set(const std::vector<State *> &factoredState);
/**
* Get the factored state.
* @return The list of states.
*/
virtual std::vector<State *> &get();
/**
* Get a particular state at a index.
* @param index The index to retrieve the state.
* @return The state at the index provided.
*/
virtual State *get(unsigned int index);
/**
* Get the number of states within the joint state.
* @return The number of states within the joint state.
*/
virtual int get_num_states() const;
/**
* Overload the equals operator to set this factored state equal to the state provided.
* @param other The factored state to copy.
* @throw StateException The other state is not a FactoredState.
* @return The new version of this state.
*/
virtual State &operator=(State &other);
/**
* Returns a string representation of this state.
* @return Returns the string representing this state.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this state in a collection of states.
* @return Returns the hash value of this state.
*/
virtual unsigned int hash_value() const;
protected:
/**
* The factored state is defined as a *tuple of states*, i.e., a specific factored state. To
* remain general, this is a vector, but should remain a fixed size. This class does *not*
* manage the memory of these state objects.
*/
std::vector<State *> states;
};
#endif // FACTORED_STATE_H
|
kylewray/librbr
|
librbr/include/dec_pomdp/dec_pomdp.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef DEC_POMDP_H
#define DEC_POMDP_H
#include "../core/agents/agents.h"
#include "../core/states/states.h"
#include "../core/actions/actions.h"
#include "../core/observations/observations.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/observation_transitions/observation_transitions.h"
#include "../core/rewards/rewards.h"
#include "../core/initial.h"
#include "../core/horizon.h"
#include "../pomdp/pomdp.h"
/**
* A Decentralized Partially Observable Markov Decision Process (Dec-POMDP).
*/
class DecPOMDP : public POMDP {
public:
/**
* The default constructor for the DecPOMDP class.
*/
DecPOMDP();
/**
* A constructor for the DecPOMDP class.
* @param N The agents.
* @param S The states.
* @param A The actions.
* @param Z The observations.
* @param T The state transitions, which uses the states and actions parameters.
* @param O The observation transitions, which uses the states, actions, and observations parameters.
* @param R The rewards, which uses the states and actions parameters.
* @param s The initial state, which uses the states parameter.
* @param h The horizon.
*/
DecPOMDP(Agents *N, States *S, Actions *A, Observations *Z, StateTransitions *T, ObservationTransitions *O,
Rewards *R, Horizon *h);
/**
* The deconstructor for the DecPOMDP class.
*/
virtual ~DecPOMDP();
/**
* Get the agents object.
* @return The agents object.
*/
Agents *get_agents();
protected:
/**
* The agents in the SCP; e.g., a vector of strings.
*/
Agents *agents;
};
#endif // DEC_POMDP_H
|
kylewray/librbr
|
librbr/include/core/states/named_state.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef NAMED_STATE_H
#define NAMED_STATE_H
#include <string>
#include "state.h"
/**
* A state object identified by a unique name.
*/
class NamedState : virtual public State {
public:
/**
* The default constructor of the NamedState object.
*/
NamedState();
/**
* The constructor of the NamedState object which allows initial specification of the unique name.
* @param initialName The unique name of the state.
*/
NamedState(std::string initialName);
/**
* The copy constructor of the NamedState object.
* @param other The state to copy.
*/
NamedState(const NamedState &other);
/**
* The default deconstructor of the NamedState object.
*/
virtual ~NamedState();
/**
* Set the name.
* @param newName The new name.
*/
virtual void set_name(std::string newName);
/**
* Get the name.
* @return The current name.
*/
virtual std::string get_name() const;
/**
* Overload the equals operator to set this state equal to the state provided.
* @param other The state to copy.
* @throw StateException The other state is not a NamedState.
* @return The new version of this state.
*/
virtual State &operator=(const State &other);
/**
* Returns a string representation of this state.
* @return Returns the string representing this state.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this state in a collection of states.
* @return Returns the hash value of this state.
*/
virtual unsigned int hash_value() const;
/**
* Create a hash value for use in searching based on the name specified.
* @param nameToHash The name to convert to a hash value.
*/
static unsigned int hash_value(std::string nameToHash);
protected:
/**
* All states must have the ability to convert the internal representation to a string.
* For most policy solvers, this must be unique; however, this need not always be the case,
* e.g., continuous states.
*/
std::string name;
};
#endif // NAMED_STATE_H
|
kylewray/librbr
|
librbr/include/management/conversion.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CONVERSION_H
#define CONVERSION_H
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/observations/observations_map.h"
#include "../core/state_transitions/state_transitions.h"
#include "../core/observation_transitions/observation_transitions.h"
#include "../core/rewards/sas_rewards.h"
#include "../core/rewards/saso_rewards.h"
#include "../mdp/mdp.h"
#include "../pomdp/pomdp.h"
/**
* Convert a map-based MDP to an array-based MDP.
* @param mdp The map-based MDP, which must have map state
* transitions and rewards.
* @throw CoreException The MDP provided was invalid.
* @return The new array-based MDP, for its state transitions and rewards.
*/
MDP *convert_map_to_array(MDP *mdp);
/**
* Convert the components of a map-based MDP to an array-based MDP.
* @param states The states.
* @param actions The actions.
* @param stateTransitions The state transitions.
* @param rewards The state-action-state rewards.
* @param initial The initial state.
* @param horizon The horizon.
* @throw CoreException The MDP provided was invalid.
* @return The new array-based MDP, for its state transitions and rewards.
*/
MDP *convert_map_to_array(StatesMap *states, ActionsMap *actions,
StateTransitions *stateTransitions, SASRewards *rewards,
Horizon *horizon);
/**
* Convert a map-based POMDP to an array-based POMDP.
* @param pomdp The map-based POMDP, which must have map state
* and observation transitions, as well as rewards.
* @throw CoreException The POMDP provided was invalid.
* @return The new array-based POMDP, for its rewards and its state and
* observation transitions.
*/
POMDP *convert_map_to_array(POMDP *pomdp);
#endif // CONVERSION_H
|
kylewray/librbr
|
librbr/include/core/observation_transitions/observation_transitions_map.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef OBSERVATION_TRANSITIONS_MAP_H
#define OBSERVATION_TRANSITIONS_MAP_H
#include <unordered_map>
#include "observation_transitions.h"
#include "../observations/observations.h"
#include "../observations/observations_map.h"
#include "../observations/observation.h"
#include "../states/state.h"
#include "../actions/action.h"
/**
* A class for finite observation transitions in an MDP-like object. Informally, there are two basic ways to
* store finite observation transitions: a table lookup mapping observation-action-state triples to real values,
* or a generator function based on one of these triples. In both cases, we require that any class with
* finite observation transitions provide certain get functions so that any generic solver can handle both cases.
*
* If you want to create a generator function-based ObservationTransitionsMap class, please create a child
* class which implements the function in the virtual functions described below. You will likely ignore
* the internal observationTrantions vector variable here.
*/
class ObservationTransitionsMap : virtual public ObservationTransitions {
public:
/**
* The default constructor for the ObservationTransitionsMap class.
*/
ObservationTransitionsMap();
/**
* The default deconstructor for the ObservationTransitionsMap class.
*/
virtual ~ObservationTransitionsMap();
/**
* Set a observation transition from a particular observation-action-state triple to a probability.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @param observation The next observation to which we assign a probability.
* @param probability The probability of the observation given we took the action and landed in the state given.
*/
virtual void set(Action *previousAction, State *state, Observation *observation, double probability);
/**
* The probability of a transition following the observation-action-state triple provided.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @param observation The next observation to which we assign a probability.
* @return The probability of the observation given we took the action and landed in the state given.
*/
virtual double get(Action *previousAction, State *state, Observation *observation);
/**
* Add an available observation.
* @param previousAction The previous action taken at the previous state.
* @param state The resultant state.
* @param availableObservation The available observation.
* @throw ObservationTransitionException The action-state pair could not be found.
*/
void add_available(Action *previousAction, State *state, Observation *availableObservation);
/**
* Return a list of the observations available given a previous state and the action taken there.
* @param Z A set of observations.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @return The list of available observations.
*/
virtual const std::vector<Observation *> &available(Observations *Z, Action *previousAction, State *state);
/**
* Reset the observation transitions, clearing the internal mapping.
*/
virtual void reset();
private:
/**
* The actual get function which returns a value. This will throw an error if the value is undefined.
* It is used as a helper function for the public get function.
* @param previousAction The action taken at the previous state which resulted in the current state.
* @param state The current state.
* @param observation The next observation to which we assign a probability.
* @throw ObservationTransitionException The observation transition was not defined.
* @return The probability of the observation given we took the action and landed in the state given.
*/
virtual double get_value(Action *previousAction, State *state, Observation *observation);
/**
* Compute the available observations for the action and state pair provided, then store the result
* in availableObservations via the 'avail' parameter.
* @param Z The finite set of observations.
* @param a The current action.
* @param sp The next state.
* @param avail The reference to the available vector.
*/
virtual void compute_available(ObservationsMap *Z, Action *a, State *sp, std::vector<Observation *> &avail);
/**
* The list of all state-action-state transitions.
*/
std::unordered_map<Action *,
std::unordered_map<State *,
std::unordered_map<Observation *, double> > > observationTransitions;
/**
* A special action (implicitly constant) referring to an action wildcard.
*/
Action *actionWildcard;
/**
* A special state (implicitly constant) referring to a state wildcard.
*/
State *stateWildcard;
/**
* A special observation (implicitly constant) referring to an observation wildcard.
*/
Observation *observationWildcard;
/**
* A mapping from action-state pairs to a vector of available observations.
*/
std::unordered_map<Action *, std::unordered_map<State *, std::vector<Observation *> > > availableObservations;
};
#endif // OBSERVATION_TRANSITIONS_MAP_H
|
kylewray/librbr
|
librbr/include/management/unified_file.h
|
<gh_stars>0
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef UNIFIED_FILE_H
#define UNIFIED_FILE_H
#include <string>
#include <vector>
#include "../core/agents/agents.h"
#include "../core/states/states_map.h"
#include "../core/states/factored_states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/actions/joint_actions_map.h"
#include "../core/observations/observations_map.h"
#include "../core/observations/joint_observations_map.h"
#include "../core/state_transitions/state_transitions_map.h"
#include "../core/observation_transitions/observation_transitions_map.h"
#include "../core/rewards/sas_rewards_map.h"
#include "../core/initial.h"
#include "../core/horizon.h"
#include "../mdp/mdp.h"
#include "../pomdp/pomdp.h"
#include "../dec_pomdp/dec_pomdp.h"
#include "../utilities/string_manipulation.h"
/**
* A file loading and saving class called UnifiedFile which acts as an intermediate
* representation for any MDP-like object. It can load any *.mdp, *.pomdp, *.decmdp,
* or *.decpomdp file and store all variables found within the file. Other class
* objects such as MDP or Dec-POMDP may then use a UnifiedFile object to copy all
* their required internal variables, or even just a subset of the variables.
*/
class UnifiedFile {
public:
/**
* The default constructor for a unified file.
*/
UnifiedFile();
/**
* The constructor which enables automatic loading of the specified MDP-like file.
* @param path The filename of the MDP-like file to load.
*/
UnifiedFile(std::string path);
/**
* The deconstructor for a unified file which cleans up the memory.
*/
~UnifiedFile();
/**
* A function which loads any MDP-like file.
* @param path The filename and relative path of the MDP-like file to load.
* @return Returns @code{true} if an error occurred, @code{false} otherwise.
*/
bool load(std::string path);
/**
* A function which saves the information as a MDP-like file.
* @param path The filename and relative path of the MDP-like file to save.
* @return Returns @code{true} if an error occurred, @code{false} otherwise.
*/
bool save(std::string path);
/**
* Reset the internal objects in the unified file.
*/
void reset();
/**
* Get an MDP version of a loaded file. This releases control of the memory to the
* MDP object, and therefore removes pointers to any loaded file information.
* @throw CoreException The MDP was missing a vital component to be defined.
* @return An MDP defined by the file loaded.
*/
MDP *get_mdp();
/**
* Get an POMDP version of a loaded file. This releases control of the memory to the
* MDP object, and therefore removes pointers to any loaded file information.
* @throw CoreException The MDP was missing a vital component to be defined.
* @return A POMDP defined by the file loaded.
*/
POMDP *get_pomdp();
/**
* Get an Dec-POMDP version of a loaded file. This releases control of the memory to the
* MDP object, and therefore removes pointers to any loaded file information.
* @throw CoreException The MDP was missing a vital component to be defined.
* @return A Dec-POMDP defined by the file loaded.
*/
DecPOMDP *get_dec_pomdp();
private:
/**
* Load the horizon from the file's data.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_horizon(std::vector<std::string> items);
/**
* Load the discount factor from the file's data.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_discount_factor(std::vector<std::string> items);
/**
* Load the initial state from the file's data.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_initial_state(std::vector<std::string> items);
/**
* Load the initial state from the file's data, following the special inclusive structure.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_initial_state_inclusive(std::vector<std::string> items);
/**
* Load the initial state from the file's data, following the special exclusive structure.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_initial_state_exclusive(std::vector<std::string> items);
/**
* Load the value type (reward or cost) from the file's data.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_value(std::vector<std::string> items);
/**
* Load the agents from the file's data.
* @param items The list of items on the same line.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
bool load_agents(std::vector<std::string> items);
/**
* Load the states from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a sequence of factored states (not necessarily for each agent).
*/
int load_states(std::vector<std::string> items);
/**
* Load the factored states from the file's data.
* @param factorIndex The index of the factored state.
* @param line The line string from the file.
* @return Return @code{true} if an error occurred, and @code{false} otherwise.
*/
int load_factored_states(unsigned int factorIndex, std::string line);
/**
* Load the actions from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a sequence of actions for each agent.
*/
int load_actions(std::vector<std::string> items);
/**
* Load the actions of one agent from the file's data.
* @param agentIndex The index of the agent in the joint action.
* @param line The line string from the file.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a sequence of actions.
*/
int load_agent_actions(unsigned int agentIndex, std::string line);
/**
* Load the observations from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a sequence of observations for each agent.
*/
int load_observations(std::vector<std::string> items);
/**
* Load the observations of one agent from the file's data.
* @param agentIndex The index of the agent in the joint observation.
* @param line The line string from the file.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a sequence of actions.
*/
int load_agent_observations(unsigned int agentIndex, std::string line);
/**
* Load the state transitions from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, 1 if this begins
* loading a vector of state transitions, 2 if this begins loading a
* matrix of state transitions.
*/
int load_state_transition(std::vector<std::string> items);
/**
* Load a state transition vector from the file's data.
* @param line The line to parse containing a vector of probabilities.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_state_transition_vector(std::string line);
/**
* Load a state transition matrix from the file's data.
* @param stateIndex The current state index for the start state.
* @param line The line to parse containing a vector of probabilities.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_state_transition_matrix(unsigned int stateIndex, std::string line);
/**
* Load the observation transitions from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a matrix of observation transitions.
*/
int load_observation_transition(std::vector<std::string> items);
/**
* Load a observation transition vector from the file's data.
* @param line The line to parse containing a vector of probabilities.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_observation_transition_vector(std::string line);
/**
* Load a state transition matrix from the file's data.
* @param stateIndex The current state index for the end state.
* @param line The line to parse containing a vector of probabilities.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_observation_transition_matrix(unsigned int stateIndex, std::string line);
/**
* Load the rewards from the file's data.
* @param items The list of items on the same line.
* @return Return -1 if an error occurred, 0 if successful, and 1 if this begins
* loading a matrix of rewards.
*/
int load_reward(std::vector<std::string> items);
/**
* Load a reward vector from the file's data.
* @param line The line to parse containing a vector of rewards or costs.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_reward_vector(std::string line);
/**
* Load a reward matrix from the file's data.
* @param stateIndex The current state index for the end state.
* @param line The line to parse containing a vector of rewards or costs.
* @return Return @code{true} if an error occurred, @code{false} otherwise.
*/
bool load_reward_matrix(unsigned int stateIndex, std::string line);
/**
* Release control over the memory of the variables.
*/
void release();
/**
* The agents in the MDP-like object; e.g., a vector of strings.
*/
Agents *agents;
/**
* The states in the MDP-like object; e.g., factored vectors of strings.
*/
StatesMap *states;
/**
* The actions in the MDP-like object; e.g., factored vectors of strings.
*/
ActionsMap *actions;
/**
* The observations in the MDP-like object; e.g., factored vectors of strings.
*/
ObservationsMap *observations;
/**
* The state transition function in the MDP-like object; e.g., a three-dimensional array mapping to a double.
*/
StateTransitionsMap *stateTransitions;
/**
* The observation transition function in the MDP-like object; e.g., a three-dimensional array mapping to a double.
*/
ObservationTransitionsMap *observationTransitions;
/**
* The reward function in the MDP-like object; e.g., a two-dimensional array mapping to a double.
*/
SASRewards *rewards;
/**
* The horizon, either a finite time or a discount factor.
*/
Horizon *horizon;
/**
* The initial state.
*/
Initial *initialState;
/**
* If this represents a reward or a cost.
*/
bool rewardValue;
/**
* The number of rows in the file (primarily for error output purposes).
*/
unsigned int rows;
/**
* The name of the file (primarily for error output purposes).
*/
std::string filename;
/**
* A variable which holds the error message.
*/
char error[1024];
/**
* A helper state variable for loading vectors or matrices.
*/
State *loadingState;
/**
* A helper action variable for loading vectors or matrices.
*/
Action *loadingAction;
/**
* A helper observation variable for loading vectors or matrices.
*/
Observation *loadingObservation;
/**
* An ordered list of states for use in loading vectors or matrices.
*/
std::vector<State *> orderedStates;
/**
* An ordered list of observations for use in loading vectors or matrices.
*/
std::vector<Observation *> orderedObservations;
};
#endif // UNIFIED_FILE_H
|
kylewray/librbr
|
librbr/include/core/rewards/saso_rewards.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SASO_REWARDS_H
#define SASO_REWARDS_H
#include <unordered_map>
#include "rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
#include "../observations/observation.h"
/**
* A class for state-action-state-observation rewards in an MDP-like object. Informally, there are
* two basic ways to store state-action-state-observation rewards: a table lookup mapping
* state-action-state-observation quadruples to real values, or a generator function based on a
* given state-action-state-observation quadruple. In both cases, we require that any class with
* provide certain get functions so that any generic solver can handle both cases.
*
* If you want to create a map, table, or generator SASORewards class, please create a child class
* which implements the function in the virtual functions described below.
*
* Always use this class for MDP-like object solvers (as part of a dynamic cast, for example). The
* particular underlying storage structure will be defined by a child class of SASORewards, e.g.,
* SASORewardsMap.
*/
class SASORewards : virtual public Rewards {
public:
/**
* The default constructor for the SASORewards class.
*/
SASORewards();
/**
* The default deconstructor for the SASORewards class.
*/
virtual ~SASORewards();
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @param reward The reward from the provided state-action-state-observation quadruple.
*/
virtual void set(State *state, Action *action, State *nextState,
Observation *observation, double reward) = 0;
/**
* The probability of a transition following the state-action-state-observation quadruple provided.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState,
Observation *observation) = 0;
/**
* Get the minimal R-value.
* @return The minimal R-value.
*/
virtual double get_min() const = 0;
/**
* Get the maximal R-value.
* @return The maximal R-value.
*/
virtual double get_max() const = 0;
/**
* Reset the rewards, clearing the internal mapping.
*/
virtual void reset() = 0;
};
#endif // SASO_REWARDS_H
|
kylewray/librbr
|
librbr/include/core/states/states_map.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STATES_MAP_H
#define STATES_MAP_H
#include <unordered_map>
#include <vector>
#include "state.h"
#include "states.h"
#include "../actions/action.h"
/**
* A class for finite sets of states in an MDP-like object. Informally, there are two basic ways to
* store finite states: a vector of states or a generator function based on a state and action. In both
* cases, we require that any class with finite states provide certain get functions so that any generic
* solver can handle both cases.
*
* If you want to create a generator function-based StatesMap class, please create a child class which
* implements the function in the virtual functions described below. You will likely ignore the internal
* states vector variable here.
*/
class StatesMap : virtual public States {
public:
/**
* The default constructor for the StatesMap class.
*/
StatesMap();
/**
* The constructor for the StatesMap class which allows the specification of an initial set of states.
* @param states The initial vector of states.
*/
StatesMap(const std::vector<State *> &states);
/**
* The default deconstructor for the StatesMap class.
*/
virtual ~StatesMap();
/**
* Add a state to the set of available states.
* @param newState The new state to include in the set of available states.
*/
void add(State *newState);
/**
* Remove a state to the set of available states. This frees the memory.
* @param removeState The state to remove from the set of available states.
* @throw StateException The state was not found in the states list.
*/
void remove(State *removeState);
/**
* Set the internal states list given another list, performing a deep copy. This resets
* the current list of states and frees the memory.
* @param newStates The vector of new states to use.
*/
void set(const std::vector<State *> &newStates);
/**
* Check if this state has already been created or not.
* @param state The state to check if it is created or not.
* @return Returns @code{true} if the state exists in the states hash; @code{false} otherwise.
*/
bool exists(const State *state) const;
/**
* Get a state with a particular hash value.
* @param hash The hash of the state.
* @throw StateException There are no states with the hash value specified.
* @return The state with the particular hash value specified.
*/
State *get(unsigned int hash);
/**
* Return the number of states.
* @return The number of states.
*/
unsigned int get_num_states() const;
/**
* Reset the states, clearing the internal list and freeing the memory.
*/
virtual void reset();
/**
* To facilitate easy iteration, return a constant beginning of the states vector.
* @return The iterator which points to a constant beginning of the states vector.
*/
std::unordered_map<unsigned int, State *>::iterator begin();
/**
* To facilitate easy iteration, return a constant end of the states vector.
* @return The iterator which points to a constant end of the states vector.
*/
std::unordered_map<unsigned int, State *>::iterator end();
protected:
/**
* The mapping of state hash values to states. This is the main container of states.
*/
std::unordered_map<unsigned int, State *> states;
};
/**
* Get the state pointer of a state iterator.
* @param stateIterator The state iterator to retrieve the state pointer from.
*/
State *resolve(std::unordered_map<unsigned int, State *>::value_type &stateIterator);
/**
* Get the hash of a state iterator.
* @param stateIterator The state iterator to retrieve the hash value from.
*/
unsigned int hash_value(std::unordered_map<unsigned int, State *>::value_type &stateIterator);
#endif // STATES_MAP_H
|
kylewray/librbr
|
librbr/include/core/states/indexed_state.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef INDEXED_STATE_H
#define INDEXED_STATE_H
#include <string>
#include "state.h"
/**
* A state object identified by a unique index which is determined using a static variable,
* incremented each time a new IndexedState is created.
*/
class IndexedState : virtual public State {
public:
/**
* The default constructor of the IndexedState object.
*/
IndexedState();
/**
* The copy constructor of the IndexedState object.
* @param other The state to copy.
*/
IndexedState(const IndexedState &other);
/**
* The default deconstructor of the IndexedState object.
*/
virtual ~IndexedState();
/**
* Get the index of this state.
* @return The index of this state.
*/
virtual unsigned int get_index() const;
/**
* Overload the equals operator to set this state equal to the state provided.
* @param other The state to copy.
* @throw StateException The other state is not a IndexedState.
* @return The new version of this state.
*/
virtual State &operator=(const State &other);
/**
* Returns a string representation of this state.
* @return Returns the string representing this state.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this state in a collection of states.
* @return Returns the hash value of this state.
*/
virtual unsigned int hash_value() const;
/**
* Get the number of states which have been created. This is the value of the indexer.
* @return The number of states which have been created.
*/
static unsigned int get_num_states();
/**
* Reset the internal static variable which assigns indexes (called the indexer).
*/
static void reset_indexer();
protected:
/**
* All indexed states have an integer for their index. This is also used as their hash.
*/
unsigned int index;
/**
* A static variable which assigns indexes to the states. This defaults to zero.
*/
static unsigned int indexer;
};
#endif // INDEXED_STATE_H
|
kylewray/librbr
|
librbr/include/core/actions/joint_action.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef JOINT_ACTION_H
#define JOINT_ACTION_H
#include <string>
#include <vector>
#include "action.h"
/**
* A joint action object. This is essentially a list of actions, each action being an action object itself.
* Note: This class does *not* manage the memory of the actions provided. Memory should be managed in
* a class such as FiniteJointActions.
*/
class JointAction : virtual public Action {
public:
/**
* The constructor of the JointAction object which allows initial specification of the
* number of joint actions.
* @param numJointActions The number of joint actions in the tuple.
*/
JointAction(unsigned int numJointActions);
/**
* The constructor of the JointAction object which allows initial specification of the
* actual joint action tuple (vector).
* @param jointState The list of actions which define this joint action.
*/
JointAction(const std::vector<Action *> &jointAction);
/**
* The copy constructor of the JointAction object.
* @param other The joint action to copy.
*/
JointAction(JointAction &other);
/**
* The default deconstructor of the JointAction object.
*/
virtual ~JointAction();
/**
* Set the joint action given a list of actions.
* @param jointAction The list of actions which define this joint action.
*/
virtual void set(const std::vector<Action *> &jointAction);
/**
* Get the joint action.
* @return The list of actions.
*/
virtual std::vector<Action *> &get();
/**
* Get a particular action at a index.
* @param index The index to retrieve the action.
* @return The action at the index provided.
*/
virtual Action *get(unsigned int index);
/**
* Get the number of actions within the joint action.
* @return The number of actions within the joint action.
*/
virtual unsigned int get_num_actions() const;
/**
* Overload the equals operator to set this joint action equal to the state provided.
* @param other The joint action to copy.
* @param ActionException The other action is not a JointAction.
* @return The new version of this action.
*/
virtual Action &operator=(Action &other);
/**
* Returns a string representation of this action.
* @return Returns the string representing this action.
*/
virtual std::string to_string() const;
/**
* Returns a hash value used to quickly identify this action in a collection of actions.
* @return Returns the hash value of this action.
*/
virtual unsigned int hash_value() const;
protected:
/**
* The joint action is defined as a tuple of actions. To remain general, this is a vector, but
* should remain a fixed size. This class does *not* manage the memory of these action objects.
*/
std::vector<Action *> actions;
};
#endif // JOINT_ACTION_H
|
kylewray/librbr
|
librbr/include/core/states/factored_states_map.h
|
<filename>librbr/include/core/states/factored_states_map.h
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FACTORED_STATES_MAP_H
#define FACTORED_STATES_MAP_H
#include <vector>
#include "state.h"
#include "states.h"
#include "states_map.h"
/**
* A class for finite sets of factored states in an MDP-like object. Informally, there are two basic ways to
* store finite states: a vector of states or a generator function based on a state and action. In both
* cases, we require that any class with finite states provide certain get functions so that any generic
* solver can handle both cases.
*
* If you want to create a generator function-based FiniteFactoredStates class, please create a child class which
* implements the function in the virtual functions described below. You will likely ignore the internal
* states vector variable here.
*
* Note: The protected "states" variable implicitly must only store FactoredState objects, not State objects.
*/
class FactoredStatesMap : virtual public StatesMap {
public:
/**
* The default constructor for the FactoredStatesMap class.
*/
FactoredStatesMap();
/**
* The constructor for the FactoredStatesMap class which requires that you
* specify the number of factors.
* @param numFactors The number of state factors, minimum of 1.
*/
FactoredStatesMap(unsigned int numFactors);
/**
* The default deconstructor for the FactoredStatesMap class.
*/
virtual ~FactoredStatesMap();
/**
* Add a new factor states to the set of available states in a factor. This does *not* update the
* states list; please call update() once all factors have been set.
* @param newStates The new states to include in the set of available states.
* @throw StateException The vector was empty, or contained null pointers.
*/
void add_factor(const std::vector<State *> &newStates);
/**
* Add a state to the set of available states in a factor. This does *not* update the states list; please
* call update() once all factors have been set.
* @param factorIndex The index of the factor to add the states to.
* @param newState The new state to include in the set of available states.
* @throw StateException The index was invalid.
*/
void add(unsigned int factorIndex, State *newState);
/**
* Remove a state to the set of available states in a factor. This frees the memory. This does *not*
* update the states list; please call update() once all factors have been set.
* @param factorIndex The index of the factor to add the states to.
* @param removeState The state to remove from the set of available states.
* @throw StateException The index was invalid, or the state was not found in the states list.
*/
void remove(unsigned int factorIndex, State *removeState);
/**
* Set the internal states list for a factor given another list, performing a deep copy. This resets
* the current list of states and frees the memory. This does *not* update the states list; please
* call update() once all factors have been set.
* @param factorIndex The index of the factor to add the states to.
* @param newStates The vector of new states to use.
* @throw StateException The index was invalid, or newStates was empty.
*/
void set(unsigned int factorIndex, const std::vector<State *> &newStates);
/**
* Get the state at the corresponding index, given the particular factor. The factor index
* is defined by the number of factored states, and an state's index is defined by the
* order in which they are added and removed.
* @param factorIndex The index of the factor.
* @param stateIndex The index of the state.
* @throw StateException The index was invalid.
* @return The state at the corresponding index.
*/
State *get(unsigned int factorIndex, unsigned int stateIndex);
/**
* Update the internal states list which holds all permutations of factored states in an efficient structure.
* Note: This *must* be called after sequences of add(), remove(), and/or set() calls.
* @throw StateException A state factor has not been defined.
*/
void update();
/**
* Get the number of factored states.
* @return The number of factors.
*/
unsigned int get_num_factors();
/**
* Reset the factored states, clearing the internal list and freeing the memory.
*/
virtual void reset();
protected:
/**
* The list of all available states for each state factor.
*/
std::vector<std::vector<State *> > factoredStates;
private:
/**
* A helper function for updating the internal "states" variable as part of the update() function.
* @param currentFactoredState The current (incomplete) factored state as a vector of states.
* @param currentFactorIndex The current factor index.
*/
void update_step(std::vector<State *> currentFactoredState, unsigned int currentFactorIndex);
};
#endif // FACTORED_STATES_MAP_H
|
kylewray/librbr
|
librbr/include/core/rewards/sa_rewards.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SA_REWARDS_H
#define SA_REWARDS_H
#include <unordered_map>
#include "sas_rewards.h"
#include "../states/state.h"
#include "../actions/action.h"
/**
* A class for state-action rewards in an MDP-like object. Informally, there are two basic
* ways to store state-action rewards: a table lookup mapping state-action pairs to real
* values, or a generator function based on a given state-action-state triple. In both cases, we
* require that any class with provide certain get functions so that any generic solver can handle
* both cases.
*
* If you want to create a map, table, or generator SASRewards class, please create a child class
* which implements the function in the virtual functions described below.
*
* Always use this class for MDP-like object solvers (as part of a dynamic cast, for example). The
* particular underlying storage structure will be defined by a child class of SARewards, e.g.,
* SARewardsMap.
*/
class SARewards : virtual public SASRewards {
public:
/**
* The default constructor for the SARewards class.
*/
SARewards();
/**
* The default deconstructor for the SARewards class.
*/
virtual ~SARewards();
/**
* Set a state transition from a particular state-action pair to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param reward The reward from the provided state-action-state triple.
*/
virtual void set(State *state, Action *action, double reward) = 0;
/**
* Set a state transition from a particular state-action-state triple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param reward The reward from the provided state-action-state triple.
*/
virtual void set(State *state, Action *action, State *nextState, double reward) = 0;
/**
* Set a state transition from a particular state-action-state-observation quadruple to a probability.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @param reward The reward from the provided state-action-state-observation quadruple.
*/
virtual void set(State *state, Action *action, State *nextState,
Observation *observation, double reward) = 0;
/**
* The probability of a transition following the state-action pair provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action) = 0;
/**
* The probability of a transition following the state-action-state triple provided.
* @param state The current state of the system.
* @param action The action taken at the current state.
* @param nextState The next state with which we assign the reward.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState) = 0;
/**
* The probability of a transition following the state-action-state-observation quadruple provided.
* @param state The current state of the system.
* @param action The action taken in the current state.
* @param nextState The next state with which we assign the reward.
* @param observation The observation made at the next state.
* @return The reward from taking the given action in the given state.
*/
virtual double get(State *state, Action *action, State *nextState,
Observation *observation) = 0;
/**
* Get the minimal R-value.
* @return The minimal R-value.
*/
virtual double get_min() const = 0;
/**
* Get the maximal R-value.
* @return The maximal R-value.
*/
virtual double get_max() const = 0;
/**
* Reset the rewards, clearing the internal mapping.
*/
virtual void reset() = 0;
};
#endif // SA_REWARDS_H
|
kylewray/librbr
|
librbr/include/pomdp/pomdp_utilities.h
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 <NAME>, University of Massachusetts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef POMDP_UTILITIES_H
#define POMDP_UTILITIES_H
#include <vector>
#include "../core/states/state.h"
#include "../core/states/belief_state.h"
#include "../core/actions/action.h"
#include "../core/observations/observation.h"
#include "../core/states/states_map.h"
#include "../core/actions/actions_map.h"
#include "../core/observations/observations_map.h"
#include "../core/state_transitions/state_transitions_map.h"
#include "../core/observation_transitions/observation_transitions_map.h"
#include "../core/rewards/rewards.h"
#include "../core/horizon.h"
#include "../core/policy/policy_alpha_vector.h"
/**
* Create the commonly used Gamma_{a,*}.
* @param S The set of finite states.
* @param Z The set of finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param R The state-action rewards function.
* @param action The action taken at this time step.
* @throw RewardException The rewards argument was invalid.
* @return The alpha vector which is the single element in Gamma_{a,*}.
*/
PolicyAlphaVector *create_gamma_a_star(StatesMap *S,
ObservationsMap *Z, StateTransitions *T, ObservationTransitions *O,
Rewards *R, Action *action);
/**
* Perform the belief state update equation on the current belief. This creates a new belief state in memory.
* @param S The finite states object.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param belief The current belief state.
* @param action The action taken in the current belief state.
* @param observation The observation observed after taking the action in the current belief state.
* @return The resultant new belief state.
*/
BeliefState *belief_state_update(StatesMap *S, StateTransitions *T,
ObservationTransitions *O, BeliefState *belief, Action *action,
Observation *observation);
/**
* Compute the Bellman update/backup using the cross sum operation, fully expanding all possible alpha vectors. Since the value
* function V' = HV, is over the belief state space, and we can represent the value function approximately as a PWLC set of alpha
* vectors, it returns this set of alpha vectors.
* @param S The finite states.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param h The horizon.
* @param gammaAStar The initial gamma which is always used in the cross sum: Gamma_{a,*}.
* @param gamma The current Bellman backup, represented as the set Gamma storing alpha-vectors.
* @param action The action taken.
* @return The Gamma_{a} which contains the new set of optimal alpha-vectors, given a particular action.
*/
std::vector<PolicyAlphaVector *> bellman_update_cross_sum(StatesMap *S, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O,
Horizon *h, std::vector<PolicyAlphaVector *> &gammaAStar, std::vector<PolicyAlphaVector *> &gamma,
Action *action);
/**
* Compute the Bellman update/backup for one specific belief state, returning the new optimal alpha-vector for this belief state. In
* this case, we assume an action has been taken to construct the new alpha vector.
* @param S The finite states.
* @param Z The finite observations.
* @param T The finite state transition function.
* @param O The finite observation transition function.
* @param h The horizon.
* @param gammaAStar The initial gamma which is always used in the cross sum: Gamma_{a,*}.
* @param gamma The current Bellman backup, represented as the set Gamma storing alpha-vectors.
* @param action The action taken.
* @param b The belief state for which to compute the updated alpha vector.
* @return The optimal alpha-vector at this belief state, given a particular action.
*/
PolicyAlphaVector *bellman_update_belief_state(StatesMap *S, ObservationsMap *Z,
StateTransitions *T, ObservationTransitions *O,
Horizon *h, std::vector<PolicyAlphaVector *> &gammaAStar, std::vector<PolicyAlphaVector *> &gamma,
Action *action, BeliefState *b);
#endif // POMDP_UTILITIES_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.