extlibs/android/sdk/android-sdk-linux
extlibs/android/sdk/android-sdk-macosx
extlibs/android/sdk/android-sdk-windows
-extlibs/boost/boost_1_58_0
+extlibs/boost/*
extlibs/tinycbor/tinycbor
*.tgz
*.zip
# Build 'resource' sub-project
SConscript(build_dir + 'resource/SConscript')
-if target_os not in ['arduino','darwin','ios', 'android']:
+if target_os not in ['arduino','darwin','ios', 'android', 'msys_nt', 'windows']:
SConscript(build_dir + 'examples/OICMiddle/SConscript')
# Build 'service' sub-project
if target_os == 'arduino':
env.UploadHelp()
-# to install the generated pc file into custome prefix location
+# to install the generated pc file into custom prefix location
env.UserInstallTargetPCFile('iotivity.pc', 'iotivity.pc')
'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
'windows': ['windows', 'winrt', 'android', 'arduino'],
'darwin': ['darwin', 'ios', 'android', 'arduino'],
+ 'msys_nt' :['msys_nt'],
}
# Map of os and allowed archs (os: allowed archs)
'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
'windows': ['x86', 'amd64', 'arm'],
+ 'msys_nt':['x86', 'x86_64'],
'winrt': ['arm'],
'darwin': ['i386', 'x86_64'],
'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
host = platform.system().lower()
+# the host string contains version of windows. 6.3, 6.4, 10.0 which is 8.0, 8.1, and 10 respectively.
+# Let's canonicalize the msys_nt-XX.X system name by stripping version off.
+if 'msys_nt' in host:
+ host = 'msys_nt'
+
if not host_target_map.has_key(host):
print "\nError: Current system (%s) isn't supported\n" % host
Exit(1)
else:
i_n = ienv.Install(user_prefix + '/lib', targets)
ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+ ienv.Alias("install", i_n)
def __installbin(ienv, targets, name):
user_prefix = env.get('PREFIX')
user_prefix = env.get('PREFIX')
if user_prefix:
i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
- ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(os.path.join(env.get('BUILD_DIR'), 'include', dir), targets)
+ ienv.Alias("install", i_n)
def __installpcfile(ienv, targets, name):
user_prefix = env.get('PREFIX')
i_n = ienv.Install(user_lib + '/pkgconfig', targets)
else:
i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
- ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR') + 'lib/pkgconfig', targets)
+ ienv.Alias("install", i_n)
def __append_target(ienv, name, targets = None):
if targets:
'\@ROUTING_DEFINE\@': routing_define
}
else:
- pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'),
- '\@EXEC_PREFIX\@': env.get('BUILD_DIR'),
+ pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
+ '\@EXEC_PREFIX\@': env.get('BUILD_DIR').encode('string_escape'),
'\@VERSION\@': '1.0.1',
'\@LIB_INSTALL_DIR\@': user_lib,
'\@ROUTING_DEFINE\@': routing_define
# POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
conf.CheckPThreadsSupport()
+######################################################################
+# Generate macros for presence of headers
+######################################################################
+cxx_headers = ['arpa/inet.h',
+ 'fcntl.h',
+ 'grp.h',
+ 'in6addr.h',
+ 'linux/limits.h',
+ 'memory.h',
+ 'netdb.h',
+ 'netinet/in.h',
+ 'pthread.h',
+ 'pwd.h',
+ 'stdlib.h',
+ 'string.h',
+ 'strings.h',
+ 'sys/socket.h',
+ 'sys/stat.h',
+ 'sys/time.h',
+ 'sys/timeb.h',
+ 'sys/types.h',
+ 'sys/unistd.h',
+ 'syslog.h',
+ 'time.h',
+ 'unistd.h',
+ 'uuid/uuid.h',
+ 'windows.h',
+ 'winsock2.h',
+ 'ws2tcpip.h']
+
+if target_os == 'arduino':
+ # Detection of headers on the Arduino platform is currently broken.
+ cxx_headers = []
+
+if target_os == 'msys_nt':
+ # WinPThread provides a pthread.h, but we want to use native threads.
+ cxx_headers.remove('pthread.h')
+
+def get_define_from_header_file(header_file):
+ header_file_converted = header_file.replace("/","_").replace(".","_").upper()
+ return "HAVE_" + header_file_converted
+
+for header_file_name in cxx_headers:
+ if conf.CheckCXXHeader(header_file_name):
+ conf.env.AppendUnique(CPPDEFINES = [get_define_from_header_file(header_file_name)])
+
env = conf.Finish()
######################################################################
else:
env.AppendUnique(CCFLAGS = ['-g'])
+# Force header presence defines
+env.AppendUnique(CPPDEFINES = ['HAVE_ARDUINO_TIME_H'])
+
# BOARD / CPU option
# Get IDE version
# External library include files are in <src_dir>/deps/<target_os>/include
# the library binaries are in <src_dir>/deps/<target_os>/lib/<arch>
-env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
-env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
+if target_os not in ['windows']:
+ env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
# Check whether a library exists, if not, notify user to install it or try to
# download the source code and build it
--- /dev/null
+##
+# This script sets compiler flags for
+# MinGW in the MSYS environment.
+##
+Import('env')
+
+# Set common flags
+# Overwrite suffixes and prefixes
+if env['TARGET_OS'] == 'msys_nt':
+ env['SHLIBPREFIX'] = 'lib'
+
+env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+target_arch = env.get('TARGET_ARCH')
+
+if env['CC'] == 'gcc':
+ if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+ else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+ env.AppendUnique(CFLAGS = ['-std=c99'])
+ env.AppendUnique(CXXFLAGS = ['-std=c++11'])
+ env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-Wa,-mbig-obj'])
+ env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_GNU_SOURCE', '__msys_nt__', '_WIN32_WINNT=0x0600'])
+
+ # Set arch flags
+ if target_arch in ['x86']:
+ env.AppendUnique(CCFLAGS = ['-m32'])
+ env.AppendUnique(LINKFLAGS = ['-m32'])
+ elif target_arch in ['x86_64']:
+ env.AppendUnique(CCFLAGS = ['-m64'])
+ env.AppendUnique(LINKFLAGS = ['-m64'])
# read tools for Windows system
if env["PLATFORM"] <> "darwin" and "win" in env["PLATFORM"] :
- if env.WhereIs("7z") :
+ if env.WhereIs('7z', env.get('PATH')):
toolset["EXTRACTOR"]["TARGZ"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TARGZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TARGZ"]["LISTFLAGS"] = "x"
toolset["EXTRACTOR"]["TARGZ"]["LISTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
toolset["EXTRACTOR"]["TARGZ"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TARGZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["TARBZ"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TARBZ"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TARBZ"]["LISTFLAGS"] = "x"
toolset["EXTRACTOR"]["TARBZ"]["LISTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} l -sii -ttar -y -so"
toolset["EXTRACTOR"]["TARBZ"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TARBZ"]["EXTRACTSUFFIX"] = "-so -y | ${UNPACK['EXTRACTOR']['TARGZ']['RUN']} x -sii -ttar -y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["BZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["BZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["BZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["BZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["BZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["BZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["GZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["GZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["GZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["GZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["GZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["GZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "7z"
toolset["EXTRACTOR"]["ZIP"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["ZIP"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["ZIP"]["LISTSUFFIX"] = "-y -so"
toolset["EXTRACTOR"]["ZIP"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"] = "-y -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["ZIP"]["EXTRACTSUFFIX"] = "-y -o${UNPACK['EXTRACTDIR']}"
toolset["EXTRACTOR"]["TAR"]["RUN"] = "7z"
toolset["EXTRACTOR"]["TAR"]["LISTEXTRACTOR"] = __fileextractor_win_7zip
toolset["EXTRACTOR"]["TAR"]["LISTFLAGS"] = "l"
toolset["EXTRACTOR"]["TAR"]["LISTSUFFIX"] = "-y -ttar -so"
toolset["EXTRACTOR"]["TAR"]["EXTRACTFLAGS"] = "x"
- toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"] = "-y -ttar -oc:${UNPACK['EXTRACTDIR']}"
+ toolset["EXTRACTOR"]["TAR"]["EXTRACTSUFFIX"] = "-y -ttar -o${UNPACK['EXTRACTDIR']}"
+ else:
+ print '''*********************** Error ************************
+* *
+* Please make sure that 7-zip is in your System PATH *
+* *
+******************************************************
+'''
# here can add some other Windows tools, that can handle the archive files
# but I don't know which ones can handle all file types
# read the tools on *nix systems and sets the default parameters
- elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+ elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
if env.WhereIs("unzip") :
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "unzip"
# This script includes windows specific config (MSVS/MSVC)
##
Import('env')
+import os.path
# Set common flags
-env.AppendUnique(CXXFLAGS=['/wd4244', '/wd4267','/wd4345', '/wd4355', '/wd4800', '/wd4996'])
-env.AppendUnique(CCFLAGS=['/EHsc'])
+if env['CC'] == 'cl':
+ # C4244 conversion from one type to another type results in a possible loss of data.
+ # C4267 conversion from size_t to a smaller type.
+ # C4355 'this' used in base member initializer list.
+ # C4800 forcing value to bool 'true' or 'false'.
+ # C4996 deprecated declaration.
+ # C4820 added padding to the end of a struct.
+ # C4514 unreferenced inline function has been removed
+ # C4365 signed/unsigned mismatch
+ # C4503 decorated name length exceeded, name was truncated
+ env.AppendUnique(CXXFLAGS=['/wd4244', '/wd4267', '/wd4355', '/wd4800', '/wd4996', '/wd4820', '/wd4514', '/wd4365', '/wd4503'])
+ env.AppendUnique(CCFLAGS=['/EHsc'])
+
+ vs_version = env['MSVC_VERSION']
+
+ # Enable special exports for unit test purposes
+ if env.get('TEST') == '1':
+ env.AppendUnique(CPPDEFINES = ['ENABLE_TEST_EXPORTS'])
+ # Set release/debug flags
+ if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+ elif env.get('TARGET_ARCH') in ['x86', 'x86_64'] or "14.0" in vs_version:
+ env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/RTC1', '/Gm'])
+ env.AppendUnique(LINKFLAGS = ['/debug'])
+ else:
+ env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/Zi', '/RTC1', '/Gm'])
+ env.AppendUnique(LINKFLAGS = ['/debug'])
+ env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+ env.AppendUnique(PATH = os.environ['PATH'])
+
+elif env['CC'] == 'gcc':
+ print "\nError: gcc not supported on Windows. Use Visual Studio!\n"
+ Exit(1);
-# Set release/debug flags
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['/MD', '/O2', '/GF'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['/MDd', '/Od', '/ZI', '/GZ', '/Gm'])
- env.AppendUnique(CPPDEFINES = ['_DEBUG'])
- env.AppendUnique(LINKFLAGS = ['/debug'])
target_os = env.get('TARGET_OS')
target_arch = env.get('TARGET_ARCH')
+src_dir = env.get('SRC_DIR')
+
+boost_version = '1.60.0'
+
+# TODO: Remove coupling between build scripts and 1_58_0 version for Android
+if target_os in ['android']:
+ boost_version = '1.58.0'
+
+boost_base_name = 'boost_'+string.replace(boost_version,'.','_')
+boost_arch_name = boost_base_name+'.zip'
+boost_b2_name = boost_base_name+os.sep+'b2'
+boost_url = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
+
+boost_dir = os.path.join(src_dir, 'extlibs','boost')
+boost_bootstrap = os.path.join(boost_dir,'bootstrap.bat')
if 'linux' == target_os :
# Check for Boost libraries in /usr/boost
print 'TODO: Perform platform check for linux'
raise SCons.Errors.EnvironmentError('Unsupported platform')
-if 'android' == target_os :
+elif target_os in ['windows']:
+ if not os.path.exists(boost_bootstrap) and target_os == 'windows':
+ # TODO: Enable installation of Boost via SConscript
+ print '''
+*********************************** Error: ****************************************
+* Please download boost from the following website:
+*
+* ''' + boost_url + '''
+*
+* and extract the contents directly into:
+*
+* ''' + boost_dir + '''
+*
+* such that you can find:
+*
+* ''' + boost_bootstrap + '''
+*
+***********************************************************************************
+'''
+ Exit(1)
+
+elif target_os in ['android']:
env.Tool('URLDownload', toolpath=['../../tools/scons'])
env.Tool('UnpackAll', toolpath=['../../tools/scons'])
env.Tool('BoostBootstrap', toolpath=['../../tools/scons'])
env.Tool('BoostBuild', toolpath=['../../tools/scons'])
- boost_version = '1.58.0'
- boost_base_name = 'boost_'+string.replace(boost_version,'.','_')
- boost_arch_name = boost_base_name+'.zip'
- boost_b2_name = boost_base_name+os.sep+'b2'
- boost_url = 'http://downloads.sourceforge.net/project/boost/boost/'+boost_version+'/'+boost_arch_name+'?r=&ts=1421801329&use_mirror=iweb'
-
host_os = sys.platform
if host_os == 'linux2' :
#define cJSON_IsReference 256
+#include <platform_features.h>
+
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
-extern void cJSON_InitHooks(cJSON_Hooks* hooks);
+OC_EXPORT extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
-extern cJSON *cJSON_Parse(const char *value);
+OC_EXPORT extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
-extern char *cJSON_Print(cJSON *item);
+OC_EXPORT extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
-extern char *cJSON_PrintUnformatted(cJSON *item);
+OC_EXPORT extern char *cJSON_PrintUnformatted(cJSON *item);
/* Delete a cJSON entity and all subentities. */
-extern void cJSON_Delete(cJSON *c);
+OC_EXPORT extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
-extern int cJSON_GetArraySize(cJSON *array);
+OC_EXPORT extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
-extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
+OC_EXPORT extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
-extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
+OC_EXPORT extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
-extern const char *cJSON_GetErrorPtr(void);
-
+OC_EXPORT extern const char *cJSON_GetErrorPtr(void);
+
/* These calls create a cJSON item of the appropriate type. */
-extern cJSON *cJSON_CreateNull(void);
-extern cJSON *cJSON_CreateTrue(void);
-extern cJSON *cJSON_CreateFalse(void);
-extern cJSON *cJSON_CreateBool(int b);
-extern cJSON *cJSON_CreateNumber(double num);
-extern cJSON *cJSON_CreateString(const char *string);
-extern cJSON *cJSON_CreateArray(void);
-extern cJSON *cJSON_CreateObject(void);
+OC_EXPORT extern cJSON *cJSON_CreateNull(void);
+OC_EXPORT extern cJSON *cJSON_CreateTrue(void);
+OC_EXPORT extern cJSON *cJSON_CreateFalse(void);
+OC_EXPORT extern cJSON *cJSON_CreateBool(int b);
+OC_EXPORT extern cJSON *cJSON_CreateNumber(double num);
+OC_EXPORT extern cJSON *cJSON_CreateString(const char *string);
+OC_EXPORT extern cJSON *cJSON_CreateArray(void);
+OC_EXPORT extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
-extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
-extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
-extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
-extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
+OC_EXPORT extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
+OC_EXPORT extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
-extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
-extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
-extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
-extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
+OC_EXPORT extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+OC_EXPORT extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
-extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
-extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
-extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
-extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
-
+OC_EXPORT extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
+OC_EXPORT extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
+OC_EXPORT extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
+OC_EXPORT extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
+
/* Update array items. */
-extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
-extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
+OC_EXPORT extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
-extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
+OC_EXPORT extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
-extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
+OC_EXPORT extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
-extern void cJSON_Minify(char *json);
+OC_EXPORT extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
target_os = env.get('TARGET_OS')
src_dir = env.get('SRC_DIR')
-targets_need_gtest = ['darwin','linux']
-gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
-gtest_zip_file = src_dir + '/extlibs/gtest/gtest-1.7.0.zip'
+targets_need_gtest = ['darwin','linux', 'msys_nt', 'windows']
+gtest_dir = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0')
+gtest_zip_file = os.path.join(src_dir, 'extlibs', 'gtest', 'gtest-1.7.0.zip')
gtest_url = 'https://googletest.googlecode.com/files/gtest-1.7.0.zip'
if target_os in targets_need_gtest:
gtest_zip = gtest_zip_file
# Unzip gtest
- print 'Unzipping google unit test'
- env.UnpackAll(gtest_dir, gtest_zip)
+ if not os.path.exists(os.path.join(gtest_dir, 'configure')):
+ print 'Unzipping google unit test'
+ env.UnpackAll(gtest_dir, gtest_zip)
if target_os == 'darwin':
env.Configure(gtest_dir, 'make')
+elif target_os == 'msys_nt':
+ if os.path.exists(gtest_dir):
+ gtest_lib_dir = gtest_dir + '/lib'
+ gtest_dotlib_dir = gtest_lib_dir + '/.libs'
+ if not os.path.exists(gtest_lib_dir):
+ # Create lib dir
+ os.mkdir(gtest_lib_dir)
+ os.mkdir(gtest_dotlib_dir)
+
+ # Run configure on gtest
+ print 'Configuring google unit test for compilation'
+ env.Configure(gtest_dir, 'cmake -G "Unix Makefiles" .')
+
+ # Run make on gtest
+ print 'Making google unit test'
+ env.Configure(gtest_dir, 'make')
+
+ print 'Moving libraries to lib folder'
+ env.Configure(gtest_dir, 'cp libgtest.a lib')
+ env.Configure(gtest_dir, 'mv libgtest.a lib/.libs')
+ env.Configure(gtest_dir, 'cp libgtest_main.a lib')
+ env.Configure(gtest_dir, 'mv libgtest_main.a lib/.libs')
+
+elif target_os == 'windows':
+ if os.path.exists(gtest_dir):
+ gtest_lib_dir = os.path.join(gtest_dir, 'lib')
+ gtest_dotlib_dir = os.path.join(gtest_lib_dir, '.libs')
+ if env.get('RELEASE'):
+ output_dir = os.path.join(gtest_dir, 'Release') + os.sep
+ else:
+ output_dir = os.path.join(gtest_dir, 'Debug') + os.sep
+
+ # Three parts to the gtest config string...
+ # 1. "Visual Studio" toolchain name.
+ # 2. VS Version + Year ("14 2015", "12 2013").
+ # 3. Target Architecture ("Win64", "Win32").
+ vs_version_year = ""
+ vs_target_arch = ""
+ vs_num = env['MSVC_VERSION']
+ if "12.0" in vs_num:
+ vs_version_year = "Visual Studio 12 2013"
+ elif "14.0" in vs_num:
+ vs_version_year = "Visual Studio 14 2015"
+ else:
+ print "Error: unknown Visual Studio version %s" % vs_num
+
+ vs_arch = env['TARGET_ARCH']
+ if "amd64" in vs_arch:
+ vs_target_arch = "Win64"
+ elif "x86" in vs_arch:
+ vs_target_arch = ""
+ else:
+ print "Error: unknown Visual Studio target arch %s" % vs_arch
+
+ vs_target_string = vs_version_year + " " + vs_target_arch
+
+ # Exit if we didn't get a match for one of the above.
+ if not vs_version_year or not vs_target_arch:
+ Exit(1)
+
+ if not env.WhereIs('cmake', env.get('PATH')):
+ print '''*********************** Error ************************
+* *
+* Please make sure that CMake is in your System PATH *
+* *
+* You can download CMake from: *
+* https://cmake.org/download/ *
+* *
+******************************************************
+'''
+ Exit(1)
+
+ if not os.path.exists(gtest_lib_dir):
+ # Create lib dir
+ os.mkdir(gtest_lib_dir)
+ os.mkdir(gtest_dotlib_dir)
+
+ # Run configure on gtest
+ print 'Configuring google unit test for compilation'
+ env.Configure(gtest_dir, 'cmake . -G"'+vs_target_string+'" -Dgtest_force_shared_crt=ON')
+
+ # Run make on gtest
+ print 'Making google unit test'
+ env.Configure(gtest_dir, 'msbuild gtest.vcxproj')
+ env.Configure(gtest_dir, 'msbuild gtest_main.vcxproj')
+
+ print 'Moving libraries to lib folder'
+ env.Configure(gtest_dir, 'copy '+output_dir+'gtest.lib %s' % gtest_lib_dir)
+ env.Configure(gtest_dir, 'move '+output_dir+'gtest.lib %s' % gtest_dotlib_dir )
+ env.Configure(gtest_dir, 'copy '+output_dir+'gtest_main.lib %s' % gtest_lib_dir)
+ env.Configure(gtest_dir, 'move '+output_dir+'gtest_main.lib %s' % gtest_dotlib_dir)
+
target_os = sqlite_env.get('TARGET_OS')
src_dir = sqlite_env.get('SRC_DIR')
-targets_need_sqlite = ['linux', 'android', 'tizen']
+targets_need_sqlite = ['linux', 'android', 'tizen', 'msys_nt', 'windows']
sqlite_dir = src_dir + '/extlibs/sqlite3/'
sqlite_build_dir = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101/'
sqlite_zip_file = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101.zip'
-sqlite_url = 'http://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
+sqlite_url = 'https://www.sqlite.org/2015/sqlite-amalgamation-3081101.zip'
# Download
if target_os in targets_need_sqlite:
os.remove(sqlite_zip_file)
shutil.rmtree(sqlite_build_dir)
-# Build will be done with provisioning manager module.
\ No newline at end of file
+# Build will be done with provisioning manager module.
# *****************************************************************/
Import('env')
-env.AppendUnique(TIMER_SRC = 'timer.c')
-
-libtimer = env.StaticLibrary('libtimer', env.get('TIMER_SRC'), OBJPREFIX='libtimer_')
-env.InstallTarget(libtimer, 'libtimer');
+timer_src = [ 'timer.c' ]
+libtimer = env.StaticLibrary('timer', timer_src, OBJPREFIX='libtimer_')
+env.InstallTarget(libtimer, 'timer');
#define _BSD_SOURCE
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_MEMORY_H
#include <memory.h>
+#endif
+#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
-
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
+#include "platform_features.h"
+
#include <stdio.h>
#include "timer.h"
int initThread()
{
int res;
- long t = 0;
- res = pthread_create(&thread_id, NULL, loop, (void *) t);
+ res = pthread_create(&thread_id, NULL, loop, NULL);
if (res)
{
#ifndef TIMER_H_
#define TIMER_H_
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
-#else
+#endif
+#ifdef HAVE_ARDUINO_TIME_H
#include <Time.h>
#endif
dtls_env.AppendUnique(CPPPATH = [root_dir+'ecc/'])
dtls_env.AppendUnique(CPPPATH = [root_dir+'sha2/'])
-if target_os not in ['arduino', 'windows', 'winrt']:
- dtls_env.AppendUnique(CPPDEFINES = ['HAVE_SYS_TIME_H'])
-
######################################################################
# Source files and Target(s)
######################################################################
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
samples_env.PrependUnique(LIBS = ['tinydtls'])
+ if target_os in ['windows', 'msys_nt']:
+ samples_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32'])
+
Alias("samples", [dtlsserver, dtlsclient])
samples_env.AppendTarget('samples')
* has finished */
#define DTLS_EVENT_RENEGOTIATE 0x01DF /**< re-negotiation has started */
-static inline int
+INLINE_API int
dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
{
return -((level << 8) | desc);
}
-static inline int
+INLINE_API int
dtls_alert_fatal_create(dtls_alert_t desc)
{
return dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, desc);
(A)[i] |= (C) & 0xFF; \
}
-static inline void
+INLINE_API void
block0(size_t M, /* number of auth bytes */
size_t L, /* number of bytes to encode message length */
size_t la, /* l(a) octets additional authenticated data */
}
}
-static inline void
+INLINE_API void
encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
unsigned char *msg, size_t len,
unsigned char A[DTLS_CCM_BLOCKSIZE],
memxor(msg, S, len);
}
-static inline void
+INLINE_API void
mac(rijndael_ctx *ctx,
unsigned char *msg, size_t len,
unsigned char B[DTLS_CCM_BLOCKSIZE],
#include "netq.h"
#include "hmac.h"
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
#include <pthread.h>
#endif
if (Seed) dtls_hmac_update(Context, (Seed), (Length))
static struct dtls_cipher_context_t cipher_context;
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
static pthread_mutex_t cipher_context_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
{
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
pthread_mutex_lock(&cipher_context_mutex);
#endif
return &cipher_context;
static void dtls_cipher_context_release(void)
{
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
pthread_mutex_unlock(&cipher_context_mutex);
#endif
}
/* The following macros provide access to the components of the
* key_block in the security parameters. */
-static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
{
switch(cipher)
{
}
-static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
+INLINE_API int dtls_kb_iv_size(dtls_cipher_t cipher)
{
switch(cipher)
{
#ifdef HAVE_TIME_H
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, time_t t) {
struct tm *tmp;
tmp = localtime(&t);
#else /* alternative implementation: just print the timestamp */
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, clock_time_t t) {
#ifdef HAVE_SNPRINTF
return snprintf(s, len, "%u.%03u",
*
* @return The length of @p s.
*/
-static inline size_t
+INLINE_API size_t
dtls_strnlen(const char *s, size_t maxlen) {
size_t n = 0;
while(*s++ && n < maxlen)
static size_t
dsrv_print_addr(const session_t *addr, char *buf, size_t len) {
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
const void *addrptr = NULL;
-#ifdef __ANDROID__
+#if defined(__ANDROID__) || defined(_WIN32)
unsigned short int port;
#else
in_port_t port;
#ifdef CONTIKI_TARGET_MBXXX
extern char __Stack_Init, _estack;
-static inline void check_stack() {
+INLINE_API void check_stack() {
const char *p = &__Stack_Init;
while (p < &_estack && *p == 0x38) {
p++;
PRINTF("Stack: %d bytes used (%d free)\n", &_estack - p, p - &__Stack_Init);
}
#else /* CONTIKI_TARGET_MBXXX */
-static inline void check_stack() {
+INLINE_API void check_stack() {
}
#endif /* CONTIKI_TARGET_MBXXX */
#else /* WITH_CONTKI */
#define PRINTF(...)
-static inline void check_stack() {
+INLINE_API void check_stack() {
}
#endif
#else /* NDEBUG */
-static inline log_t dtls_get_log_level()
+INLINE_API log_t dtls_get_log_level()
{
return DTLS_LOG_EMERG;
}
-static inline void dtls_set_log_level(log_t level)
+INLINE_API void dtls_set_log_level(log_t level)
{}
-static inline void dsrv_log(log_t level, char *format, ...)
+INLINE_API void dsrv_log(log_t level, char *format, ...)
{}
-static inline void hexdump(const unsigned char *packet, int length)
+INLINE_API void hexdump(const unsigned char *packet, int length)
{}
-static inline void dump(unsigned char *buf, size_t len)
+INLINE_API void dump(unsigned char *buf, size_t len)
{}
-static inline void
+INLINE_API void
dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend)
{}
-static inline void
+INLINE_API void
dtls_dsrv_log_addr(log_t level, const char *name, const struct __session_t *addr)
{}
static dtls_context_t the_dtls_context;
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
malloc_context() {
return &the_dtls_context;
}
-static inline void
+INLINE_API void
free_context(dtls_context_t *context) {
}
#else /* WITH_CONTIKI */
-static inline dtls_context_t *
+INLINE_API dtls_context_t *
malloc_context() {
return (dtls_context_t *)malloc(sizeof(dtls_context_t));
}
-static inline void
+INLINE_API void
free_context(dtls_context_t *context) {
free(context);
}
* \return pointer to the next byte after the written header.
* The length will be set to 0 and has to be changed before sending.
*/
-static inline uint8 *
+INLINE_API uint8 *
dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
uint8 *buf) {
* bytes. Increments message sequence number counter of \p peer.
* \return pointer to the next byte after \p buf
*/
-static inline uint8 *
+INLINE_API uint8 *
dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
int length,
int frag_offset, int frag_length,
};
/** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
-static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#if defined(DTLS_ECC) || defined(DTLS_X509)
return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
}
/** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
-static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
+INLINE_API int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
{
#ifdef DTLS_PSK
return cipher == TLS_PSK_WITH_AES_128_CCM_8;
}
/** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
{
#ifdef DTLS_ECC
return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
}
/** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
-static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
+INLINE_API int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
{
#if defined(DTLS_ECC) && defined(DTLS_PSK)
return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
/** returns true if the application is configured for psk */
-static inline int is_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_psk_supported(dtls_context_t *ctx)
{
#ifdef DTLS_PSK
return ctx && ctx->h && ctx->h->get_psk_info;
}
/** returns true if the application is configured for ecdhe_ecdsa */
-static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
}
/** returns true if the application is configured for x509 */
-static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
+INLINE_API int is_x509_supported(dtls_context_t *ctx, int is_client)
{
#ifdef DTLS_X509
return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
/** Returns true if the application is configured for ecdhe_ecdsa with
* client authentication */
-static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
{
#ifdef DTLS_ECC
return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
/** Returns true if the application is configured for x509 with
* client authentication */
-static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
+INLINE_API int is_x509_client_auth_supported(dtls_context_t *ctx)
{
#ifdef DTLS_X509
return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
}
/** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
-static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdh_anon_supported(dtls_context_t *ctx)
{
#ifdef DTLS_ECC
return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
}
/** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
-static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
+INLINE_API int is_ecdhe_psk_supported(dtls_context_t *ctx)
{
#if defined(DTLS_ECC) && defined(DTLS_PSK)
return is_psk_supported(ctx);
* Parse the ClientKeyExchange and update the internal handshake state with
* the new data.
*/
-static inline int
+INLINE_API int
check_client_keyexchange(dtls_context_t *ctx,
dtls_handshake_parameters_t *handshake,
uint8 *data, size_t length) {
return 0;
}
-static inline void
+INLINE_API void
update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
dtls_debug_dump("add MAC data", data, length);
dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
sizeof(peer->handshake_params->hs_state.hs_hash));
}
-static inline size_t
+INLINE_API size_t
finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
}
-static inline void
+INLINE_API void
clear_hs_hash(dtls_peer_t *peer) {
assert(peer);
dtls_debug("clear MAC\n");
return res <= 0 ? res : overall_len - (len - res);
}
-static inline int
+INLINE_API int
dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
dtls_alert_t description) {
uint8_t msg[] = { level, description };
return 0;
}
-static inline int
+INLINE_API int
dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
uint8 buf[1] = {1};
dtls_new_context(void *app_data) {
dtls_context_t *c;
dtls_tick_t now;
-#ifndef WITH_CONTIKI
+#if defined(_WIN32)
+ unsigned int randValue;
+ errno_t err;
+#endif
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
FILE *urandom = fopen("/dev/urandom", "r");
unsigned char buf[sizeof(unsigned long)];
#endif /* WITH_CONTIKI */
#ifdef WITH_CONTIKI
/* FIXME: need something better to init PRNG here */
dtls_prng_init(now);
+#elif defined(_WIN32)
+ err = rand_s(&randValue);
+ if (err != 0)
+ {
+ dtls_emerg("cannot initialize PRNG\n");
+ return NULL;
+ }
+ dtls_prng_init(randValue);
#else /* WITH_CONTIKI */
if (!urandom) {
dtls_emerg("cannot initialize PRNG\n");
#define dtls_get_app_data(CTX) ((CTX)->app)
/** Sets the callback handler object for @p ctx to @p h. */
-static inline void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
+INLINE_API void dtls_set_handler(dtls_context_t *ctx, dtls_handler_t *h) {
ctx->h = h;
}
#define DTLS_CT_HANDSHAKE 22
#define DTLS_CT_APPLICATION_DATA 23
+#if defined(_MSC_VER)
+#define PACKED_STRUCT __pragma(pack(1)) typedef struct
+#else
+#define PACKED_STRUCT typedef struct __attribute__((__packed__))
+#endif
+
/** Generic header structure of the DTLS record layer. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint8 content_type; /**< content type of the included message */
uint16 version; /**< Protocol version */
uint16 epoch; /**< counter for cipher state changes */
#define DTLS_HT_FINISHED 20
/** Header structure for the DTLS handshake protocol. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint8 msg_type; /**< Type of handshake message (one of DTLS_HT_) */
uint24 length; /**< length of this message */
uint16 message_seq; /**< Message sequence number */
} dtls_handshake_header_t;
/** Structure of the Client Hello message. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint16 version; /**< Client version */
uint32 gmt_random; /**< GMT time of the random byte creation */
unsigned char random[28]; /**< Client random bytes */
} dtls_client_hello_t;
/** Structure of the Hello Verify Request. */
-typedef struct __attribute__((__packed__)) {
+PACKED_STRUCT {
uint16 version; /**< Server version */
uint8 cookie_length; /**< Length of the included cookie */
uint8 cookie[]; /**< up to 32 bytes making up the cookie */
#define DTLS_X509 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
+#ifndef _WIN32
#define HAVE_ARPA_INET_H 1
+#endif
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netdb.h> header file. */
+#ifndef _WIN32
#define HAVE_NETDB_H 1
+#endif
/* Define to 1 if you have the <netinet/in.h> header file. */
+#ifndef _WIN32
#define HAVE_NETINET_IN_H 1
+#endif
/* Define to 1 if you have the `select' function. */
#define HAVE_SELECT 1
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
+#ifndef _WIN32
#define HAVE_SYS_SOCKET_H 1
+#endif
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
+#ifndef _WIN32
#define HAVE_SYS_TIME_H 1
+#endif
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+#define ssize_t SSIZE_T
+#define snprintf vs12_snprintf
+#endif
+#if defined(_WIN32)
+#define MSG_DONTWAIT 0
+#define HAVE_WINSOCK2_H 1
+#define HAVE_WS2TCPIP_H 1
+#endif
/************************************************************************/
/* Specific Contiki platforms */
}
#else /* WITH_CONTIKI */
+#ifdef _WIN32
+#include <windows.h>
+#endif
time_t dtls_clock_offset;
void
dtls_clock_init(void) {
+#ifdef _WIN32
+ /* Use clock offset in milliseconds */
+ dtls_clock_offset = GetTickCount();
+#else
#ifdef HAVE_TIME_H
+ /* Use clock offset in seconds */
dtls_clock_offset = time(NULL);
#else
# ifdef __GNUC__
# endif
dtls_clock_offset = 0;
#endif
+#endif
}
void dtls_ticks(dtls_tick_t *t) {
+#ifdef _WIN32
+ *t = ((GetTickCount() - dtls_clock_offset) * DTLS_TICKS_PER_SECOND / 1000);
+#else
#ifdef HAVE_SYS_TIME_H
struct timeval tv;
gettimeofday(&tv, NULL);
#else
#error "clock not implemented"
#endif
+#endif
}
#endif /* WITH_CONTIKI */
#define _DTLS_DTLS_TIME_H_
#include <stdint.h>
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
#include "tinydtls.h"
/**
* XORs \p n bytes byte-by-byte starting at \p y to the memory area
* starting at \p x. */
-static inline void
+INLINE_API void
memxor(unsigned char *x, const unsigned char *y, size_t n) {
while(n--) {
*x ^= *y;
* \param len Number of bytes to compare.
* \return \c 1 if \p a and \p b are equal, \c 0 otherwise.
*/
-static inline int
+INLINE_API int
equals(unsigned char *a, unsigned char *b, size_t len) {
int result = 1;
while (len--) {
#ifdef HAVE_FLS
#define dtls_fls(i) fls(i)
#else
-static inline int
+INLINE_API int
dtls_fls(unsigned int i) {
int n;
for (n = 0; i; n++)
#ifndef WITH_CONTIKI
#include <stdlib.h>
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
dtls_hmac_context_new() {
return (dtls_hmac_context_t *)malloc(sizeof(dtls_hmac_context_t));
}
-static inline void
+INLINE_API void
dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
free(ctx);
}
#include "memb.h"
MEMB(hmac_context_storage, dtls_hmac_context_t, DTLS_HASH_MAX);
-static inline dtls_hmac_context_t *
+INLINE_API dtls_hmac_context_t *
dtls_hmac_context_new() {
return (dtls_hmac_context_t *)memb_alloc(&hmac_context_storage);
}
-static inline void
+INLINE_API void
dtls_hmac_context_free(dtls_hmac_context_t *ctx) {
memb_free(&hmac_context_storage, ctx);
}
typedef dtls_hash_ctx *dtls_hash_t;
#define DTLS_HASH_CTX_SIZE sizeof(dtls_sha256_ctx)
-static inline void
+INLINE_API void
dtls_hash_init(dtls_hash_t ctx) {
dtls_sha256_init((dtls_sha256_ctx *)ctx);
}
-static inline void
+INLINE_API void
dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len) {
dtls_sha256_update((dtls_sha256_ctx *)ctx, input, len);
}
-static inline size_t
+INLINE_API size_t
dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
dtls_sha256_final(buf, (dtls_sha256_ctx *)ctx);
return DTLS_SHA256_DIGEST_LENGTH;
#endif /* WITH_SHA256 */
#ifndef WITH_CONTIKI
-static inline void dtls_hmac_storage_init()
+INLINE_API void dtls_hmac_storage_init()
{ }
#else
void dtls_hmac_storage_init();
#ifndef WITH_CONTIKI
#include <stdlib.h>
-static inline netq_t *
+INLINE_API netq_t *
netq_malloc_node(size_t size) {
return (netq_t *)malloc(sizeof(netq_t) + size);
}
-static inline void
+INLINE_API void
netq_free_node(netq_t *node) {
free(node);
}
MEMB(netq_storage, netq_t, NETQ_MAXCNT);
-static inline netq_t *
+INLINE_API netq_t *
netq_malloc_node(size_t size) {
return (netq_t *)memb_alloc(&netq_storage);
}
-static inline void
+INLINE_API void
netq_free_node(netq_t *node) {
memb_free(&netq_storage, node);
}
} netq_t;
#ifndef WITH_CONTIKI
-static inline void netq_init()
+INLINE_API void netq_init()
{ }
#else
void netq_init();
#endif
/* this one is for consistency... */
-static inline int dtls_int_to_uint8(unsigned char *field, uint8_t value)
+INLINE_API int dtls_int_to_uint8(unsigned char *field, uint8_t value)
{
field[0] = value & 0xff;
return 1;
}
-static inline int dtls_int_to_uint16(unsigned char *field, uint16_t value)
+INLINE_API int dtls_int_to_uint16(unsigned char *field, uint16_t value)
{
field[0] = (value >> 8) & 0xff;
field[1] = value & 0xff;
return 2;
}
-static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint24(unsigned char *field, uint32_t value)
{
field[0] = (value >> 16) & 0xff;
field[1] = (value >> 8) & 0xff;
return 3;
}
-static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
+INLINE_API int dtls_int_to_uint32(unsigned char *field, uint32_t value)
{
field[0] = (value >> 24) & 0xff;
field[1] = (value >> 16) & 0xff;
return 4;
}
-static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint48(unsigned char *field, uint64_t value)
{
field[0] = (value >> 40) & 0xff;
field[1] = (value >> 32) & 0xff;
return 6;
}
-static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
+INLINE_API int dtls_int_to_uint64(unsigned char *field, uint64_t value)
{
field[0] = (value >> 56) & 0xff;
field[1] = (value >> 48) & 0xff;
return 8;
}
-static inline uint8_t dtls_uint8_to_int(const unsigned char *field)
+INLINE_API uint8_t dtls_uint8_to_int(const unsigned char *field)
{
return (uint8_t)field[0];
}
-static inline uint16_t dtls_uint16_to_int(const unsigned char *field)
+INLINE_API uint16_t dtls_uint16_to_int(const unsigned char *field)
{
return ((uint16_t)field[0] << 8)
| (uint16_t)field[1];
}
-static inline uint32_t dtls_uint24_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint24_to_int(const unsigned char *field)
{
return ((uint32_t)field[0] << 16)
| ((uint32_t)field[1] << 8)
| (uint32_t)field[2];
}
-static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
+INLINE_API uint32_t dtls_uint32_to_int(const unsigned char *field)
{
return ((uint32_t)field[0] << 24)
| ((uint32_t)field[1] << 16)
| (uint32_t)field[3];
}
-static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint48_to_int(const unsigned char *field)
{
return ((uint64_t)field[0] << 40)
| ((uint64_t)field[1] << 32)
| (uint64_t)field[5];
}
-static inline uint64_t dtls_uint64_to_int(const unsigned char *field)
+INLINE_API uint64_t dtls_uint64_to_int(const unsigned char *field)
{
return ((uint64_t)field[0] << 56)
| ((uint64_t)field[1] << 48)
{
}
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
dtls_malloc_peer() {
return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
}
memb_init(&peer_storage);
}
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
dtls_malloc_peer() {
return memb_alloc(&peer_storage);
}
dtls_handshake_parameters_t *handshake_params;
} dtls_peer_t;
-static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
+INLINE_API dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
{
if (peer->security_params[0] && peer->security_params[0]->epoch == epoch) {
return peer->security_params[0];
}
}
-static inline dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params(dtls_peer_t *peer)
{
return peer->security_params[0];
}
-static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
+INLINE_API dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t *peer)
{
if (peer->security_params[1])
dtls_security_free(peer->security_params[1]);
return peer->security_params[1];
}
-static inline void dtls_security_params_free_other(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_free_other(dtls_peer_t *peer)
{
dtls_security_parameters_t * security0 = peer->security_params[0];
dtls_security_parameters_t * security1 = peer->security_params[1];
peer->security_params[1] = NULL;
}
-static inline void dtls_security_params_switch(dtls_peer_t *peer)
+INLINE_API void dtls_security_params_switch(dtls_peer_t *peer)
{
dtls_security_parameters_t * security = peer->security_params[1];
void dtls_free_peer(dtls_peer_t *peer);
/** Returns the current state of @p peer. */
-static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
+INLINE_API dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
return peer->state;
}
* Checks if given @p peer is connected. This function returns
* @c 1 if connected, or @c 0 otherwise.
*/
-static inline int dtls_peer_is_connected(const dtls_peer_t *peer) {
+INLINE_API int dtls_peer_is_connected(const dtls_peer_t *peer) {
return peer->state == DTLS_STATE_CONNECTED;
}
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len) {
while (len--)
*buf++ = rand() & 0xFF;
return 1;
}
-static inline void
+INLINE_API void
dtls_prng_init(unsigned short seed) {
srand(seed);
}
#include "random.h"
#ifdef HAVE_PRNG
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len)
{
return contiki_prng_impl(buf, len);
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
dtls_prng(unsigned char *buf, size_t len) {
unsigned short v = random_rand();
while (len > sizeof(v)) {
}
#endif /* HAVE_PRNG */
-static inline void
+INLINE_API void
dtls_prng_init(unsigned short seed) {
random_init(seed);
}
#else /* WITH_CONTIKI */
-static inline int
+INLINE_API int
_dtls_address_equals_impl(const session_t *a,
const session_t *b) {
if (a->ifindex != b->ifindex ||
#include <string.h>
+#include "dtls_config.h"
#include "tinydtls.h"
#include "global.h"
#else /* WITH_CONTIKI */
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#include <stdint.h>
typedef struct {
socklen_t size; /**< size of addr */
(struct_ptr)->LIST_CONCAT(name,_list) = NULL; \
}
-static inline void *
+INLINE_API void *
list_head(list_t list) {
return *list;
}
-static inline void
+INLINE_API void
list_remove(list_t list, void *item) {
LL_DELETE(*(struct list **)list, (struct list *)item);
}
-static inline void
+INLINE_API void
list_add(list_t list, void *item) {
list_remove(list, item);
LL_APPEND(*(struct list **)list, (struct list *)item);
}
-static inline void
+INLINE_API void
list_push(list_t list, void *item) {
LL_PREPEND(*(struct list **)list, (struct list *)item);
}
-static inline void *
+INLINE_API void *
list_pop(list_t list) {
struct list *l;
l = *list;
return l;
}
-static inline void
+INLINE_API void
list_insert(list_t list, void *previtem, void *newitem) {
if(previtem == NULL) {
list_push(list, newitem);
}
}
-static inline void *
+INLINE_API void *
list_item_next(void *item)
{
return item == NULL? NULL: ((struct list *)item)->next;
#include <stdio.h>
#include <string.h>
#include <errno.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <ctype.h>
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
#include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
#include "global.h"
#include "debug.h"
dtls_free_context(dtls_context);
dtls_free_context(orig_dtls_context);
signal(sig, SIG_DFL);
+#ifdef _WIN32
+ exit(sig);
+#else
kill(getpid(), sig);
+#endif
}
/* stolen from libcoap: */
return 0;
}
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
}
#if 0
#endif
on = 1;
#ifdef IPV6_RECVPKTINFO
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#else /* IPV6_RECVPKTINFO */
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#endif /* IPV6_RECVPKTINFO */
dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
#include <signal.h>
+#include <getopt.h>
+#include "platform_features.h"
#include "tinydtls.h"
#include "dtls.h"
return 0;
}
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on) ) < 0) {
dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
}
#if 0
#endif
on = 1;
#ifdef IPV6_RECVPKTINFO
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#else /* IPV6_RECVPKTINFO */
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on) ) < 0) {
#endif /* IPV6_RECVPKTINFO */
dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
}
/** Define to 1 if building with Hardware Abstraction Layer */
#define DTLS_CRYPTO_HAL 0
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _WIN32
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
#endif /* _DTLS_TINYDTLS_H_ */
(head)=(head)->next; \
} else { \
char *_tmp = (char*)(head); \
- while (head->next && (head->next != (del))) { \
- head = head->next; \
+ while ((head)->next && ((head)->next != (del))) { \
+ (head) = (head)->next; \
} \
- if (head->next) { \
- head->next = ((del)->next); \
+ if ((head)->next) { \
+ (head)->next = ((del)->next); \
} \
{ \
char **_head_alias = (char**)&(head); \
build_sample = env.get('BUILD_SAMPLE')
src_dir = env.get('SRC_DIR')
-if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen']:
+if target_os not in ['android', 'arduino', 'darwin', 'ios', 'tizen', 'msys_nt', 'windows']:
SConscript(os.path.join('zigbee_wrapper', 'SConscript'))
calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))
else:
calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))
-env.InstallTarget(calib, 'libplugin_interface')
-env.UserInstallTargetLib(calib, 'libplugin_interface')
+env.InstallTarget(calib, 'plugin_interface')
+env.UserInstallTargetLib(calib, 'plugin_interface')
#
##
-import os
-
Import('env')
target_os = env.get('TARGET_OS')
# Build liblogger
SConscript('csdk/logger/SConscript')
-if target_os not in ['arduino', 'darwin', 'ios', 'android']:
+if target_os not in ['arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows']:
env.AppendUnique(LIBS=['rt'])
# Build libcoap
# Build examples
SConscript('examples/SConscript')
-if target_os == 'linux':
+if target_os in ['linux', 'windows']:
# Build C Samples
SConscript('csdk/stack/samples/linux/SimpleClientServer/SConscript')
elif target_os == 'arduino':
SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
+elif target_os == 'msys_nt':
+ # Build secure samples. Using linux samples for now.
+ SConscript('csdk/stack/samples/linux/secure/SConscript')
+
+ # Build C/C++ unit tests
+ SConscript('unit_tests.scons')
target_os = env.get('TARGET_OS')
+# Add platform-specific helper library
+if target_os in ['windows', 'msys_nt']:
+ SConscript('windows/SConscript')
+
env.AppendUnique(CPPPATH = [
os.path.join(Dir('.').abspath),
- os.path.join(Dir('.').abspath, 'oic_malloc/include'),
- os.path.join(Dir('.').abspath, 'oic_string/include'),
- os.path.join(Dir('.').abspath, 'oic_time/include'),
- os.path.join(Dir('.').abspath, 'ocrandom/include')
+ os.path.join(Dir('.').abspath, 'oic_malloc', 'include'),
+ os.path.join(Dir('.').abspath, 'oic_string', 'include'),
+ os.path.join(Dir('.').abspath, 'oic_time', 'include'),
+ os.path.join(Dir('.').abspath, 'ocrandom', 'include')
])
if target_os == 'tizen':
env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
else:
- env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'c_common')])
if target_os in ['tizen', 'linux']:
env.ParseConfig("pkg-config --cflags --libs uuid")
env.PrependUnique(LIBS = ['c_common'])
common_env = env.Clone()
+common_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource')])
######################################################################
# Build flags
extern "C" {
#endif
-#if defined(__ANDROID__) || defined(__linux__)
+#ifndef ARDUINO
#include <time.h>
-#elif defined ARDUINO
+#else
// MEGA has 16 input pins whereas Due has only 12 input pins
#define ANALOG_IN (10)
#endif
#define _POSIX_C_SOURCE 200809L
#endif
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
-#include "fcntl.h"
-#include "unistd.h"
+#include "platform_features.h"
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDLIB_H
#include <stdlib.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
#if defined(__ANDROID__)
#include <ctype.h>
#include <linux/time.h>
#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
#endif
#include "ocrandom.h"
#include <stdio.h>
-#if !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#ifdef HAVE_UUID_UUID_H
#include <uuid/uuid.h>
#endif
-#if !defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
#define NANO_SEC 1000000000
-#endif
#ifdef ARDUINO
#include "Arduino.h"
int8_t OCSeedRandom()
{
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
+#ifndef ARDUINO
// Get current time to Seed.
uint64_t currentTime = 0;
#ifdef __ANDROID__
struct timespec getTs;
clock_gettime(CLOCK_MONOTONIC, &getTs);
currentTime = (getTs.tv_sec * (uint64_t)NANO_SEC + getTs.tv_nsec)/1000;
+#elif _WIN32
+ LARGE_INTEGER count;
+ if (QueryPerformanceCounter(&count)) {
+ currentTime = count.QuadPart;
+ }
#elif _POSIX_TIMERS > 0
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
gettimeofday(&tv, NULL);
currentTime = tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
#endif
-
+#if defined(__unix__) || defined(__APPLE__)
int32_t fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0)
{
srand(randomSeed | currentTime);
}
else
+#endif
{
// Do time based seed when problem in accessing "/dev/urandom"
srand(currentTime);
uint8_t OCGetRandomByte(void)
{
-#if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
- return rand() & 0x00FF;
-#elif defined ARDUINO
#ifdef HAVE_SRANDOM
return random() & 0x00FF;
#else
return rand() & 0x00FF;
#endif
-#endif
}
uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound)
uuid[15] = parseUuidPart(&uuidString[34]);
return RAND_UUID_OK;
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
// note: uuid_t is typedefed as unsigned char[16] on linux/apple
uuid_generate(uuid);
return RAND_UUID_OK;
close(fd);
return RAND_UUID_READ_ERROR;
}
-#elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
+#elif defined(HAVE_UUID_UUID_H)
uint8_t uuid[UUID_SIZE];
int8_t ret = OCGenerateUuid(uuid);
#define US_PER_MS (1000)
#define NS_PER_US (1000)
#define NS_PER_MS (1000000)
+#define HNS_PER_US (10)
#ifdef __cplusplus
#include <stddef.h> // For NULL
-#ifndef WITH_ARDUINO
+#if defined(_WIN32)
+# include <windows.h>
+#elif !defined(WITH_ARDUINO)
# if _POSIX_TIMERS > 0
# include <time.h> // For clock_gettime()
# else
#ifdef WITH_ARDUINO
currentTime = (TIME_IN_MS == precision) ? millis() : micros();
+#elif defined(_WIN32)
+ FILETIME fileTime;
+ ULARGE_INTEGER time;
+
+ GetSystemTimePreciseAsFileTime(&fileTime);
+
+ // fileTime should now be a QWORD hundred-nanoseconds time since 1601
+
+ // MSDN recommends using ULARGE_INTEGER as an intermediate representation for math.
+ time.LowPart = fileTime.dwLowDateTime;
+ time.HighPart = fileTime.dwHighDateTime;
+
+ currentTime =
+ (TIME_IN_MS == precision)
+ ? time.QuadPart / (HNS_PER_US * US_PER_MS)
+ : time.QuadPart / (HNS_PER_US);
#else
# if _POSIX_TIMERS > 0
# if defined(CLOCK_MONOTONIC_COARSE)
#if (__STDC_VERSION__ >= 201112L)
#include <assert.h>
#define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
+#elif defined(_WIN32)
+ #if defined(__msys_nt__) && !defined(__cplusplus)
+ #define static_assert _Static_assert
+ #endif
+ #define OC_STATIC_ASSERT(condition, msg) static_assert(condition, msg)
#else
#define OC_STATIC_ASSERT(condition, msg) ((void)sizeof(char[2*!!(condition) - 1]))
#endif
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _MSC_VER
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
+#ifdef _MSC_VER
+# ifdef OC_EXPORT_DLL
+# define OC_EXPORT __declspec(dllexport)
+# else
+# define OC_EXPORT __declspec(dllimport)
+# endif
+# ifdef ENABLE_TEST_EXPORTS
+# define OC_EXPORT_TEST OC_EXPORT
+# else
+# define OC_EXPORT_TEST
+# endif
+# define OC_ANNOTATE_UNUSED
+#else
+# define OC_ANNOTATE_UNUSED __attribute__((unused))
+# define OC_EXPORT
+# define OC_EXPORT_TEST
+#endif
+
+#ifdef _WIN32
+# define __func__ __FUNCTION__
+# define strncasecmp _strnicmp
+# define strtok_r strtok_s
+# if _MSC_VER && (_MSC_VER < 1900)
+# include "windows/include/vs12_snprintf.h"
+# endif
+# define ssize_t SSIZE_T
+# define F_OK 0
+# define sleep(SECS) Sleep(1000*(SECS))
+# ifdef __cplusplus
+# define SUPPORTS_DEFAULT_CTOR
+# endif
+# include "windows/include/win_sleep.h"
+# include "windows/include/pthread_create.h"
+#endif
+
+#ifdef HAVE_WINSOCK2_H
+# define OPTVAL_T(t) (const char*)(t)
+#else
+# define OPTVAL_T(t) (t)
+#endif
+
#endif
--- /dev/null
+##
+# Builds Windows-specific helper library
+##
+Import('env')
+import os.path
+
+# Include any headers that might be missing on Windows
+env.AppendUnique(CPPPATH = [os.path.abspath('./include')])
+
+######################################################################
+# Source files and Targets
+######################################################################
+src_dir = os.path.abspath('./src')
+helper_src = [
+ os.path.join(src_dir, 'getopt.c'),
+ os.path.join(src_dir, 'win_sleep.c'),
+ os.path.join(src_dir, 'snprintf.c'),
+ os.path.join(src_dir, 'pthread_create.c')
+ ]
+
+static_libwinhelper = env.StaticLibrary('win_helper', helper_src)
+env.InstallTarget(static_libwinhelper, 'win_helper')
+env.UserInstallTargetLib(static_libwinhelper, 'win_helper')
+
+env.AppendUnique(LIBS = ['win_helper'])
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#ifndef __GETOPT_H__
+#define __GETOPT_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char *optarg;
+extern int optind;
+
+int getopt(int argc, char *const argv[], const char *optstring);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#ifndef __PTHREAD_CREATE_H__
+#define __PTHREAD_CREATE_H__
+#ifndef WIN_PTHREADS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void* pthread_t;
+typedef void pthread_attr_t;
+
+int pthread_create(
+ pthread_t *thread,
+ const pthread_attr_t *attr,
+ void *(*start_routine)(void *),
+ void *arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //WIN_PTHREADS_H
+#endif //__PTHREAD_CREATE_H__
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* 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 __VS12_SNPRINTF_H__
+#define __VS12_SNPRINTF_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdlib.h>
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...);
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+# define snprintf vs12_snprintf
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* 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 __WIN_SLEEP_H__
+#define __WIN_SLEEP_H__
+
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+struct timespec
+{
+ time_t tv_sec; // Seconds - >= 0
+ long tv_nsec; // Nanoseconds - [0, 999999999]
+};
+#endif
+
+int nanosleep(const struct timespec *req, struct timespec *rem);
+int usleep(unsigned int usec);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#include "getopt.h"
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+char* optarg = NULL;
+int optind = 1;
+
+int getopt(int argc, char *const argv[], const char *optstring)
+{
+ if ((optind >= argc) || (argv[optind][0] != '-') || (argv[optind][0] == 0))
+ {
+ return -1;
+ }
+
+ int opt = argv[optind][1];
+ const char *p = strchr(optstring, opt);
+
+ if (p == NULL) {
+ return '?';
+ }
+ if (p[1] == ':') {
+ optind++;
+ if (optind >= argc) {
+ return '?';
+ }
+ optarg = argv[optind];
+ optind++;
+ }
+ return opt;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null
+/** @todo: Add Microsoft license information */
+
+#include "pthread_create.h"
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int pthread_create(
+ pthread_t *thread,
+ const pthread_attr_t *attr,
+ void *(*start_routine)(void *),
+ void *arg)
+{
+ *thread = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)start_routine, arg, 0, NULL);
+ return (*thread == NULL) ? GetLastError() : 0;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* 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 "vs12_snprintf.h"
+#include <stdio.h>
+#include <stdarg.h>
+
+int vs12_snprintf(char *buffer, size_t count, const char *format, ...)
+{
+ int length;
+ va_list args;
+
+ va_start(args, format);
+
+ length = _vsnprintf(buffer, count, format, args);
+
+ va_end(args);
+
+ if (length > count)
+ {
+ buffer[count - 1] = '\0';
+ }
+
+ return length;
+}
+
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+* 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 <assert.h>
+#include <windows.h>
+#include "win_sleep.h"
+
+#define NS_PER_MS (1000000)
+#define US_PER_MS (1000)
+
+int usleep(unsigned int usec)
+{
+ assert((usec % US_PER_MS) == 0); // granularity check
+ Sleep(usec / US_PER_MS);
+ return 0;
+}
+
+int nanosleep(const struct timespec *req, struct timespec *rem)
+{
+ assert(req != NULL);
+ assert(rem == NULL);
+ assert(req->tv_sec == 0);
+ assert((req->tv_nsec % NS_PER_MS) == 0); // granularity check
+
+ Sleep(req->tv_nsec / NS_PER_MS);
+
+ return 0;
+}
+
liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os in ['android', 'linux', 'tizen']:
+liboctbstack_env.PrependUnique(LIBS = ['ocsrm', 'coap'])
+if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows']:
liboctbstack_env.PrependUnique(LIBS = ['connectivity_abstraction'])
if with_ra_ibb:
if with_ra:
liboctbstack_env.AppendUnique(LIBS = ['ra_xmpp'])
-liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
-liboctbstack_env.PrependUnique(LIBS = ['ocsrm'])
+if target_os in ['windows', 'msys_nt']:
+ liboctbstack_env.AppendUnique(CPPDEFINES = ['OC_EXPORT_DLL'])
+ liboctbstack_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi'])
+else:
+ liboctbstack_env.AppendUnique(LIBS = ['m'])
if target_os in ['tizen', 'linux']:
liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
-if target_os not in ['android', 'arduino', 'windows', 'winrt']:
+if target_os not in ['android', 'arduino', 'windows', 'winrt', 'msys_nt']:
liboctbstack_env.AppendUnique(LIBS = ['pthread'])
if target_os == 'arduino':
liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-elif target_os not in ['darwin','ios']:
+elif target_os not in ['darwin','ios', 'msys_nt', 'windows']:
liboctbstack_env.AppendUnique(CFLAGS = ['-fPIC'])
if target_os in ['darwin', 'ios']:
env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
liboctbstack_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os not in ['arduino']:
+if target_os not in ['arduino', 'windows']:
liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
liboctbstack_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,liboctbstack.so'])
if env.get('WITH_RD') == '1':
liboctbstack_env.PrependUnique(CPPPATH = ['../../service/resource-directory/include'])
+ liboctbstack_env.PrependUnique(LIBPATH = [env.get('BUILD_DIR') + 'service/resource-directory/include'])
liboctbstack_env.AppendUnique(CPPDEFINES = ['-DWITH_RD'])
liboctbstack_env.AppendUnique(LIBS = ['resource_directory'])
liboctbstack_src.extend(env['cbor_files'])
-if target_os in ['arduino','darwin','ios'] :
- static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
- liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack')
- liboctbstack_env.UserInstallTargetLib(static_liboctbstack, 'liboctbstack')
- liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
- liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
-else:
- static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+if target_os == 'windows':
+ liboctbstack_env.AppendUnique(CPPDEFINES = ['CBOR_API=__declspec(dllexport)',
+ 'CBOR_PRIVATE_API=__declspec(dllexport)'
+ ])
+
+static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
+octbstack_libs = Flatten(static_liboctbstack)
+
+if target_os not in ['arduino','darwin','ios'] :
shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
- liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
- liboctbstack_env.UserInstallTargetLib([static_liboctbstack, shared_liboctbstack], 'liboctbstack')
- liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
- liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
+ octbstack_libs += Flatten(shared_liboctbstack)
liboctbstack_env.UserInstallTargetHeader('stack/include/ocstack.h', 'resource', 'ocstack.h')
liboctbstack_env.UserInstallTargetHeader('stack/include/ocpresence.h', 'resource', 'ocpresence.h')
+
+liboctbstack_env.InstallTarget(octbstack_libs, 'octbstack')
+liboctbstack_env.UserInstallTargetLib(octbstack_libs, 'octbstack')
+
+liboctbstack_env.UserInstallTargetHeader('stack/include/ocstackconfig.h', 'resource', 'ocstackconfig.h')
+liboctbstack_env.UserInstallTargetHeader('stack/include/octypes.h', 'resource', 'octypes.h')
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER', 'NFC_ADAPTER'])
elif target_os in['darwin','ios']:
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
+ elif target_os in ['msys_nt', 'windows']:
+ env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER'])
else:
env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
print "CA Transport is ALL"
#include <sys/poll.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#include <mswsock.h>
+#endif
+
#ifdef __cplusplus
extern "C"
{
*/
typedef char *CAToken_t;
-// The following flags are the same as the equivalent OIC values in
-// octypes.h, allowing direct copying with slight fixup.
-// The CA layer should used the OC types when build allows that.
+/** The following flags are the same as the equivalent OIC values in
+ * octypes.h, allowing direct copying with slight fixup.
+ * The CA layer should used the OC types when build allows that.
+ */
#ifdef RA_ADAPTER
#define MAX_ADDR_STR_SIZE_CA (256)
#else
-#define MAX_ADDR_STR_SIZE_CA (40)
+/** Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * Which is 64, +1 for null terminator => 65
+ * OCDevAddr (defined in OCTypes.h) must be the same
+ * as CAEndpoint_t (defined here)
+ */
+#define MAX_ADDR_STR_SIZE_CA (65)
#endif
typedef enum
CATransportFlags_t flags; // transport modifiers
uint16_t port; // for IP
char addr[MAX_ADDR_STR_SIZE_CA]; // address for all
- uint32_t interface; // usually zero for default interface
+ uint32_t ifindex; // usually zero for default interface
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
char routeData[MAX_ADDR_STR_SIZE_CA]; /**< GatewayId:ClientId of
destination. **/
struct sockets
{
- void *threadpool; /**< threadpool between Initialize and Start */
- CASocket_t u6; /**< unicast IPv6 */
- CASocket_t u6s; /**< unicast IPv6 secure */
- CASocket_t u4; /**< unicast IPv4 */
- CASocket_t u4s; /**< unicast IPv4 secure */
- CASocket_t m6; /**< multicast IPv6 */
- CASocket_t m6s; /**< multicast IPv6 secure */
- CASocket_t m4; /**< multicast IPv4 */
- CASocket_t m4s; /**< multicast IPv4 secure */
- int netlinkFd; /**< netlink */
- int shutdownFds[2]; /**< shutdown pipe */
- int selectTimeout; /**< in seconds */
- int maxfd; /**< highest fd (for select) */
- bool started; /**< the IP adapter has started */
- bool terminate; /**< the IP adapter needs to stop */
- bool ipv6enabled; /**< IPv6 enabled by OCInit flags */
- bool ipv4enabled; /**< IPv4 enabled by OCInit flags */
- bool dualstack; /**< IPv6 and IPv4 enabled */
+ void *threadpool; /**< threadpool between Initialize and Start */
+ CASocket_t u6; /**< unicast IPv6 */
+ CASocket_t u6s; /**< unicast IPv6 secure */
+ CASocket_t u4; /**< unicast IPv4 */
+ CASocket_t u4s; /**< unicast IPv4 secure */
+ CASocket_t m6; /**< multicast IPv6 */
+ CASocket_t m6s; /**< multicast IPv6 secure */
+ CASocket_t m4; /**< multicast IPv4 */
+ CASocket_t m4s; /**< multicast IPv4 secure */
+ int netlinkFd; /**< netlink */
+#if defined(_WIN32)
+ WSAEVENT shutdownEvent; /**< Event used to signal threads to stop */
+#else
+ int shutdownFds[2]; /**< fds used to signal threads to stop */
+#endif
+ int selectTimeout; /**< in seconds */
+ int maxfd; /**< highest fd (for select) */
+ bool started; /**< the IP adapter has started */
+ bool terminate; /**< the IP adapter needs to stop */
+ bool ipv6enabled; /**< IPv6 enabled by OCInit flags */
+ bool ipv4enabled; /**< IPv4 enabled by OCInit flags */
+ bool dualstack; /**< IPv6 and IPv4 enabled */
+#if defined (_WIN32)
+ LPFN_WSARECVMSG wsaRecvMsg; /**< Win32 function pointer to WSARecvMsg() */
+#endif
struct networkmonitors
{
Exit(1)
if env.get('RELEASE'):
- build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
+ build_dir = os.path.join(dir, 'out', target_os, target_arch, 'release') + os.sep
else:
- build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
+ build_dir = os.path.join(dir, 'out', target_os, target_arch, 'debug') + os.sep
env.VariantDir(build_dir, dir, duplicate=0)
env.Replace(BUILD_DIR = build_dir)
if user_prefix:
i_n = ienv.Install(user_prefix + '/lib', targets)
ienv.Alias("install", i_n)
+ else:
+ i_n = ienv.Install(env.get('BUILD_DIR') + '/lib', targets)
+ ienv.Alias("install", i_n)
def __installbin(ienv, targets, name):
user_prefix = env.get('PREFIX')
ca_common_src_path + 'caremotehandler.c'
]
-if env['POSIX_SUPPORTED']:
+if env['POSIX_SUPPORTED'] or (ca_os in ['windows']):
platform_src = [
ca_common_src_path + 'cathreadpool_pthreads.c',
ca_common_src_path + 'camutex_pthreads.c'
typedef struct _tagMutexInfo_t
{
+#if defined(_MSC_VER)
+ uint8_t unused; //VS doesnt like empty structs
+#endif
} ca_mutex_internal;
typedef struct _tagEventInfo_t
{
+#if defined(_MSC_VER)
+ uint8_t unused; //VS doesnt like empty structs
+#endif
} ca_cond_internal;
/**
ca_mutex ca_mutex_new(void)
{
- return &g_mutexInfo;
+ return (ca_mutex)&g_mutexInfo;
}
bool ca_mutex_free(ca_mutex mutex)
ca_cond ca_cond_new(void)
{
- return &g_condInfo;
+ return (ca_cond)&g_condInfo;
}
void ca_cond_free(ca_cond cond)
#define _POSIX_C_SOURCE 200809L
#endif
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
-#include <errno.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#include <stdio.h>
+#include <errno.h>
#include <assert.h>
#include <oic_malloc.h>
-
+#include "platform_features.h"
#include "camutex.h"
#include "logger.h"
typedef struct _tagMutexInfo_t
{
+#if defined(_WIN32)
+ CRITICAL_SECTION mutex;
+#else
pthread_mutex_t mutex;
+#endif
} ca_mutex_internal;
typedef struct _tagEventInfo_t
{
+#if defined(_WIN32)
+ CONDITION_VARIABLE cond;
+#else
pthread_cond_t cond;
pthread_condattr_t condattr;
+#endif
} ca_cond_internal;
ca_mutex ca_mutex_new(void)
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) OICMalloc(sizeof(ca_mutex_internal));
if (NULL != mutexInfo)
{
+#if defined(_WIN32)
+ InitializeCriticalSection(&mutexInfo->mutex);
+ retVal = (ca_mutex)mutexInfo;
+#else
// create the mutex with the attributes set
int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT);
if (0 == ret)
OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
OICFree(mutexInfo);
}
+#endif
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "%s Failed to allocate mutex!", __func__);
}
return retVal;
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ DeleteCriticalSection(&mutexInfo->mutex);
+ OICFree(mutexInfo);
+ bRet=true;
+#else
int ret = pthread_mutex_destroy(&mutexInfo->mutex);
if (0 == ret)
{
{
OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
}
+#endif
}
else
{
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ EnterCriticalSection(&mutexInfo->mutex);
+#else
int ret = pthread_mutex_lock(&mutexInfo->mutex);
if(ret != 0)
{
OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
exit(ret);
}
+#endif
}
else
{
ca_mutex_internal *mutexInfo = (ca_mutex_internal*) mutex;
if (mutexInfo)
{
+#if defined(_WIN32)
+ LeaveCriticalSection(&mutexInfo->mutex);
+#else
int ret = pthread_mutex_unlock(&mutexInfo->mutex);
if(ret != 0)
{
exit(ret);
}
(void)ret;
+#endif
}
else
{
- OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
- return;
+ OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
+ return;
}
}
ca_cond_internal *eventInfo = (ca_cond_internal*) OICMalloc(sizeof(ca_cond_internal));
if (NULL != eventInfo)
{
+#if defined(_WIN32)
+ InitializeConditionVariable(&eventInfo->cond);
+ retVal = (ca_cond) eventInfo;
+#else
int ret = pthread_condattr_init(&(eventInfo->condattr));
if(0 != ret)
{
return retVal;
}
-#if defined(__ANDROID__) || _POSIX_TIMERS > 0
-#ifdef __ANDROID__
+ #if defined(__ANDROID__) || _POSIX_TIMERS > 0
+ #ifdef __ANDROID__
if (camutex_condattr_setclock) {
ret = camutex_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#else
+ #else
{
ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
-#endif /* __ANDROID__ */
+ #endif /* __ANDROID__ */
if(0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
return retVal;
}
}
-#endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
+ #endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
if (0 == ret)
{
pthread_condattr_destroy(&(eventInfo->condattr));
OICFree(eventInfo);
}
+#endif
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
}
return retVal;
ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ OICFree(cond);
+#else
int ret = pthread_cond_destroy(&(eventInfo->cond));
int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
if (0 == ret && 0 == ret2)
OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
__func__, ret, ret2);
}
+#endif
}
else
{
ca_cond_internal *eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ WakeConditionVariable(&eventInfo->cond);
+#else
int ret = pthread_cond_signal(&(eventInfo->cond));
if (0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable", __func__);
}
+#endif
}
else
{
ca_cond_internal* eventInfo = (ca_cond_internal*) cond;
if (eventInfo != NULL)
{
+#if defined(_WIN32)
+ WakeAllConditionVariable(&eventInfo->cond);
+#else
int ret = pthread_cond_broadcast(&(eventInfo->cond));
if (0 != ret)
{
OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable", __func__);
}
+#endif
}
else
{
ca_cond_wait_for(cond, mutex, 0L);
}
+#ifndef TIMEVAL_TO_TIMESPEC
+#define TIMEVAL_TO_TIMESPEC(tv, ts) { \
+ (ts)->tv_sec = (tv)->tv_sec; \
+ (ts)->tv_nsec = (tv)->tv_usec * 1000; \
+}
+#endif
+
+#if !defined(_WIN32)
struct timespec ca_get_current_time()
{
#if defined(__ANDROID__) || _POSIX_TIMERS > 0
ts->tv_nsec = (totalNs)% NANOSECS_PER_SEC;
ts->tv_sec += secPart + secOfNs;
}
+#endif
CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseconds)
{
if (microseconds > 0)
{
+#if defined(_WIN32)
+ // Wait for the given time
+ DWORD milli = (DWORD)(microseconds / 1000);
+ if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, milli))
+ {
+ if (GetLastError() == ERROR_TIMEOUT)
+ {
+ retVal = CA_WAIT_TIMEDOUT;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() with Timeout failed %i", GetLastError());
+ retVal = CA_WAIT_INVAL;
+ }
+ }else
+ {
+ retVal = CA_WAIT_SUCCESS;
+ }
+#else
int ret;
struct timespec abstime;
retVal = CA_WAIT_INVAL;
break;
}
+#endif
}
else
{
+#if defined(_WIN32)
+ // Wait forever
+ if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, INFINITE))
+ {
+ OIC_LOG_V(ERROR, TAG, "SleepConditionVariableCS() w/o Timeout failed %i", GetLastError());
+ retVal = CA_WAIT_INVAL;
+ }else
+ {
+ retVal = CA_WAIT_SUCCESS;
+ }
+#else
// Wait forever
int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
retVal = ret == 0 ? CA_WAIT_SUCCESS : CA_WAIT_INVAL;
+#endif
}
-
return retVal;
}
#define _GNU_SOURCE
#endif
#include <errno.h>
+#if defined HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#if defined HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
#include "cathreadpool.h"
#include "logger.h"
#include "oic_malloc.h"
#include "uarraylist.h"
#include "camutex.h"
+#include "platform_features.h"
#define TAG PCF("UTHREADPOOL")
info->data = data;
pthread_t threadHandle;
-
int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
if(result != 0)
for(uint32_t i = 0; i<u_arraylist_length(thread_pool->details->threads_list); ++i)
{
pthread_t tid = (pthread_t)u_arraylist_get(thread_pool->details->threads_list, i);
+#if defined(_WIN32)
+ DWORD joinres = WaitForSingleObject(tid, INFINITE);
+ if (WAIT_OBJECT_0 != joinres)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
+ }
+ CloseHandle(tid);
+#else
int joinres = pthread_join(tid, NULL);
if(0 != joinres)
{
OIC_LOG_V(ERROR, TAG, "Failed to join thread at index %u with error %d", i, joinres);
}
+#endif
}
u_arraylist_free(&(thread_pool->details->threads_list));
#ifndef CA_ADAPTER_NET_DTLS_H_
#define CA_ADAPTER_NET_DTLS_H_
+#include "platform_features.h"
#include "dtls.h"
#include "uarraylist.h"
#include "camutex.h"
#include <jni.h>
#endif
-#ifndef WITH_ARDUINO
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
env.get('ARDUINO_HOME')+'/libraries/Ethernet/src/utility',
])
-if target_os not in ['arduino', 'windows', 'winrt']:
+if target_os not in ['arduino', 'windows', 'winrt', 'msys_nt']:
libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '_DEFAULT_SOURCE'])
libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99','-fPIC'])
libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
'-fdata-sections', '-fno-exceptions'])
+if target_os == 'msys_nt':
+ libcoap_env.AppendUnique(CPPDEFINES = ['_DEFAULT_SOURCE'])
+ libcoap_env.AppendUnique(CFLAGS = ['-std=c99'])
+
if target_os in ['linux', 'tizen', 'android', 'ios', 'arduino']:
if with_tcp == True:
libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
'block.c'
]
-libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_')
+libcoap = libcoap_env.StaticLibrary('coap', libcoap_src, OBJPREFIX='libcoap_')
-libcoap_env.InstallTarget([libcoap], 'libcoap')
+libcoap_env.InstallTarget([libcoap], 'coap')
#include <sys/socket.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
#ifdef WITH_ARDUINO
#define DEV_ADDR_SIZE_MAX (16)
#endif
#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr))
#endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
/** multi-purpose address abstraction */
typedef struct coap_address_t
}addr;
}coap_address_t;
-static inline int
+INLINE_API int
_coap_address_equals_impl(const coap_address_t *a,
const coap_address_t *b)
{
return 0;
}
-static inline int
+INLINE_API int
_coap_is_mcast_impl(const coap_address_t *a)
{
if (!a)
uint8_t addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
} coap_address_t;
-static inline int
+INLINE_API int
_coap_address_equals_impl(const coap_address_t *a,
const coap_address_t *b)
{
return 1;
}
-static inline int
+INLINE_API int
_coap_is_mcast_impl(const coap_address_t *a)
{
if (!a)
*
* @param addr The coap_address_t object to initialize.
*/
-static inline void coap_address_init(coap_address_t *addr)
+INLINE_API void coap_address_init(coap_address_t *addr)
{
assert(addr);
memset(addr, 0, sizeof(coap_address_t));
* @c 1 if addresses are equal, @c 0 otherwise. The parameters @p a
* and @p b must not be @c NULL;
*/
-static inline int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
+INLINE_API int coap_address_equals(const coap_address_t *a, const coap_address_t *b)
{
assert(a);
assert(b);
* Checks if given address @p a denotes a multicast address. This
* function returns @c 1 if @p a is multicast, @c 0 otherwise.
*/
-static inline int coap_is_mcast(const coap_address_t *a)
+INLINE_API int coap_is_mcast(const coap_address_t *a)
{
return a && _coap_is_mcast_impl(a);
}
*
* @param s The state object to update.
*/
-static inline void coap_touch_async(coap_async_state_t *s)
+INLINE_API void coap_touch_async(coap_async_state_t *s)
{
coap_ticks(&s->created);
}
*
* @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
*/
-inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
*
* @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
*/
-inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
*
* @return @c 1 if the bit is set, @c 0 otherwise.
*/
-inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
+INLINE_API int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
{
if (size <= (size_t)(bit >> 3))
return -1;
* Checks if more than @p num blocks are required to deliver @p data_len
* bytes of data for a block size of 1 << (@p szx + 4).
*/
-static inline int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
+INLINE_API int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx)
{
return ((num + 1) << (szx + 4)) < data_len;
}
/** Sets the More-bit in @p block_opt */
-static inline void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
+INLINE_API void coap_opt_block_set_m(coap_opt_t *block_opt, int m)
{
if (m)
*(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08;
#ifdef HAVE_TIME_H
#include <time.h>
#endif
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
#ifdef WITH_LWIP
#include <stdint.h>
typedef uint32_t coap_tick_t;
- static inline void coap_ticks_impl(coap_tick_t *t)
+ INLINE_API void coap_ticks_impl(coap_tick_t *t)
{
*t = sys_now();
}
- static inline void coap_clock_init_impl(void)
+ INLINE_API void coap_clock_init_impl(void)
{
}
/** Set at startup to initialize the internal clock (time in seconds). */
extern clock_time_t clock_offset;
- static inline void
+ INLINE_API void
contiki_clock_init_impl(void)
{
clock_init();
#define coap_clock_init contiki_clock_init_impl
- static inline void
+ INLINE_API void
contiki_ticks_impl(coap_tick_t *t)
{
*t = clock_time();
#define coap_ticks contiki_ticks_impl
#endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
typedef unsigned int coap_tick_t;
/**
/** Set at startup to initialize the internal clock (time in seconds). */
extern time_t clock_offset;
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || _WIN32 */
#ifdef WITH_ARDUINO
#include "Time.h"
#endif /* WITH_ARDUINO */
#ifndef coap_clock_init
- static inline void coap_clock_init_impl(void)
+ INLINE_API void coap_clock_init_impl(void)
{
#ifdef HAVE_TIME_H
clock_offset = time(NULL);
#endif /* coap_clock_init */
#ifndef coap_ticks
- static inline void coap_ticks_impl(coap_tick_t *t)
+ INLINE_API void coap_ticks_impl(coap_tick_t *t)
{
#ifdef HAVE_SYS_TIME_H
struct timeval tv;
#endif
*t = (tv - clock_offset) * COAP_TICKS_PER_SECOND;
# else
+#ifdef HAVE_TIME_H
+ time_t tv = time(NULL);
+ *t = difftime(tv, clock_offset) * COAP_TICKS_PER_SECOND;
+#else
# error "clock not implemented"
+#endif /* HAVE_TIME_H */
# endif /* WITH_ARDUINO */
#endif /* HAVE_SYS_TIME_H */
}
* Returns @c 1 if and only if @p a is less than @p b where less is
* defined on a signed data type.
*/
- static inline
+ INLINE_API
int coap_time_lt(coap_tick_t a, coap_tick_t b)
{
return ((coap_tick_diff_t)(a - b)) < 0;
* Returns @c 1 if and only if @p a is less than or equal @p b where
* less is defined on a signed data type.
*/
- static inline
+ INLINE_API
int coap_time_le(coap_tick_t a, coap_tick_t b)
{
return a == b || coap_time_lt(a, b);
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_ARPA_INET_H 1
-#endif
-
/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
-/* Define to 1 if you have the <netdb.h> header file. */
-#define HAVE_NETDB_H 1
-
/* Define to 1 if you have the <netinet/in.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_NETINET_IN_H 1
#endif
#define HAVE_STRRCHR 1
/* Define to 1 if you have the <syslog.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_SYSLOG_H 1
#endif
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_SOCKET_H 1
-#endif
-
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
-/* Define to 1 if you have the <sys/time.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TIME_H 1
+/* Define to 1 if you have the <sys/unistd.h> header file. */
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
+#define HAVE_SYS_UNISTD_H 1
#endif
-/* Define to 1 if you have the <sys/types.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_TYPES_H 1
+/* Define to 1 if you have <Ws2tcpip.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WS2TCPIP_H 1
#endif
-/* Define to 1 if you have the <sys/unistd.h> header file. */
-#ifndef WITH_ARDUINO
-#define HAVE_SYS_UNISTD_H 1
+/* Define to 1 if you have <Winsock2.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINSOCK2_H 1
+#endif
+
+/* Define to 1 if you have <Windows.h> header file. */
+#if defined(_WIN32)
+#define HAVE_WINDOWS_H 1
#endif
/* Define to 1 if you have the <time.h> header file. */
#endif
/* Define to 1 if you have the <unistd.h> header file. */
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_WIN32)
#define HAVE_UNISTD_H 1
#endif
# endif
#endif
+#ifndef INLINE_API
+# if defined(__cplusplus)
+# define INLINE_API inline
+# else
+# ifdef _MSC_VER
+# define INLINE_API static __inline
+# else
+# define INLINE_API static inline
+# endif
+# endif
+#endif
+
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
#ifdef HAVE_TIME_H
-static inline size_t print_timestamp(char *s, size_t len, coap_tick_t t)
+INLINE_API size_t print_timestamp(char *s, size_t len, coap_tick_t t)
{
struct tm *tmp;
time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND);
#else /* alternative implementation: just print the timestamp */
-static inline size_t
+INLINE_API size_t
print_timestamp(char *s, size_t len, coap_tick_t t)
{
#ifdef HAVE_SNPRINTF
*
* @return The length of @p s.
*/
-static inline size_t
+INLINE_API size_t
strnlen(const char *s, size_t maxlen)
{
size_t n = 0;
size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
{
-#ifdef HAVE_ARPA_INET_H
+#if defined(HAVE_ARPA_INET_H) || defined(_WIN32)
const void *addrptr = NULL;
#if defined(__ANDROID__)
__uint16_t port;
+#elif defined(_WIN32)
+ uint16_t port;
#else
in_port_t port;
#endif
return 0;
}
+#ifdef HAVE_SNPRINTF
p += snprintf((char *) p, buf + len - p + 1, ":%d", port);
+#else /* HAVE_SNPRINTF */
+ /* @todo manual conversion of port number */
+#endif /* HAVE_SNPRINTF */
return buf + len - p;
#else /* HAVE_ARPA_INET_H */
#if (BSD >= 199103) || defined(WITH_CONTIKI)
# include <string.h>
#else
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO) && !defined(_MSC_VER)
# include <strings.h>
#endif
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
+#ifdef _WIN32
+#define ssize_t SSIZE_T
+#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
#ifdef WITH_LWIP
#include <lwip/pbuf.h>
#include "block.h"
#include "net.h"
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
time_t clock_offset=0;
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
coap_free(node);
static void coap_retransmittimer_execute(void *arg);
static void coap_retransmittimer_restart(coap_context_t *ctx);
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
memp_free(MEMP_COAP_NODE, node);
PROCESS(coap_retransmit_process, "message retransmit process");
-static inline coap_queue_t *
+INLINE_API coap_queue_t *
coap_malloc_node()
{
return (coap_queue_t *)memb_alloc(&node_storage);
}
-static inline void
+INLINE_API void
coap_free_node(coap_queue_t *node)
{
memb_free(&node_storage, node);
coap_context_t *
coap_new_context(const coap_address_t *listen_addr)
{
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
int reuse = 1;
#elif WITH_CONTIKI
coap_register_option(c, COAP_OPTION_BLOCK2);
coap_register_option(c, COAP_OPTION_BLOCK1);
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
if ( c->sockfd < 0 )
{
goto onerror;
}
- if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 )
+ if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse) ) < 0 )
{
#ifndef NDEBUG
coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n");
void coap_free_context(coap_context_t *context)
{
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(_WIN32)
coap_resource_t *res;
#ifndef COAP_RESOURCES_NOHASH
coap_resource_t *rtmp;
coap_retransmittimer_restart(context);
#endif
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, res)
{
}
#endif /* WITH_POSIX || WITH_LWIP */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
/* coap_delete_list(context->subscriptions); */
close( context->sockfd );
coap_free( context );
/* Compare the complete address structure in case of IPv4. For IPv6,
* we need to look at the transport address only. */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
switch (peer->addr.sa.sa_family)
{
case AF_INET:
}
#endif
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t
coap_send_impl(coap_context_t *context,
if ( !context || !dst || !pdu )
return id;
- bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
+ bytes_written = sendto( context->sockfd, (char*)pdu->hdr, pdu->length, 0,
&dst->addr.sa, dst->size);
if (bytes_written >= 0)
* This function returns @c 1 on success, or @c 0 if the option @p opt
* would exceed @p maxpos.
*/
-static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
+INLINE_API int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
{
if (opt && opt < maxpos)
{
#ifndef WITH_ARDUINO
int coap_read(coap_context_t *ctx)
{
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
static char buf[COAP_MAX_PDU_SIZE];
#endif
#if defined(WITH_LWIP) || defined(WITH_CONTIKI)
coap_address_init(&src);
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(_WIN32)
bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
#endif /* WITH_POSIX || WITH_ARDUINO */
}
-static inline int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
+INLINE_API int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
size_t blen)
{
return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
* Quick hack to determine the size of the resource description for
* .well-known/core.
*/
-static inline size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
+INLINE_API size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
{
unsigned char buf[1];
size_t len = 0;
}
}
-static inline void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
+INLINE_API void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
{
/* Call application-specific reponse handler when available. If
}
}
-static inline int
+INLINE_API int
#ifdef __GNUC__
handle_locally(coap_context_t *context __attribute__ ((unused)),
coap_queue_t *node __attribute__ ((unused)))
* to sendqueue_basetime. */
coap_tick_t sendqueue_basetime;
coap_queue_t *sendqueue, *recvqueue;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
int sockfd; /**< send/receive socket */
#endif /* WITH_POSIX || WITH_ARDUINO */
#ifdef WITH_CONTIKI
* @param context The context to register the handler for.
* @param handler The response handler to register.
*/
- static inline void coap_register_response_handler(coap_context_t *context,
+ INLINE_API void coap_register_response_handler(coap_context_t *context,
coap_response_handler_t handler)
{
context->response_handler = handler;
* @param ctx The context to use.
* @param type The option type to register.
*/
- inline static void coap_register_option(coap_context_t *ctx, unsigned char type)
+ INLINE_API void coap_register_option(coap_context_t *ctx, unsigned char type)
{
coap_option_setb(ctx->known_options, type);
}
* @param context the current coap_context_t object
* @return incremented message id in network byte order
*/
-static inline unsigned short coap_new_message_id(coap_context_t *context)
+INLINE_API unsigned short coap_new_message_id(coap_context_t *context)
{
++(context->message_id);
#if defined(WITH_ARDUINO)
* @return The transaction id if RST was sent or @c COAP_INVALID_TID
* on error.
*/
- static inline coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
+ INLINE_API coap_tid_t coap_send_rst(coap_context_t *context, const coap_address_t *dst,
coap_pdu_t *request)
{
return coap_send_message_type(context, dst, request, COAP_MESSAGE_RST);
*
* @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
*/
- inline static int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
+ INLINE_API int coap_remove_transaction(coap_queue_t **queue, coap_tid_t id)
{
coap_queue_t *node;
if (!coap_remove_from_queue(queue, id, &node))
return oi;
}
-static inline int opt_finished(coap_opt_iterator_t *oi)
+INLINE_API int opt_finished(coap_opt_iterator_t *oi)
{
assert(oi);
*
* @param f The filter to clear.
*/
-static inline void coap_option_filter_clear(coap_opt_filter_t f)
+INLINE_API void coap_option_filter_clear(coap_opt_filter_t f)
{
memset(f, 0, sizeof(coap_opt_filter_t));
}
*
* @return @c 1 if bit was set, @c -1 otherwise.
*/
-inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_setb(coap_opt_filter_t filter, unsigned short type)
{
return bits_setb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
*
* @return @c 1 if bit was set, @c -1 otherwise.
*/
-inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_clrb(coap_opt_filter_t filter, unsigned short type)
{
return bits_clrb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
*
* @return @c 1 if bit was set, @c 0 if not, @c -1 on error.
*/
-inline static int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
+INLINE_API int coap_option_getb(const coap_opt_filter_t filter, unsigned short type)
{
return bits_getb((uint8_t *) filter, sizeof(coap_opt_filter_t), type);
}
#endif
/* size must be large enough for hdr */
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
pdu = (coap_pdu_t *) coap_malloc(sizeof(coap_pdu_t) + size);
#endif
#ifdef WITH_CONTIKI
{
struct
{
- unsigned int token_length :4; /* length of Token */
- unsigned int type :2; /* type flag */
- unsigned int version :2; /* protocol version */
- unsigned int code :8; /* request method (value 1--10) or response code (value 40-255) */
+ unsigned short token_length :4; /* length of Token */
+ unsigned short type :2; /* type flag */
+ unsigned short version :2; /* protocol version */
+ unsigned short code :8; /* request method (value 1--10) or response code (value 40-255) */
unsigned short id; /* transaction id (network byte order!) */
unsigned char token[]; /* the actual token, if any */
} coap_hdr_udp_t;
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int coap_prng_impl(unsigned char *buf, size_t len)
+INLINE_API int coap_prng_impl(unsigned char *buf, size_t len)
{
while (len--)
*buf++ = rand() & 0xFF;
* implementation for prng(). You might want to change prng() to use
* a better PRNG on your specific platform.
*/
-static inline int
+INLINE_API int
contiki_prng_impl(unsigned char *buf, size_t len)
{
unsigned short v = random_rand();
#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
#endif
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
#include "utlist.h"
#include "mem.h"
}
#endif /* WITH_CONTIKI */
+#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
+#endif
/* Helper functions for conditional output of character sequences into
* a given buffer. The first Offset characters are skipped.
{
coap_resource_t *r;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
#endif
#ifdef WITH_LWIP
if (!resource || !name)
return NULL;
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
#endif
#ifdef WITH_LWIP
if (!resource)
return 0;
-#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) || defined(_WIN32)
#ifdef COAP_RESOURCES_NOHASH
LL_DELETE(context->resources, resource);
#else
if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
coap_free(resource->uri.s);
-#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO) || defined(_WIN32)
coap_free(resource);
#endif
#ifdef WITH_LWIP
* @param method The CoAP request method to handle.
* @param handler The handler to register with @p resource.
*/
-static inline void coap_register_handler(coap_resource_t *resource, unsigned char method,
+INLINE_API void coap_register_handler(coap_resource_t *resource, unsigned char method,
coap_method_handler_t handler)
{
assert(resource);
(struct_ptr)->LIST_CONCAT(name,_list) = NULL; \
}
-static inline void *
+INLINE_API void *
list_head(list_t the_list)
{
return *the_list;
}
-static inline void list_remove(list_t the_list, void *item)
+INLINE_API void list_remove(list_t the_list, void *item)
{
if (list_head(the_list))
LL_DELETE(*(struct list **)the_list, (struct list *)item);
}
-static inline void list_add(list_t the_list, void *item)
+INLINE_API void list_add(list_t the_list, void *item)
{
list_remove(the_list, item);
LL_APPEND(*(struct list **)the_list, (struct list *)item);
}
-static inline void list_push(list_t the_list, void *item)
+INLINE_API void list_push(list_t the_list, void *item)
{
LL_PREPEND(*(struct list **)the_list, (struct list *)item);
}
-static inline void *
+INLINE_API void *
list_pop(list_t the_list)
{
struct list *l;
return l;
}
-static inline void list_insert(list_t the_list, void *previtem, void *newitem)
+INLINE_API void list_insert(list_t the_list, void *previtem, void *newitem)
{
if (previtem == NULL)
{
}
}
-static inline void *
+INLINE_API void *
list_item_next(void *item)
{
return item == NULL ? NULL : ((struct list *) item)->next;
* @return A pointer to the first occurence of @p c, or @c NULL
* if not found.
*/
-static inline unsigned char *
+INLINE_API unsigned char *
strnchr(unsigned char *s, size_t len, unsigned char c)
{
while (len && *s++ != c)
/* The function signature of coap_hash() is different from
* segment_handler_t hence we use this wrapper as safe typecast. */
-static inline void hash_segment(unsigned char *s, size_t len, void *data)
+INLINE_API void hash_segment(unsigned char *s, size_t len, void *data)
{
coap_hash(s, len, (unsigned char *) data);
}
when compiling c++ code), this code uses whatever method is needed
or, for VS2008 where neither is available, uses casting workarounds. */
#ifdef _MSC_VER /* MS compiler */
-#if _MSC_VER >= 1600 && __cplusplus /* VS2010 and newer in C++ mode */
+#if (_MSC_VER >= 1600) && (defined(__cplusplus) && (__cplusplus >= 201103L)) /* VS2010 and newer in C++ mode */
#define LDECLTYPE(x) decltype(x)
#else /* VS2008 or older (or VS2010 in C mode) */
#define NO_DECLTYPE
(head)=(head)->next; \
} else { \
char *_tmp = (char*)(head); \
- while (head->next && (head->next != (del))) { \
- head = head->next; \
+ while ((head)->next && ((head)->next != (del))) { \
+ (head) = (head)->next; \
} \
- if (head->next) { \
- head->next = ((del)->next); \
+ if ((head)->next) { \
+ (head)->next = ((del)->next); \
} \
{ \
char **_head_alias = (char**)&(head); \
env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
env.AppendUnique(CPPPATH = [ os.path.join(root_dir, 'inc'),
- os.path.join(root_dir, 'lib/libcoap-4.1.1'),
- os.path.join(src_dir, '/resource/csdk/logger/include/'),
- os.path.join(root_dir, 'common/inc'),
- os.path.join(root_dir, 'util/inc') ])
+ os.path.join(root_dir, 'lib', 'libcoap-4.1.1'),
+ os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+ os.path.join(root_dir, 'common', 'inc'),
+ os.path.join(root_dir, 'util', 'inc') ])
if ca_os not in ['arduino', 'windows', 'winrt']:
env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
# Getting common source files
-env.SConscript('./../common/SConscript')
+env.SConscript(os.path.join(root_dir, 'common', 'SConscript'))
# Getting util source files
-env.SConscript(root_dir + '/util/SConscript')
+env.SConscript(os.path.join(root_dir, 'util', 'SConscript'))
# The tinydtls library is found in '#extlibs/tinydtls', where the '#'
# is interpreted by SCons as the top-level iotivity directory where
# the SConscruct file is found.
+build_dir = env.get('BUILD_DIR')
if env.get('SECURED') == '1':
- if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/tinydtls'):
- env.SConscript(os.path.join(root_dir, 'extlibs/tinydtls/SConscript'))
- else:
- env.SConscript('#extlibs/tinydtls/SConscript')
- if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/timer'):
- env.SConscript(os.path.join(root_dir, 'extlibs/timer/SConscript'))
- env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/timer')])
- else:
- env.SConscript('#extlibs/timer/SConscript')
- env.AppendUnique(CPPPATH = ['#extlibs/timer'])
+ env.SConscript(build_dir + 'extlibs/tinydtls/SConscript')
+ env.SConscript(build_dir + 'extlibs/timer/SConscript')
+ env.AppendUnique(CPPPATH = ['#extlibs/timer'])
env.AppendUnique(CA_SRC = [os.path.join(ca_path,
'adapter_util/caadapterutils.c')])
print "Include path is %s" % env.get('CPPPATH')
print "Files path is %s" % env.get('CA_SRC')
-
+
lib_env = env.Clone()
+if env.get('LOGGING'):
+ lib_env.AppendUnique(CPPDEFINES=['TB_LOG'])
+
if ca_os == 'android':
- lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
+ lib_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
if ca_os in ['android', 'tizen']:
lib_env.AppendUnique(LIBS = ['coap'])
lib_env.AppendUnique(LIBS = ['timer'])
if ca_os != 'android':
lib_env.AppendUnique(LIBS = ['rt'])
- calib = lib_env.SharedLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
+ calib = lib_env.SharedLibrary('connectivity_abstraction', env.get('CA_SRC'))
+elif ca_os in ['msys_nt', 'windows']:
+ lib_env.AppendUnique(LIBS = ['coap', 'mswsock', 'ws2_32', 'iphlpapi', 'logger'])
+ if lib_env.get('SECURED') == '1':
+ lib_env.AppendUnique(LIBS = ['tinydtls'])
+ lib_env.AppendUnique(LIBS = ['timer'])
+ calib = lib_env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
else:
calib = lib_env.StaticLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
-lib_env.InstallTarget(calib, 'libconnectivity_abstraction')
-lib_env.UserInstallTargetLib(calib, 'libconnectivity_abstraction')
+lib_env.InstallTarget(calib, 'connectivity_abstraction')
+lib_env.UserInstallTargetLib(calib, 'connectivity_abstraction')
#include "oic_string.h"
#include "global.h"
#include "timer.h"
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
+#endif
/* tinyDTLS library error code */
#define TINY_DTLS_ERROR (-1)
endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
endpoint.flags |= CA_SECURE;
endpoint.adapter = CA_ADAPTER_IP;
- endpoint.interface = session->ifindex;
+ endpoint.ifindex = session->ifindex;
int type = 0;
//Mutex is not required for g_caDtlsContext. It will be called in same thread.
#include "oic_malloc.h"
#include <errno.h>
-#ifndef WITH_ARDUINO
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
+#endif
+#if defined(HAVE_WINSOCK2_H) && defined(HAVE_WS2TCPIP_H)
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
NI_NUMERICHOST|NI_NUMERICSERV);
if (r)
{
+#if defined(EAI_SYSTEM)
if (EAI_SYSTEM == r)
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
"getnameinfo failed: %s", gai_strerror(r));
}
+#elif defined(_WIN32)
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getnameinfo failed: errno %i", WSAGetLastError());
+#else
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getnameinfo failed: %s", gai_strerror(r));
+#endif
return;
}
*port = ntohs(((struct sockaddr_in *)sockAddr)->sin_port); // IPv4 and IPv6
int r = getaddrinfo(host, NULL, &hints, &addrs);
if (r)
{
+#if defined(EAI_SYSTEM)
if (EAI_SYSTEM == r)
{
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
"getaddrinfo failed: %s", gai_strerror(r));
}
+#elif defined(_WIN32)
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: errno %i", WSAGetLastError());
+#else
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
+ "getaddrinfo failed: %s", gai_strerror(r));
+#endif
return;
}
// assumption: in this case, getaddrinfo will only return one addrinfo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
+#endif
#include "caqueueingthread.h"
#include "oic_malloc.h"
#include <string.h>
#ifndef SINGLE_THREAD
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#if HAVE_SYS_TIMEB_H
+#include <sys/timeb.h>
+#endif
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
+#endif
#if defined(__ANDROID__)
#include <linux/time.h>
} CARetransmissionData_t;
static const uint64_t USECS_PER_SEC = 1000000;
+static const uint64_t MSECS_PER_SEC = 1000;
/**
* @brief getCurrent monotonic time
*/
static uint64_t CAGetTimeoutValue()
{
+#if !defined(_WIN32)
return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
(uint64_t) 1000;
+#else
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (rand() & 0xFF)) >> 8)) *
+ (uint64_t) 1000;
+#endif
}
CAResult_t CARetransmissionStart(CARetransmission_t *context)
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+ struct __timeb64 tb;
+ _ftime64_s(&tb);
+ currentTime = tb.time * USECS_PER_SEC + tb.millitm * MSECS_PER_SEC;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
target_files += [ os.path.join(src_dir,
'linux/caipnwmonitor.c') ]
+if target_os in ['msys_nt']:
+ target_files += [ os.path.join(src_dir, 'windows/caipnwmonitor.c') ]
+
# The list of BLE adapter source files is a combination of both the
# common and target-specific source file lists.
env.AppendUnique(CA_SRC = common_files + target_files)
eps[j].flags = CA_IPV4;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
eps[j].port = caglobals.ip.u4.port;
j++;
}
eps[j].flags = CA_IPV4;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
eps[j].port = caglobals.ip.u4.port;
j++;
}
-/*****************************************************************j
+/* ****************************************************************
*
* Copyright 2014 Samsung Electronics All Rights Reserved.
*
#endif
#include <sys/types.h>
+#if !defined(_WIN32)
#include <sys/socket.h>
+#endif
+
+#if defined(_WIN32)
+#include <assert.h>
+#include <winsock2.h>
+#include <ws2def.h>
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#endif
+
#include <stdio.h>
+#if !defined(_MSC_VER)
#include <unistd.h>
+#endif //!defined(_MSC_VER)
#include <sys/types.h>
#include <fcntl.h>
+#if !defined(_WIN32)
#include <sys/select.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
+#endif
#include <errno.h>
#ifdef __linux__
#include <linux/netlink.h>
#include "camutex.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "platform_features.h"
+
+#define USE_IP_MREQN
+#if defined(_WIN32)
+#undef USE_IP_MREQN
+#endif
/*
* Logging tag for module name
NULL
};
-static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+#if defined (_WIN32)
+#define IFF_UP_RUNNING_FLAGS (IFF_UP)
+ char* caips_get_error(){
+ static char buffer[32];
+ snprintf(buffer, 32, "%i", WSAGetLastError());
+ return buffer;
+ }
+#define CAIPS_GET_ERROR \
+ caips_get_error()
+#else
+#define IFF_UP_RUNNING_FLAGS (IFF_UP|IFF_RUNNING)
+
+#define CAIPS_GET_ERROR \
+ strerror(errno)
+#endif
static CAIPErrorHandleCallback g_ipErrorHandler = NULL;
+static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;
+
static void CAFindReadyMessage();
+#if !defined(WSA_WAIT_EVENT_0)
static void CASelectReturned(fd_set *readFds, int ret);
+#else
+static void CAEventReturned(HANDLE);
+#endif
static void CAProcessNewInterface(CAInterface_t *ifchanged);
static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
-#define SET(TYPE, FDS) \
- if (caglobals.ip.TYPE.fd != -1) \
- { \
- FD_SET(caglobals.ip.TYPE.fd, FDS); \
- }
+static void CAReceiveHandler(void *data)
+{
+ (void)data;
-#define ISSET(TYPE, FDS, FLAGS) \
- if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
- { \
- fd = caglobals.ip.TYPE.fd; \
- flags = FLAGS; \
+ while (!caglobals.ip.terminate)
+ {
+ CAFindReadyMessage();
}
+}
+
+#if !defined(WSA_WAIT_EVENT_0)
#define CLOSE_SOCKET(TYPE) \
if (caglobals.ip.TYPE.fd != -1) \
caglobals.ip.TYPE.fd = -1; \
}
-void CADeInitializeIPGlobals()
-{
- CLOSE_SOCKET(u6);
- CLOSE_SOCKET(u6s);
- CLOSE_SOCKET(u4);
- CLOSE_SOCKET(u4s);
- CLOSE_SOCKET(m6);
- CLOSE_SOCKET(m6s);
- CLOSE_SOCKET(m4);
- CLOSE_SOCKET(m4s);
-
- if (caglobals.ip.netlinkFd != -1)
- {
- close(caglobals.ip.netlinkFd);
- caglobals.ip.netlinkFd = -1;
+#define SET(TYPE, FDS) \
+ if (caglobals.ip.TYPE.fd != -1) \
+ { \
+ FD_SET(caglobals.ip.TYPE.fd, FDS); \
}
-}
-static void CAReceiveHandler(void *data)
-{
- (void)data;
-
- while (!caglobals.ip.terminate)
- {
- CAFindReadyMessage();
+#define ISSET(TYPE, FDS, FLAGS) \
+ if (caglobals.ip.TYPE.fd != -1 && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
+ { \
+ fd = caglobals.ip.TYPE.fd; \
+ flags = FLAGS; \
}
-}
+
static void CAFindReadyMessage()
{
SET(m6s, &readFds)
SET(m4, &readFds)
SET(m4s, &readFds)
+
if (caglobals.ip.shutdownFds[0] != -1)
{
FD_SET(caglobals.ip.shutdownFds[0], &readFds);
OIC_LOG_V(DEBUG, TAG, "Packet receiver Stop request received.");
return;
}
+
if (ret <= 0)
{
if (ret < 0)
{
- OIC_LOG_V(FATAL, TAG, "select error %s", strerror(errno));
+ OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
}
return;
}
else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
else ISSET(m4, readFds, CA_MULTICAST | CA_IPV4)
else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
- else if (FD_ISSET(caglobals.ip.netlinkFd, readFds))
+ else if ((caglobals.ip.netlinkFd != -1) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
{
CAInterface_t *ifchanged = CAFindInterfaceChange();
if (ifchanged)
{
break;
}
-
(void)CAReceiveMessage(fd, flags);
FD_CLR(fd, readFds);
}
}
+#else // if defined(WSA_WAIT_EVENT_0)
+
+#define CLOSE_SOCKET(TYPE) \
+ if (caglobals.ip.TYPE.fd != -1) \
+ { \
+ closesocket(caglobals.ip.TYPE.fd); \
+ caglobals.ip.TYPE.fd = -1; \
+ }
+
+#define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
+{ \
+ ARRAY[INDEX] = HANDLE; \
+ INDEX++; \
+}
+
+// Turn handle into WSAEvent and push to ARRAY
+#define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
+ if (SOCKET != -1) \
+ { \
+ WSAEVENT NewEvent; \
+ NewEvent = WSACreateEvent(); \
+ if (WSA_INVALID_EVENT != NewEvent) \
+ { \
+ if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
+ if (!WSACloseEvent(NewEvent)) \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+ } \
+ } \
+ else \
+ { \
+ PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
+ } \
+ } \
+ else \
+ { \
+ OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
+ }\
+ }
+
+#define INSERT_FD(FD, ARRAY, INDEX) \
+ { \
+ if (-1 != FD) \
+ { \
+ ARRAY[INDEX] = FD; \
+ } \
+ }
+
+
+// Inserts the FD into the FD_ARRAY and pushes the socket event into ARRAY
+#define PUSH_IP_SOCKET(TYPE, ARRAY, FD_ARRAY, INDEX) \
+ { \
+ if (-1 != caglobals.ip.TYPE.fd) \
+ { \
+ INSERT_FD(caglobals.ip.TYPE.fd, FD_ARRAY, INDEX); \
+ PUSH_SOCKET(caglobals.ip.TYPE.fd, ARRAY, INDEX); \
+ } \
+ }
+
+#define IS_MATCHING_IP_HANDLE(TYPE, HANDLE, FLAGS) \
+ if ((caglobals.ip.TYPE.fd != -1) && (caglobals.ip.TYPE.fd == HANDLE)) \
+ { \
+ fd = caglobals.ip.TYPE.fd; \
+ flags = FLAGS; \
+ }
+
+#define EVENT_ARRAY_SIZE 10
+
+static void CAFindReadyMessage()
+{
+ int fdArray[EVENT_ARRAY_SIZE];
+ HANDLE eventArray[EVENT_ARRAY_SIZE];
+ int arraySize = 0;
+ int eventIndex;
+
+ // fdArray and eventArray should have same number of elements
+ OC_STATIC_ASSERT(_countof(fdArray) == _countof(eventArray), "Arrays should have same number of elements");
+
+ PUSH_IP_SOCKET(u6, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(u6s, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(u4, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(u4s, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(m6, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(m6s, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(m4, eventArray, fdArray, arraySize);
+ PUSH_IP_SOCKET(m4s, eventArray, fdArray, arraySize);
+
+ if (-1 != caglobals.ip.shutdownEvent)
+ {
+ INSERT_FD(caglobals.ip.shutdownEvent, fdArray, arraySize);
+ PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
+ }
+
+ /** @todo Support netlink events */
+
+ // Should not have overflowed buffer
+ assert(arraySize <= (_countof(fdArray)));
+
+ // Timeout is unnecessary on Windows
+ assert(-1 == caglobals.ip.selectTimeout);
+
+ while (!caglobals.ip.terminate)
+ {
+ int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);
+
+ switch (ret)
+ {
+ case WSA_WAIT_FAILED:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
+ break;
+ case WSA_WAIT_IO_COMPLETION:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
+ break;
+ case WSA_WAIT_TIMEOUT:
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
+ break;
+ default:
+ eventIndex = ret - WSA_WAIT_EVENT_0;
+ if ((eventIndex >= 0) && (eventIndex < arraySize))
+ {
+ if (false == WSAResetEvent(eventArray[eventIndex]))
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
+ }
+ CAEventReturned(fdArray[eventIndex]);
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
+ }
+ break;
+ }
+
+ }
+
+ while (arraySize > 0)
+ {
+ arraySize--;
+ if (!WSACloseEvent(eventArray[arraySize]))
+ {
+ OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
+ }
+ }
+}
+
+static void CAEventReturned(HANDLE handle)
+{
+ int fd = -1;
+ CATransportFlags_t flags = CA_DEFAULT_FLAGS;
+
+ while (!caglobals.ip.terminate)
+ {
+ IS_MATCHING_IP_HANDLE(u6, handle, CA_IPV6)
+ else IS_MATCHING_IP_HANDLE(u6s, handle, CA_IPV6 | CA_SECURE)
+ else IS_MATCHING_IP_HANDLE(u4, handle, CA_IPV4)
+ else IS_MATCHING_IP_HANDLE(u4s, handle, CA_IPV4 | CA_SECURE)
+ else IS_MATCHING_IP_HANDLE(m6, handle, CA_MULTICAST | CA_IPV6)
+ else IS_MATCHING_IP_HANDLE(m6s, handle, CA_MULTICAST | CA_IPV6 | CA_SECURE)
+ else IS_MATCHING_IP_HANDLE(m4, handle, CA_MULTICAST | CA_IPV4)
+ else IS_MATCHING_IP_HANDLE(m4s, handle, CA_MULTICAST | CA_IPV4 | CA_SECURE)
+ else if ((caglobals.ip.shutdownEvent != -1) && (caglobals.ip.shutdownEvent == handle))
+ {
+ break;
+ }
+ else
+ {
+ break;
+ }
+ (void)CAReceiveMessage(handle, flags);
+ // We will never get more than one match per handle, so always break.
+ break;
+ }
+
+ if (caglobals.ip.terminate)
+ {
+ if (-1 != caglobals.ip.shutdownEvent)
+ {
+ // We presume the shutdownEvent will be closed in CAFindReadyMessage
+ caglobals.ip.shutdownEvent = -1;
+ WSACleanup();
+ }
+ }
+}
+
+#endif
+
+void CADeInitializeIPGlobals()
+{
+ CLOSE_SOCKET(u6);
+ CLOSE_SOCKET(u6s);
+ CLOSE_SOCKET(u4);
+ CLOSE_SOCKET(u4s);
+ CLOSE_SOCKET(m6);
+ CLOSE_SOCKET(m6s);
+ CLOSE_SOCKET(m4);
+ CLOSE_SOCKET(m4s);
+
+ if (caglobals.ip.netlinkFd != -1)
+ {
+#ifdef _WIN32
+ closesocket(caglobals.ip.netlinkFd);
+#else
+ close(caglobals.ip.netlinkFd);
+#endif
+ caglobals.ip.netlinkFd = -1;
+ }
+}
+
static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
{
char recvBuffer[COAP_MAX_PDU_SIZE];
int level, type, namelen;
struct sockaddr_storage srcAddr;
unsigned char *pktinfo = NULL;
+#if !defined(WSA_CMSG_DATA)
struct cmsghdr *cmp = NULL;
- struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
+ struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
union control
{
struct cmsghdr cmsg;
}
}
}
+#else // if defined(WSA_CMSG_DATA)
+ union control
+ {
+ WSACMSGHDR cmsg;
+ uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
+ } cmsg;
+ memset(&cmsg, 0, sizeof(cmsg));
+
+ if (flags & CA_IPV6)
+ {
+ namelen = sizeof (struct sockaddr_in6);
+ level = IPPROTO_IPV6;
+ type = IPV6_PKTINFO;
+ }
+ else
+ {
+ namelen = sizeof (struct sockaddr_in);
+ level = IPPROTO_IP;
+ type = IP_PKTINFO;
+ }
+
+ WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
+ WSAMSG msg = {.name = &srcAddr,
+ .namelen = namelen,
+ .lpBuffers = &iov,
+ .dwBufferCount = 1,
+ .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
+ };
+
+ uint32_t recvLen = 0;
+ uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
+ OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
+ if (SOCKET_ERROR == ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
+ }
+ if (flags & CA_MULTICAST)
+ {
+ for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
+ cmp = WSA_CMSG_NXTHDR(&msg, cmp))
+ {
+ if (cmp->cmsg_level == level && cmp->cmsg_type == type)
+ {
+ pktinfo = WSA_CMSG_DATA(cmp);
+ }
+ }
+ }
+#endif // !defined(WSA_CMSG_DATA)
CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
if (flags & CA_IPV6)
{
- sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
- ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
-
+ /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
if ((flags & CA_MULTICAST) && pktinfo)
{
struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
}
}
- CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
+ CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
if (flags & CA_SECURE)
{
}
return CA_STATUS_OK;
+
}
void CAIPPullData()
int fd = socket(family, socktype, IPPROTO_UDP);
if (-1 == fd)
{
- OIC_LOG_V(ERROR, TAG, "create socket failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
return -1;
}
-#ifndef SOCK_CLOEXEC
+#if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
int fl = fcntl(fd, F_GETFD);
if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
{
return -1;
}
#endif
-
struct sockaddr_storage sa = { .ss_family = family };
socklen_t socklen;
{
int on = 1;
- if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
+ if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
}
- if (isMulticast && *port) // only do this for multicast ports
+ if (isMulticast && *port) // only do this for multicast ports
{
+#if defined(IPV6_RECVPKTINFO)
if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+#else
+ if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
}
}
}
else
{
- if (isMulticast && *port) // only do this for multicast ports
+ if (isMulticast && *port) // only do this for multicast ports
{
int on = 1;
- if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
+ if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
}
}
socklen = sizeof (struct sockaddr_in);
}
- if (isMulticast && *port) // use the given port
+ if (isMulticast && *port) // use the given port
{
int on = 1;
- if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof (on)))
+ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
{
- OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
+#endif
return -1;
}
}
if (-1 == bind(fd, (struct sockaddr *)&sa, socklen))
{
- OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
+#endif
return -1;
}
- if (!*port) // return the assigned port
+ if (!*port) // return the assigned port
{
if (-1 == getsockname(fd, (struct sockaddr *)&sa, &socklen))
{
- OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
+#ifdef _WIN32
+ closesocket(fd);
+#else
close(fd);
+#endif
return -1;
}
*port = ntohs(family == AF_INET6 ?
static void CAInitializeNetlink()
{
+ caglobals.ip.netlinkFd = -1;
#ifdef __linux__
// create NETLINK fd for interface change notifications
struct sockaddr_nl sa = { AF_NETLINK, 0, 0, RTMGRP_LINK };
#endif
}
-static void CAInitializePipe()
+static void CAInitializeFastShutdownMechanism()
{
- caglobals.ip.selectTimeout = -1;
-#ifdef HAVE_PIPE2
- int ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+ caglobals.ip.selectTimeout = -1; // don't poll for shutdown
+ int ret = -1;
+#if defined(WSA_WAIT_EVENT_0)
+ caglobals.ip.shutdownEvent = -1;
+ caglobals.ip.shutdownEvent = WSACreateEvent();
+
+ if (caglobals.ip.shutdownEvent == WSA_INVALID_EVENT)
+ {
+ caglobals.ip.shutdownEvent = -1;
+ }
+ else
+ {
+ ret = 0;
+ }
+#elif defined(HAVE_PIPE2)
+ ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
+ CHECKFD(caglobals.ip.shutdownFds[0]);
+ CHECKFD(caglobals.ip.shutdownFds[1]);
#else
- int ret = pipe(caglobals.ip.shutdownFds);
+ ret = pipe(caglobals.ip.shutdownFds);
if (-1 != ret)
{
ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
caglobals.ip.shutdownFds[1] = -1;
}
}
+ CHECKFD(caglobals.ip.shutdownFds[0]);
+ CHECKFD(caglobals.ip.shutdownFds[1]);
#endif
if (-1 == ret)
{
- OIC_LOG_V(ERROR, TAG, "pipe failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
}
}
{
return res;
}
-
+#if defined (_WIN32)
+ WORD wVersionRequested = MAKEWORD(2, 2);
+ WSADATA wsaData ={.wVersion = 0};
+ int err = WSAStartup(wVersionRequested, &wsaData);
+ if (err != 0)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
+ return CA_STATUS_FAILED;
+ }
+ OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
+#endif
if (!IPv4MulticastAddress.s_addr)
{
(void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
caglobals.ip.m4.port, caglobals.ip.m4s.port);
- // create pipe for fast shutdown
- CAInitializePipe();
- CHECKFD(caglobals.ip.shutdownFds[0]);
- CHECKFD(caglobals.ip.shutdownFds[1]);
+#if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
+ caglobals.ip.wsaRecvMsg = NULL;
+ GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
+ DWORD copied = 0;
+ err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
+ if (0 != err)
+ {
+ OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
+ return CA_STATUS_FAILED;
+ }
+#endif
+ // set up appropriate FD mechanism for fast shutdown
+ CAInitializeFastShutdownMechanism();
// create source of network interface change notifications
CAInitializeNetlink();
caglobals.ip.started = false;
caglobals.ip.terminate = true;
+#if !defined(WSA_WAIT_EVENT_0)
if (caglobals.ip.shutdownFds[1] != -1)
{
close(caglobals.ip.shutdownFds[1]);
{
// receive thread will stop in SELECT_TIMEOUT seconds.
}
+#else
+ if (!WSASetEvent(caglobals.ip.shutdownEvent))
+ {
+ OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+ }
+#endif
}
void CAWakeUpForChange()
{
+#if !defined(WSA_WAIT_EVENT_0)
if (caglobals.ip.shutdownFds[1] != -1)
{
ssize_t len = 0;
OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
}
}
+#else
+ if (!WSASetEvent(caglobals.ip.shutdownEvent))
+ {
+ OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
+ }
+#endif
}
-static void applyMulticastToInterface4(struct in_addr inaddr)
+static void applyMulticastToInterface4(uint32_t ifindex)
{
if (!caglobals.ip.ipv4enabled)
{
return;
}
+#if defined(USE_IP_MREQN)
struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
- .imr_address = inaddr,
- .imr_ifindex = 0 };
- if (setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+ .imr_address.s_addr = htonl(INADDR_ANY),
+ .imr_ifindex = ifindex };
+#else
+ struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
+ .imr_interface.s_addr = htonl(ifindex) };
+#endif
+
+ int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (-1 == ret)
{
+#if !defined(WSAEINVAL)
if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, " IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
}
}
- if (setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)))
+ ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (-1 == ret)
{
+#if !defined(WSAEINVAL)
if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "secure IPv4 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
}
}
}
-static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t interface)
+static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
{
- struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr, .ipv6mr_interface = interface};
-
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof (mreq)))
+ struct ipv6_mreq mreq = {.ipv6mr_multiaddr = *addr,
+ .ipv6mr_interface = ifindex };
+ int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
+ if (-1 == ret)
{
- if (EADDRINUSE != errno)
+#if !defined(_WIN32)
+ if (EADDRINUSE != errno)
+#else
+ if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
+#endif
{
- OIC_LOG_V(ERROR, TAG, "IPv6 IP_ADD_MEMBERSHIP failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
}
}
}
-static void applyMulticastToInterface6(uint32_t interface)
+static void applyMulticastToInterface6(uint32_t ifindex)
{
if (!caglobals.ip.ipv6enabled)
{
return;
}
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, interface);
- applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, interface);
- //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, interface);
-
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, interface);
- applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, interface);
- //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
+ applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
+ //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);
+
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
+ applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
+ //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
}
CAResult_t CAIPStartListenServer()
u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
if (!iflist)
{
- OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
return CA_STATUS_FAILED;
}
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
if (ifitem->family == AF_INET)
{
- struct in_addr inaddr;
- inaddr.s_addr = ifitem->ipv4addr;
- applyMulticastToInterface4(inaddr);
- OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s", ifitem->name);
+ OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface %i to multicast group", ifitem->index);
+ applyMulticastToInterface4(ifitem->index);
}
if (ifitem->family == AF_INET6)
{
+ OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface %i to multicast group", ifitem->index);
applyMulticastToInterface6(ifitem->index);
- OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
}
}
{
continue;
}
-
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
if (ifitem->family == AF_INET)
{
- close(caglobals.ip.m4.fd);
- close(caglobals.ip.m4s.fd);
- caglobals.ip.m4.fd = -1;
- caglobals.ip.m4s.fd = -1;
+ CLOSE_SOCKET(m4);
+ CLOSE_SOCKET(m4s);
OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
}
if (ifitem->family == AF_INET6)
{
- close(caglobals.ip.m6.fd);
- close(caglobals.ip.m6s.fd);
- caglobals.ip.m6.fd = -1;
- caglobals.ip.m6s.fd = -1;
+ CLOSE_SOCKET(m6);
+ CLOSE_SOCKET(m6s);
OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
}
}
OIC_LOG(DEBUG, TAG, "ifitem is null");
return;
}
+
if (ifitem->family == AF_INET6)
{
applyMulticastToInterface6(ifitem->index);
}
if (ifitem->family == AF_INET)
{
- struct in_addr inaddr = { .s_addr = ifitem->ipv4addr };
- applyMulticastToInterface4(inaddr);
+ applyMulticastToInterface4(ifitem->index);
}
}
}
char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
- (void)secure; // eliminates release warning
+
+ (void)cast; // eliminates release warning
+ (void)fam;
+
struct sockaddr_storage sock;
CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);
socklen_t socklen;
if (sock.ss_family == AF_INET6)
{
- struct sockaddr_in6 *sock6 = (struct sockaddr_in6 *)&sock;
- if (!sock6->sin6_scope_id)
- {
- sock6->sin6_scope_id = endpoint->interface;
- }
+ /** @todo figure out correct usage for ifindex, and sin6_scope_id */
socklen = sizeof(struct sockaddr_in6);
}
else
{
socklen = sizeof(struct sockaddr_in);
}
-
+#if !defined(_WIN32)
ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
if (-1 == len)
{
// If logging is not defined/enabled.
- (void)cast;
- (void)fam;
if (g_ipErrorHandler)
{
g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
{
OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
}
+#else
+ int err = 0;
+ int len = 0;
+ int sent = 0;
+ do {
+ len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
+ if (SOCKET_ERROR == len)
+ {
+ err = WSAGetLastError();
+ if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
+ {
+ // If logging is not defined/enabled.
+ if (g_ipErrorHandler)
+ {
+ g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
+ }
+
+ OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
+ }
+ }
+ else
+ {
+ sent += len;
+ if (sent != len)
+ {
+ OIC_LOG_V(DEBUG, TAG, "%s%s %s sendTo (Partial Send) is successful: "
+ "currently sent: %ld bytes, "
+ "total sent: %ld bytes, "
+ "remaining: %ld bytes",
+ secure, cast, fam, len, sent, dlen-sent);
+ }
+ else
+ {
+ OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
+ secure, cast, fam, len);
+ }
+ }
+ } while ((SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
+#endif
}
static void sendMulticastData6(const u_arraylist_t *iflist,
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
}
int index = ifitem->index;
- if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &index, sizeof (index)))
+ if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
{
- OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", strerror(errno));
+ OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
return;
}
sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
{
VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
+#if defined(USE_IP_MREQN)
struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
- .imr_ifindex = 0 };
+ .imr_address.s_addr = htonl(INADDR_ANY),
+ .imr_ifindex = 0};
+#else
+ struct ip_mreq mreq = { .imr_multiaddr = IPv4MulticastAddress,
+ .imr_interface = {0}};
+#endif
+
OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
int fd = caglobals.ip.u4.fd;
{
continue;
}
- if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
{
continue;
}
{
continue;
}
-
- struct in_addr inaddr;
- inaddr.s_addr = ifitem->ipv4addr;
- mreq.imr_address = inaddr;
- if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof (mreq)))
+#if defined(USE_IP_MREQN)
+ mreq.imr_ifindex = ifitem->index;
+#else
+ mreq.imr_interface.s_addr = htonl(ifitem->index);
+#endif
+ if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
{
OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
- strerror(errno));
+ CAIPS_GET_ERROR);
}
sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
}
}
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
if (ifitem->family == AF_INET6)
{
{
eps[j].flags = CA_IPV4;
eps[j].port = caglobals.ip.u4.port;
-
- inet_ntop(AF_INET, &(ifitem->ipv4addr), eps[j].addr, MAX_ADDR_STR_SIZE_CA);
+ /** @todo eps[j].addr not populated with IPv4 address string.
+ * it was using ifitem->ipv4addr to accomplish this.
+ * Need to understand what ipv4addr means to whom*/
}
#ifdef __WITH_DTLS__
j++;
eps[j].adapter = CA_ADAPTER_IP;
- eps[j].interface = 0;
+ eps[j].ifindex = 0;
if (ifitem->family == AF_INET6)
{
--- /dev/null
+#######################################################
+# Build IP adapter for MSYS2
+#######################################################
+
+Import('env', 'src_dir')
+import os.path
+target_os = env.get('TARGET_OS')
+env.AppendUnique(CPPPATH = [ os.path.join(src_dir, target_os) ])
+
+src_files = [ 'caipnwmonitor.c' ]
+
+Return('src_files')
--- /dev/null
+/* *****************************************************************
+*
+* Copyright 2016 Intel Corporation
+*
+*
+*
+* 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 "caipinterface.h"
+
+#include <sys/types.h>
+#include <string.h>
+#include <errno.h>
+#include <winsock2.h>
+#include "platform_features.h"
+#include <iptypes.h>
+#include <stdbool.h>
+#include "caadapterutils.h"
+#include "logger.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+#define TAG "IP_MONITOR"
+
+/** @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStartNetworkMonitor()
+{
+ return CA_STATUS_OK;
+}
+
+/** @todo Implement network interface monitoring in case the IP changes.
+ * Not critical for win32 bring-up.
+ */
+CAResult_t CAIPStopNetworkMonitor()
+{
+ return CA_STATUS_OK;
+}
+
+/** @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+int CAGetPollingInterval(int interval)
+{
+ return interval;
+}
+
+/** @todo Implement network interface monitoring.
+ * Not used in win32, but caipserver currently requires this function
+ * be defined. not critical.
+ */
+CAInterface_t *CAFindInterfaceChange()
+{
+ CAInterface_t *foundNewInterface = NULL;
+ return foundNewInterface;
+}
+
+/** @todo Implement network interface monitoring.
+ * Not critical for win32 bring-up.
+ */
+void CAIPSetNetworkMonitorCallback(CAIPConnectionStateChangeCallback callback)
+{
+ return;
+}
+
+bool IsValidAdapter(PIP_ADAPTER_ADDRESSES pAdapterAddr, int desiredIndex, uint16_t family)
+{
+ bool valid = true;
+
+ // If desiredIndex is non-zero, then only retrieve adapter corresponding to desiredIndex.
+ // If desiredIndex is zero, then retrieve all adapters.
+ if (desiredIndex && (pAdapterAddr->IfIndex != desiredIndex))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i not interesting.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ if (pAdapterAddr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is loopback.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ // If the adapter must support the requested family
+ if ((family == AF_INET6) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED) == 0))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv6", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+ else if ((family == AF_INET) && ((pAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED) == 0))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i does not support IPv4", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+
+ if ((pAdapterAddr->OperStatus & IfOperStatusUp) == 0)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tInterface %i is not operational.", pAdapterAddr->IfIndex);
+ valid = false;
+ }
+ return valid;
+
+}
+
+
+bool AddCAInterface(u_arraylist_t *iflist, const char * name, uint32_t index, uint16_t family)
+{
+ bool bSucceeded = false;
+ CAInterface_t *ifitem = (CAInterface_t *)OICCalloc(1, sizeof(*ifitem));
+ if (ifitem)
+ {
+ OICStrcpy(ifitem->name, INTERFACE_NAME_MAX, name);
+ ifitem->index = index;
+ ifitem->family = family;
+ ifitem->flags |= IFF_UP;// IsValidAddress() will have filtered out non-operational addresses already.
+
+ if (u_arraylist_add(iflist, ifitem))
+ {
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "u_arraylist_add failed");
+ OICFree(ifitem);
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Allocating memory for a CAInterface_t failed");
+ }
+ return bSucceeded;
+}
+
+bool AddInterfaces(PIP_ADAPTER_ADDRESSES pAdapterAddr, u_arraylist_t *iflist, int desiredIndex)
+{
+ bool bSucceeded = false;
+ for (PIP_ADAPTER_ADDRESSES pCurAdapterAddr = pAdapterAddr;
+ pCurAdapterAddr != NULL; pCurAdapterAddr = pCurAdapterAddr->Next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "\tInterface Index: %u", pCurAdapterAddr->IfIndex);
+ OIC_LOG_V(DEBUG, TAG, "\tInterface name: %s", pCurAdapterAddr->AdapterName);
+
+ // Prefer IPv6 over IPv4.
+ if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV6_ENABLED)
+ {
+ // Do not add loopback, duplicate, or non-operational adapters
+ if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET6))
+ {
+ if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET6))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv6 interface %i", pCurAdapterAddr->IfIndex);
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "\tAdding IPv6 interface %i failed", pCurAdapterAddr->IfIndex);
+ break;
+ }
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+ }
+ }
+ else if (pCurAdapterAddr->Flags & IP_ADAPTER_IPV4_ENABLED)
+ {
+ // Do not add loopback, duplicate, or non-operational adapters
+ if (IsValidAdapter(pCurAdapterAddr, desiredIndex, AF_INET))
+ {
+ if (AddCAInterface(iflist, pCurAdapterAddr->AdapterName, pCurAdapterAddr->IfIndex, AF_INET))
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tAdded IPv4 interface %i", pCurAdapterAddr->IfIndex);
+ bSucceeded = true;
+ }
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "\tAdding IPv4 interface %i failed", pCurAdapterAddr->IfIndex);
+ break;
+ }
+ }
+ else
+ {
+ OIC_LOG_V(DEBUG, TAG, "\t\tIPv6 interface %i not valid, skipping...", pCurAdapterAddr->IfIndex);
+ }
+
+ }
+ }
+ return bSucceeded;
+}
+
+PIP_ADAPTER_ADDRESSES GetAdapters()
+{
+ ULONG ulOutBufLen = sizeof(IP_ADAPTER_ADDRESSES);
+ PIP_ADAPTER_ADDRESSES pAdapterAddr = (IP_ADAPTER_ADDRESSES *) OICMalloc(ulOutBufLen);
+ if (pAdapterAddr != NULL)
+ {
+ ULONG flags = 0;
+ ULONG ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+ if (ERROR_BUFFER_OVERFLOW == ret)
+ {
+ // Redo with updated length
+ OICFree(pAdapterAddr);
+ pAdapterAddr = (PIP_ADAPTER_ADDRESSES) OICMalloc(ulOutBufLen);
+ if (pAdapterAddr != NULL) {
+ ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapterAddr, &ulOutBufLen);
+ if (NO_ERROR != ret)
+ {
+ OIC_LOG(ERROR, TAG, "GetAdaptersAddresses() failed");
+ OICFree(pAdapterAddr);
+ pAdapterAddr = NULL;
+ }
+ else
+ {
+ // Succeeded getting adapters
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Second time allocating memory for GetAdaptersAddresses() failed");
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Expected GetAdaptersAddresses() to fail on first try, but it didn't.");
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "First time allocating memory for GetAdaptersAddresses() failed");
+ }
+ return pAdapterAddr;
+}
+
+u_arraylist_t *CAIPGetInterfaceInformation(int desiredIndex)
+{
+ u_arraylist_t *iflist = u_arraylist_create();
+ if (iflist)
+ {
+ PIP_ADAPTER_ADDRESSES pAdapterAddr = NULL;
+ pAdapterAddr = GetAdapters();
+ if (pAdapterAddr)
+ {
+ // Cycle through adapters
+ // Add valid adapters to the interface list.
+ bool ret = AddInterfaces(pAdapterAddr, iflist, desiredIndex);
+ if (false == ret)
+ {
+ OIC_LOG(ERROR, TAG, "AddInterfaces() failed");
+ u_arraylist_destroy(iflist);
+ iflist = NULL;
+ }
+
+ // Finished with Adapter List
+ OICFree(pAdapterAddr);
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Enumerating Adapters failed");
+ u_arraylist_destroy(iflist);
+ iflist = NULL;
+ }
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "Failed to create iflist");
+ }
+ return iflist;
+}
# Build flags
######################################################################
catest_env.PrependUnique(CPPPATH = [
- '../../ocsocket/include',
'../../logger/include',
'../../stack/include',
'../../extlibs/cjson',
catest_env.Replace(LINKFLAGS = tmplist)
catest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-catest_env.AppendUnique(LIBS = ['pthread'])
catest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
catest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-catest_env.PrependUnique(LIBS = ['m',
- 'octbstack',
+catest_env.PrependUnique(LIBS = ['octbstack',
'connectivity_abstraction',
'coap',
'gtest',
target_os = env.get('TARGET_OS')
-if target_os not in ['arduino', 'darwin', 'ios']:
+if target_os not in ['arduino', 'darwin', 'ios', 'msys_nt', 'windows']:
catest_env.AppendUnique(LIBS=['rt'])
if env.get('SECURED') == '1':
- catest_env.AppendUnique(LIBS = ['tinydtls'])
+ catest_env.AppendUnique(LIBS = ['tinydtls'])
+ catest_env.AppendUnique(LIBS = ['timer'])
+
+if env.get('WITH_RD') == '1':
+ catest_env.PrependUnique(LIBS = ['resource_directory'])
if env.get('LOGGING'):
catest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os in ['msys_nt', 'windows']:
+ catest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ catest_env.AppendUnique(LIBS = ['ws2_32',
+ 'advapi32',
+ 'iphlpapi'])
+else:
+ catest_env.PrependUnique(LIBS = ['m', 'pthread'])
+
######################################################################
# Source files and Targets
######################################################################
env.AppendTarget('test')
if env.get('TEST') == '1':
- if target_os == 'linux':
+ if target_os in ['linux', 'windows']:
+ catest_env.AppendENVPath('PATH', env.get('BUILD_DIR'))
from tools.scons.RunTest import *
run_test(catest_env,
'resource_csdk_connectivity_test.memcheck',
*
******************************************************************/
+#include "platform_features.h"
#include "gtest/gtest.h"
#include "cainterface.h"
#include "cautilinterface.h"
}
#endif //__WITH_DTLS__
-int main(int argc, char **argv)
-{
- testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
// CAInitialize TC
// check return value
TEST(InitializeTest, TC_01_Positive_01)
#include <camutex.h>
#include <cathreadpool.h>
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#include "platform_features.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#define HNS_PER_US 10
//#define DEBUG_VERBOSE 1
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
+#elif defined(_WIN32)
+ FILETIME time;
+ ULARGE_INTEGER microseconds;
+
+ GetSystemTimeAsFileTime(&time);
+
+ // Time is in hundreds of nanoseconds, so we must convert to uS
+ microseconds.LowPart = time.dwLowDateTime;
+ microseconds.HighPart = time.dwHighDateTime;
+ microseconds.QuadPart /= HNS_PER_US;
+
+ currentTime = microseconds.QuadPart;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
DBG_printf("Thread_%d: completed.\n", pData->id);
}
+#ifdef _WIN32
+/** @todo: Enable. Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_02_SIGNAL)
+#else
TEST(ConditionTests, TC_02_SIGNAL)
+#endif
{
const int MAX_WAIT_MS = 2000;
ca_thread_pool_t mythreadpool;
ca_thread_pool_free(mythreadpool);
}
-TEST(CondTests, TC_04_TIMECHECK)
+#ifdef _WIN32
+/** @todo: Enable. Need to solve nanosleep issue */
+TEST(ConditionTests, DISABLED_TC_04_TIMECHECK)
+#else
+TEST(ConditionTests, TC_04_TIMECHECK)
+#endif
{
uint64_t begin = getAbsTime();
double secondsDiff = (end - beg) / (double) USECS_PER_SEC;
+#ifdef _WIN32
+ // Windows does not guarantee that the thread will resume execution from a
+ // yield within any given time frame. We will assume that the threads
+ // should have resumed within one second of the requested timeout value.
+ EXPECT_NEAR(TARGET_WAIT, secondsDiff, 1.00);
+#else
EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
+#endif
ca_mutex_unlock(sharedMutex);
#include "gtest/gtest.h"
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
/**
pthread_key_delete(key);
}
}
+#else
+void workaroundHook()
+{
+ return;
+};
+#endif
TEST(BaseTest, WorldIsSane)
Import('env')
import os
-env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, './include')])
+env.AppendUnique(CPPPATH = [os.path.join(Dir('.').abspath, 'include'),
+ '../../c_common'
+ ])
+
if env.get('TARGET_OS') in ['arduino']:
env.AppendUnique(CPPPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common/oic_string/include')])
if env.get('TARGET_OS') == 'tizen':
env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
else:
- env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/csdk/logger/')])
+ env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'logger')])
env.PrependUnique(LIBS = ['logger'])
FATAL = DLOG_ERROR
} LogLevel;
#else
+
+/** @todo temporary work-around until better names with prefixes are used for the enum values. */
+#ifdef ERROR
+#undef ERROR
+#endif
+
typedef enum {
DEBUG = 0,
INFO,
#define OCLog(level,tag,mes) LOG_(LOG_ID_MAIN, (level), (tag), mes)
#define OCLogv(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, (level),tag,fmt,##args)
-#elif defined(ANDROID) || defined(__linux__) || defined(__APPLE__)
+#elif !defined(ARDUINO)
/**
* Configure logger to use a context that defines a custom logger function
*
#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
OCLogBuffer((level), (tag), (buffer), (bufferSize))
-#else // These macros are defined for Linux, Android, and Arduino
+#else // These macros are defined for Linux, Android, Win32, and Arduino
#define OIC_LOG_INIT() OCLogInit()
#define OIC_LOG_CONFIG(ctx) OCLogConfig((ctx))
#define OIC_LOG_SHUTDOWN() OCLogShutdown()
#define OIC_LOG(level, tag, logStr) OCLog((level), (tag), (logStr))
-// Define variable argument log function for Linux and Android
+// Define variable argument log function for Linux, Android, and Win32
#define OIC_LOG_V(level, tag, ...) OCLogv((level), (tag), __VA_ARGS__)
#endif //ARDUINO
#define _POSIX_C_SOURCE 200809L
#endif
-// Platform check can be extended to check and/or define more, or could be
-// moved into a config.h
-#if !defined(__ARDUINO__) && !defined(ARDUINO)
-#define HAVE_UNISTD_H 1
-#endif
-
// Pull in _POSIX_TIMERS feature test macro to check for
// clock_gettime() support.
#ifdef HAVE_UNISTD_H
#include <unistd.h>
-
-// if we have unistd.h, we're a Unix system
+#endif
#include <time.h>
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include "logger.h"
#include "string.h"
#include "logger_types.h"
+#include "platform_features.h"
#ifndef __TIZEN__
static oc_log_ctx_t *logCtx = 0;
#endif
+
+#if defined(_MSC_VER)
+#define LINE_BUFFER_SIZE (16 * 2) + 16 + 1 // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#else
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+#endif //defined(_MSC_VER)
+
#ifdef __ANDROID__
-#elif defined __linux__ || defined __APPLE__
+#elif defined __linux__ || defined __APPLE__ || defined _WIN32
static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO,
OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL};
#endif
-// Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
-
// Convert LogLevel to platform-specific severity level. Store in PROGMEM on Arduino
#ifdef __ANDROID__
#ifdef ADB_SHELL
static android_LogPriority LEVEL[] =
{ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
#endif
-#elif defined (__linux__) || defined (__APPLE__)
- static const char *LEVEL[] __attribute__ ((unused)) =
- {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(__linux__) || defined(__APPLE__) || defined(__msys_nt__)
+ static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined(_MSC_VER)
+ static const char * LEVEL[] = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
#elif defined ARDUINO
#include <stdarg.h>
#include "Arduino.h"
#else
#define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';}
#endif
-#endif // __ANDROID__
+#else // !defined(__ANDROID__) && !defined(ARDUINO)
+ static const char *LEVEL[] __attribute__ ((unused)) =
+ {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#endif
#ifndef ARDUINO
void OCLogShutdown()
{
-#if defined(__linux__) || defined(__APPLE__)
+#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
if (logCtx && logCtx->destroy)
{
logCtx->destroy(logCtx);
if (!format || !tag) {
return;
}
- char buffer[MAX_LOG_V_BUFFER_SIZE] = {};
+ char buffer[MAX_LOG_V_BUFFER_SIZE] = {0};
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof buffer - 1, format, args);
__android_log_write(LEVEL[level], tag, logStr);
#endif
- #elif defined __linux__ || defined __APPLE__
+ #else
if (logCtx && logCtx->write_level)
{
logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr);
sec = when.tv_sec % 60;
ms = when.tv_nsec / 1000000;
}
+ #elif defined(_WIN32)
+ SYSTEMTIME systemTime = {0};
+ GetLocalTime(&systemTime);
+ min = (int)systemTime.wMinute;
+ sec = (int)systemTime.wSecond;
+ ms = (int)systemTime.wMilliseconds;
#else
struct timeval now;
if (!gettimeofday(&now, NULL))
OIC_LOG_V(DEBUG, RM_TAG, "createoption dlen %u slen [%u]", dLen, sLen);
unsigned int totalLength = 0;
+#if defined(_MSC_VER)
+ char *tempData = NULL;
+#else
void *tempData = NULL;
+#endif
if (0 == dLen && 0 == sLen)
{
OIC_LOG(DEBUG, RM_TAG, "Source and destination is not present");
##
Import('env')
+import os
lib_env = env.Clone()
SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
if target_os not in ['arduino', 'windows', 'winrt']:
libocsrm_env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
- libocsrm_env.AppendUnique(CFLAGS = ['-std=c99'])
- libocsrm_env.AppendUnique(CPPDEFINES = ['HAVE_STRINGS_H'])
-
-if target_os not in ['windows', 'winrt']:
- libocsrm_env.AppendUnique(CFLAGS = ['-Wall'])
+ libocsrm_env.AppendUnique(CFLAGS = ['-std=c99', '-Wall'])
libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-libocsrm_env.AppendUnique(LIBS = ['coap', 'm'])
+libocsrm_env.AppendUnique(LIBS = ['coap'])
if target_os == 'arduino':
libocsrm_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO'])
-else:
+elif target_os not in ['windows', 'msys_nt']:
libocsrm_env.AppendUnique(CFLAGS = ['-fPIC'])
+ libocsrm_env.AppendUnique(LIBS = ['m'])
+
+if target_os in ['windows', 'msys_nt']:
+ libocsrm_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
if target_os in ['darwin', 'ios']:
libocsrm_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
libocsrm_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
libocsrm_env.AppendUnique(LIBS = ['coap'])
-if not env.get('RELEASE'):
+if env.get('LOGGING'):
libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
if env.get('DTLS_WITH_X509') == '1':
# Source files and Targets
######################################################################
OCSRM_SRC = 'src/'
+libocsrm_src = [
+ OCSRM_SRC + 'secureresourcemanager.c',
+ OCSRM_SRC + 'resourcemanager.c',
+ OCSRM_SRC + 'aclresource.c',
+ OCSRM_SRC + 'verresource.c',
+ OCSRM_SRC + 'amaclresource.c',
+ OCSRM_SRC + 'amsmgr.c',
+ OCSRM_SRC + 'pstatresource.c',
+ OCSRM_SRC + 'doxmresource.c',
+ OCSRM_SRC + 'credresource.c',
+ OCSRM_SRC + 'svcresource.c',
+ OCSRM_SRC + 'pconfresource.c',
+ OCSRM_SRC + 'dpairingresource.c',
+ OCSRM_SRC + 'policyengine.c',
+ OCSRM_SRC + 'psinterface.c',
+ OCSRM_SRC + 'srmresourcestrings.c',
+ OCSRM_SRC + 'srmutility.c',
+ OCSRM_SRC + 'iotvticalendar.c',
+ OCSRM_SRC + 'base64.c',
+ OCSRM_SRC + 'directpairing.c'
+ ]
+
if env.get('SECURED') == '1':
- libocsrm_src = [
- OCSRM_SRC + 'secureresourcemanager.c',
- OCSRM_SRC + 'resourcemanager.c',
- OCSRM_SRC + 'aclresource.c',
- OCSRM_SRC + 'amaclresource.c',
- OCSRM_SRC + 'amsmgr.c',
- OCSRM_SRC + 'pstatresource.c',
- OCSRM_SRC + 'doxmresource.c',
- OCSRM_SRC + 'credresource.c',
- OCSRM_SRC + 'svcresource.c',
- OCSRM_SRC + 'pconfresource.c',
- OCSRM_SRC + 'dpairingresource.c',
- OCSRM_SRC + 'verresource.c',
- OCSRM_SRC + 'policyengine.c',
- OCSRM_SRC + 'psinterface.c',
- OCSRM_SRC + 'srmresourcestrings.c',
- OCSRM_SRC + 'srmutility.c',
- OCSRM_SRC + 'iotvticalendar.c',
- OCSRM_SRC + 'oxmpincommon.c',
- OCSRM_SRC + 'base64.c',
- #pbkdf2.c is required to PIN based OxM only.
- #But we did not use a separate build options to prevent the build command becomes complicated.
- OCSRM_SRC + 'pbkdf2.c',
- OCSRM_SRC + 'directpairing.c'
- ]
-else:
- libocsrm_src = [
- OCSRM_SRC + 'secureresourcemanager.c',
- OCSRM_SRC + 'resourcemanager.c',
- OCSRM_SRC + 'aclresource.c',
- OCSRM_SRC + 'amaclresource.c',
- OCSRM_SRC + 'amsmgr.c',
- OCSRM_SRC + 'pstatresource.c',
- OCSRM_SRC + 'doxmresource.c',
- OCSRM_SRC + 'credresource.c',
- OCSRM_SRC + 'svcresource.c',
- OCSRM_SRC + 'pconfresource.c',
- OCSRM_SRC + 'dpairingresource.c',
- OCSRM_SRC + 'policyengine.c',
- OCSRM_SRC + 'verresource.c',
- OCSRM_SRC + 'psinterface.c',
- OCSRM_SRC + 'srmresourcestrings.c',
- OCSRM_SRC + 'srmutility.c',
- OCSRM_SRC + 'iotvticalendar.c',
- OCSRM_SRC + 'base64.c',
- OCSRM_SRC + 'directpairing.c'
- ]
+ libocsrm_src = libocsrm_src + [OCSRM_SRC + 'oxmpincommon.c', OCSRM_SRC + 'pbkdf2.c']
+
+if target_os in ['windows', 'msys_nt']:
+ libocsrm_src = libocsrm_src + [OCSRM_SRC + 'strptime.c']
if env.get('DTLS_WITH_X509') == '1' and env.get('SECURED') == '1':
crl_src = [OCSRM_SRC + 'crlresource.c']
libocsrm_src = libocsrm_src + crl_src
+libocsrm_conf = Configure(libocsrm_env)
+if libocsrm_conf.CheckFunc('strptime'):
+ libocsrm_conf.env.AppendUnique(CPPDEFINES = ['HAVE_STRPTIME'])
+libocsrm_env = libocsrm_conf.Finish()
-libocsrm = libocsrm_env.StaticLibrary('libocsrm', libocsrm_src)
+libocsrm = libocsrm_env.StaticLibrary('ocsrm', libocsrm_src)
-libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
+libocsrm_env.InstallTarget(libocsrm, 'ocsrm')
-if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
+if target_os in ['linux', 'android', 'tizen', 'msys_nt', 'windows'] and env.get('SECURED') == '1':
SConscript('provisioning/SConscript')
if target_os in ['linux'] and env.get('SECURED') == '1':
#ifndef IOTVT_SRM_RSRC_STRINGS_H
#define IOTVT_SRM_RSRC_STRINGS_H
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "securevirtualresourcetypes.h"
extern const char * SVR_DB_FILE_NAME;
//Security Version
extern const char * DEFAULT_SEC_VERSION;
+#ifdef __cplusplus
+}
+#endif
+
#endif //IOTVT_SRM_RSRC_STRINGS_H
#include "byte_array.h"
#endif /* __WITH_X509__ */
+#include "platform_features.h"
+
#ifdef __cplusplus
extern "C" {
#endif
/**
* Extract Reason Code from Access Response.
*/
-static inline SRMAccessResponseReasonCode_t GetReasonCode(
+INLINE_API SRMAccessResponseReasonCode_t GetReasonCode(
SRMAccessResponse_t response)
{
SRMAccessResponseReasonCode_t reason =
/**
* Returns 'true' iff request should be passed on to RI layer.
*/
-static inline bool IsAccessGranted(SRMAccessResponse_t response)
+INLINE_API bool IsAccessGranted(SRMAccessResponse_t response)
{
if(ACCESS_GRANTED == (response & ACCESS_GRANTED))
{
{
// <Attribute ID>:<Read/Write>:<Multiple/Single>:<Mandatory?>:<Type>
//TODO fill in from OIC Security Spec
+#if defined(_MSC_VER)
+ uint8_t unused; // VS doesn't like empty structs
+#endif
};
/**
if target_os != 'tizen':
provisioning_env.AppendUnique(CPPPATH = ['../../../../extlibs/sqlite3'])
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__'])
-provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
-if target_os not in ['windows', 'winrt']:
- provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-D__WITH_DTLS__'])
+provisioning_env.AppendUnique(CPPDEFINES= ['__WITH_DTLS__'])
+if target_os not in ['windows']:
+ provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+if target_os not in ['windows', 'msys_nt']:
+ provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
# Note: 'pthread' is in libc for android. On other platform, if use
# new gcc(>4.9?) it isn't required, otherwise, it's required
if target_os != 'android':
provisioning_env.AppendUnique(LIBS = ['-lpthread', '-ldl'])
+provisioning_conf = Configure(provisioning_env)
+if provisioning_conf.CheckFunc('clock_gettime'):
+ provisioning_conf.env.AppendUnique(CPPDEFINES = ['HAVE_CLOCK_GETTIME'])
+if provisioning_conf.CheckFunc('GetSystemTimeAsFileTime') or target_os == 'windows':
+ # TODO: Remove target_os check.
+ # We currently check for 'windows' as well, because the environment can
+ # sometimes get so polluted that CheckFunc ceases to work!
+ provisioning_conf.env.AppendUnique(CPPDEFINES = ['HAVE_GETSYSTEMTIMEASFILETIME'])
+provisioning_env = provisioning_conf.Finish()
provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
if env.get('DTLS_WITH_X509') == '1':
provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
-if target_os != 'android':
+if target_os not in ['msys_nt', 'windows', 'android']:
provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
+if target_os in ['windows', 'msys_nt']:
+ provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi', 'timer'])
+
if target_os == 'tizen':
provisioning_env.ParseConfig('pkg-config --cflags --libs sqlite3')
if target_os != 'tizen':
provisioning_src = provisioning_src + [root_dir+'/extlibs/sqlite3/sqlite3.c' ]
-provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
+if target_os == 'windows':
+ # TODO: Add OC_EXPORT annotations and enable generation of Windows DLL
+ provisioningserver = provisioning_env.StaticLibrary('ocpmapi', provisioning_src)
+else:
+ provisioningserver = provisioning_env.SharedLibrary('ocpmapi', provisioning_src)
-provisioning_env.InstallTarget(provisioningserver, 'libocpmapi')
-provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
+provisioning_env.InstallTarget(provisioningserver, 'ocpmapi')
+provisioning_env.UserInstallTargetLib(provisioningserver, 'ocpmapi')
if env.get('DTLS_WITH_X509') == '1':
SConscript('ck_manager/SConscript')
-if target_os in ['linux']:
+if target_os in ['linux', 'msys_nt', 'windows']:
SConscript('sample/SConscript')
#
Import('env')
+import os.path
provisioning_env = env.Clone()
'../../../connectivity/api'
])
-provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__','-std=c99'])
-provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+target_os = env.get('TARGET_OS')
provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-provisioning_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
-provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap'])
+provisioning_env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+
+if target_os not in ['windows']:
+ provisioning_env.AppendUnique(CFLAGS = ['-std=c99'])
+ provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+ provisioning_env.AppendUnique(LIBS = ['-lpthread'])
+
+if target_os not in ['msys_nt', 'windows']:
+ provisioning_env.AppendUnique(LIBS = ['-ldl', 'm'])
+ provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
+ provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+else:
+ provisioning_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ provisioning_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32', 'timer'])
+
+provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm', 'octbstack', 'connectivity_abstraction', 'coap'])
if env.get('SECURED') == '1':
provisioning_env.AppendUnique(LIBS = ['tinydtls'])
if env.get('DTLS_WITH_X509') == '1':
provisioning_env.AppendUnique(LIBS = ['CKManager'])
provisioning_env.AppendUnique(LIBS = ['asn1'])
-provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
#include <stdio.h>
#include <string.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#include "platform_features.h"
#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include <signal.h>
#include "ocstack.h"
-#include "logger.h"
#include "ocpayload.h"
+#include "pinoxmcommon.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
#define TAG "SAMPLE_JUSTWORKS"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
-#include <signal.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include <signal.h>
#include "ocstack.h"
-#include "logger.h"
#include "ocpayload.h"
#include "pinoxmcommon.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
#define TAG "SAMPLE_RANDOMPIN"
int gQuitFlag = 0;
#define _POSIX_C_SOURCE 200809L
#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
#include <stdbool.h>
#include <string.h>
#define _POSIX_C_SOURCE 200112L
#endif
+#if HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
+#ifdef HAVE_TIME_H
#include <time.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
#include "ocstack.h"
#include "oic_malloc.h"
*/
OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
{
+ OCStackResult res = OC_STACK_OK;
+#if defined(HAVE_GETSYSTEMTIMEASFILETIME)
+ FILETIME startTime = {0};
+ FILETIME currTime = {0};
+ int clock_res = 1;
+
+ GetSystemTimeAsFileTime(&startTime);
+#elif defined(HAVE_CLOCK_GETTIME)
struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
struct timespec currTime = {.tv_sec=0, .tv_nsec=0};
- OCStackResult res = OC_STACK_OK;
-#ifdef _POSIX_MONOTONIC_CLOCK
+# if defined(_POSIX_MONOTONIC_CLOCK)
int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
-#else
+# else
int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
+# endif // defined(_POSIX_MONOTONIC_CLOCK)
+
+#else
+ ERROR Need PMTimeout implementation
+ return OC_STACK_ERROR;
#endif
+
if (0 != clock_res)
{
return OC_STACK_ERROR;
}
while (OC_STACK_OK == res)
{
-#ifdef _POSIX_MONOTONIC_CLOCK
+#if defined(HAVE_GETSYSTEMTIMEASFILETIME)
+ GetSystemTimeAsFileTime(&currTime);
+#elif defined(HAVE_CLOCK_GETTIME)
+
+# if defined(_POSIX_MONOTONIC_CLOCK)
clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
-#else
+# else
clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
-#endif
+# endif
if (0 != clock_res)
{
return OC_STACK_TIMEOUT;
}
+#else
+ ERROR Need PMTimeout implementation
+#endif
+
+#if defined(HAVE_GETSYSTEMTIMEASFILETIME)
+#define HNS_TO_S(VAL) ((VAL)/(10*1000*1000))
+ ULARGE_INTEGER currTimeInt;
+ ULARGE_INTEGER startTimeInt;
+
+ currTimeInt.LowPart = currTime.dwLowDateTime;
+ currTimeInt.HighPart = currTime.dwHighDateTime;
+
+ startTimeInt.LowPart = startTime.dwLowDateTime;
+ startTimeInt.HighPart = startTime.dwHighDateTime;
+
+ long elapsed = (long)HNS_TO_S(currTimeInt.QuadPart - startTimeInt.QuadPart);
+#elif defined(HAVE_CLOCK_GETTIME)
long elapsed = (currTime.tv_sec - startTime.tv_sec);
+#else
+ ERROR Need PMTimeout implementation
+#endif
if (elapsed > waittime)
{
return OC_STACK_OK;
}
bool PMGenerateQuery(bool isSecure,
- const char* address, const uint16_t port,
- const OCConnectivityType connType,
+ const char* address, uint16_t port,
+ OCConnectivityType connType,
char* buffer, size_t bufferSize, const char* uri)
{
if(!address || !buffer || !uri)
#include <stdio.h>
#include <string.h>
#include <stdint.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include "ocprovisioningmanager.h"
#include "secureresourceprovider.h"
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
#include <string.h>
-#else
+#elif HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdlib.h>
OCStackResult ret = OC_STACK_ERROR;
const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
OCCallbackData cbData = {.context=NULL};
VERIFY_NON_NULL(TAG, context, ERROR);
return OC_STACK_KEEP_TRANSACTION;
}
- OicUuid_t deviceId = {.id={}};
+ OicUuid_t deviceId = {.id={0}};
memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
OICFree(doxm);
const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
OCCallbackData cbData = {.context=NULL};
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
snprintf(uri, sizeof(uri), RES_DOXM_QUERY_FMT, OC_RSRVD_WELL_KNOWN_URI,
OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
{
OCStackResult ret = OC_STACK_ERROR;
const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
- char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+ char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {0};
uint32_t outLen = 0;
- char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
+ char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
OCCallbackData cbData = {.context=NULL};
OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
B64Result b64Ret;
void ProcessAMSRequest(PEContext_t *context)
{
- OicUuid_t emptyUuid = {.id={}};
+ OicUuid_t emptyUuid = {.id={0}};
OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
if (NULL != context)
{
#define __STDC_LIMIT_MACROS
#include <stdlib.h>
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
#include <string.h>
-#else
+#endif
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <stdint.h>
case CA_DTLS_PSK_HINT:
case CA_DTLS_PSK_IDENTITY:
{
- OicUuid_t deviceID = {.id={}};
+ OicUuid_t deviceID = {.id={0}};
// Retrieve Device ID from doxm resource
if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
{
#ifndef _POSIX_C_SOURCE\r
#define _POSIX_C_SOURCE 200112L\r
#endif\r
-#ifndef WITH_ARDUINO\r
+#ifdef HAVE_UNISTD_H\r
#include <unistd.h>\r
+#endif\r
+#ifdef HAVE_TIME_H\r
#include <time.h>\r
+#endif\r
+#ifdef HAVE_SYS_TIME_H\r
#include <sys/time.h>\r
#endif\r
+#ifdef HAVE_STRING_H\r
#include <string.h>\r
+#endif\r
\r
#include "ocstack.h"\r
#include "oic_malloc.h"\r
}\r
\r
OCStackResult ret;\r
- struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
- struct timespec currTime = {.tv_sec=0, .tv_nsec=0};\r
- struct timespec timeout;\r
\r
const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf";\r
\r
}\r
\r
// wait..\r
- timeout.tv_sec = 0;\r
- timeout.tv_nsec = 100000000L;\r
\r
int clock_res = -1;\r
+#if defined(_MSC_VER)\r
+ time_t startTime;\r
+ clock_res = (time(&startTime) == -1);\r
+#else\r
+ struct timespec startTime = {.tv_sec=0, .tv_nsec=0};\r
#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);\r
#endif\r
+#endif\r
if (0 != clock_res)\r
{\r
OIC_LOG(ERROR, TAG, "clock error");\r
\r
while (1)\r
{\r
+#if defined(_MSC_VER)\r
+ time_t currTime;\r
+ clock_res = (time(&currTime) == -1);\r
+#else\r
+ struct timespec currTime = {.tv_sec=0, .tv_nsec=0};\r
#if defined(__ANDROID__) || _POSIX_TIMERS > 0\r
clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);\r
#endif\r
+#endif\r
if (0 != clock_res)\r
{\r
OIC_LOG(ERROR, TAG, "clock error");\r
ret = OC_STACK_ERROR;\r
break;\r
}\r
+#if defined(_MSC_VER)\r
+ long elapsed = currTime - startTime;\r
+#else\r
long elapsed = (currTime.tv_sec - startTime.tv_sec);\r
+#endif\r
if (elapsed > waittime)\r
{\r
break;\r
}\r
else\r
{\r
+ struct timespec timeout = {.tv_sec=0, .tv_nsec=100000000L};\r
nanosleep(&timeout, NULL);\r
}\r
}\r
\r
- //Waiting for each response.\r
+ // Waiting for each response.\r
ret = OCCancel(handle, OC_LOW_QOS, NULL, 0);\r
if (OC_STACK_OK != ret)\r
{\r
#include "ocpayload.h"
#include "payload_logging.h"
#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//Not supported on Arduino due lack of absolute time need to implement iCalendar
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
#define _XOPEN_SOURCE //Needed by strptime
#include <string.h>
#include "iotvticalendar.h"
#include "oic_string.h"
+#ifndef HAVE_STRPTIME
+char *strptime(const char *buf, const char *fmt, struct tm *tm);
+#endif
+
static char dtFormat[] = "%Y%m%dT%H%M%S"; //date-time format
static char dFormat[] = "%Y%m%d"; // date format
static const char BYDAY[] = "BYDAY";
static const char DAILY[] = "DAILY";
+/**
+ * Parses periodStr and populate struct IotvtICalPeriod_t
+ *
+ * @param periodStr string to be parsed.
+ * @param period IotvtICalPeriod_t struct to be populated.
+ *
+ * @return IOTVTICAL_INVALID_PARAMETER -- if parameter are invalid
+ * IOTVTICAL_INVALID_PERIOD -- if period string has invalid format
+ * IOTVTICAL_INVALID_SUCCESS -- if no error while parsing
+ */
IotvtICalResult_t ParsePeriod(const char *periodStr, IotvtICalPeriod_t *period)
{
if ((NULL == periodStr) || (NULL == period))
#include <string.h>
#include <math.h>
+#include "platform_features.h"
#include "pbkdf2.h"
#include "hmac.h"
#include "debug.h"
#include <stdlib.h>
#include "psinterface.h"
#include "security_internals.h"
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
+#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
return retVal;
}
-inline static bool IsRequestSubjectEmpty(PEContext_t *context)
+INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
{
- OicUuid_t emptySubject = {.id={}};
+ OicUuid_t emptySubject = {.id={0}};
if(NULL == context)
{
*
* @return true if 'permission' bits include all 'request' bits.
*/
-static inline bool IsPermissionAllowingRequest(const uint16_t permission,
+INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
const uint16_t request)
{
if (request == (request & permission))
*
* @return true if 'subject' is the wildcard, false if it is not.
*/
-static inline bool IsWildCardSubject(OicUuid_t *subject)
+INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
{
if(NULL == subject)
{
// Else request is a "normal" request that must be tested against ACL
else
{
- OicUuid_t saveSubject = {.id={}};
+ OicUuid_t saveSubject = {.id={0}};
bool isSubEmpty = IsRequestSubjectEmpty(context);
ProcessAccessRequest(context);
#define TAG "SRM-PSI"
//SVR database buffer block size
+#ifdef _WIN32
+#define DB_FILE_SIZE_BLOCK 1023
+#else
const size_t DB_FILE_SIZE_BLOCK = 1023;
+#endif
/**
* Gets the Secure Virtual Database size
if (IsAccessGranted(response) && gRequestHandler)
{
- return (gRequestHandler(endPoint, requestInfo));
+ gRequestHandler(endPoint, requestInfo);
+ return;
}
// Form a 'Error', 'slow response' or 'access deny' response and send to peer
void SRMDeInitPolicyEngine()
{
- return DeInitPolicyEngine(&g_policyEngineContext);
+ DeInitPolicyEngine(&g_policyEngineContext);
}
bool SRMIsSecurityResourceURI(const char* uri)
do
{
- unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+ unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {0};
uint32_t outLen = 0;
B64Result b64Ret = B64_OK;
--- /dev/null
+/** @todo: Add Microsoft copyright */
+#include <stdio.h>
+#include <ctype.h>
+#include <time.h>
+#include <memory.h>
+#include <stdbool.h>
+
+#define TM_BASE_YEAR 1900
+
+static const int ydays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+
+bool is_leap_year(int yy)
+{
+ int yyyy = yy + TM_BASE_YEAR;
+
+ bool bLeap = false;
+ if (yyyy % 100 == 0)
+ {
+ return yyyy % 400 == 0;
+ }
+ return yyyy % 4 == 0;
+}
+
+
+char * strptime(const char *buf, const char *fmt, struct tm *tm)
+{
+ char c;
+ int temp = 0;
+
+ //initialize the tm struct values
+ memset(tm, 0, sizeof(struct tm));
+ tm->tm_mday = 1;
+
+ while (buf && (c = *fmt++))
+ {
+ temp = 0;
+ if (c == '%')
+ {
+ switch (c = *fmt++)
+ {
+ case '%':
+ if (c != *buf++)
+ {
+ return NULL;
+ }
+ break;
+
+ case 'd': /* day of the month (1..31)*/
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 1 && temp <= 31)
+ {
+ tm->tm_mday = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'H': /* hour (0..23) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 23)
+ {
+ tm->tm_hour = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'M': /* minute (0..59) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 59)
+ {
+ tm->tm_min = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'm': /* month (1..12) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 1 && temp <= 12)
+ {
+ tm->tm_mon = temp - 1;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'S': /* seconds (0..59) */
+ sscanf(buf, "%2d", &temp);
+ if (temp >= 0 && temp <= 59)
+ {
+ tm->tm_sec = temp;
+ buf += 2;
+ }
+ else
+ return NULL;
+ break;
+
+ case 'Y': /* year */
+ sscanf(buf, "%4d", &temp);
+ if (temp >= 0 && temp <= 9999)
+ {
+ tm->tm_year = temp - TM_BASE_YEAR;
+ buf += 4;
+ }
+ else
+ return NULL;
+ break;
+
+ default:
+ return NULL;
+ }
+ }
+ else
+ {
+ if (c != *buf++)
+ return NULL;
+ }
+ }
+
+ //calculate tm_wday and tm_yday
+ tm->tm_yday = ydays[tm->tm_mon] + ((is_leap_year(tm->tm_year) && (tm->tm_mon >= 2)) ? 1 : 0) + tm->tm_mday - 1;
+
+ //1st Jan 1900 was Monday, hence weekday = the number of days from 1/1/1900 modulus 7 + 1
+ tm->tm_wday = (365 * tm->tm_year) + (tm->tm_year / 4) + tm->tm_yday + 1; //1st Jan 1900 was Monday, hence add 1
+ if (is_leap_year(tm->tm_year))
+ tm->tm_wday--;
+ tm->tm_wday %= 7;
+
+ return (char*)buf;
+}
srmtest_env = env.Clone()
src_dir = srmtest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
'gtest_main'])
if env.get('SECURED') == '1':
- srmtest_env.AppendUnique(LIBS = ['tinydtls'])
+ srmtest_env.AppendUnique(LIBS = ['tinydtls', 'timer'])
-if not env.get('RELEASE'):
+if env.get('LOGGING'):
srmtest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os == 'windows':
+ srmtest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ srmtest_env.AppendUnique(LIBS = ['advapi32', 'kernel32', 'ws2_32', 'iphlpapi'])
+else:
+ # TODO: Implement feature check.
+ srmtest_env.AppendUnique(CPPDEFINES = ['HAVE_LOCALTIME_R'])
+
######################################################################
# Source files and Targets
######################################################################
Alias("test", [unittest])
unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
+unittest_build_dir = os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'security', 'unittest') + os.sep
-srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
+srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir.encode('string_escape')])
srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
unittest_src_dir + 'oic_unittest.json'))
env.AppendTarget('test')
if env.get('TEST') == '1':
target_os = env.get('TARGET_OS')
- if target_os == 'linux':
+ if target_os in ['linux', 'windows']:
out_dir = env.get('BUILD_DIR')
result_dir = env.get('BUILD_DIR') + '/test_out/'
if not os.path.isdir(result_dir):
os.makedirs(result_dir)
srmtest_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir])
srmtest_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir])
+ srmtest_env.AppendENVPath('PATH', [os.path.join(out_dir, 'resource', 'csdk')])
srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
AlwaysBuild ('ut')
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
#include <sys/stat.h>
#include "ocstack.h"
#include "psinterface.h"
#define TAG "SRM-ACL-UT"
// These paths match jenkins build configuration.
-const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
-const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
+const char* DEFAULT_ACL_FILE_NAME = "oic_unittest_default_acl.dat";
+const char* ACL1_FILE_NAME = "oic_unittest_acl1.dat";
#define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
DeleteACLList(acl);
}
+extern "C" {
+ // gAcl is a pointer to the the global ACL used by SRM
+ extern OicSecAcl_t *gAcl;
+}
+
// GetACLResource tests
TEST(ACLResourceTest, GetACLResourceTests)
{
}
}
+#ifndef HAVE_LOCALTIME_R
+
+#define localtime_r localtime_r_compat
+
+/**
+ * @description An implementation of `localtime_r` for systems which only
+ * have a `localtime` implementation.
+ */
+static tm* localtime_r_compat(const time_t* timer, tm* result)
+{
+ if (NULL == result)
+ {
+ OIC_LOG(ERROR, TAG, "localtime_r received null results parameter");
+ }
+
+ if (NULL == timer)
+ {
+ OIC_LOG(WARNING, TAG, "localtime_r received null timer parameter");
+ }
+
+ tm* tempPtr = localtime(timer);
+ memcpy(result, tempPtr, sizeof(tm));
+ return result;
+}
+#endif
static void checkValidityOfRequest(char *recurStr, char *periodStr,int startTime, int endTime,
int byDay)
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
#include "ocstack.h"
#include "cainterface.h"
#include "srmresourcestrings.h"
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include "gtest/gtest.h"
#include "ocpayload.h"
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "gtest/gtest.h"
+#ifdef HAVE_PWD_H
#include <pwd.h>
+#endif
+#ifdef HAVE_GRP_H
#include <grp.h>
+#endif
+#ifdef HAVE_LINUX_LIMITS_H
#include <linux/limits.h>
+#endif
#include "ocstack.h"
#include "cainterface.h"
#include "secureresourcemanager.h"
EXPECT_TRUE(&gpsi == ps);
}
+#if !(defined(HAVE_LINUX_LIMITS_H) && defined(HAVE_PWD_H))
+TEST(PersistentStorageHandlerTest, DISABLED_PersistentStorageValidHandlers)
+{
+ /** @todo: Implement test on non-Linux platform */
+}
+#else
TEST(PersistentStorageHandlerTest, PersistentStorageValidHandlers)
{
OCPersistentStorage *psi = SRMGetPersistentStorageHandler();
}
psi->unlink(outFilePath);
}
+#endif
+
#define STRINGIZE(x) STRINGIZE2(x)
// TODO: Remove this, once all cbor related are completed.
-char* ReadFile(const char* filename)
+char* ReadFileToBuffer(const char* filename)
{
FILE *fp = NULL;
#ifndef IOTVT_SRM_TEST_COMMON_H
#define IOTVT_SRM_TEST_COMMON_H
-char* ReadFile(const char* filename);
+char* ReadFileToBuffer(const char* filename);
bool ReadCBORFile(const char* filename, const char* rsrcName, uint8_t **payload, size_t *size);
void SetPersistentHandler(OCPersistentStorage *ps, bool set);
extern "C"
{
#endif
-OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
+OC_EXPORT_TEST OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType type,
const uint8_t* payload, size_t payloadSize);
-OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
+OC_EXPORT_TEST OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t* size);
#ifdef __cplusplus
}
OCResourceProperty resourceProperties, uint8_t enable);
#endif
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out);
typedef struct OCResource OCResource;
-void OCPayloadDestroy(OCPayload* payload);
+OC_EXPORT void OCPayloadDestroy(OCPayload* payload);
// Representation Payload
-OCRepPayload* OCRepPayloadCreate();
+OC_EXPORT OCRepPayload* OCRepPayloadCreate();
-size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+OC_EXPORT size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
+OC_EXPORT OCRepPayload* OCRepPayloadClone(const OCRepPayload* payload);
-void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
+OC_EXPORT void OCRepPayloadAppend(OCRepPayload* parent, OCRepPayload* child);
-bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
+OC_EXPORT bool OCRepPayloadSetUri(OCRepPayload* payload, const char* uri);
-bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceType(OCRepPayload* payload, const char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface);
-bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface);
+OC_EXPORT bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceType);
+OC_EXPORT bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface);
-bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
-bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadIsNull(const OCRepPayload* payload, const char* name);
+OC_EXPORT bool OCRepPayloadSetNull(OCRepPayload* payload, const char* name);
-bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
-bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
+OC_EXPORT bool OCRepPayloadSetPropInt(OCRepPayload* payload, const char* name, int64_t value);
+OC_EXPORT bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64_t* value);
-bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
-bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
+OC_EXPORT bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
+OC_EXPORT bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
/**
* This function allocates memory for the byte string and sets it in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
+OC_EXPORT bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
/**
* This function sets the byte string in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
OCByteString* value);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
OCByteString* value);
-bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
-bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
-bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
+OC_EXPORT bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
+OC_EXPORT bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
+OC_EXPORT bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
-bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
-bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
+OC_EXPORT bool OCRepPayloadSetPropBool(OCRepPayload* payload, const char* name, bool value);
+OC_EXPORT bool OCRepPayloadGetPropBool(const OCRepPayload* payload, const char* name, bool* value);
-bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
-bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name,
- OCRepPayload* value);
-bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
+OC_EXPORT bool OCRepPayloadSetPropObject(OCRepPayload* payload, const char* name, const OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name, OCRepPayload* value);
+OC_EXPORT bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
/**
* This function allocates memory for the byte string array and sets it in the payload.
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
/**
*
* @return true on success, false upon failure.
*/
-bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
const int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetIntArray(const OCRepPayload* payload, const char* name,
int64_t** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArrayAsOwner(OCRepPayload* payload, const char* name,
double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetDoubleArray(OCRepPayload* payload, const char* name,
const double* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetDoubleArray(const OCRepPayload* payload, const char* name,
double** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArrayAsOwner(OCRepPayload* payload, const char* name,
char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetStringArray(OCRepPayload* payload, const char* name,
const char** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetStringArray(const OCRepPayload* payload, const char* name,
char*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArrayAsOwner(OCRepPayload* payload, const char* name,
bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetBoolArray(OCRepPayload* payload, const char* name,
const bool* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetBoolArray(const OCRepPayload* payload, const char* name,
bool** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArrayAsOwner(OCRepPayload* payload, const char* name,
OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadSetPropObjectArray(OCRepPayload* payload, const char* name,
const OCRepPayload** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
+OC_EXPORT bool OCRepPayloadGetPropObjectArray(const OCRepPayload* payload, const char* name,
OCRepPayload*** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
-void OCRepPayloadDestroy(OCRepPayload* payload);
+OC_EXPORT void OCRepPayloadDestroy(OCRepPayload* payload);
// Discovery Payload
-OCDiscoveryPayload* OCDiscoveryPayloadCreate();
+OC_EXPORT OCDiscoveryPayload* OCDiscoveryPayloadCreate();
-OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
-void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
+OC_EXPORT OCSecurityPayload* OCSecurityPayloadCreate(const uint8_t* securityData, size_t size);
+OC_EXPORT void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
-void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
+OC_EXPORT void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
uint16_t securePort, uint16_t tcpPort);
-void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
-bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
+OC_EXPORT void OCDiscoveryPayloadAddNewResource(OCDiscoveryPayload* payload, OCResourcePayload* res);
+OC_EXPORT bool OCResourcePayloadAddStringLL(OCStringLL **payload, const char* type);
-size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
-OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
+OC_EXPORT size_t OCDiscoveryPayloadGetResourceCount(OCDiscoveryPayload* payload);
+OC_EXPORT OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, size_t index);
-void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
-void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
+OC_EXPORT void OCDiscoveryResourceDestroy(OCResourcePayload* payload);
+OC_EXPORT void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
// Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
+OC_EXPORT OCDevicePayload* OCDevicePayloadCreate(const char* sid, const char* dname,
const OCStringLL *types, const char* specVer, const char* dmVer);
-void OCDevicePayloadDestroy(OCDevicePayload* payload);
+OC_EXPORT void OCDevicePayloadDestroy(OCDevicePayload* payload);
// Platform Payload
-OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
-void OCPlatformInfoDestroy(OCPlatformInfo *info);
-void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
+OC_EXPORT OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
+OC_EXPORT void OCPlatformInfoDestroy(OCPlatformInfo *info);
+OC_EXPORT void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
// Presence Payload
-OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
+OC_EXPORT OCPresencePayload* OCPresencePayloadCreate(uint32_t seqNum, uint32_t maxAge,
OCPresenceTrigger trigger, const char* resourceType);
-void OCPresencePayloadDestroy(OCPresencePayload* payload);
+OC_EXPORT void OCPresencePayloadDestroy(OCPresencePayload* payload);
// Helper API
-OCStringLL* CloneOCStringLL (OCStringLL* ll);
-void OCFreeOCStringLL(OCStringLL* ll);
+OC_EXPORT OCStringLL* CloneOCStringLL (OCStringLL* ll);
+OC_EXPORT void OCFreeOCStringLL(OCStringLL* ll);
#ifdef __cplusplus
}
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
+OC_EXPORT OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlags clientFlags);
/**
* This function Initializes the OC Stack. Must be called prior to starting the stack.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
+OC_EXPORT OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode);
#ifdef RA_ADAPTER
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStop();
+OC_EXPORT OCStackResult OCStop();
/**
* This function starts receiving the multicast traffic. This can be only called
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCProcess();
+OC_EXPORT OCStackResult OCProcess();
/**
* This function discovers or Perform requests on a specified resource
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDoResource(OCDoHandle *handle,
- OCMethod method,
- const char *requestUri,
- const OCDevAddr *destination,
- OCPayload* payload,
- OCConnectivityType connectivityType,
- OCQualityOfService qos,
- OCCallbackData *cbData,
- OCHeaderOption *options,
- uint8_t numOptions);
+OC_EXPORT OCStackResult OCDoResource(OCDoHandle *handle,
+ OCMethod method,
+ const char *requestUri,
+ const OCDevAddr *destination,
+ OCPayload* payload,
+ OCConnectivityType connectivityType,
+ OCQualityOfService qos,
+ OCCallbackData *cbData,
+ OCHeaderOption *options,
+ uint8_t numOptions);
/**
* This function cancels a request associated with a specific @ref OCDoResource invocation.
*
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options,
- uint8_t numOptions);
+OC_EXPORT OCStackResult OCCancel(OCDoHandle handle,
+ OCQualityOfService qos,
+ OCHeaderOption * options,
+ uint8_t numOptions);
/**
* Register Persistent storage callback.
* OC_STACK_OK No errors; Success.
* OC_STACK_INVALID_PARAM Invalid parameter.
*/
-OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
+OC_EXPORT OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
#ifdef WITH_PRESENCE
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStartPresence(const uint32_t ttl);
+OC_EXPORT OCStackResult OCStartPresence(const uint32_t ttl);
/**
* When operating in OCServer or OCClientServer mode, this API will stop sending
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCStopPresence();
+OC_EXPORT OCStackResult OCStopPresence();
#endif
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
+OC_EXPORT OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler, void* callbackParameter);
/**
* This function sets device information.
* ::OC_STACK_INVALID_PARAM invalid parameter.
* ::OC_STACK_ERROR stack process error.
*/
-OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
+OC_EXPORT OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
/**
* This function sets platform information.
* ::OC_STACK_INVALID_PARAM invalid parameter.
* ::OC_STACK_ERROR stack process error.
*/
-OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
+OC_EXPORT OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
/**
* This function creates a resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCCreateResource(OCResourceHandle *handle,
- const char *resourceTypeName,
- const char *resourceInterfaceName,
- const char *uri,
- OCEntityHandler entityHandler,
- void* callbackParam,
- uint8_t resourceProperties);
+OC_EXPORT OCStackResult OCCreateResource(OCResourceHandle *handle,
+ const char *resourceTypeName,
+ const char *resourceInterfaceName,
+ const char *uri,
+ OCEntityHandler entityHandler,
+ void* callbackParam,
+ uint8_t resourceProperties);
/**
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
/**
* This function removes a resource from a collection resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
+OC_EXPORT OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle);
/**
* This function binds a resource type to a resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
- const char *resourceTypeName);
+OC_EXPORT OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
+ const char *resourceTypeName);
/**
* This function binds a resource interface to a resource.
*
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
- const char *resourceInterfaceName);
+OC_EXPORT OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
+ const char *resourceInterfaceName);
/**
* This function binds an entity handler to the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler,
- void *callbackParameter);
+OC_EXPORT OCStackResult OCBindResourceHandler(OCResourceHandle handle,
+ OCEntityHandler entityHandler,
+ void *callbackParameter);
/**
* This function gets the number of resources that have been created in the stack.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResources(uint8_t *numResources);
+OC_EXPORT OCStackResult OCGetNumberOfResources(uint8_t *numResources);
/**
* This function gets a resource handle by index.
*
* @return Found resource handle or NULL if not found.
*/
-OCResourceHandle OCGetResourceHandle(uint8_t index);
+OC_EXPORT OCResourceHandle OCGetResourceHandle(uint8_t index);
/**
* This function deletes resource specified by handle. Deletes resource and all
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDeleteResource(OCResourceHandle handle);
+OC_EXPORT OCStackResult OCDeleteResource(OCResourceHandle handle);
/**
* Get a string representation the server instance ID.
*
* @return A string representation the server instance ID.
*/
-const char* OCGetServerInstanceIDString(void);
+OC_EXPORT const char* OCGetServerInstanceIDString(void);
/**
* This function gets the URI of the resource specified by handle.
*
* @return URI string if resource found or NULL if not found.
*/
-const char *OCGetResourceUri(OCResourceHandle handle);
+OC_EXPORT const char *OCGetResourceUri(OCResourceHandle handle);
/**
* This function gets the properties of the resource specified by handle.
* @note that after a resource is created, the OC_ACTIVE property is set for the resource by the
* stack.
*/
-OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
+OC_EXPORT OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
/**
* This function gets the number of resource types of the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
+OC_EXPORT OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes);
/**
* This function gets name of resource type of the resource.
*
* @return Resource type name if resource found or NULL if resource not found.
*/
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
/**
* This function gets the number of resource interfaces of the resource.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+OC_EXPORT OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
uint8_t *numResourceInterfaces);
/**
*
* @return Resource interface name if resource found or NULL if resource not found.
*/
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
+OC_EXPORT const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
/**
* This function gets methods of resource interface of the resource.
*
* @return Allowed methods if resource found or NULL if resource not found.
*/
-uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
+OC_EXPORT uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index);
/**
* This function gets resource handle from the collection resource by index.
*
* @return Handle to contained resource if resource found or NULL if resource not found.
*/
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+OC_EXPORT OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
uint8_t index);
/**
*
* @return Entity handler if resource found or NULL resource not found.
*/
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
+OC_EXPORT OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
/**
* This function notify all registered observers that the resource representation has
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
+OC_EXPORT OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos);
/**
* Notify specific observers with updated value of representation.
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult
+OC_EXPORT OCStackResult
OCNotifyListOfObservers (OCResourceHandle handle,
OCObservationId *obsIdList,
uint8_t numberOfIds,
*
* @return ::OC_STACK_OK on success, some other value upon failure.
*/
-OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
+OC_EXPORT OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
//#ifdef DIRECT_PAIRING
/**
* client before returning the list of devices.
* @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
*/
-const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
+OC_EXPORT const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
/**
* The function is responsible for return of paired device list via direct-pairing. It will list
*
* @return OCDirectPairingDev_t pointer in case of success and NULL otherwise.
*/
-const OCDPDev_t* OCGetDirectPairedDevices();
+OC_EXPORT const OCDPDev_t* OCGetDirectPairedDevices();
/**
* The function is responsible for establishment of direct-pairing. It will proceed mode negotiation
* @param[in] resultCallback Callback fucntion to event status of process.
* @return OTM_SUCCESS in case of success and other value otherwise.
*/
-OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
- OCDirectPairingCB resultCallback);
+OC_EXPORT OCStackResult OCDoDirectPairing(OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+ OCDirectPairingCB resultCallback);
//#endif // DIRECT_PAIRING
#ifdef __cplusplus
#ifdef RA_ADAPTER
#define MAX_ADDR_STR_SIZE (256)
#else
-/** Max Address could be "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx]:xxxxx" */
-#define MAX_ADDR_STR_SIZE (59)
+/** Max Address could be
+ * "coap+tcp://[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:yyy.yyy.yyy.yyy]:xxxxx"
+ * +1 for null terminator.
+ */
+#define MAX_ADDR_STR_SIZE (65)
#endif
/** Length of MAC address */
char addr[MAX_ADDR_STR_SIZE];
/** usually zero for default interface.*/
- uint32_t interface;
+ uint32_t ifindex;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
char routeData[MAX_ADDR_STR_SIZE]; //destination GatewayID:ClientId
#endif
char *type;
/** Interface */
- OCStringLL *interface;
+ OCStringLL *iface;
/** This structure holds the old /oic/res response. */
OCResourcePayload *resources;
#ifdef TB_LOG
#define OIC_LOG_PAYLOAD(level, payload) OCPayloadLog((level),(payload))
#define UUID_SIZE (16)
-const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
-OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
+OC_EXPORT const char *convertTriggerEnumToString(OCPresenceTrigger trigger);
+OC_EXPORT OCPresenceTrigger convertTriggerStringToEnum(const char * triggerStr);
-static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
+INLINE_API void OCPayloadLogRep(LogLevel level, OCRepPayload* payload)
{
OIC_LOG(level, (PL_TAG), "Payload Type: Representation");
OCRepPayload* rep = payload;
}
-static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
+INLINE_API void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Discovery");
int i = 1;
OIC_LOG_V(level, PL_TAG, "\tResource Type: %s", payload->type);
}
OIC_LOG(level, PL_TAG, "\tInterface:");
- for (OCStringLL *itf = payload->interface; itf; itf = itf->next)
+ for (OCStringLL *itf = payload->iface; itf; itf = itf->next)
{
OIC_LOG_V(level, PL_TAG, "\t\t%s", itf->value);
}
}
}
-static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
+INLINE_API void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Device");
OIC_LOG_V(level, PL_TAG, "\tSID:%s", payload->sid);
}
}
-static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
+INLINE_API void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Platform");
OIC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
}
}
-static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
+INLINE_API void OCPayloadLogPresence(LogLevel level, OCPresencePayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Presence");
OIC_LOG_V(level, PL_TAG, "\tSequence Number:%u", payload->sequenceNumber);
OIC_LOG_V(level, PL_TAG, "\tResource Type:%s", payload->resourceType);
}
-static inline void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
+INLINE_API void OCPayloadLogSecurity(LogLevel level, OCSecurityPayload* payload)
{
OIC_LOG(level, PL_TAG, "Payload Type: Security");
OIC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
}
-static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
+INLINE_API void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
{
if (!payload)
{
}
}
-static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
+INLINE_API void OCPayloadLog(LogLevel level, OCPayload* payload)
{
if(!payload)
{
* @param level LogLevel for the print.
* @param tags Structure of the tags payload.
*/
-void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
+OC_EXPORT void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
/**
* Prints links payload.
* @param level LogLevel for the print.
* @param tags Structure of the links payload.
*/
-void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
+OC_EXPORT void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
#ifdef __cplusplus
}
'../../../../logger/include',
'../../../../stack/include',
'../../../../../../extlibs/cjson',
+ '../../../../../../extlibs/boost',
'../../../../../oc_logger/include',
'../../../../../connectivity/lib/libcoap-4.1.1'
])
-samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+cc = env.get('CC')
+if cc in ['gcc']:
+ samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+ samples_env.AppendUnique(LIBS=['-lpthread'])
samples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-samples_env.AppendUnique(LIBS = ['-lpthread' ])
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-if target_os in ['darwin', 'ios']:
- samples_env.PrependUnique(LIBS = ['m','octbstack', 'ocsrm', 'connectivity_abstraction','coap' ])
-elif target_os not in ['arduino']:
- samples_env.PrependUnique(LIBS = ['m', 'octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+
+if target_os not in ['arduino', 'windows', 'darwin', 'ios', 'msys_nt']:
samples_env.AppendUnique(LIBS = ['rt'])
+if target_os not in ['windows']:
+ samples_env.PrependUnique(LIBS = ['m'])
+
if env.get('SECURED') == '1':
samples_env.AppendUnique(LIBS = ['tinydtls'])
#include <stdio.h>
#include <stdlib.h>
#include <ocstack.h>
+#include <getopt.h>
const char *getResult(OCStackResult result)
{
--- /dev/null
+#ifndef COMMON_H_
+#define COMMON_H_
+
+const char *getResult(OCStackResult result);
+void StripNewLineChar(char* str);
+
+#endif
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "occlient.h"
#include "ocpayload.h"
#include "payload_logging.h"
+#include "common.h"
+#include "platform_features.h"
#ifdef ROUTING_GATEWAY
/**
static char discoveryAddr[100];
static std::string coapServerResource = "/a/light";
-void StripNewLineChar(char* str);
-
#ifdef WITH_PRESENCE
// The handle for observe registration
OCDoHandle gPresenceHandle;
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <stdint.h>
#include <sstream>
#include <iostream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "payload_logging.h"
#include "oic_malloc.h"
#include "oic_string.h"
+#include "common.h"
#define MAX_IP_ADDR_ST_SZ 16 //string size of "155.255.255.255" (15 + 1)
#define MAX_PORT_ST_SZ 6 //string size of "65535" (5 + 1)
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <ocstack.h>
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocpayload.h"
#include "payload_logging.h"
#include "logger.h"
-const char *getResult(OCStackResult result);
+#include "common.h"
std::string getQueryStrForGetPut();
#define TAG ("occlient")
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "occlientslow.h"
#include "oic_string.h"
#include "ocpayload.h"
#include "payload_logging.h"
+#include "common.h"
// Tracking user input
static int UnicastDiscovery = 0;
//The following variable determines the interface protocol (IP, etc)
//to be used for sending unicast messages. Default set to IP.
-static OCConnectivityType AdapterType = CT_ADAPTER_IP;
+static OCConnectivityType adapterType = CT_ADAPTER_IP;
static OCDevAddr endpoint;
static const char *RESOURCE_DISCOVERY_QUERY = "%s/oic/res";
-void StripNewLineChar(char* str);
int gQuitFlag = 0;
ret = OCDoResource(NULL, method, query.str().c_str(), dest,
(method == OC_REST_PUT) ? putPayload() : NULL,
- AdapterType, qos, &cbData, options, numOptions);
+ adapterType, qos, &cbData, options, numOptions);
if (ret != OC_STACK_OK)
{
if(ConnectivityType == CT_ADAPTER_DEFAULT || ConnectivityType == CT_IP)
{
- AdapterType = CT_ADAPTER_IP;
+ adapterType = CT_ADAPTER_IP;
}
else
{
OIC_LOG(INFO, TAG, "Default Connectivity type selected...");
- AdapterType = CT_ADAPTER_IP;
+ adapterType = CT_ADAPTER_IP;
}
InitDiscovery();
#include "ocpayload.h"
#include "payload_logging.h"
#include "ocremoteaccessclient.h"
+#include "common.h"
#define SET_BUT_NOT_USED(x) (void) x
// Tracking user input
static OCDevAddr responseAddr;
//Use ipv4addr for both InitDiscovery and InitPlatformOrDeviceDiscovery
char remoteServerJabberID[MAX_ADDR_STR_SIZE];
-void StripNewLineChar(char* str);
static uint16_t maxNotification = 15;
// The handle for the observe registration
#include <string.h>
#include <string>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <array>
+#include <getopt.h>
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
#include "ocserver.h"
+#include "common.h"
+#include "platform_features.h"
//string length of "/a/light/" + std::numeric_limits<int>::digits10 + '\0'"
// 9 + 9 + 1 = 19
OCStackResult result = OC_STACK_ERROR;
uint8_t j = 0;
- uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2;
- OCObservationId obsNotify[numNotifies];
+ OCObservationId obsNotify[(SAMPLE_MAX_NUM_OBSERVATIONS)/2];
while (!gQuitFlag)
{
if (observeThreadStarted)
{
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId_observe);
pthread_join(threadId_observe, NULL);
+#endif
}
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId_presence);
pthread_join(threadId_presence, NULL);
+#endif
OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include "ocstack.h"
#include "logger.h"
#include "ocserverbasicops.h"
#include <string.h>
#include <string>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <ocstack.h>
#include <logger.h>
+#include <getopt.h>
#include "ocpayload.h"
-
-const char *getResult(OCStackResult result);
+#include "common.h"
+#include "platform_features.h"
#define TAG PCF("ocservercontainer")
/*
* Cancel the light thread and wait for it to terminate
*/
+#ifdef HAVE_PTHREAD_H
pthread_cancel(threadId);
pthread_join(threadId, NULL);
+#endif
OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
+#endif
+#include <boost/config.hpp>
#include <list>
#include "ocstack.h"
#include "oic_malloc.h"
volatile sig_atomic_t gQuitFlag = 0;
static std::list<OCEntityHandlerRequest *> gRequestList;
-static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
+BOOST_STATIC_CONSTEXPR unsigned int SLOW_RESPONSE_DELAY_SEC = 5;
static LEDResource LED;
-static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
+BOOST_STATIC_CONSTEXPR unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2;
static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
//char *gResourceUri= const_cast<char *>("/a/led");
return copyOfRequest;
}
+#if !defined(SIGALRM)
+void AlarmHandler(int sig);
+int WINAPI AlarmThread(void *seconds)
+{
+ sleep((unsigned int)seconds);
+ AlarmHandler(0);
+ return 0;
+}
+
+void alarm(unsigned int seconds)
+{
+ CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AlarmThread, (void*)seconds, 0, NULL);
+}
+#endif
+
OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
OCEntityHandlerRequest *entityHandlerRequest, void* /*callbackParam*/)
{
// slow response when fired
void AlarmHandler(int sig)
{
+#ifdef SIGALRM
if (sig == SIGALRM)
+#endif
{
OIC_LOG (INFO, TAG, "Server starting slow response");
if (gRequestList.empty())
// Declare and create the example resource: LED
createLEDResource(gResourceUri, &LED, false, 42);
+#ifdef SIGALRM
// Initialize slow response alarm
signal(SIGALRM, AlarmHandler);
+#endif
// Break from loop with Ctrl-C
OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
# Note: 'pthread' is in libc for android.
if target_os != 'android':
samples_env.AppendUnique(LIBS = ['-lpthread'])
+ samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-samples_env.PrependUnique(LIBS = ['octbstack', 'm', 'connectivity_abstraction', 'coap'])
+if target_os in ['windows', 'msys_nt']:
+ samples_env.PrependUnique(LIBS = ['ocsrm', 'ws2_32', 'iphlpapi'])
+else:
+ samples_env.PrependUnique(LIBS = ['m'])
+samples_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'coap'])
if env.get('SECURED') == '1':
samples_env.AppendUnique(LIBS = ['tinydtls'])
-samples_env.Append(LINKFLAGS = ['-Wl,--no-as-needed'])
-
if target_os == 'android':
samples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
samples_env.AppendUnique(LIBS = ['gnustl_shared'])
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <signal.h>
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "common.h"
#include <stdlib.h>
#include <string.h>
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif
+#endif
#include <iostream>
#include <sstream>
+#include <getopt.h>
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "occlientbasicops.h"
#include <stdlib.h>\r
#include <string.h>\r
#include <signal.h>\r
+#ifdef HAVE_UNISTD_H\r
#include <unistd.h>\r
+#endif\r
+#ifdef HAVE_PTHREAD_H\r
#include <pthread.h>\r
+#endif\r
#include <iostream>\r
#include <sstream>\r
+#if defined(HAVE_WINDOWS_H)\r
+#include <windows.h>\r
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */\r
+#ifdef ERROR\r
+#undef ERROR\r
+#endif\r
+#endif // defined(HAVE_WINDOWS_H)\r
+#include "platform_features.h"\r
#include "ocstack.h"\r
#include "logger.h"\r
#include "ocpayload.h"\r
\r
void *CLInterface(void *data)\r
{\r
- printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);\r
+ printf(RED_BEGIN "#Ready to operation ('h' for help)#\n" COLOR_END);\r
\r
(void)data;\r
OCStackResult ret;\r
- char query[MAX_LINE] = {0,};\r
- const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";\r
+ char query[MAX_LINE] = {0};\r
+ const char prompt[] = BOLD_BEGIN "IoTivity-DP#" COLOR_END" ";\r
const char* helpmsg[6] = {\r
- GREEN_BEGIN"# h (or help) : show help message"COLOR_END,\r
- GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,\r
- GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,\r
- GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,\r
- GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,\r
- GREEN_BEGIN"# q (quit) : quit test"COLOR_END,\r
+ GREEN_BEGIN "# h (or help) : show help message" COLOR_END,\r
+ GREEN_BEGIN "# dd (DP device discovery) : discover Direct-Pairing devices" COLOR_END,\r
+ GREEN_BEGIN "# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing" COLOR_END,\r
+ GREEN_BEGIN "# sd (send data) : send data to device" COLOR_END,\r
+ GREEN_BEGIN "# ll (list all device) : list all discovered/paired devices" COLOR_END,\r
+ GREEN_BEGIN "# q (quit) : quit test" COLOR_END,\r
};\r
\r
for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)\r
return 0;\r
}\r
\r
+#if defined(_WIN32)\r
+ Sleep(100);\r
+#else\r
nanosleep(&timeout, NULL);\r
+#endif // defined(_WIN32)\r
+\r
}\r
OIC_LOG(INFO, TAG, "Exiting occlient main loop...");\r
\r
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <signal.h>
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#include "platform_features.h"
#include "ocstack.h"
#include "logger.h"
#include "ocpayload.h"
cp -f %{ROOTDIR}/resource/csdk/connectivity/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir}
if echo %{SECURED}|grep -qi '1'; then
- cp -f %{ROOTDIR}/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
+ cp -f %{ROOTDIR}/out/tizen/*/*/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
fi
cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstack.h* %{DEST_INC_DIR}/
#include "oic_malloc.h"
#include <string.h>
-#ifdef WITH_ARDUINO
-#include "Time.h"
-#else
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
+#ifdef HAVE_ARDUINO_TIME_H
+#include "Time.h"
+#endif
#include "coap_time.h"
#include "cacommon.h"
#define NUM_PARAM_IN_QUERY 2 // The expected number of parameters in a query
#define NUM_FIELDS_IN_QUERY 2 // The expected number of fields in a query
+#include "platform_features.h"
+
static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
{
if (!resource || !rtPtr)
}
}
-bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* interface)
+bool OCRepPayloadAddInterface(OCRepPayload* payload, const char* iface)
{
- return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(interface));
+ return OCRepPayloadAddInterfaceAsOwner(payload, OICStrdup(iface));
}
-bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
+bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* iface)
{
- if (!payload || !interface)
+ if (!payload || !iface)
{
return false;
}
{
return false;
}
- cur->next->value = interface;
+ cur->next->value = iface;
return true;
}
else
{
return false;
}
- payload->interfaces->value = interface;
+ payload->interfaces->value = iface;
return true;
}
}
{
if (!array)
{
- return NULL;
+ return false;
}
size_t dimTotal = calcDimTotal(dimensions);
OICFree(payload->uri);
OICFree(payload->type);
OICFree(payload->name);
- OCFreeOCStringLL(payload->interface);
+ OCFreeOCStringLL(payload->iface);
OCDiscoveryResourceDestroy(payload->resources);
OICFree(payload);
}
// TinyCbor Version 47a78569c0 or better on master is required for the re-allocation
// strategy to work. If you receive the following assertion error, please do a git-pull
// from the extlibs/tinycbor/tinycbor directory
- #define CborNeedsUpdating (CborErrorOutOfMemory < CborErrorDataTooLarge)
+ #define CborNeedsUpdating (((unsigned int)CborErrorOutOfMemory) < ((unsigned int)CborErrorDataTooLarge))
OC_STATIC_ASSERT(!CborNeedsUpdating, "tinycbor needs to be updated to at least 47a78569c0");
#undef CborNeedsUpdating
VERIFY_CBOR_SUCCESS(TAG, err, "Failed setting RT");
// Insert interfaces
- if (payload->interface)
+ if (payload->iface)
{
- err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->interface);
+ err |= OCStringLLJoin(&rootMap, OC_RSRVD_INTERFACE, payload->iface);
VERIFY_CBOR_SUCCESS(TAG, err, "Failed adding interface types tag/value");
}
#include "ocstackinternal.h"
#include "payload_logging.h"
#include "rdpayload.h"
+#include "platform_features.h"
#define TAG "OIC_RI_PAYLOADPARSE"
err = cbor_value_map_find_value(&rootMap, OC_RSRVD_INTERFACE, &curVal);
if (cbor_value_is_valid(&curVal))
{
- err = OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->interface);
+ err = OCParseStringLL(&rootMap, OC_RSRVD_INTERFACE, &out->iface);
}
- if (!out->interface)
+ if (!out->iface)
{
- if (!OCResourcePayloadAddStringLL(&out->interface, OC_RSRVD_INTERFACE_LL))
+ if (!OCResourcePayloadAddStringLL(&out->iface, OC_RSRVD_INTERFACE_LL))
{
err = CborErrorOutOfMemory;
}
// Refer http://pubs.opengroup.org/onlinepubs/009695399/
#define _POSIX_C_SOURCE 200112L
-#ifdef WITH_ARDUINO
+#ifdef WITH_STRING_H
#include <string.h>
-#else
+#endif
+#ifdef WITH_STRINGS_H
#include <strings.h>
#endif
#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OIC_LOG((logLevel), \
TAG, #arg " is NULL"); return (retVal); } }
+#include "platform_features.h"
+
extern OCResource *headResource;
static OCPlatformInfo savedPlatformInfo = {0};
static OCDeviceInfo savedDeviceInfo = {0};
}
discPayload->type = OICStrdup(OC_RSRVD_RESOURCE_TYPE_RES);
VERIFY_NON_NULL(discPayload->type, ERROR, OC_STACK_NO_MEMORY);
- OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_LL);
- OCResourcePayloadAddStringLL(&discPayload->interface, OC_RSRVD_INTERFACE_DEFAULT);
- VERIFY_NON_NULL(discPayload->interface, ERROR, OC_STACK_NO_MEMORY);
+ OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_LL);
+ OCResourcePayloadAddStringLL(&discPayload->iface, OC_RSRVD_INTERFACE_DEFAULT);
+ VERIFY_NON_NULL(discPayload->iface, ERROR, OC_STACK_NO_MEMORY);
}
bool foundResourceAtRD = false;
for (;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
responseInfo.info.type = CA_MSG_NONCONFIRM;
}
- char rspToken[CA_MAX_TOKEN_LEN + 1] = {};
+ char rspToken[CA_MAX_TOKEN_LEN + 1] = {0};
responseInfo.info.messageId = serverRequest->coapID;
responseInfo.info.token = (CAToken_t)rspToken;
#include "directpairing.h"
//#endif
-#ifdef WITH_ARDUINO
+#ifdef HAVE_ARDUINO_TIME_H
#include "Time.h"
-#else
+#endif
+#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include "coap_time.h"
#include "utlist.h"
#include "pdu.h"
-#ifndef ARDUINO
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
out->flags = CAToOCTransportFlags(in->flags);
OICStrcpy(out->addr, sizeof(out->addr), in->addr);
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
memcpy(out->routeData, in->routeData, sizeof(out->routeData));
#endif
memcpy(out->routeData, in->routeData, sizeof(out->routeData));
#endif
out->port = in->port;
- out->interface = in->interface;
+ out->ifindex = in->ifindex;
}
void FixUpClientResponse(OCClientResponse *cr)
#include "logger.h"
#include "timer.h"
-#ifndef WITH_ARDUINO
-#include <pthread.h>
-#endif
+#include "platform_features.h"
#define TAG "OIC_RI_GROUP"
pointer = NULL; \
}
-#ifndef WITH_ARDUINO
-pthread_mutex_t lock;
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+ #include <pthread.h>
+ pthread_mutex_t lock;
+ #define MUTEX_LOCK(ARG_NAME) { pthread_mutex_lock(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME) { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+ #include <Windows.h>
+ CRITICAL_SECTION lock;
+ #define MUTEX_LOCK(ARG_NAME) { EnterCriticalSection(ARG_NAME); }
+ #define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#elif defined(WITH_ARDUINO)
+
+ #define MUTEX_LOCK(ARG_NAME) { }
+ #define MUTEX_UNLOCK(ARG_NAME) { }
+
+#else
+
+ ERROR Need mutex implementation on this platform
+
#endif
enum ACTION_TYPE
{
OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
ScheduledResourceInfo *tmp = NULL;
if (*head != NULL)
{
*head = add;
}
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
}
ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
{
OIC_LOG(INFO, TAG, "GetScheduledResource Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
time_t t_now;
ScheduledResourceInfo *tmp = NULL;
tmp = head;
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
time(&t_now);
#else
t_now = now();
while (tmp)
{
time_t diffTm = 0;
-#ifndef WITH_ARDUINO
diffTm = timespec_diff(tmp->time, t_now);
-#else
- diffTm = timespec_diff(tmp->time, t_now);
-#endif
if (diffTm <= (time_t) 0)
{
}
exit:
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (tmp == NULL)
{
OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
{
OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
+
ScheduledResourceInfo *tmp = NULL;
tmp = head;
}
exit:
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (tmp == NULL)
{
OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
void RemoveScheduledResource(ScheduledResourceInfo **head,
ScheduledResourceInfo* del)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+
+ MUTEX_LOCK(&lock);
+
OIC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
ScheduledResourceInfo *tmp = NULL;
if (del == NULL)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
return;
}
}
OCFREE(del)
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
}
typedef struct aggregatehandleinfo
// yyyy-mm-dd hh:mm:ss d
iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
VARIFY_PARAM_NULL(iterToken, result, exit)
-#ifndef WITH_ARDUINO
+#if !defined(WITH_ARDUINO)
if( 2 != sscanf(iterToken, "%ld %u", &(*set)->timesteps, &(*set)->type) )
{
// If the return value should be 2, the number of items in the argument. Otherwise, it fails.
OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
goto exit;
}
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+
+ MUTEX_LOCK(&lock);
+
DoAction(info->resource, info->actionset, info->ehRequest);
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+
+ MUTEX_UNLOCK(&lock);
+
if (info->actionset->type == RECURSIVE)
{
if (info->actionset->timesteps > 0)
{
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->resource = info->resource;
schedule->actionset = info->actionset;
schedule->ehRequest = info->ehRequest;
&DoScheduledGroupAction);
OIC_LOG(INFO, TAG, "Reregisteration.");
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
AddScheduledResource(&scheduleResourceList, schedule);
}
else
char *doWhat = NULL;
char *details = NULL;
+#if defined(_WIN32)
+ static bool initializedCriticalSection = false;
+
+ if(false == initializedCriticalSection) {
+ /** @todo Find a way to DeleteCriticalSection somewhere. */
+ InitializeCriticalSection(&lock);
+ initializedCriticalSection = true;
+ }
+#endif
+
stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
if(stackRet != OC_STACK_OK)
OIC_LOG(INFO, TAG, "Building New Call Info.");
memset(schedule, 0,
sizeof(ScheduledResourceInfo));
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->resource = resource;
schedule->actionset = actionset;
schedule->ehRequest =
(OCServerRequest*) ehRequest->requestHandle;
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
if (delay > 0)
{
OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
actionset->timesteps);
-#ifndef WITH_ARDUINO
- pthread_mutex_lock(&lock);
-#endif
+ MUTEX_LOCK(&lock);
schedule->time = registerTimer(delay,
&schedule->timer_id,
&DoScheduledGroupAction);
-#ifndef WITH_ARDUINO
- pthread_mutex_unlock(&lock);
-#endif
+ MUTEX_UNLOCK(&lock);
AddScheduledResource(&scheduleResourceList,
schedule);
stackRet = OC_STACK_OK;
entry->timeStamp = OICGetCurrentTime(TIME_IN_US);
entry->remoteAddr.adapter = endpoint->adapter;
entry->remoteAddr.flags = endpoint->flags;
- entry->remoteAddr.interface = endpoint->interface;
+ entry->remoteAddr.ifindex = endpoint->ifindex;
entry->remoteAddr.port = endpoint->port;
strncpy(entry->remoteAddr.addr, endpoint->addr, sizeof(entry->remoteAddr.addr));
])
stacktest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-stacktest_env.AppendUnique(LIBS = ['-lpthread'])
stacktest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
stacktest_env.AppendUnique(LIBPATH = [src_dir + '/extlibs/gtest/gtest-1.7.0/lib/.libs'])
-stacktest_env.PrependUnique(LIBS = ['m',
- 'octbstack',
+stacktest_env.PrependUnique(LIBS = ['octbstack',
'ocsrm',
'connectivity_abstraction',
'coap',
if env.get('LOGGING'):
stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+if target_os in ['msys_nt', 'windows']:
+ stacktest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+ stacktest_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'kernel32'])
+else:
+ stacktest_env.PrependUnique(LIBS = ['m', 'pthread'])
+
######################################################################
# Source files and Targets
######################################################################
env.AppendTarget('test')
if env.get('TEST') == '1':
- target_os = env.get('TARGET_OS')
- if target_os == 'linux':
+ if target_os in ['windows']:
+ stacktest_env.AppendENVPath('PATH', [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ if target_os in ['linux', 'windows']:
from tools.scons.RunTest import *
run_test(stacktest_env,
'resource_csdk_stack_test.memcheck',
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <stdlib.h>
//-----------------------------------------------------------------------------
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <stdlib.h>
//-----------------------------------------------------------------------------
examples_env.AppendUnique(LIBS = ['octbstack'])
examples_env.AppendUnique(LIBS = ['oc'])
+if target_os in ['msys_nt', 'windows']:
+ examples_env.PrependUnique(LIBS = ['mswsock', 'ws2_32', 'iphlpapi', 'ole32'])
+
if env.get('SECURED') == '1':
- examples_env.AppendUnique(LIBS = ['tinydtls'])
+ examples_env.AppendUnique(LIBS = ['tinydtls'])
+ examples_env.AppendUnique(CPPDEFINES = ['_WITH_DTLS_'])
+ if target_os in ['msys_nt', 'windows']:
+ examples_env.AppendUnique(LIBS = ['advapi32'])
if target_os == 'android':
examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
if target_os in ['darwin', 'ios']:
examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+if env.get('LOGGING'):
+ examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+if target_os in ['msys_nt', 'windows']:
+ examples_env.AppendUnique(LIBS = ['Comctl32', 'Gdi32', 'User32'])
+
+if env.get('LOGGING'):
+ examples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+def make_single_file_cpp_program(program_name):
+ return examples_env.Program(program_name, program_name + ".cpp")
+
######################################################################
# Source files and Targets
######################################################################
-simpleserver = examples_env.Program('simpleserver', 'simpleserver.cpp')
-simpleclient = examples_env.Program('simpleclient', 'simpleclient.cpp')
-simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp')
-simpleclientHQ = examples_env.Program('simpleclientHQ', 'simpleclientHQ.cpp')
-fridgeserver = examples_env.Program('fridgeserver', 'fridgeserver.cpp')
-fridgeclient = examples_env.Program('fridgeclient', 'fridgeclient.cpp')
-presenceserver = examples_env.Program('presenceserver', 'presenceserver.cpp')
-presenceclient = examples_env.Program('presenceclient', 'presenceclient.cpp')
-simpleclientserver = examples_env.Program('simpleclientserver', 'simpleclientserver.cpp')
-roomserver = examples_env.Program('roomserver', 'roomserver.cpp')
-roomclient = examples_env.Program('roomclient', 'roomclient.cpp')
-garageserver = examples_env.Program('garageserver', 'garageserver.cpp')
-garageclient = examples_env.Program('garageclient', 'garageclient.cpp')
-groupserver = examples_env.Program('groupserver', 'groupserver.cpp')
-groupclient = examples_env.Program('groupclient', 'groupclient.cpp')
-lightserver = examples_env.Program('lightserver', 'lightserver.cpp')
-devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp')
-devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp')
-threadingsample = examples_env.Program('threadingsample', 'threadingsample.cpp')
+example_names = [
+ 'simpleserver', 'simpleclient',
+ 'simpleclientserver',
+ 'devicediscoveryserver', 'devicediscoveryclient'
+ ]
+
+if target_os not in ['windows', 'msys_nt']:
+ example_names += [
+ 'simpleserverHQ', 'simpleclientHQ',
+ 'fridgeserver', 'fridgeclient',
+ 'presenceserver', 'presenceclient',
+ 'roomserver', 'roomclient',
+ 'garageserver',
+ 'garageclient',
+ 'groupserver',
+ 'groupclient',
+ 'lightserver',
+ 'threadingsample',
+ ]
+examples = map(make_single_file_cpp_program, example_names)
+
+######################################################################
+# Other examples
+######################################################################
clientjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_client.dat')
serverjson = examples_env.Install(env.get('BUILD_DIR') + '/resource/examples/',
env.get('SRC_DIR') + '/resource/examples/' + 'oic_svr_db_server.dat')
-Alias("examples", [simpleserver, simpleclient,
- simpleserverHQ, simpleclientHQ,
- fridgeserver, fridgeclient,
- presenceserver, presenceclient,
- simpleclientserver, roomserver, roomclient, garageserver,
- garageclient,
- groupserver, groupclient,
- lightserver,
- devicediscoveryserver, devicediscoveryclient,
- threadingsample,
- serverjson, clientjson
- ])
+
+examples += [clientjson, serverjson]
+
+if target_os in ['msys_nt', 'windows']:
+ winUIClient = examples_env.Program('winUIClient', ['winuiclientgui.cpp', 'winuiclient.cpp'])
+ mediaserver = examples_env.Program('mediaserver', 'mediaserver.cpp')
+ examples += [winUIClient, mediaserver]
+
+Alias("examples", examples)
env.AppendTarget('examples')
/// (properties and methods) and host this resource on the server.
///
+#include <unistd.h>
#include <functional>
#include <pthread.h>
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+#include <mutex>
+#include "platform_features.h"
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include <windows.h>
+#include <objbase.h>
+
+#include <commctrl.h>
+#include <mmdeviceapi.h>
+#include <endpointvolume.h>
+#include <stdio.h>
+#include <math.h> /* log */
+
+#define SAFE_RELEASE(x) \
+ if ((x) != NULL) \
+ { (x)->Release(); (x) = NULL; }
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeMediaRepresentation (void *param);
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
+void playPause(void);
+void setVolume(int vol);
+int getVolume(void);
+
+// Specifies where to notify all observers or list of observers
+// false: notifies all observers
+// true: notifies list of observers
+bool isListOfObservers = false;
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'MediaResource'. This resource has
+/// two simple properties named 'state' and 'volume'
+
+class MediaResource
+{
+
+public:
+ /// Access this property from a TB client
+ std::string m_name;
+ bool m_state;
+ int m_volume;
+ std::string m_mediaUri;
+ OCResourceHandle m_resourceHandle;
+ OCRepresentation m_mediaRep;
+ ObservationIds m_interestedObservers;
+
+public:
+ /// Constructor
+ MediaResource()
+ :m_name("Media Player"), m_state(false), m_volume(0), m_mediaUri("/a/media"),
+ m_resourceHandle(nullptr)
+ {
+ // Initialize representation
+ m_mediaRep.setUri(m_mediaUri);
+
+ m_mediaRep.setValue("state", m_state);
+ m_mediaRep.setValue("volume", m_volume);
+ m_mediaRep.setValue("name", m_name);
+ }
+
+ /* Note that this does not need to be a member function: for classes you do not have
+ access to, you can accomplish this with a free function: */
+
+ /// This function internally calls registerResource API.
+ void createResource()
+ {
+ //URI of the resource
+ std::string resourceURI = m_mediaUri;
+ //resource type name. In this case, it is media
+ std::string resourceTypeName = "core.media";
+ // resource interface.
+ std::string resourceInterface = DEFAULT_INTERFACE;
+
+ // OCResourceProperty is defined ocstack.h
+ uint8_t resourceProperty;
+ if(isSecure)
+ {
+ resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE;
+ }
+ else
+ {
+ resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+ }
+ EntityHandler cb = std::bind(&MediaResource::entityHandler, this,PH::_1);
+
+ // This will internally create and register the resource.
+ OCStackResult result = OCPlatform::registerResource(
+ m_resourceHandle, resourceURI, resourceTypeName,
+ resourceInterface, cb, resourceProperty);
+
+ if (OC_STACK_OK != result)
+ {
+ cout << "Resource creation was unsuccessful\n";
+ }
+ }
+
+ OCResourceHandle getHandle()
+ {
+ return m_resourceHandle;
+ }
+
+ // Puts representation.
+ // Gets values from the representation and
+ // updates the internal state
+ void put(OCRepresentation& rep)
+ {
+ try
+ {
+ if (rep.getValue("state", m_state))
+ {
+ cout << "\t\t\t\t" << "state: " << m_state << endl;
+ if(m_state)
+ {
+ playPause();
+ }
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "state not found in the representation" << endl;
+ }
+
+ if (rep.getValue("volume", m_volume))
+ {
+ cout << "\t\t\t\t" << "volume: " << m_volume << endl;
+ if((0 <= m_volume) && (m_volume <= 100))
+ {
+ setVolume(m_volume);
+ }
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "volume not found in the representation" << endl;
+ }
+ }
+ catch (exception& e)
+ {
+ cout << e.what() << endl;
+ }
+
+ }
+
+ // Post representation.
+ // Post can create new resource or simply act like put.
+ // Gets values from the representation and
+ // updates the internal state
+ OCRepresentation post(OCRepresentation& rep)
+ {
+ put(rep);
+ return get();
+ }
+
+
+ // gets the updated representation.
+ // Updates the representation with latest internal state before
+ // sending out.
+ OCRepresentation get()
+ {
+ m_mediaRep.setValue("state", m_state);
+ m_mediaRep.setValue("volume", m_volume);
+
+ return m_mediaRep;
+ }
+
+ void addType(const std::string& type) const
+ {
+ OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+ void addInterface(const std::string& intf) const
+ {
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, intf);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
+{
+ cout << "\tIn Server CPP entity handler:\n";
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if(request)
+ {
+ // Get the request type and request flag
+ std::string requestType = request->getRequestType();
+ int requestFlag = request->getRequestHandlerFlag();
+
+ if(requestFlag & RequestHandlerFlag::RequestFlag)
+ {
+ cout << "\t\trequestFlag : Request\n";
+ auto pResponse = std::make_shared<OC::OCResourceResponse>();
+ pResponse->setRequestHandle(request->getRequestHandle());
+ pResponse->setResourceHandle(request->getResourceHandle());
+
+ // Check for query params (if any)
+ QueryParamsMap queries = request->getQueryParameters();
+
+ if (!queries.empty())
+ {
+ cout << "\nQuery processing upto entityHandler" << std::endl;
+ }
+ for (auto it : queries)
+ {
+ cout << "Query key: " << it.first << " value : " << it.second
+ << std::endl;
+ }
+
+ // If the request type is GET
+ if(requestType == "GET")
+ {
+ cout << "\t\t\trequestType : GET\n";
+ if(isSlowResponse) // Slow response case
+ {
+ static int startedThread = 0;
+ if(!startedThread)
+ {
+ std::thread t(handleSlowResponse, (void *)this, request);
+ startedThread = 1;
+ t.detach();
+ }
+ ehResult = OC_EH_SLOW;
+ }
+ else // normal response case.
+ {
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(get());
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ }
+ else if(requestType == "PUT")
+ {
+ cout << "\t\t\trequestType : PUT\n";
+ OCRepresentation rep = request->getResourceRepresentation();
+
+ // Do related operations related to PUT request
+ // Update the mediaResource
+ put(rep);
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(get());
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if(requestType == "POST")
+ {
+ cout << "\t\t\trequestType : POST\n";
+
+ OCRepresentation rep = request->getResourceRepresentation();
+
+ // Do related operations related to POST request
+ OCRepresentation rep_post = post(rep);
+ pResponse->setResourceRepresentation(rep_post);
+ pResponse->setErrorCode(200);
+ if(rep_post.hasAttribute("createduri"))
+ {
+ pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+ pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
+ }
+ else
+ {
+ pResponse->setResponseResult(OC_EH_OK);
+ }
+
+ if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if(requestType == "DELETE")
+ {
+ cout << "Delete request received" << endl;
+ }
+ }
+
+ if(requestFlag & RequestHandlerFlag::ObserverFlag)
+ {
+ ObservationInfo observationInfo = request->getObservationInfo();
+ if(ObserveAction::ObserveRegister == observationInfo.action)
+ {
+ m_interestedObservers.push_back(observationInfo.obsId);
+ }
+ else if(ObserveAction::ObserveUnregister == observationInfo.action)
+ {
+ m_interestedObservers.erase(std::remove(
+ m_interestedObservers.begin(),
+ m_interestedObservers.end(),
+ observationInfo.obsId),
+ m_interestedObservers.end());
+ }
+
+ cout << "\t\trequestFlag : Observer\n";
+ gObservation = 1;
+ static int startedThread = 0;
+
+ // Observation happens on a different thread in ChangeMediaRepresentation function.
+ // If we have not created the thread already, we will create one here.
+
+ if(!startedThread)
+ {
+ std::thread t(ChangeMediaRepresentation, (void *)this);
+ startedThread = 1;
+ t.detach();
+ }
+
+ ehResult = OC_EH_OK;
+ }
+ }
+ else
+ {
+ cout << "Request invalid" << std::endl;
+ }
+
+ return ehResult;
+}
+
+};
+
+// ChangeMediaRepresentaion is an observation function,
+// which notifies any changes to the resource to stack
+// via notifyObservers
+void * ChangeMediaRepresentation (void *param)
+{
+ int prevVolume = 0;
+ MediaResource* mediaPtr = (MediaResource*) param;
+
+ // This function continuously monitors for the changes
+ while (1)
+ {
+ Sleep(100);
+
+ if (gObservation)
+ {
+ prevVolume = mediaPtr->m_volume;
+ mediaPtr->m_volume = getVolume();
+ if (prevVolume == mediaPtr->m_volume)
+ continue;
+
+ cout << "Volume changed from " << prevVolume << "% to " << mediaPtr->m_volume << "%\n";
+
+ // If under observation if there are any changes to the media resource
+ // we call notifyObservors
+ //
+ // For demostration we are changing the volume value and notifying.
+
+ cout << "\nVolume updated to : " << mediaPtr->m_volume << endl;
+ cout << "Notifying observers with resource handle: " << mediaPtr->getHandle() << endl;
+
+ OCStackResult result = OC_STACK_OK;
+
+ if(isListOfObservers)
+ {
+ std::shared_ptr<OCResourceResponse> resourceResponse =
+ {std::make_shared<OCResourceResponse>()};
+
+ resourceResponse->setErrorCode(200);
+ resourceResponse->setResourceRepresentation(mediaPtr->get(), DEFAULT_INTERFACE);
+
+ result = OCPlatform::notifyListOfObservers( mediaPtr->getHandle(),
+ mediaPtr->m_interestedObservers,
+ resourceResponse);
+ }
+ else
+ {
+ result = OCPlatform::notifyAllObservers(mediaPtr->getHandle());
+ }
+
+ if(OC_STACK_NO_OBSERVERS == result)
+ {
+ cout << "No More observers, stopping notifications" << endl;
+ gObservation = 0;
+ }
+ }
+ }
+
+ return NULL;
+}
+
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
+{
+ // This function handles slow response case
+ MediaResource* mediaPtr = (MediaResource*) param;
+ // Induce a case for slow response by using sleep
+ cout << "SLOW response" << std::endl;
+ sleep (10);
+
+ auto pResponse = std::make_shared<OC::OCResourceResponse>();
+ pResponse->setRequestHandle(pRequest->getRequestHandle());
+ pResponse->setResourceHandle(pRequest->getResourceHandle());
+ pResponse->setResourceRepresentation(mediaPtr->get());
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+
+ // Set the slow response flag back to false
+ isSlowResponse = false;
+ OCPlatform::sendResponse(pResponse);
+ return NULL;
+}
+
+void PrintUsage()
+{
+ cout << std::endl;
+ cout << "Usage : mediaserver <value>\n";
+ cout << " Default - Non-secure resource and notify all observers\n";
+ cout << " 1 - Non-secure resource and notify list of observers\n\n";
+ cout << " 2 - Secure resource and notify all observers\n";
+ cout << " 3 - Secure resource and notify list of observers\n\n";
+ cout << " 4 - Non-secure resource, GET slow response, notify all observers\n";
+}
+
+static FILE* client_open(const char* /*path*/, const char *mode)
+{
+ return fopen("./oic_svr_db_server.json", mode);
+}
+
+void playPause()
+{
+ INPUT ip;
+
+ // Set up a generic keyboard event.
+ ip.type = INPUT_KEYBOARD;
+ ip.ki.wScan = 0; // hardware scan code for key
+ ip.ki.time = 0;
+ ip.ki.dwExtraInfo = 0;
+ ip.ki.wVk = VK_MEDIA_PLAY_PAUSE; // virtual-key code for the "a" key
+ ip.ki.dwFlags = 0; // 0 for key press
+
+ SendInput(1, &ip, sizeof(INPUT));
+ // Release the "Play/Pause" key
+ ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
+ SendInput(1, &ip, sizeof(INPUT));
+}
+
+int getVolume()
+{
+ IAudioEndpointVolume *g_pEndptVol = NULL;
+ HRESULT hr = S_OK;
+ IMMDeviceEnumerator *pEnumerator = NULL;
+ IMMDevice *pDevice = NULL;
+ OSVERSIONINFO VersionInfo;
+
+ ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ GetVersionEx(&VersionInfo);
+ CoInitialize(NULL);
+
+ // Get enumerator for audio endpoint devices.
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+ NULL, CLSCTX_INPROC_SERVER,
+ __uuidof(IMMDeviceEnumerator),
+ (void**)&pEnumerator);
+
+ // Get default audio-rendering device.
+ hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+ hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+ CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+ float currentVal;
+ hr = g_pEndptVol->GetMasterVolumeLevelScalar(¤tVal);
+ fflush(stdout); // just in case
+
+ SAFE_RELEASE(pEnumerator)
+ SAFE_RELEASE(pDevice)
+ SAFE_RELEASE(g_pEndptVol)
+ CoUninitialize();
+ return ((int) round(100 * currentVal));
+
+}
+
+void setVolume(int vol)
+{
+ IAudioEndpointVolume *g_pEndptVol = NULL;
+ HRESULT hr = S_OK;
+ IMMDeviceEnumerator *pEnumerator = NULL;
+ IMMDevice *pDevice = NULL;
+ OSVERSIONINFO VersionInfo;
+
+ ZeroMemory(&VersionInfo, sizeof(OSVERSIONINFO));
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ GetVersionEx(&VersionInfo);
+ CoInitialize(NULL);
+
+ // Get enumerator for audio endpoint devices.
+ hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),
+ NULL, CLSCTX_INPROC_SERVER,
+ __uuidof(IMMDeviceEnumerator),
+ (void**)&pEnumerator);
+
+ // Get default audio-rendering device.
+ hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pDevice);
+
+ hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),
+ CLSCTX_ALL, NULL, (void**)&g_pEndptVol);
+ float got = (float)vol/100.0; // needs to be within 1.0 to 0.0
+ hr = g_pEndptVol->SetMasterVolumeLevelScalar(got, NULL);
+ fflush(stdout); // just in case
+
+ SAFE_RELEASE(pEnumerator)
+ SAFE_RELEASE(pDevice)
+ SAFE_RELEASE(g_pEndptVol)
+ CoUninitialize();
+}
+
+int main(int argc, char* argv[])
+{
+ OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+ if (argc == 1)
+ {
+ isListOfObservers = false;
+ isSecure = false;
+ }
+ else if (argc == 2)
+ {
+ int value = atoi(argv[1]);
+ switch (value)
+ {
+ case 1:
+ isListOfObservers = true;
+ isSecure = false;
+ break;
+ case 2:
+ isListOfObservers = false;
+ isSecure = true;
+ break;
+ case 3:
+ isListOfObservers = true;
+ isSecure = true;
+ break;
+ case 4:
+ isSlowResponse = true;
+ break;
+ default:
+ PrintUsage();
+ break;
+ }
+ }
+ else
+ {
+ PrintUsage();
+ return -1;
+ }
+
+ // Create PlatformConfig object
+ PlatformConfig cfg {
+ OC::ServiceType::InProc,
+ OC::ModeType::Server,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ OC::QualityOfService::LowQos,
+ &ps
+ };
+
+ OCPlatform::Configure(cfg);
+ try
+ {
+ // Create the instance of the resource class
+ // (in this case instance of class 'MediaResource').
+ MediaResource myMedia;
+
+ // Invoke createResource function of class media.
+ myMedia.createResource();
+ cout << "Created resource." << std::endl;
+
+ // A condition variable will free the mutex it is given, then do a non-
+ // intensive block until 'notify' is called on it. In this case, since we
+ // don't ever call cv.notify, this should be a non-processor intensive version
+ // of while(true);
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock<std::mutex> lock(blocker);
+ cout <<"Waiting" << std::endl;
+ cv.wait(lock, []{return false;});
+ }
+ catch(OCException &e)
+ {
+ cout << "OCException in main : " << e.what() << endl;
+ }
+
+ // No explicit call to stop the platform.
+ // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+ return 0;
+}
+
#include <pthread.h>
#include <mutex>
#include <condition_variable>
-
+#include <getopt.h>
#include "OCPlatform.h"
#include "OCApi.h"
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
using namespace std;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
// OCClient.cpp : Defines the entry point for the console application.
//
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
#include <string>
#include <map>
#include <cstdlib>
-#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCPlatform.h"
#include "OCApi.h"
+#if defined(__msys_nt__)
+#include <Windows.h>
+#define sleep(x) Sleep(1000*x)
+#endif
+
using namespace OC;
struct dereference_compare
/// This sample provides steps to define an interface for a resource
/// (properties and methods) and host this resource on the server.
///
-
#include <functional>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include "platform_features.h"
using namespace OC;
using namespace std;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
m_interestedObservers.end());
}
+#if defined(_WIN32)
+ DWORD threadId;
+ HANDLE threadHandle;
+#else
pthread_t threadId;
+#endif
cout << "\t\trequestFlag : Observer\n";
gObservation = 1;
// If we have not created the thread already, we will create one here.
if(!startedThread)
{
+#if defined(_WIN32)
+ threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ChangeLightRepresentation, (void*)this, 0, &threadId);
+#else
pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
+#endif
startedThread = 1;
}
ehResult = OC_EH_OK;
#include "OCPlatform.h"
#include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
using namespace std;
namespace PH = std::placeholders;
}
}
- void addInterface(const std::string& interface) const
+ void addInterface(const std::string& iface) const
{
- OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
if (OC_STACK_OK != result)
{
cout << "Binding TypeName to Resource was unsuccessful\n";
#include "OCPlatform.h"
#include "OCApi.h"
+
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
+#include "platform_features.h"
+
using namespace OC;
static std::ostringstream requestURI;
--- /dev/null
+/* ****************************************************************\r
+ *\r
+ * Copyright 2016 Intel Corporation All Rights Reserved.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ ******************************************************************/\r
+\r
+#include <string>\r
+#include "winuiclient.h"\r
+#include <Windows.h>\r
+#include <Commctrl.h>\r
+#include <functional>\r
+\r
+extern int g_CurSliderVal;\r
+extern HWND hwndVolumeSlider, hwndVolumeExpectedLabel;\r
+using namespace WinUIClient;\r
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);\r
+\r
+WinUIClientApp::WinUIClientApp(OCPersistentStorage ps)\r
+ : persistentStorage(ps),\r
+ OBSERVE_TYPE_TO_USE(ObserveType::Observe)\r
+{\r
+\r
+}\r
+\r
+WinUIClientApp::~WinUIClientApp()\r
+{\r
+\r
+}\r
+\r
+void WinUIClientApp::Initialize()\r
+{\r
+ // Create PlatformConfig object\r
+ PlatformConfig cfg {\r
+ OC::ServiceType::InProc,\r
+ OC::ModeType::Both,\r
+ "0.0.0.0",\r
+ 0,\r
+ OC::QualityOfService::LowQos,\r
+ &persistentStorage\r
+ };\r
+\r
+ OCPlatform::Configure(cfg);\r
+}\r
+\r
+void WinUIClientApp::Run()\r
+{\r
+ try\r
+ {\r
+ // makes it so that all boolean values are printed as 'true/false' in this stream\r
+ std::cout.setf(std::ios::boolalpha);\r
+ // Find all resources\r
+ std::ostringstream requestURI;// << "?rt=core.media";\r
+ std::string s = OC_RSRVD_WELL_KNOWN_URI;\r
+ requestURI << s;\r
+\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+ std::cout<< "Finding Resource... " <<std::endl;\r
+\r
+ // Find resource is done twice so that we discover the original resources a second time.\r
+ // These resources will have the same uniqueidentifier (yet be different objects), so that\r
+ // we can verify/show the duplicate-checking code in foundResource(above);\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+ std::cout<< "Finding Resource for second time..." << std::endl;\r
+\r
+ }catch(OCException& e)\r
+ {\r
+ std::cerr << "Exception in main: "<<e.what();\r
+ }\r
+}\r
+\r
+void WinUIClientApp::FindResources()\r
+{\r
+ std::ostringstream requestURI;\r
+ requestURI << OC_RSRVD_WELL_KNOWN_URI;// << "?rt=core.media";\r
+ OCPlatform::findResource("", requestURI.str(),\r
+ CT_DEFAULT, std::bind(&WinUIClientApp::foundResource, this, std::placeholders::_1));\r
+}\r
+\r
+\r
+// Callback to found resources\r
+void WinUIClientApp::foundResource(std::shared_ptr<OCResource> resource)\r
+{\r
+ std::cout << "In foundResource\n";\r
+ std::string resourceURI;\r
+ std::string hostAddress;\r
+ try\r
+ {\r
+ {\r
+ std::lock_guard<std::mutex> lock(curResourceLock);\r
+ if (discoveredResources.find(resource->uniqueIdentifier()) == discoveredResources.end())\r
+ {\r
+ std::cout << "Found resource " << resource->uniqueIdentifier() <<\r
+ " for the first time on server with ID: "<< resource->sid()<<std::endl;\r
+ discoveredResources[resource->uniqueIdentifier()] = resource;\r
+ }\r
+ else\r
+ {\r
+ std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;\r
+ }\r
+\r
+ if (curResource)\r
+ {\r
+ std::cout << "Found another resource, ignoring"<<std::endl;\r
+ return;\r
+ }\r
+ }\r
+\r
+ // Do some operations with resource object.\r
+ if (resource)\r
+ {\r
+ std::cout<<"DISCOVERED Resource:"<<std::endl;\r
+ // Get the resource URI\r
+ resourceURI = resource->uri();\r
+ std::cout << "\tURI of the resource: " << resourceURI << std::endl;\r
+\r
+ // Get the resource host address\r
+ hostAddress = resource->host();\r
+ std::cout << "\tHost address of the resource: " << hostAddress << std::endl;\r
+\r
+ // Get the resource types\r
+ std::cout << "\tList of resource types: " << std::endl;\r
+ for(auto &resourceTypes : resource->getResourceTypes())\r
+ {\r
+ std::cout << "\t\t" << resourceTypes << std::endl;\r
+ }\r
+\r
+ // Get the resource interfaces\r
+ std::cout << "\tList of resource interfaces: " << std::endl;\r
+ for(auto &resourceInterfaces : resource->getResourceInterfaces())\r
+ {\r
+ std::cout << "\t\t" << resourceInterfaces << std::endl;\r
+ }\r
+\r
+ if (resourceURI == "/a/media")\r
+ {\r
+ curResource = resource;\r
+ // Call a local function which will internally invoke get API on the resource pointer\r
+ this->GetMediaRepresentation();\r
+ this->BeginObserving();\r
+ }\r
+ }\r
+ else\r
+ {\r
+ // Resource is invalid\r
+ std::cout << "Resource is invalid" << std::endl;\r
+ }\r
+\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cerr << "Exception in foundResource: "<< e.what() << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to get representation of media resource\r
+void WinUIClientApp::GetMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ std::cout << "Getting Media Representation..."<<std::endl;\r
+ // Invoke resource's get API with the callback parameter\r
+\r
+ QueryParamsMap test;\r
+ curResource->get(test, std::bind(&WinUIClientApp::onGet, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "No Current Resource to GetMediaRepresentation..."<<std::endl;\r
+ }\r
+}\r
+\r
+// Callback handler on GET request\r
+void WinUIClientApp::onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK)\r
+ {\r
+ std::cout << "GET request was successful" << std::endl;\r
+ std::cout << "Resource URI: " << rep.getUri() << std::endl;\r
+\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ g_CurSliderVal = mymedia.m_volume;\r
+ SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onGET Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onGet" << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PutMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ OCRepresentation rep;\r
+\r
+ std::cout << "Putting media representation..."<<std::endl;\r
+\r
+ rep.setValue("state", mymedia.m_state);\r
+ rep.setValue("volume", mymedia.m_volume);\r
+\r
+ // Invoke resource's put API with rep, query map and the callback parameter\r
+ curResource->put(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPut, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+ }\r
+}\r
+\r
+// callback handler on PUT request\r
+void WinUIClientApp::onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK)\r
+ {\r
+ std::cout << "PUT request was successful" << std::endl;\r
+\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPut Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPut" << std::endl;\r
+ }\r
+}\r
+\r
+// Local function to put a different state for this resource\r
+void WinUIClientApp::PostMediaRepresentation()\r
+{\r
+ if (curResource)\r
+ {\r
+ OCRepresentation rep;\r
+\r
+ std::cout << "Posting media representation..."<<std::endl;\r
+\r
+ rep.setValue("state", mymedia.m_state);\r
+ rep.setValue("volume", mymedia.m_volume);\r
+\r
+ // Invoke resource's post API with rep, query map and the callback parameter\r
+ curResource->post(rep, QueryParamsMap(), std::bind(&WinUIClientApp::onPost, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));\r
+ }\r
+}\r
+\r
+void WinUIClientApp::onPost(const HeaderOptions& /*headerOptions*/,\r
+ const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+ {\r
+ std::cout << "POST request was successful" << std::endl;\r
+\r
+ if (rep.hasAttribute("createduri"))\r
+ {\r
+ std::cout << "\tUri of the created resource: "\r
+ << rep.getValue<std::string>("createduri") << std::endl;\r
+ }\r
+ else\r
+ {\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+ }\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPost Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch (std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPost" << std::endl;\r
+ }\r
+}\r
+\r
+void WinUIClientApp::onPost2(const HeaderOptions& /*headerOptions*/,\r
+ const OCRepresentation& rep, const int eCode)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED)\r
+ {\r
+ std::cout << "POST request was successful" << std::endl;\r
+\r
+ if (rep.hasAttribute("createduri"))\r
+ {\r
+ std::cout << "\tUri of the created resource: "\r
+ << rep.getValue<std::string>("createduri") << std::endl;\r
+ }\r
+ else\r
+ {\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+ }\r
+\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onPost2 Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ catch(std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onPost2" << std::endl;\r
+ }\r
+\r
+}\r
+\r
+void WinUIClientApp::onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep,\r
+ const int& eCode, const int& sequenceNumber)\r
+{\r
+ try\r
+ {\r
+ if (eCode == OC_STACK_OK && sequenceNumber != OC_OBSERVE_NO_OPTION)\r
+ {\r
+ if (sequenceNumber == OC_OBSERVE_REGISTER)\r
+ {\r
+ std::cout << "Observe registration action is successful" << std::endl;\r
+ }\r
+ else if (sequenceNumber == OC_OBSERVE_DEREGISTER)\r
+ {\r
+ std::cout << "Observe De-registration action is successful" << std::endl;\r
+ }\r
+\r
+ std::cout << "OBSERVE RESULT:"<<std::endl;\r
+ std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;\r
+ rep.getValue("state", mymedia.m_state);\r
+ rep.getValue("volume", mymedia.m_volume);\r
+ rep.getValue("name", mymedia.m_name);\r
+\r
+ std::cout << "\tstate: " << mymedia.m_state << std::endl;\r
+ std::cout << "\tvolume: " << mymedia.m_volume << std::endl;\r
+ std::cout << "\tname: " << mymedia.m_name << std::endl;\r
+\r
+ g_CurSliderVal = mymedia.m_volume;\r
+ SendMessage(hwndVolumeSlider, TBM_SETPOS, TRUE, g_CurSliderVal);\r
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);\r
+ }\r
+ else\r
+ {\r
+ if (sequenceNumber == OC_OBSERVE_NO_OPTION)\r
+ {\r
+ std::cout << "Observe registration or de-registration action is failed" << std::endl;\r
+ }\r
+ else\r
+ {\r
+ std::cout << "onObserve Response error: " << eCode << std::endl;\r
+ std::exit(-1);\r
+ }\r
+ }\r
+ }\r
+ catch (std::exception& e)\r
+ {\r
+ std::cout << "Exception: " << e.what() << " in onObserve" << std::endl;\r
+ }\r
+\r
+}\r
+\r
+void WinUIClientApp::BeginObserving()\r
+{\r
+ if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)\r
+ std::cout << std::endl << "Observe is used." << std::endl << std::endl;\r
+ else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)\r
+ std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;\r
+\r
+ curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), std::bind(&WinUIClientApp::onObserve, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));\r
+}\r
+\r
+void WinUIClientApp::CancelObserving()\r
+{\r
+ std::cout<<"Cancelling Observe..."<<std::endl;\r
+ OCStackResult result = curResource->cancelObserve();\r
+}\r
+\r
+std::shared_ptr<OCResource> WinUIClientApp::GetResource()\r
+{\r
+ return curResource;\r
+}\r
+\r
+int WinUIClientApp::observe_count()\r
+{\r
+ static int oc = 0;\r
+ return ++oc;\r
+}\r
+\r
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * 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 WINUICLIENT_H_
+#define WINUICLIENT_H_
+
+#include <memory>
+#include <mutex>
+#include <map>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "OCResource.h"
+
+using namespace OC;
+namespace WinUIClient{
+
+ class Media
+ {
+ public:
+
+ bool m_state;
+ int m_volume;
+ std::string m_name;
+
+ Media() : m_state(false), m_volume(0), m_name("")
+ {
+ }
+ };
+
+ class WinUIClientApp
+ {
+ public:
+ WinUIClientApp(OCPersistentStorage ps);
+ ~WinUIClientApp();
+
+ void Initialize();
+ void Run();
+ void FindResources();
+ void GetMediaRepresentation();
+ void PutMediaRepresentation();
+ void PostMediaRepresentation();
+ void BeginObserving();
+ void CancelObserving();
+
+ std::shared_ptr<OCResource> GetResource();
+ Media GetMedia(){return mymedia;}
+ void SetMedia(bool state, int volume){mymedia.m_state = state; mymedia.m_volume=volume;}
+ bool observing;
+
+ private:
+ void foundResource(std::shared_ptr<OCResource> resource);
+ void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPost(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode);
+ void onPost2(const HeaderOptions& /*headerOptions*/,const OCRepresentation& rep, const int eCode);
+ void onObserve(const HeaderOptions /*headerOptions*/, const OCRepresentation& rep, const int& eCode, const int& sequenceNumber);
+ private:
+ int observe_count();
+
+ private:
+ typedef std::map<OCResourceIdentifier, std::shared_ptr<OCResource>> DiscoveredResourceMap;
+
+ OCPersistentStorage persistentStorage;
+ Media mymedia;
+ DiscoveredResourceMap discoveredResources;
+ std::shared_ptr<OCResource> curResource;
+ ObserveType OBSERVE_TYPE_TO_USE;
+ std::mutex curResourceLock;
+ };
+
+}
+
+#endif
+
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Intel Corporation All Rights Reserved.
+ *
+ * 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>
+#include "winuiclient.h"
+
+#include <Windows.h>
+#include <Commctrl.h>
+
+#define ID_TRACKBAR 0x50505
+#define ID_BUTTONPLAYPAUSE 0xFFF0
+#define ID_BUTTONFIND 0xFFF1
+#define ID_BUTTONGET 0xFFF2
+#define ID_BUTTONPUT 0xFFF3
+#define ID_BUTTONPOST 0xFFF4
+#define ID_BUTTONBEGINOBSERVE 0xFFF5
+#define ID_BUTTONCANCELOBSERVE 0xFFF6
+
+int g_CurSliderVal = 0;
+
+HWND hwnd, icon_button, hwndVolumeSlider, hwndVolumeExpectedLabel;
+HWND hwndButtonPlayPause, hwndButtonFind, hwndButtonGet, hwndButtonPut, hwndButtonPost, hwndButtonBeginObserve, hwndButtonCancelObserve;
+HINSTANCE hInstance, g_hinstTrackBar, g_hinstVolumeSlider, g_hinstVolumeLabel;
+HANDLE Timer, Thread;
+HICON hIcon1;
+HBRUSH g_BkgndBrush;
+
+WinUIClient::WinUIClientApp* app = NULL;
+
+LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...);
+HWND WINAPI CreateTrackbar(HWND parent, int x, int y, int w, int h,UINT iMin, UINT iMax, UINT iSelMin, UINT iSelMax);
+HWND WINAPI CreateLabel(HWND parent, LPCTSTR lpText, int x, int y, int w, int h);
+HWND WINAPI CreateButton(HWND parent, UINT_PTR id, LPCTSTR caption, int x, int y, int w, int h);
+
+FILE* client_open(const char* /*path*/, const char *mode)
+{
+ return fopen("./oic_svr_db_client.dat", mode);
+}
+
+int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
+ LPSTR lpCmdLine, int nCmdShow )
+{
+ MSG msg;
+ WNDCLASS wc = {sizeof(WNDCLASS)};
+ wc.lpszClassName = TEXT( "Static Control" );
+ wc.hInstance = hInstance ;
+ wc.hbrBackground = GetSysColorBrush(COLOR_MENU);
+ wc.lpfnWndProc = WndProc;
+ wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
+ wc.hCursor = LoadCursor (NULL, IDC_ARROW);
+
+ RegisterClass(&wc);
+ hwnd = CreateWindow( wc.lpszClassName, TEXT("IoTivity Media Client - Windows UI"),
+ WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,
+ 100, 100, 275, 170, 0, 0, hInstance, 0);
+
+ InitCommonControls(); // loads common control's DLL
+
+ hwndVolumeSlider =
+ CreateTrackbar(hwnd,
+ 10,10,
+ 170,40,
+ 0,100,
+ 0,0);
+ hwndVolumeExpectedLabel =
+ CreateLabel(hwnd,
+ "Expected Volume",
+ 10,50,
+ 240,30);
+
+ LabelPrintf(hwndVolumeExpectedLabel,
+ "Expected Volume: %i",
+ 0);
+
+ hwndButtonPlayPause =
+ CreateButton(hwnd,
+ ID_BUTTONPLAYPAUSE,
+ "PlayPause",
+ 180,10,
+ 80,35);
+
+ hwndButtonFind =
+ CreateButton(hwnd,
+ ID_BUTTONFIND,
+ "Find",
+ 10,75,
+ 64,25);
+
+ hwndButtonGet =
+ CreateButton(hwnd,
+ ID_BUTTONGET,
+ "Get",
+ 10,105,
+ 64,25);
+
+ hwndButtonPut =
+ CreateButton(hwnd,
+ ID_BUTTONPUT,
+ "Put",
+ 80,75,
+ 64,25);
+
+ hwndButtonPost =
+ CreateButton(hwnd,
+ ID_BUTTONPOST,
+ "Post",
+ 80,105,
+ 64,25);
+ hwndButtonBeginObserve =
+ CreateButton(hwnd,
+ ID_BUTTONBEGINOBSERVE,
+ "Bgn Obs",
+ 150,75,
+ 64,25);
+ hwndButtonCancelObserve =
+ CreateButton(hwnd,
+ ID_BUTTONCANCELOBSERVE,
+ "Cncl Obs",
+ 150,105,
+ 64,25);
+
+
+ ShowWindow(hwnd, nCmdShow);
+ UpdateWindow(hwnd);
+
+ while (GetMessage(&msg, NULL, 0, 0))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+
+ return (int) msg.wParam;
+}
+
+LRESULT
+CALLBACK
+WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
+{
+ HDC hDC;
+ RECT rect;
+ WinUIClient::Media myMedia;
+
+ switch(msg){
+ case WM_HSCROLL:
+ switch (LOWORD(wParam)) {
+ case TB_ENDTRACK:
+ g_CurSliderVal = SendMessage(hwndVolumeSlider, TBM_GETPOS, 0, 0);
+ LabelPrintf(hwndVolumeExpectedLabel,"Volume: %i", g_CurSliderVal);
+
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PostMediaRepresentation();
+ break;
+ }
+ break;
+ case WM_CREATE:
+ {
+ hIcon1 = LoadIcon (NULL, IDI_WARNING);
+ SendMessage(icon_button,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcon1);
+ GetClientRect(hwnd, &rect);
+ g_BkgndBrush = GetSysColorBrush(COLOR_MENU);
+
+ OCPersistentStorage ps = {client_open, fread, fwrite, fclose, unlink };
+ app = new WinUIClient::WinUIClientApp(ps);
+ app->Initialize();
+ app->Run();
+ }
+ break;
+ case WM_DESTROY:
+
+ delete app;
+
+ PostQuitMessage(0);
+ break;
+ case WM_ERASEBKGND:
+ GetClientRect(hwnd, &rect);
+ hDC = GetDC(hwnd);
+ SelectObject((HDC)wParam, g_BkgndBrush);
+ Rectangle((HDC)hDC, rect.left, rect.top, rect.right, rect.bottom);
+ ReleaseDC(hwnd, hDC);
+ break;
+ case WM_SIZE:
+ break;
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONDOWN:
+ break;
+ case WM_MOUSELEAVE:
+ case WM_RBUTTONUP:
+ case WM_LBUTTONUP:
+ break;
+ case WM_COMMAND:
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+
+ switch (LOWORD(wParam))
+ {
+ case ID_BUTTONPLAYPAUSE:
+ myMedia = app->GetMedia();
+
+ // HACK: We are using m_state in a stateless way.
+ // True means "toggle". The server does not have state
+ // knowledge about whether or not media is playing on the
+ // system. It's dumb and hits the "PlayPause" key on the
+ // keyboard.
+ //
+ myMedia.m_state = true;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ myMedia.m_state = false;
+
+ app->PutMediaRepresentation();
+ break;
+ case ID_BUTTONFIND:
+ app->FindResources();
+ break;
+ case ID_BUTTONGET:
+ app->GetMediaRepresentation();
+ break;
+ case ID_BUTTONPUT:
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PutMediaRepresentation();
+ break;
+ case ID_BUTTONPOST:
+ myMedia = app->GetMedia();
+ myMedia.m_volume = g_CurSliderVal;
+ app->SetMedia(myMedia.m_state, myMedia.m_volume);
+ app->PostMediaRepresentation();
+ break;
+ case ID_BUTTONBEGINOBSERVE:
+ app->BeginObserving();
+ break;
+ case ID_BUTTONCANCELOBSERVE:
+ app->CancelObserving();
+ break;
+ }
+ }
+ break;
+ default:
+ return DefWindowProc(hwnd, msg, wParam, lParam);
+ }
+
+ return 0;
+}
+
+#define GWL_HINSTANCE -6
+HWND WINAPI CreateButton(HWND parent,
+ UINT_PTR id,
+ LPCTSTR caption ,
+ int x,
+ int y,
+ int w,
+ int h
+ )
+{
+ HWND hwndButton = CreateWindow(
+ "BUTTON", // Predefined class; Unicode assumed
+ caption, // Button text
+ WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
+ x, // x position
+ y, // y position
+ w, // Button width
+ h, // Button height
+ parent, // Parent window
+ (HMENU)id, // No menu.
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+ NULL); // Pointer not needed.
+
+ return hwndButton;
+}
+
+HWND WINAPI CreateLabel(
+ HWND parent, // handle of parent window
+ LPCTSTR lpText,
+ int x,
+ int y,
+ int w,
+ int h
+)
+{
+ HWND hwndPowerLabel = CreateWindow("static", "ST_U",
+ WS_CHILD | WS_VISIBLE | WS_TABSTOP,
+ x, y, w, h,
+ parent, (HMENU)(501),
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),
+ NULL);
+ SetWindowText(hwndPowerLabel, lpText);
+ return hwndPowerLabel;
+}
+
+// CreateTrackbar - creates and initializes a trackbar.
+//
+// Global variable
+// g_hinstTrackBar - instance handle
+//
+HWND WINAPI CreateTrackbar(
+ HWND parent, // handle of dialog box (parent window)
+ int x,
+ int y,
+ int w,
+ int h,
+ UINT iMin, // minimum value in trackbar range
+ UINT iMax, // maximum value in trackbar range
+ UINT iSelMin, // minimum value in trackbar selection
+ UINT iSelMax) // maximum value in trackbar selection
+{
+ HWND hwndVolumeSlider = CreateWindowEx(
+ 0, // no extended styles
+ TRACKBAR_CLASS, // class name
+ "Trackbar Control", // title (caption)
+ WS_CHILD |
+ WS_VISIBLE |
+ TBS_AUTOTICKS |
+ TBS_ENABLESELRANGE, // style
+ x,y,w,h, // position ,size
+ parent, // parent window
+ (HMENU)ID_TRACKBAR, // control identifier
+ (HINSTANCE)GetWindowLongPtr(parent, GWL_HINSTANCE),// instance
+ NULL // no WM_CREATE parameter
+ );
+
+ SendMessage(hwndVolumeSlider, TBM_SETRANGE,
+ (WPARAM) TRUE, // redraw flag
+ (LPARAM) MAKELONG(iMin, iMax)); // min. & max. positions
+
+ SendMessage(hwndVolumeSlider, TBM_SETPAGESIZE,
+ 0, (LPARAM) 4); // new page size
+
+ SendMessage(hwndVolumeSlider, TBM_SETSEL,
+ (WPARAM) FALSE, // redraw flag
+ (LPARAM) MAKELONG(iSelMin, iSelMax));
+
+ SendMessage(hwndVolumeSlider, TBM_SETPOS,
+ (WPARAM) TRUE, // redraw flag
+ (LPARAM) iSelMin);
+
+ SetFocus(hwndVolumeSlider);
+
+ return hwndVolumeSlider;
+}
+
+void LabelPrintf (HWND hwndEdit, TCHAR * szFormat, ...)
+{
+ TCHAR szBuffer [1024] ;
+ va_list pArgList ;
+
+ va_start (pArgList, szFormat) ;
+ wvsprintf (szBuffer, szFormat, pArgList) ;
+ va_end (pArgList) ;
+
+ SetWindowText(hwndEdit, szBuffer);
+}
+
template<>
struct AttributeTypeConvert<NullType>
{
- constexpr static AttributeType type = AttributeType::Null;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Null;
};
template<>
struct AttributeTypeConvert<int>
{
- constexpr static AttributeType type = AttributeType::Integer;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Integer;
};
template<>
struct AttributeTypeConvert<double>
{
- constexpr static AttributeType type = AttributeType::Double;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Double;
};
template<>
struct AttributeTypeConvert<bool>
{
- constexpr static AttributeType type = AttributeType::Boolean;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Boolean;
};
template<>
struct AttributeTypeConvert<std::string>
{
- constexpr static AttributeType type = AttributeType::String;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::String;
};
template<>
struct AttributeTypeConvert<OCRepresentation>
{
- constexpr static AttributeType type = AttributeType::OCRepresentation;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::OCRepresentation;
};
template<>
struct AttributeTypeConvert<std::vector<uint8_t>>
{
- constexpr static AttributeType type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR AttributeType type = AttributeType::Binary;
};
std::ostream& operator << (std::ostream& os, const AttributeType at);
#include <map>
#include <memory>
#include <iterator>
+#if defined(_MSC_VER)
+#include <functional>
+//Squelch "decorated name length exceeded, name was truncated"
+// This compensates for templates full of templates
+#pragma warning(disable : 4503)
+#endif
#include "octypes.h"
#include "OCHeaderOption.h"
namespace OC
{
+#if defined(_MSC_VER)
+ extern std::ostream& oclog();
+#else
typedef boost::iostreams::stream<OC::oc_log_stream> log_target_t;
namespace detail
{
return detail::oclog_target();
};
-
+#endif
} // namespace OC
namespace OC
OCHeaderOption(const OCHeaderOption&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCHeaderOption(OCHeaderOption&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCHeaderOption(OCHeaderOption&&) = default;
+#endif
OCHeaderOption& operator=(const OCHeaderOption&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCHeaderOption& operator=(OCHeaderOption&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCHeaderOption& operator=(OCHeaderOption&&) = default;
+#endif
/**
* API to get Option ID
#ifndef OC_REPRESENTATION_H_
#define OC_REPRESENTATION_H_
+#define GCC_VERSION (__GNUC__ * 10000 \
+ + __GNUC_MINOR__ * 100 \
+ + __GNUC_PATCHLEVEL__)
#include <string>
#include <sstream>
// this fix will work in the meantime.
OCRepresentation(): m_interfaceType(InterfaceType::None){}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCRepresentation(OCRepresentation&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ }
+#else
OCRepresentation(OCRepresentation&&) = default;
+#endif
OCRepresentation(const OCRepresentation&) = default;
OCRepresentation& operator=(const OCRepresentation&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCRepresentation& operator=(OCRepresentation&& o)
+ {
+ std::memmove(this, &o, sizeof(o));
+ return *this;
+ }
+#else
OCRepresentation& operator=(OCRepresentation&&) = default;
+#endif
virtual ~OCRepresentation(){}
// Enable-if required to prevent conversions to alternate types. This prevents
// ambigious conversions in the case where conversions can include a number of
// types, such as the string constructor.
+#if (defined(_MSC_VER) ) || (defined(__GNUC__) && (GCC_VERSION <= 50000))
+ template<typename T, typename std::enable_if<
+ std::is_same<T, int>::value ||
+ std::is_same<T, double>::value ||
+ std::is_same<T, bool>::value ||
+ std::is_same<T, std::string>::value ||
+ std::is_same<T, OCRepresentation>::value ||
+ std::is_same<T, std::vector<int>>::value ||
+ std::is_same<T, std::vector<std::vector<int>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<int>>>>::value ||
+ std::is_same<T, std::vector<double>>::value ||
+ std::is_same<T, std::vector<std::vector<double>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<double>>>>::value ||
+ std::is_same<T, std::vector<bool>>::value ||
+ std::is_same<T, std::vector<std::vector<bool>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<bool>>>>::value ||
+ std::is_same<T, std::vector<std::string>>::value ||
+ std::is_same<T, std::vector<std::vector<std::string>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<std::string>>>>::value ||
+ std::is_same<T, std::vector<OCRepresentation>>::value ||
+ std::is_same<T, std::vector<std::vector<OCRepresentation>>>::value ||
+ std::is_same<T, std::vector<std::vector<std::vector<OCRepresentation>>>>::value
+ , int>::type = 0// enable_if
+ >
+#else
template<typename T, typename std::enable_if<
is_component<T,
remove_first<AttributeValue>::type
>::value
, int>::type = 0
>
+#endif
operator T() const
{
return this->getValue<T>();
OCResourceIdentifier(const OCResourceIdentifier&) = default;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceIdentifier(OCResourceIdentifier&& o):
+ m_resourceUri(std::move(o.m_resourceUri)),
+ m_representation(o.m_representation)
+ {
+ }
+#else
OCResourceIdentifier(OCResourceIdentifier&&) = default;
+#endif
OCResourceIdentifier& operator=(const OCResourceIdentifier&) = delete;
public:
typedef std::shared_ptr<OCResource> Ptr;
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResource(OCResource&& o):
+ m_clientWrapper(std::move(o.m_clientWrapper)),
+ m_uri(std::move(o.m_uri)),
+ m_resourceId(std::move(o.m_resourceId)),
+ m_devAddr(std::move(o.m_devAddr)),
+ m_useHostString(o.m_useHostString),
+ m_isObservable(o.m_isObservable),
+ m_isCollection(o.m_isCollection),
+ m_resourceTypes(std::move(o.m_resourceTypes)),
+ m_interfaces(std::move(o.m_interfaces)),
+ m_children(std::move(m_children)),
+ m_observeHandle(std::move(m_observeHandle)),
+ m_headerOptions(std::move(m_headerOptions))
+ {
+ }
+#else
OCResource(OCResource&&) = default;
- OCResource& operator=(OCResource&&) = default;
+#endif
+ // Explicitly delete the copy ctor since VS2013 would try to generate one, and
+ // the standard says that defaulting the move ctor should delete the copy ctor.
+ OCResource(const OCResource&) = delete;
+
+ // We cannot support copy/move assigns since OCResourceIdentifier doesn't.
+ OCResource& operator=(OCResource&&) = delete;
+ OCResource& operator=(const OCResource&) = delete;
/**
* Virtual destructor
{
}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceRequest(OCResourceRequest&& o):
+ m_requestType(std::move(o.m_requestType)),
+ m_resourceUri(std::move(o.m_resourceUri)),
+ m_queryParameters(std::move(o.m_queryParameters)),
+ m_requestHandlerFlag(o.m_requestHandlerFlag),
+ m_representation(std::move(o.m_representation)),
+ m_observationInfo(std::move(o.m_observationInfo)),
+ m_headerOptions(std::move(o.m_headerOptions)),
+ m_requestHandle(std::move(o.m_requestHandle)),
+ m_resourceHandle(std::move(o.m_resourceHandle))
+ {
+ }
+ OCResourceRequest& operator=(OCResourceRequest&& o)
+ {
+ m_requestType = std::move(o.m_requestType);
+ m_resourceUri = std::move(o.m_resourceUri);
+ m_queryParameters = std::move(o.m_queryParameters);
+ m_requestHandlerFlag = o.m_requestHandlerFlag;
+ m_representation = std::move(o.m_representation);
+ m_observationInfo = std::move(o.m_observationInfo);
+ m_headerOptions = std::move(o.m_headerOptions);
+ m_requestHandle = std::move(o.m_requestHandle);
+ m_resourceHandle = std::move(o.m_resourceHandle);
+ }
+#else
OCResourceRequest(OCResourceRequest&&) = default;
OCResourceRequest& operator=(OCResourceRequest&&) = default;
+#endif
+
/**
* Virtual destructor
*/
{
}
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+ OCResourceResponse(OCResourceResponse&& o):
+ m_newResourceUri(std::move(o.m_newResourceUri)),
+ m_errorCode(o.m_errorCode),
+ m_headerOptions(std::move(o.m_headerOptions)),
+ m_interface(std::move(o.m_interface)),
+ m_representation(std::move(o.m_representation)),
+ m_requestHandle(std::move(o.m_requestHandle)),
+ m_resourceHandle(std::move(o.m_resourceHandle)),
+ m_responseResult(std::move(o.m_responseResult))
+ {
+ }
+ OCResourceResponse& operator=(OCResourceResponse&& o)
+ {
+ m_newResourceUri = std::move(o.m_newResourceUri);
+ m_errorCode = o.m_errorCode;
+ m_headerOptions = std::move(o.m_headerOptions);
+ m_interface = std::move(o.m_interface);
+ m_representation = std::move(o.m_representation);
+ m_requestHandle = std::move(o.m_requestHandle);
+ m_resourceHandle = std::move(o.m_resourceHandle);
+ m_responseResult = std::move(o.m_responseResult);
+ }
+#else
OCResourceResponse(OCResourceResponse&&) = default;
OCResourceResponse& operator=(OCResourceResponse&&) = default;
+#endif
virtual ~OCResourceResponse(void) {}
/**
* @param rep reference to the resource's representation
* @param interface specifies the interface
*/
- void setResourceRepresentation(OCRepresentation& rep, std::string interface) {
- m_interface = interface;
+ void setResourceRepresentation(OCRepresentation& rep, std::string iface) {
+ m_interface = iface;
m_representation = rep;
}
* @param rep rvalue reference to the resource's representation
* @param interface specifies the interface
*/
- void setResourceRepresentation(OCRepresentation&& rep, std::string interface) {
- setResourceRepresentation(rep, interface);
+ void setResourceRepresentation(OCRepresentation&& rep, std::string iface) {
+ setResourceRepresentation(rep, iface);
}
/**
template<typename T, typename = void>
struct is_vector
{
- constexpr static bool value = false;
+ BOOST_STATIC_CONSTEXPR bool value = false;
};
template<typename T>
>::type
>
{
- constexpr static bool value = true;
+ BOOST_STATIC_CONSTEXPR bool value = true;
};
// type trait to remove the first type from a parameter-packed list
template<typename ToTest, template <typename...> class Base, typename T>
struct is_component<ToTest, Base<T> >
{
- static constexpr bool value = std::is_same<ToTest, T>::value;
+ BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value;
};
// Recursive specialization to handle cases with multiple values
template<typename ToTest, template <typename...> class Base, typename T, typename ...Rest>
struct is_component<ToTest, Base<T, Rest...> >
{
- static constexpr bool value = std::is_same<ToTest, T>::value
+ BOOST_STATIC_CONSTEXPR bool value = std::is_same<ToTest, T>::value
|| is_component<ToTest, Base<Rest...> >::value;
};
} // namespace OC
return m_missingInterface;
}
- virtual const char* what() const noexcept
+ virtual const char* what() const BOOST_NOEXCEPT
{
std::string ret;
namespace OC
{
+
+#if defined(_WIN32)
+/** @todo: Remove temporary hacks to solve error C2059: syntax error: 'constant'*/
+#ifdef NO_ERROR
+#undef NO_ERROR
+#endif
+#ifdef DELETE
+#undef DELETE
+#endif
+#endif
+
namespace InitException
{
static const char NO_ERROR[] = "No Error";
liboc_logger_env.AppendUnique(CFLAGS = ['-Wall', '-std=c99', '-fPIC'])
liboc_logger_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x', '-fPIC'])
-if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+if target_os not in ['darwin', 'ios', 'windows', 'winrt', 'msys_nt']:
liboc_logger_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
######################################################################
# Source files and Targets
######################################################################
-liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c', OBJPREFIX='core_')
-liboc_logger = liboc_logger_env.SharedLibrary('oc_logger',
+
+oc_logger_libs = []
+
+if target_os in ['windows', 'msys_nt']:
+ # TODO: Add OC_EXPORT API prefixes to enable oc_logger DLL generation.
+ oc_logger_libs += liboc_logger_env.StaticLibrary('oc_logger',
['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp'])
+else:
+ oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger_core',
+ ['c/oc_logger.c'], OBJPREFIX='core_'))
+ oc_logger_libs += Flatten(liboc_logger_env.SharedLibrary('oc_logger',
+ ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp']))
-liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger')
-liboc_logger_env.UserInstallTargetLib([liboc_logger_core, liboc_logger], 'liboc_logger')
+liboc_logger_env.InstallTarget(oc_logger_libs, 'oc_logger')
+liboc_logger_env.UserInstallTargetLib(oc_logger_libs, 'oc_logger')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger.hpp', 'resource', 'oc_logger.hpp')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger.h', 'resource', 'oc_logger.h')
liboc_logger_env.UserInstallTargetHeader('include/oc_logger_types.h', 'resource', 'oc_logger_types.h')
######################################################################
examples_env.PrependUnique(CPPPATH = ['../include'])
examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-examples_env.AppendUnique(LIBS = ['oc_logger', 'stdc++'])
+examples_env.AppendUnique(LIBS = ['oc_logger'])
+examples_env.Append(LIBS = ['c_common'])
+
+compiler = env.get('CC')
+if compiler != 'cl':
+ examples_env.AppendUnique(LIBS = ['stdc++'])
target_os = env.get('TARGET_OS')
if target_os == 'android':
{}
public:
- inline void flush() noexcept { return oc_log_flush(m_log.get()); }
- inline void set_level(const oc_log_level new_level) noexcept { return oc_log_set_level(m_log.get(), new_level); }
- inline int set_module(const std::string& module_name) noexcept { return oc_log_set_module(m_log.get(), module_name.c_str()); }
+ inline void flush() BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }
+ inline void set_level(const oc_log_level new_level) BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }
+ inline int set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }
public:
std::streamsize write(const char_type *s, std::streamsize n)
namespace
{
- CAManager::AdapterChangedCallback g_adapterHandler = NULL;
- CAManager::ConnectionChangedCallback g_connectionHandler = NULL;
+ CAManager::AdapterChangedCallback g_adapterHandler = nullptr;
+ CAManager::ConnectionChangedCallback g_connectionHandler = nullptr;
}
OCStackResult convertCAResultToOCResult(CAResult_t caResult)
ClientCallbackContext::ListenContext* context =
new ClientCallbackContext::ListenContext(callback, shared_from_this());
- OCCallbackData cbdata(
- static_cast<void*>(context),
- listenCallback,
- [](void* c){delete static_cast<ClientCallbackContext::ListenContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)context;
+ cbdata.cb = listenCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::ListenContext*)c;};
auto cLock = m_csdkLock.lock();
if(cLock)
ClientCallbackContext::DeviceListenContext* context =
new ClientCallbackContext::DeviceListenContext(callback, shared_from_this());
- OCCallbackData cbdata(
- static_cast<void*>(context),
- listenDeviceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);}
- );
+ OCCallbackData cbdata;
+
+ cbdata.context = (void*)context;
+ cbdata.cb = listenDeviceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::DeviceListenContext*)c;};
auto cLock = m_csdkLock.lock();
if(cLock)
OCStackResult result;
ClientCallbackContext::GetContext* ctx =
new ClientCallbackContext::GetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- getResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::GetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = getResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::GetContext*)c;};
+
std::string uri = assembleSetResourceUri(resourceUri, queryParams);
std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
const QueryParamsMap& queryParams)
{
- if(uri.back() == '/')
+ if(!uri.empty())
{
- uri.resize(uri.size()-1);
+ if(uri.back() == '/')
+ {
+ uri.resize(uri.size()-1);
+ }
}
- ostringstream paramsList;
+ std::ostringstream paramsList;
if(queryParams.size() > 0)
{
paramsList << '?';
}
std::string queryString = paramsList.str();
+
+ if(queryString.empty())
+ {
+ return uri;
+ }
+
if(queryString.back() == ';')
{
queryString.resize(queryString.size() - 1);
}
OCStackResult result;
ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- setResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = setResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
std::string url = assembleSetResourceUri(uri, queryParams);
}
OCStackResult result;
ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- setResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::SetContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = setResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SetContext*)c;};
+
std::string url = assembleSetResourceUri(uri, queryParams).c_str();
OCStackResult result;
ClientCallbackContext::DeleteContext* ctx =
new ClientCallbackContext::DeleteContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- deleteResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::DeleteContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = deleteResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::DeleteContext*)c;};
+
auto cLock = m_csdkLock.lock();
ClientCallbackContext::ObserveContext* ctx =
new ClientCallbackContext::ObserveContext(callback);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- observeResourceCallback,
- [](void* c){delete static_cast<ClientCallbackContext::ObserveContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = observeResourceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::ObserveContext*)c;};
+
OCMethod method;
if (observeType == ObserveType::Observe)
ClientCallbackContext::SubscribePresenceContext* ctx =
new ClientCallbackContext::SubscribePresenceContext(presenceHandler);
- OCCallbackData cbdata(
- static_cast<void*>(ctx),
- subscribePresenceCallback,
- [](void* c)
- {delete static_cast<ClientCallbackContext::SubscribePresenceContext*>(c);}
- );
+ OCCallbackData cbdata;
+ cbdata.context = (void*)ctx;
+ cbdata.cb = subscribePresenceCallback;
+ cbdata.cd = [](void* c){delete (ClientCallbackContext::SubscribePresenceContext*)c;};
+
auto cLock = m_csdkLock.lock();
for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it)
{
- options[i] = OCHeaderOption(OC_COAP_ID,
- it->getOptionID(),
- it->getOptionData().length() + 1,
- reinterpret_cast<const uint8_t*>(it->getOptionData().c_str()));
+ options[i] = OCHeaderOption();
+ options[i].protocolID = OC_COAP_ID;
+ options[i].optionID = it->getOptionID();
+ options[i].optionLength = it->getOptionData().length() + 1;
+ strcpy((char*)options[i].optionData, (it->getOptionData().c_str()));
i++;
}
std::mutex serverWrapperLock;
std::map <OCResourceHandle, OC::EntityHandler> entityHandlerMap;
std::map <OCResourceHandle, std::string> resourceUriMap;
- EntityHandler defaultDeviceEntityHandler = 0;
+ EntityHandler defaultDeviceEntityHandler;
}
}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include "ocapi.h"
+#include "OCApi.h"
+
+#if defined(_MSC_VER)
+namespace OC
+{
+ std::ostream& oclog()
+ {
+ return std::cout;
+ }
+}
+#endif
((int64_t*)array)[pos] = item;
}
+#if !defined(_MSC_VER)
template<>
void get_payload_array::copy_to_array(std::_Bit_reference br, void* array, size_t pos)
{
((bool*)array)[pos] = static_cast<bool>(br);
}
+#endif
template<>
void get_payload_array::copy_to_array(std::string item, void* array, size_t pos)
break;
case AttributeType::String:
OCRepPayloadSetPropString(root, val.attrname().c_str(),
- static_cast<std::string>(val).c_str());
+ (static_cast<std::string>(val)).c_str());
break;
case AttributeType::OCRepresentation:
OCRepPayloadSetPropObjectAsOwner(root, val.attrname().c_str(),
- static_cast<OCRepresentation>(val).getPayload());
+ (static_cast<OCRepresentation>(val)).getPayload());
break;
case AttributeType::Vector:
getPayloadArray(root, val);
// contains the inner most vector-type
typedef T base_type;
// contains the AttributeType for this item
- constexpr static AttributeType enum_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type =
AttributeTypeConvert<T>::type;
// contains the AttributeType for this base-type
- constexpr static AttributeType enum_base_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
AttributeTypeConvert<T>::type;
// depth of the vector
- constexpr static size_t depth = 0;
+ BOOST_STATIC_CONSTEXPR size_t depth = 0;
};
template<typename T>
{
typedef T type;
typedef typename type_info<typename T::value_type>::base_type base_type;
- constexpr static AttributeType enum_type = AttributeType::Vector;
- constexpr static AttributeType enum_base_type =
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Vector;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type =
type_info<typename T::value_type>::enum_base_type;
- constexpr static size_t depth = 1 +
+ BOOST_STATIC_CONSTEXPR size_t depth = 1 +
type_info<typename T::value_type>::depth;
};
{
typedef std::vector<uint8_t> type;
typedef std::vector<uint8_t> base_type;
- constexpr static AttributeType enum_type = AttributeType::Binary;
- constexpr static AttributeType enum_base_type = AttributeType::Binary;
- constexpr static size_t depth = 0;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR AttributeType enum_base_type = AttributeType::Binary;
+ BOOST_STATIC_CONSTEXPR size_t depth = 0;
};
#include <boost/lexical_cast.hpp>
#include <sstream>
+#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_IN6ADDR_H
+#include <in6addr.h>
+#endif
namespace OC {
const std::vector<std::string>& interfaces)
: m_clientWrapper(clientWrapper), m_uri(uri),
m_resourceId(serverId, m_uri),
- m_devAddr{ OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
- , {0}
-#endif
- },
m_isObservable(observable), m_isCollection(false),
m_resourceTypes(resourceTypes), m_interfaces(interfaces),
m_observeHandle(nullptr)
{
+ m_devAddr = OCDevAddr{OC_DEFAULT_ADAPTER, OC_DEFAULT_FLAGS, 0, {0}, 0,
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+ {0}
+#endif
+ };
m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE)
!= m_interfaces.end();
OCStackResult result = checked_guard(m_clientWrapper.lock(),
&IClientWrapper::CancelObserveResource,
- m_observeHandle, "", m_uri, m_headerOptions, QoS);
+ m_observeHandle, (const char*)"", m_uri, m_headerOptions, QoS);
if(result == OC_STACK_OK)
{
##
Import('env')
+import os
+
# Add third party libraries
lib_env = env.Clone()
SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
oclib_env = lib_env.Clone()
+secured = lib_env.get('SECURED')
######################################################################
# Build flags
######################################################################
oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger'])
-oclib_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+oclib_env.AppendUnique(LIBS = ['oc_logger'])
+oclib_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'ocsrm'])
target_os = env.get('TARGET_OS')
if target_os == 'linux':
if target_os in ['linux'] and env.get('SIMULATOR', False):
oclib_env.Append( RPATH = env.Literal('\\$$ORIGIN'))
+if target_os in ['msys_nt', 'windows']:
+ oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'oc_logger')])
+ oclib_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')])
+ oclib_env.AppendUnique(LIBS=['octbstack', 'logger', 'oc_logger','connectivity_abstraction', 'ocsrm', 'c_common', 'routingmanager'])
+ oclib_env.AppendUnique(LIBS=[ 'coap', 'ws2_32' ,'iphlpapi'])
+ if secured == '1':
+ oclib_env.AppendUnique(LIBS=['tinydtls'])
+
######################################################################
# Source files and Targets
######################################################################
'CAManager.cpp'
]
-oclib = oclib_env.SharedLibrary('oc', oclib_src)
-oclib_env.InstallTarget(oclib, 'liboc')
-oclib_env.UserInstallTargetLib(oclib, 'liboc')
-
+if target_os in ['windows']:
+ oclib_src = oclib_src + ['OCApi.cpp']
+ # TODO: Add OC_EXPORT prefixes to enable DLL generation
+ oclib = oclib_env.StaticLibrary('oc', oclib_src)
+else:
+ oclib = oclib_env.SharedLibrary('oc', oclib_src)
+oclib_env.InstallTarget(oclib, 'oc')
+oclib_env.UserInstallTargetLib(oclib, 'oc')
header_dir = env.get('SRC_DIR') + '/resource/include/'
oclib_env.UserInstallTargetHeader(header_dir + 'OCApi.h', 'resource', 'OCApi.h')
# Too much boost warning, suppress the warning
lib_env.AppendUnique(CCFLAGS = ['-w'])
+elif target_os in ['windows']:
+ SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'boost', 'SConscript'))
+ boost_path = os.path.join(src_dir,'extlibs','boost')
+ lib_env.AppendUnique(CPPPATH = [boost_path])
elif target_os == 'ios':
lib_env.AppendUnique(FRAMEWORKS = ['boost'])
elif target_os == 'darwin':
SConscript('csdk/security/provisioning/unittest/SConscript')
SConscript('provisioning/unittests/SConscript')
-elif target_os == 'darwin':
+elif target_os == 'windows' and env.get('TEST') == '1':
# Verify that 'google unit test' library is installed. If not,
# get it and install it
SConscript(src_dir + '/extlibs/gtest/SConscript')
SConscript('csdk/stack/test/SConscript')
SConscript('csdk/connectivity/test/SConscript')
+ # Build Security Resource Manager unit tests
+ SConscript('csdk/security/unittest/SConscript')
+elif target_os in ['darwin', 'msys_nt']:
+ # Verify that 'google unit test' library is installed. If not,
+ # get it and install it
+ SConscript(src_dir + '/extlibs/gtest/SConscript')
+
+ # Build C stack's unit tests.
+ SConscript('csdk/stack/test/SConscript')
+ SConscript('csdk/connectivity/test/SConscript')
--- /dev/null
+@echo off
+REM Helper script to build and run IoTivity on Windows
+SETLOCAL ENABLEDELAYEDEXPANSION
+
+if [%1]==[] goto USAGE
+
+set IOTIVITY_DIR=%~dp0
+set HOME=%USERPROFILE%
+
+IF "%1" == "msys" (
+ set BUILD_MSYS="YES"
+ SHIFT
+) ELSE (
+ set BUILD_MSYS=
+)
+
+set CURRENT_ARG=%1
+set SECOND_ARG=%2
+set DEBUG=
+
+if "!SECOND_ARG!"=="debug" (
+ set DEBUG="%ProgramFiles(x86)%\Windows Kits\10\Debuggers\x64\cdb.exe" -2 -c "g"
+)
+
+IF "%BUILD_MSYS%" == "" (
+ IF NOT "%VS140COMNTOOLS%" == "" (
+ CALL "%VS140COMNTOOLS%"vsvars32.bat
+ ) ELSE (
+ IF NOT "%VS120COMNTOOLS%" == "" (
+ CALL "%VS120COMNTOOLS%"vsvars32.bat
+ )
+ )
+
+ IF NOT "!VSINSTALLDIR!" == "" (
+ CALL "!VSINSTALLDIR!VC\vcvarsall.bat" amd64
+ ) ELSE (
+ @ECHO WARNING: Could not find vsvarsall.bat.
+ @ECHO WARNING: VISUAL STUDIO 2013/2015 DOES NOT APPEAR TO BE INSTALLED ON THIS MACHINE
+ GOTO :EOF
+ )
+)
+
+REM We need to append the "PATH" so the octbstack.dll can be found by executables
+IF "%BUILD_MSYS%" == "" (
+ set BUILD_DIR=out\windows\amd64\debug
+ set PATH=!PATH!;!BUILD_DIR!;
+) ELSE (
+ set BUILD_DIR=out\msys_nt\x86_64\debug
+ set PATH=!PATH!;!BUILD_DIR!;C:\msys64\mingw64\bin
+)
+
+REM *** BUILD OPTIONS ***
+set TARGET_OS=windows
+set TARGET_ARCH=amd64
+set SECURED=1
+set TEST=1
+set LOGGING=OFF
+set WITH_RD=1
+REM *** BUILD OPTIONS ***
+
+if "!CURRENT_ARG!"=="server" (
+ %DEBUG% %BUILD_DIR%\resource\examples\simpleserver.exe
+) else if "!CURRENT_ARG!"=="client" (
+ %DEBUG% %BUILD_DIR%\resource\examples\simpleclient.exe
+) else if "!CURRENT_ARG!"=="mediaclient" (
+ %DEBUG% %BUILD_DIR%\debug\resource\examples\mediaclient.exe
+) else if "!CURRENT_ARG!"=="mediaserver" (
+ %DEBUG% %BUILD_DIR%\resource\examples\mediaserver.exe
+) else if "!CURRENT_ARG!"=="winuiclient" (
+ %DEBUG% %BUILD_DIR%\resource\examples\winuiclient.exe
+) else if "!CURRENT_ARG!"=="occlient" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\occlientbasicops.exe -u 0 -t 3 -c 1
+) else if "!CURRENT_ARG!"=="ocserver" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\samples\linux\SimpleClientServer\ocserverbasicops.exe
+) else if "!CURRENT_ARG!"=="test" (
+ %DEBUG% %BUILD_DIR%\resource\csdk\connectivity\test\catests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\stacktests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\stack\test\cbortests.exe
+ %DEBUG% %BUILD_DIR%\resource\csdk\security\unittest\unittest.exe
+) else if "!CURRENT_ARG!"=="build" (
+ echo Starting IoTivity build with these options:
+ echo TARGET_OS=%TARGET_OS%
+ echo TARGET_ARCH=%TARGET_ARCH%
+ echo SECURED=%SECURED%
+ echo LOGGING=%LOGGING%
+ echo WITH_RD=%WITH_RD%
+ CL.exe | findstr "Compiler Verison"
+ echo.scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD%
+ scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD%
+) else if "!CURRENT_ARG!"=="clean" (
+ scons VERBOSE=1 TARGET_OS=%TARGET_OS% TARGET_ARCH=%TARGET_ARCH% RELEASE=0 WITH_RA=0 TARGET_TRANSPORT=IP SECURED=%SECURED% WITH_TCP=0 BUILD_SAMPLE=ON LOGGING=%LOGGING% TEST=%TEST% WITH_RD=%WITH_RD% -c clean
+ rd /s /q out
+ del .sconsign.dblite
+) else if "!CURRENT_ARG!"=="cleangtest" (
+ rd /s /q extlibs\gtest\gtest-1.7.0
+ del extlibs\gtest\gtest-1.7.0.zip
+) else (
+ echo %0 - Script requires a valid argument!
+ goto :EOF
+)
+
+echo Done!
+
+goto EOF
+
+:USAGE
+echo %0 - Helper to build/test iotivity. Requires an argument.
+echo Installation: Drop this into your iotivity root directory to use it.
+echo.
+echo. Usage examples:
+echo Launch SimpleClient with debugger:
+echo %0 client debug
+echo.
+echo Launch SimpleServer:
+echo %0 server
+echo.
+echo Launch WinUIClient built in msys:
+echo %0 msys winuiclient
+echo.
+echo Build:
+echo %0 build
+echo.
+echo Run all tests:
+echo %0 test
+echo.
+echo Clean:
+echo %0 clean
+
+:EOF
# Update the new environment, usually include add header file paths,
# library path, libs to link and other compiler flags. This part is
# optional.
- new_env.AppeneUnique(xxx = [ .... ])
+ new_env.AppendUnique(xxx = [ .... ])
# Specify the target(application, library, object or others) to build
ts = new_env.Program('progam_name', [source_list])
target_os = env.get('TARGET_OS')
-if target_os not in ['arduino','darwin', 'ios']:
+if target_os not in ['arduino','darwin', 'ios', 'windows']:
# Build things manager project
SConscript('things-manager/SConscript')
if target_os in ['linux'] and env.get('SIMULATOR', False):
SConscript('simulator/SConscript')
- # Build resource directory project
- if env.get('WITH_RD') == '1':
- SConscript('resource-directory/SConscript')
+# Build resource directory project
+if env.get('WITH_RD') == '1':
+ SConscript('resource-directory/SConscript')
# Build EasySetup module
if target_os in ['arduino', 'android', 'linux','tizen']:
linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['libcoap'])
-linux_sample_env.AppendUnique(LIBS = ['libconnectivity_abstraction'])
-linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
+linux_sample_env.AppendUnique(LIBS = ['coap'])
+linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
+linux_sample_env.AppendUnique(LIBS = ['oc_logger'])
linux_sample_env.AppendUnique(LIBS = ['octbstack'])
linux_sample_env.AppendUnique(LIBS = ['oc'])
linux_sample_env.AppendUnique(LIBS = ['pthread'])
#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
+#ifdef HAVE_STRING_H
#include <string.h>
+#endif
#include <iostream>
#include <fstream>
#include <string>
##
Import('env')
+rd_env = env.Clone()
-if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
-else:
- env.AppendUnique(CCFLAGS = ['-g'])
-
-if env.get('LOGGING'):
- env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
-
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-rd_env = lib_env.Clone()
+if rd_env.get('LOGGING'):
+ rd_env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
target_os = env.get('TARGET_OS')
+src_dir = env.get('SRC_DIR')
+
######################################################################
# Build flags
######################################################################
rd_env.AppendUnique(CPPPATH = ['include'])
rd_env.AppendUnique(CPPPATH = ['src/internal'])
-rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include'])
-rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
+rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/stack/include'])
+rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
if target_os not in ['windows', 'winrt']:
rd_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra'])
######################################################################
RD_SRC_DIR = 'src/'
rd_src = [
- RD_SRC_DIR + '/internal/rd_storage.c',
+ RD_SRC_DIR + 'internal/rd_storage.c',
RD_SRC_DIR + 'rd_server.c',
RD_SRC_DIR + 'rd_client.c',
]
else :
rdsdk = rd_env.StaticLibrary('resource_directory', rd_src)
-rd_env.InstallTarget(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetLib(rdsdk, 'libresource_directory')
-rd_env.UserInstallTargetHeader('/include/rd_client.h', 'service/resource-directory', 'rd_client.h')
-rd_env.UserInstallTargetHeader('/include/rd_server.h', 'service/resource-directory', 'rd_server.h')
+rd_env.InstallTarget(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetLib(rdsdk, 'resource_directory')
+rd_env.UserInstallTargetHeader('include/rd_client.h', 'service/resource-directory', 'rd_client.h')
+rd_env.UserInstallTargetHeader('include/rd_server.h', 'service/resource-directory', 'rd_server.h')
######################################################################
# Samples for the resource directory
######################################################################
-SConscript('samples/SConscript')
+if target_os not in ['windows']:
+ SConscript('samples/SConscript')
rd_sample_app_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
rd_sample_app_env.AppendUnique(CPPPATH = ['../include'])
-rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+if target_os not in ['windows']:
+ rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
rd_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
rd_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
rd_sample_app_env.PrependUnique(LIBS = ['resource_directory', 'oc', 'octbstack'])
#include "rd_server.h"
#include <signal.h>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
int g_quitFlag = 0;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "rd_storage.h"
+#ifdef HAVE_PTHREAD_H
#include <pthread.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
#include <string.h>
#include "payload_logging.h"
#define TAG PCF("RDStorage")
-pthread_mutex_t storageMutex = PTHREAD_MUTEX_INITIALIZER;
-// This variable holds the published resources on the RD.
+// Mutex implementation macros
+#if defined(HAVE_PTHREAD_H)
+
+#include <pthread.h>
+pthread_mutex_t storageMutex;
+#define MUTEX_LOCK(ARG_NAME) { pthread_mutex_lock(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME) { pthread_mutex_unlock(ARG_NAME); }
+
+#elif defined(HAVE_WINDOWS_H)
+
+#include <windows.h>
+CRITICAL_SECTION storageMutex;
+#define MUTEX_LOCK(ARG_NAME) { EnterCriticalSection(ARG_NAME); }
+#define MUTEX_UNLOCK(ARG_NAME) { LeaveCriticalSection(ARG_NAME); }
+
+#else
+
+ERROR Need mutex implementation for this platform
+#define MUTEX_LOCK(ARG_NAME) { }
+#define MUTEX_UNLOCK(ARG_NAME) { }
+
+#endif
+
+
static OCRDStorePublishResources *g_rdStorage = NULL;
static void printStoragedResources(OCRDStorePublishResources *payload)
resources->publishedResource = storeResource;
resources->devAddr = *address;
- pthread_mutex_lock(&storageMutex);
+ MUTEX_LOCK(&storageMutex);
if (g_rdStorage)
{
OCRDStorePublishResources *temp = g_rdStorage;
{
g_rdStorage = resources;
}
- pthread_mutex_unlock(&storageMutex);
+ MUTEX_UNLOCK(&storageMutex);
printStoragedResources(g_rdStorage);
return OC_STACK_OK;
#include "oic_string.h"
#include "oic_malloc.h"
#include "payload_logging.h"
+#include "platform_features.h"
#include "rdpayload.h"
#include "ocpayload.h"
return result;
}
-static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx,
- __attribute__((unused)) OCDoHandle handle,
- __attribute__((unused)) OCClientResponse *clientResponse)
+static OCStackApplicationResult handlePublishCB(OC_ANNOTATE_UNUSED void *ctx,
+ OC_ANNOTATE_UNUSED OCDoHandle handle,
+ OC_ANNOTATE_UNUSED OCClientResponse *clientResponse)
{
OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
OIC_LOG(DEBUG, TAG, "Successfully published resources.");
}
static OCStackApplicationResult handleDiscoverCB(void *ctx,
- __attribute__((unused)) OCDoHandle handle, OCClientResponse *clientResponse)
+ OC_ANNOTATE_UNUSED OCDoHandle handle, OCClientResponse *clientResponse)
{
OIC_LOG(DEBUG, TAG, "Found Resource Directory");
OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
* This internal method is the entity handler for RD resources and
* will handle REST request (GET/PUT/POST/DEL) for them.
*/
+#ifdef _MSC_VER
+static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *ehRequest, void *callbackParameter)
+#else
static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
OCEntityHandlerRequest *ehRequest, __attribute__((unused)) void *callbackParameter)
+#endif
{
OCEntityHandlerResult ehRet = OC_EH_ERROR;
ResourceClientsdk_static = resourceClient_env.StaticLibrary('rcs_client', client_src)
ResourceClientsdk_shared = resourceClient_env.SharedLibrary('rcs_client', client_src)
-resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
-resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'librcs_client')
+resourceClient_env.InstallTarget([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
+resourceClient_env.UserInstallTargetLib([ResourceClientsdk_static,ResourceClientsdk_shared], 'rcs_client')
resourceClient_env.UserInstallTargetHeader('include/RCSAddress.h', 'service/resource-encapsulation', 'RCSAddress.h')
resourceClient_env.UserInstallTargetHeader('include/RCSDiscoveryManager.h', 'service/resource-encapsulation', 'RCSDiscoveryManager.h')
resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'service/resource-encapsulation', 'RCSRemoteResourceObject.h')
SConscript('src/resourceBroker/unittest/SConscript')
if target_os == 'android':
- SConscript('android/SConscript')
\ No newline at end of file
+ SConscript('android/SConscript')
#include <octypes.h>
+#include "boost/config.hpp"
+
namespace OIC
{
namespace Service
*/
explicit RCSException(std::string &&what);
- virtual ~RCSException() noexcept;
+ virtual ~RCSException() BOOST_NOEXCEPT;
/**
* Returns the exception description.
*
*/
- virtual const char *what() const noexcept;
+ virtual const char *what() const BOOST_NOEXCEPT;
private:
/**
class KeyValueVisitorHelper: public boost::static_visitor< >
{
public:
- KeyValueVisitorHelper(VISITOR& visitor) noexcept :
+ KeyValueVisitorHelper(VISITOR& visitor) BOOST_NOEXCEPT :
m_visitor( visitor )
{
}
*
* @see getBaseTypeId
*/
- TypeId getId() const noexcept;
+ TypeId getId() const BOOST_NOEXCEPT;
/**
* Returns the type identifier of a base type of sequence.
* @see getDepth
* @see getId
*/
- static TypeId getBaseTypeId(const Type& t) noexcept;
+ static TypeId getBaseTypeId(const Type& t) BOOST_NOEXCEPT;
/**
* Returns the depth of a type.
*
* @see getBaseTypeId
*/
- static size_t getDepth(const Type& t) noexcept;
+ static size_t getDepth(const Type& t) BOOST_NOEXCEPT;
/**
* Factory method to create Type instance from T.
* @see is_supported_type
*/
template < typename T >
- constexpr static Type typeOf(const T&) noexcept
+ constexpr static Type typeOf(const T&) BOOST_NOEXCEPT
{
return Type{ IndexOfType< T >::value };
}
* @see is_supported_type
*/
template < typename T >
- constexpr static Type typeOf() noexcept
+ constexpr static Type typeOf() BOOST_NOEXCEPT
{
return Type{ IndexOfType< T >::value };
}
//! @cond
- friend bool operator==(const Type&, const Type&) noexcept;
+ friend bool operator==(const Type&, const Type&) BOOST_NOEXCEPT;
//! @endcond
private:
- constexpr explicit Type(int which) noexcept :
+ constexpr explicit Type(int which) BOOST_NOEXCEPT :
m_which{ which }
{
}
Value();
Value(const Value&);
- Value(Value&&) noexcept;
+ Value(Value&&) BOOST_NOEXCEPT;
/**
* Constructs a Value if T is a supported type.<br/>
/**
* Exchanges the content of the object by the content of the parameter.
*/
- void swap(Value&) noexcept;
+ void swap(Value&) BOOST_NOEXCEPT;
//! @cond
friend class RCSResourceAttributes;
/**
* Returns an {@link iterator} referring to the first element.
*/
- iterator begin() noexcept;
+ iterator begin() BOOST_NOEXCEPT;
/**
* Returns an {@link iterator} referring to the <i>past-the-end element</i>.
*/
- iterator end() noexcept;
+ iterator end() BOOST_NOEXCEPT;
/**
* @copydoc cbegin()
*/
- const_iterator begin() const noexcept;
+ const_iterator begin() const BOOST_NOEXCEPT;
/**
* @copydoc cend()
*/
- const_iterator end() const noexcept;
+ const_iterator end() const BOOST_NOEXCEPT;
/**
* Returns a const_iterator referring to the first element.
*/
- const_iterator cbegin() const noexcept;
+ const_iterator cbegin() const BOOST_NOEXCEPT;
/**
* Returns a const_iterator referring to the <i>past-the-end element</i>.
*/
- const_iterator cend() const noexcept;
+ const_iterator cend() const BOOST_NOEXCEPT;
/**
* Accesses a value.
/**
* Removes all elements.
*/
- void clear() noexcept;
+ void clear() BOOST_NOEXCEPT;
/**
* Removes a single element.
*
* @see size
*/
- bool empty() const noexcept;
+ bool empty() const BOOST_NOEXCEPT;
/**
* Returns the number of elements.
*
* @see empty
*/
- size_t size() const noexcept;
+ size_t size() const BOOST_NOEXCEPT;
private:
template< typename VISITOR >
* @return true if the objects are equal, false otherwise.
*/
bool operator==(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
- noexcept;
+ BOOST_NOEXCEPT;
/**
* @relates RCSResourceAttributes::Type
* @return true if the objects are not equal, false otherwise.
*/
bool operator!=(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
- noexcept;
+ BOOST_NOEXCEPT;
/**
* @relates RCSResourceAttributes::Value
class KeyVisitor: public boost::static_visitor< const std::string& >
{
public:
- result_type operator()(iterator*) const noexcept;
- result_type operator()(const_iterator*) const noexcept;
+ result_type operator()(iterator*) const BOOST_NOEXCEPT;
+ result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
};
class ValueVisitor: public boost::static_visitor< Value& >
{
public:
- result_type operator()(iterator*) noexcept;
+ result_type operator()(iterator*) BOOST_NOEXCEPT;
result_type operator()(const_iterator*);
};
class ConstValueVisitor: public boost::static_visitor< const Value& >
{
public:
- result_type operator()(iterator*) const noexcept;
- result_type operator()(const_iterator*) const noexcept;
+ result_type operator()(iterator*) const BOOST_NOEXCEPT;
+ result_type operator()(const_iterator*) const BOOST_NOEXCEPT;
};
public:
- const std::string& key() const noexcept;
- const RCSResourceAttributes::Value& value() const noexcept;
+ const std::string& key() const BOOST_NOEXCEPT;
+ const RCSResourceAttributes::Value& value() const BOOST_NOEXCEPT;
RCSResourceAttributes::Value& value();
private:
KeyValuePair(const KeyValuePair&) = default;
- KeyValuePair(boost::variant< iterator*, const_iterator* >&&) noexcept;
+ KeyValuePair(boost::variant< iterator*, const_iterator* >&&) BOOST_NOEXCEPT;
KeyValuePair& operator=(const KeyValuePair&) = default;
else :
resourcehostingsdk = resourcehosting_env.StaticLibrary('resource_hosting', resourcehosting_src)
-resourcehosting_env.InstallTarget(resourcehostingsdk, 'libresource_hosting')
-resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'libresource_hosting')
+resourcehosting_env.InstallTarget(resourcehostingsdk, 'resource_hosting')
+resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'resource_hosting')
resourcehosting_env.UserInstallTargetHeader('include/Hosting.h',\
'service/resource-hosting', 'Hosting.h')
#include "RCSRemoteResourceObject.h"
#include "RCSResourceObject.h"
+#ifdef _MSC_VER
+#define OIC_HOSTING_LOG(level, fmt, ...) OIC_LOG_V((level), PCF("Hosting"), fmt, __VA_ARGS__)
+#else
#define OIC_HOSTING_LOG(level, fmt, args...) OIC_LOG_V((level), PCF("Hosting"), fmt, ##args)
+#endif
namespace OIC
{
#include <vector>
#include <cstdio>
#include <iostream>
-
#include <ctime>
-
#include <timer.h>
using namespace std;
#include <algorithm>
#include <thread>
+#ifdef HAVE_UNISTD_H
#include <unistd.h>
+#endif
#include <string.h>
#include "GroupManager.h"
elif target_os == 'darwin':
lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+elif target_os == 'windows':
+ boost_path = os.path.join(src_dir,'extlibs','boost')
+ lib_env.AppendUnique(CPPPATH = [boost_path])
Import('env')
lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
test_cmd = os.path.join(build_dir, test)
- if xml_file:
+ have_valgrind = False
+ if env.get('TARGET_OS') not in ['windows']:
+ have_valgrind = True
+
+ if xml_file and have_valgrind:
# Environment variables to be made available during the
# Valgrind run.
valgrind_environment = ''
# read the tools on *nix systems and sets the default parameters
- elif env["PLATFORM"] in ["darwin", "linux", "posix"] :
+ elif env["PLATFORM"] in ["darwin", "linux", "posix", "msys"] :
if env.WhereIs("unzip") :
toolset["EXTRACTOR"]["ZIP"]["RUN"] = "unzip"