Merge branch 'master' into windows-port
authorDavid Antler <david.a.antler@intel.com>
Mon, 6 Jun 2016 18:04:17 +0000 (11:04 -0700)
committerDavid Antler <david.a.antler@intel.com>
Mon, 6 Jun 2016 18:04:17 +0000 (11:04 -0700)
Change-Id: I87c2e5ee2d6c9574c2a50d83256d6845a340fd86
Signed-off-by: David Antler <david.a.antler@intel.com>
237 files changed:
.gitignore
SConstruct
build_common/SConscript
build_common/arduino/SConscript
build_common/external_libs.scons
build_common/msys_nt/SConscript [new file with mode: 0644]
build_common/tools/UnpackAll.py
build_common/windows/SConscript
extlibs/boost/SConscript
extlibs/cjson/cJSON.h
extlibs/gtest/SConscript
extlibs/sqlite3/SConscript
extlibs/timer/SConscript
extlibs/timer/timer.c
extlibs/timer/timer.h
extlibs/tinydtls/SConscript
extlibs/tinydtls/alert.h
extlibs/tinydtls/ccm.c
extlibs/tinydtls/crypto.c
extlibs/tinydtls/crypto.h
extlibs/tinydtls/debug.c
extlibs/tinydtls/debug.h
extlibs/tinydtls/dtls.c
extlibs/tinydtls/dtls.h
extlibs/tinydtls/dtls_config.h
extlibs/tinydtls/dtls_time.c
extlibs/tinydtls/dtls_time.h
extlibs/tinydtls/global.h
extlibs/tinydtls/hmac.c
extlibs/tinydtls/hmac.h
extlibs/tinydtls/netq.c
extlibs/tinydtls/netq.h
extlibs/tinydtls/numeric.h
extlibs/tinydtls/peer.c
extlibs/tinydtls/peer.h
extlibs/tinydtls/prng.h
extlibs/tinydtls/session.c
extlibs/tinydtls/session.h
extlibs/tinydtls/t_list.h
extlibs/tinydtls/tests/dtls-client.c
extlibs/tinydtls/tests/dtls-server.c
extlibs/tinydtls/tinydtls.h
extlibs/tinydtls/utlist.h
plugins/SConscript
plugins/src/SConscript
resource/SConscript
resource/c_common/SConscript
resource/c_common/ocrandom/include/ocrandom.h
resource/c_common/ocrandom/src/ocrandom.c
resource/c_common/oic_time/include/oic_time.h
resource/c_common/oic_time/src/oic_time.c
resource/c_common/platform_features.h
resource/c_common/windows/SConscript [new file with mode: 0644]
resource/c_common/windows/include/getopt.h [new file with mode: 0644]
resource/c_common/windows/include/pthread_create.h [new file with mode: 0644]
resource/c_common/windows/include/vs12_snprintf.h [new file with mode: 0644]
resource/c_common/windows/include/win_sleep.h [new file with mode: 0644]
resource/c_common/windows/src/getopt.c [new file with mode: 0644]
resource/c_common/windows/src/pthread_create.c [new file with mode: 0644]
resource/c_common/windows/src/snprintf.c [new file with mode: 0644]
resource/c_common/windows/src/win_sleep.c [new file with mode: 0644]
resource/csdk/SConscript
resource/csdk/connectivity/SConscript
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/common/SConscript
resource/csdk/connectivity/common/src/camutex_noop.c
resource/csdk/connectivity/common/src/camutex_pthreads.c
resource/csdk/connectivity/common/src/cathreadpool_pthreads.c
resource/csdk/connectivity/inc/caadapternetdtls.h
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
resource/csdk/connectivity/lib/libcoap-4.1.1/address.h
resource/csdk/connectivity/lib/libcoap-4.1.1/async.h
resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h
resource/csdk/connectivity/lib/libcoap-4.1.1/block.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h
resource/csdk/connectivity/lib/libcoap-4.1.1/config.h
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h
resource/csdk/connectivity/lib/libcoap-4.1.1/net.c
resource/csdk/connectivity/lib/libcoap-4.1.1/net.h
resource/csdk/connectivity/lib/libcoap-4.1.1/option.c
resource/csdk/connectivity/lib/libcoap-4.1.1/option.h
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h
resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h
resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c
resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/caqueueingthread.c
resource/csdk/connectivity/src/caretransmission.c
resource/csdk/connectivity/src/ip_adapter/SConscript
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp
resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/windows/SConscript [new file with mode: 0644]
resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c [new file with mode: 0644]
resource/csdk/connectivity/test/SConscript
resource/csdk/connectivity/test/ca_api_unittest.cpp
resource/csdk/connectivity/test/camutex_tests.cpp
resource/csdk/connectivity/test/catests.cpp
resource/csdk/logger/SConscript
resource/csdk/logger/include/logger.h
resource/csdk/logger/src/logger.c
resource/csdk/routing/src/routingutility.c
resource/csdk/security/SConscript
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/pmutility.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/dpairingresource.c
resource/csdk/security/src/iotvticalendar.c
resource/csdk/security/src/pbkdf2.c
resource/csdk/security/src/pconfresource.c
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmutility.c
resource/csdk/security/src/strptime.c [new file with mode: 0644]
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/iotvticalendartest.cpp
resource/csdk/security/unittest/policyengine.cpp
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/securityresourcemanager.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/stack/include/internal/ocpayloadcbor.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/include/rdpayload.h
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/common.h [new file with mode: 0644]
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocremoteaccessclient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/ocamsservice.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c
resource/csdk/stack/src/oicgroup.c
resource/csdk/stack/src/oickeepalive.c
resource/csdk/stack/test/SConscript
resource/csdk/stack/test/cbortests.cpp
resource/csdk/stack/test/stacktests.cpp
resource/examples/SConscript
resource/examples/lightserver.cpp
resource/examples/mediaserver.cpp [new file with mode: 0644]
resource/examples/presenceclient.cpp
resource/examples/presenceserver.cpp
resource/examples/simpleclient.cpp
resource/examples/simpleclientHQ.cpp
resource/examples/simpleserver.cpp
resource/examples/simpleserverHQ.cpp
resource/examples/threadingsample.cpp
resource/examples/winuiclient.cpp [new file with mode: 0644]
resource/examples/winuiclient.h [new file with mode: 0644]
resource/examples/winuiclientgui.cpp [new file with mode: 0644]
resource/include/AttributeValue.h
resource/include/OCApi.h
resource/include/OCHeaderOption.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceRequest.h
resource/include/OCResourceResponse.h
resource/include/OCUtilities.h
resource/include/ResourceInitException.h
resource/include/StringConstants.h
resource/oc_logger/SConscript
resource/oc_logger/examples/SConscript
resource/oc_logger/include/oc_log_stream.hpp
resource/src/CAManager.cpp
resource/src/InProcClientWrapper.cpp
resource/src/InProcServerWrapper.cpp
resource/src/OCApi.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons
run.bat [new file with mode: 0644]
scons_script_how_to.txt
service/SConscript
service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript
service/resource-container/src/Configuration.h
service/resource-directory/SConscript
service/resource-directory/samples/SConscript
service/resource-directory/samples/rd_main.c
service/resource-directory/src/internal/rd_storage.c
service/resource-directory/src/rd_client.c
service/resource-directory/src/rd_server.c
service/resource-encapsulation/SConscript
service/resource-encapsulation/include/RCSException.h
service/resource-encapsulation/include/RCSResourceAttributes.h
service/resource-hosting/SConscript
service/resource-hosting/src/HostingObject.h
service/things-manager/sdk/inc/ActionSet.h
service/things-manager/sdk/src/GroupManager.cpp
service/third_party_libs.scons
tools/scons/RunTest.py
tools/scons/UnpackAll.py

index f132748..7d0ce16 100644 (file)
@@ -97,7 +97,7 @@ extlibs/android/sdk/android-sdk_r24.2
 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
index 35ff720..ac76f39 100644 (file)
@@ -56,7 +56,7 @@ build_dir = env.get('BUILD_DIR')
 # 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
@@ -76,6 +76,6 @@ env.PrintTargets()
 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')
 
index 2be70ce..0ef15ee 100644 (file)
@@ -10,6 +10,7 @@ host_target_map = {
                '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)
@@ -18,6 +19,7 @@ os_arch_map = {
                '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'],
@@ -27,6 +29,11 @@ os_arch_map = {
 
 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)
@@ -230,6 +237,9 @@ def __installlib(ienv, targets, name):
                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')
@@ -241,7 +251,9 @@ def __installheader(ienv, targets, dir, name):
        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')
@@ -251,7 +263,9 @@ def __installpcfile(ienv, targets, name):
                        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:
@@ -308,8 +322,8 @@ if user_prefix:
                                '\@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
@@ -413,6 +427,52 @@ conf = Configure(env,
 # 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()
 ######################################################################
 
index 73e753e..5dffa92 100644 (file)
@@ -259,6 +259,9 @@ if env.get('RELEASE'):
 else:
        env.AppendUnique(CCFLAGS = ['-g'])
 
+# Force header presence defines
+env.AppendUnique(CPPDEFINES = ['HAVE_ARDUINO_TIME_H'])
+
 # BOARD / CPU option
 
 # Get IDE version
index 2e28220..f1e8295 100644 (file)
@@ -40,8 +40,9 @@ if target_os == 'darwin':
 
 # 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
diff --git a/build_common/msys_nt/SConscript b/build_common/msys_nt/SConscript
new file mode 100644 (file)
index 0000000..140f54b
--- /dev/null
@@ -0,0 +1,33 @@
+##
+# 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'])
index 0df17e4..514b54c 100644 (file)
@@ -307,48 +307,55 @@ def generate( env ) :
     # 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
@@ -356,7 +363,7 @@ def generate( env ) :
 
 
     # 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"
index 4c35d35..bf57dee 100644 (file)
@@ -2,16 +2,41 @@
 # 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'])
index c9fa5cf..d32b8b5 100644 (file)
@@ -8,24 +8,54 @@ modules = ['thread','program_options', 'system', 'date_time']
 
 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' :
index 867b7c3..eef7b8b 100644 (file)
@@ -39,6 +39,8 @@ extern "C"
        
 #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 */
@@ -59,71 +61,71 @@ typedef struct cJSON_Hooks {
 } 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())
index 6ecdcd1..bdff00e 100644 (file)
@@ -11,9 +11,9 @@ Import('env')
 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:
@@ -27,8 +27,9 @@ 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':
@@ -79,3 +80,95 @@ elif target_os == 'linux':
                        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)
+
index 41c65df..a7e033b 100755 (executable)
@@ -11,11 +11,11 @@ sqlite_env = env.Clone()
 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:
@@ -39,4 +39,4 @@ 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.
index edcc7ef..33d134a 100644 (file)
 # *****************************************************************/
 
 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');
 
index 43043a6..88deb05 100755 (executable)
 
 #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"
@@ -255,9 +267,8 @@ void *loop(void *threadid)
 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)
     {
index 3ecff36..3ad432a 100644 (file)
 #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
 
index 5d186a2..54cb48e 100644 (file)
@@ -40,9 +40,6 @@ dtls_env.AppendUnique(CPPPATH = [root_dir+'aes/'])
 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)
 ######################################################################
@@ -93,6 +90,9 @@ if not env.get('RELEASE'):
        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')
index 5a27faa..a589dd7 100644 (file)
@@ -66,13 +66,13 @@ typedef enum {
                                          * 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);
index 7563db8..1366145 100644 (file)
@@ -46,7 +46,7 @@
       (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 */
@@ -145,7 +145,7 @@ add_auth_data(rijndael_ctx *ctx, const unsigned char *msg, size_t la,
   } 
 }
 
-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],
@@ -158,7 +158,7 @@ encrypt(rijndael_ctx *ctx, size_t L, unsigned long counter,
   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],
index de07f49..d9ec048 100644 (file)
@@ -60,7 +60,7 @@
 #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;
@@ -82,7 +82,7 @@ static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
 
 static void dtls_cipher_context_release(void)
 {
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(_WIN32)
   pthread_mutex_unlock(&cipher_context_mutex);
 #endif
 }
index 8ea83f2..8acf787 100644 (file)
@@ -158,7 +158,7 @@ typedef struct {
 /* 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)
     {
@@ -184,7 +184,7 @@ static inline int dtls_kb_mac_secret_size(dtls_cipher_t 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)
     {
index 589c091..5b458bc 100644 (file)
@@ -87,7 +87,7 @@ static char *loglevels[] = {
 
 #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);
@@ -96,7 +96,7 @@ print_timestamp(char *s, size_t len, time_t 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", 
@@ -118,7 +118,7 @@ print_timestamp(char *s, size_t len, clock_time_t t) {
  * 
  * @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)
@@ -132,9 +132,9 @@ dtls_strnlen(const char *s, size_t 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;
index 95286f8..89af876 100644 (file)
@@ -41,7 +41,7 @@
 #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++;
@@ -50,13 +50,13 @@ static inline void check_stack() {
   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
 
@@ -102,28 +102,28 @@ void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr);
 
 #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)
 {}
 
index bb26ade..1017346 100644 (file)
@@ -138,23 +138,23 @@ PROCESS(dtls_retransmit_process, "DTLS retransmit process");
 
 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);
 }
@@ -415,7 +415,7 @@ is_record(uint8 *msg, size_t msglen) {
  * \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) {
   
@@ -449,7 +449,7 @@ dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
  * 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, 
@@ -487,7 +487,7 @@ static uint8 compression_methods[] = {
 };
 
 /** 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;
@@ -497,7 +497,7 @@ static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
 }
 
 /** 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;
@@ -507,7 +507,7 @@ static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
 }
 
 /** 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;
@@ -517,7 +517,7 @@ static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher
 }
 
 /** 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;
@@ -529,7 +529,7 @@ static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher
 
 
 /** 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;
@@ -539,7 +539,7 @@ static inline int is_psk_supported(dtls_context_t *ctx)
 }
 
 /** 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) ||
@@ -550,7 +550,7 @@ static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
 }
 
 /** 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) ||
@@ -562,7 +562,7 @@ static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
 
 /** 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;
@@ -573,7 +573,7 @@ static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
 
 /** 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;
@@ -583,7 +583,7 @@ static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
 }
 
 /** 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);
@@ -593,7 +593,7 @@ static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
 }
 
 /** 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);
@@ -1183,7 +1183,7 @@ error:
  * 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) {
@@ -1299,7 +1299,7 @@ check_client_keyexchange(dtls_context_t *ctx,
   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);
@@ -1311,12 +1311,12 @@ copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
         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");
@@ -1765,7 +1765,7 @@ dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
   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 };
@@ -2616,7 +2616,7 @@ dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
   return 0;
 }
 
-static inline int 
+INLINE_API int 
 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
   uint8 buf[1] = {1};
 
@@ -4621,7 +4621,11 @@ dtls_context_t *
 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 */
@@ -4630,6 +4634,14 @@ dtls_new_context(void *app_data) {
 #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");
index 7cdaab2..5c23ca3 100644 (file)
@@ -368,7 +368,7 @@ void dtls_free_context(dtls_context_t *ctx);
 #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;
 }
 
@@ -454,8 +454,14 @@ void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next);
 #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 */
@@ -479,7 +485,7 @@ typedef struct __attribute__((__packed__)) {
 #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 */
@@ -489,7 +495,7 @@ typedef struct __attribute__((__packed__)) {
 } 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 */
@@ -500,7 +506,7 @@ typedef struct __attribute__((__packed__)) {
 } 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 */
index c6c4e39..5e0103a 100644 (file)
@@ -73,7 +73,9 @@
 #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                                           */
index 88c292a..3018091 100644 (file)
@@ -47,12 +47,20 @@ dtls_ticks(dtls_tick_t *t) {
 }
 
 #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__
@@ -62,9 +70,13 @@ dtls_clock_init(void) {
 #  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);
@@ -73,6 +85,7 @@ void dtls_ticks(dtls_tick_t *t) {
 #else
 #error "clock not implemented"
 #endif
+#endif
 }
 
 #endif /* WITH_CONTIKI */
index 82ff062..6541b1c 100644 (file)
@@ -32,7 +32,9 @@
 #define _DTLS_DTLS_TIME_H_
 
 #include <stdint.h>
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
+#endif
 
 #include "tinydtls.h"
 
index 75877fd..8f947e7 100644 (file)
@@ -115,7 +115,7 @@ typedef enum {
 /**
  * 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;
@@ -133,7 +133,7 @@ memxor(unsigned char *x, const unsigned char *y, size_t n) {
  * \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--) {
@@ -145,7 +145,7 @@ equals(unsigned char *a, unsigned char *b, size_t 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++)
index 0a9b8f7..571a59a 100644 (file)
 #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);
 }
@@ -56,12 +56,12 @@ dtls_hmac_context_free(dtls_hmac_context_t *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);
 }
index 0eacd99..e4046a7 100644 (file)
@@ -39,17 +39,17 @@ typedef dtls_sha256_ctx dtls_hash_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;
@@ -57,7 +57,7 @@ dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx) {
 #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();
index 0a10a50..8589858 100644 (file)
 #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);
 }
@@ -41,12 +41,12 @@ netq_free_node(netq_t *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);
 }
index fea7511..c3db339 100644 (file)
@@ -55,7 +55,7 @@ typedef struct netq_t {
 } netq_t;
 
 #ifndef WITH_CONTIKI
-static inline void netq_init()
+INLINE_API void netq_init()
 { }
 #else
 void netq_init();
index e319f5b..5af0c4c 100644 (file)
 #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;
@@ -58,7 +58,7 @@ static inline int dtls_int_to_uint24(unsigned char *field, uint32_t value)
   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;
@@ -67,7 +67,7 @@ static inline int dtls_int_to_uint32(unsigned char *field, uint32_t value)
   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;
@@ -78,7 +78,7 @@ static inline int dtls_int_to_uint48(unsigned char *field, uint64_t value)
   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;
@@ -91,25 +91,25 @@ static inline int dtls_int_to_uint64(unsigned char *field, uint64_t value)
   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)
@@ -117,7 +117,7 @@ static inline uint32_t dtls_uint32_to_int(const unsigned char *field)
         | (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)
@@ -127,7 +127,7 @@ static inline uint64_t dtls_uint48_to_int(const unsigned char *field)
         | (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)
index 8f2876c..109a612 100644 (file)
@@ -32,7 +32,7 @@ void peer_init()
 {
 }
 
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
 dtls_malloc_peer() {
   return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
 }
@@ -54,7 +54,7 @@ peer_init() {
   memb_init(&peer_storage);
 }
 
-static inline dtls_peer_t *
+INLINE_API dtls_peer_t *
 dtls_malloc_peer() {
   return memb_alloc(&peer_storage);
 }
index af7c205..41fd943 100644 (file)
@@ -65,7 +65,7 @@ typedef struct dtls_peer_t {
   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];
@@ -76,12 +76,12 @@ static inline dtls_security_parameters_t *dtls_security_params_epoch(dtls_peer_t
   }
 }
 
-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]);
@@ -94,7 +94,7 @@ static inline dtls_security_parameters_t *dtls_security_params_next(dtls_peer_t
   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];
@@ -106,7 +106,7 @@ static inline void dtls_security_params_free_other(dtls_peer_t *peer)
   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];
 
@@ -133,7 +133,7 @@ dtls_peer_t *dtls_new_peer(const session_t *session);
 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;
 }
 
@@ -141,7 +141,7 @@ static inline dtls_state_t dtls_peer_state(const dtls_peer_t *peer) {
  * 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;
 }
 
index 48c1f95..daf956b 100644 (file)
  * 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);
 }
@@ -45,7 +45,7 @@ dtls_prng_init(unsigned short 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);
@@ -56,7 +56,7 @@ dtls_prng(unsigned char *buf, size_t 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)) {
@@ -71,7 +71,7 @@ dtls_prng(unsigned char *buf, size_t len) {
 }
 #endif /* HAVE_PRNG */
 
-static inline void
+INLINE_API void
 dtls_prng_init(unsigned short seed) {
        random_init(seed);
 }
index 9acf565..51155b0 100644 (file)
@@ -44,7 +44,7 @@
 
 #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 ||
index 61b5661..bd848f2 100644 (file)
@@ -28,6 +28,7 @@
 
 #include <string.h>
 
+#include "dtls_config.h"
 #include "tinydtls.h"
 #include "global.h"
 
@@ -42,9 +43,22 @@ typedef struct {
 
 #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 */
index eb72991..1c3fba9 100644 (file)
@@ -92,28 +92,28 @@ struct list {
     (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;
@@ -123,7 +123,7 @@ list_pop(list_t 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);
@@ -133,7 +133,7 @@ list_insert(list_t list, void *previtem, void *newitem) {
   } 
 }
 
-static inline void *
+INLINE_API void *
 list_item_next(void *item)
 {
   return item == NULL? NULL: ((struct list *)item)->next;
index 279d91a..08f1a30 100644 (file)
@@ -6,15 +6,29 @@
 #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"
@@ -471,7 +485,11 @@ static void dtls_handle_signal(int sig)
   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: */
@@ -778,7 +796,7 @@ main(int argc, char **argv) {
     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
@@ -790,9 +808,9 @@ main(int argc, char **argv) {
 #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));
   }
index a3ede4d..9a8918a 100644 (file)
@@ -6,13 +6,25 @@
 #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"
@@ -664,7 +676,7 @@ main(int argc, char **argv) {
     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
@@ -676,9 +688,9 @@ main(int argc, char **argv) {
 #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));
   }
index ac849ef..eca7ff7 100644 (file)
 /** 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_ */
index 9cd4532..dd72b7d 100644 (file)
@@ -338,11 +338,11 @@ do {
     (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);                                                    \
index 86c1635..8fc70bc 100644 (file)
@@ -29,7 +29,7 @@ target_os = env.get('TARGET_OS')
 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'))
 
index 939084d..e7daaa6 100644 (file)
@@ -81,6 +81,6 @@ if target_os in ['android', 'tizen']:
        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')
 
index b07bc95..554bb9d 100644 (file)
@@ -23,8 +23,6 @@
 #
 ##
 
-import os
-
 Import('env')
 
 target_os = env.get('TARGET_OS')
@@ -33,7 +31,7 @@ src_dir = env.get('SRC_DIR')
 # 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
@@ -66,7 +64,7 @@ if target_os not in ['arduino','darwin','ios','android']:
        # 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')
 
@@ -86,3 +84,10 @@ elif target_os == 'darwin':
 
 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')
index a9285ae..2b46f5c 100644 (file)
@@ -24,18 +24,22 @@ import os
 
 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")
@@ -43,6 +47,7 @@ if target_os in ['tizen', 'linux']:
 env.PrependUnique(LIBS = ['c_common'])
 
 common_env = env.Clone()
+common_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource')])
 
 ######################################################################
 # Build flags
index e096fc5..7a91dea 100644 (file)
@@ -29,9 +29,9 @@
 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
index 95472b6..118aeee 100644 (file)
 #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"
@@ -104,13 +114,18 @@ uint8_t GetRandomBit()
 
 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);
@@ -120,7 +135,7 @@ int8_t OCSeedRandom()
     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)
     {
@@ -140,6 +155,7 @@ int8_t OCSeedRandom()
         srand(randomSeed | currentTime);
     }
     else
+#endif
     {
         // Do time based seed when problem in accessing "/dev/urandom"
         srand(currentTime);
@@ -184,15 +200,11 @@ uint32_t OCGetRandom()
 
 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)
@@ -273,7 +285,7 @@ OCRandomUuidResult OCGenerateUuid(uint8_t uuid[UUID_SIZE])
     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;
@@ -318,7 +330,7 @@ OCRandomUuidResult OCGenerateUuidString(char uuidString[UUID_STRING_SIZE])
         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);
 
index 3ecdd8a..0deba60 100644 (file)
@@ -28,6 +28,7 @@
 #define US_PER_MS   (1000)
 #define NS_PER_US   (1000)
 #define NS_PER_MS   (1000000)
+#define HNS_PER_US  (10)
 
 
 #ifdef __cplusplus
index 2415d42..4a07ceb 100644 (file)
@@ -34,7 +34,9 @@
 
 #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
@@ -50,6 +52,22 @@ uint64_t OICGetCurrentTime(OICTimePrecision precision)
 
 #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)
index 3f712a3..680f367 100644 (file)
 #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
diff --git a/resource/c_common/windows/SConscript b/resource/c_common/windows/SConscript
new file mode 100644 (file)
index 0000000..85c4bf3
--- /dev/null
@@ -0,0 +1,26 @@
+##
+# 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'])
+
diff --git a/resource/c_common/windows/include/getopt.h b/resource/c_common/windows/include/getopt.h
new file mode 100644 (file)
index 0000000..8e11854
--- /dev/null
@@ -0,0 +1,20 @@
+/** @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
+
diff --git a/resource/c_common/windows/include/pthread_create.h b/resource/c_common/windows/include/pthread_create.h
new file mode 100644 (file)
index 0000000..80677ad
--- /dev/null
@@ -0,0 +1,26 @@
+/** @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__
+
diff --git a/resource/c_common/windows/include/vs12_snprintf.h b/resource/c_common/windows/include/vs12_snprintf.h
new file mode 100644 (file)
index 0000000..37f1d3f
--- /dev/null
@@ -0,0 +1,40 @@
+/* *****************************************************************
+*
+* 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
+
diff --git a/resource/c_common/windows/include/win_sleep.h b/resource/c_common/windows/include/win_sleep.h
new file mode 100644 (file)
index 0000000..8cd1479
--- /dev/null
@@ -0,0 +1,45 @@
+/* *****************************************************************
+*
+* 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
+
diff --git a/resource/c_common/windows/src/getopt.c b/resource/c_common/windows/src/getopt.c
new file mode 100644 (file)
index 0000000..d27ae09
--- /dev/null
@@ -0,0 +1,40 @@
+/** @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
+
diff --git a/resource/c_common/windows/src/pthread_create.c b/resource/c_common/windows/src/pthread_create.c
new file mode 100644 (file)
index 0000000..c7a592d
--- /dev/null
@@ -0,0 +1,23 @@
+/** @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
+
diff --git a/resource/c_common/windows/src/snprintf.c b/resource/c_common/windows/src/snprintf.c
new file mode 100644 (file)
index 0000000..01e4f16
--- /dev/null
@@ -0,0 +1,42 @@
+/* *****************************************************************
+*
+* 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;
+}
+
diff --git a/resource/c_common/windows/src/win_sleep.c b/resource/c_common/windows/src/win_sleep.c
new file mode 100644 (file)
index 0000000..f8f72f3
--- /dev/null
@@ -0,0 +1,45 @@
+/* *****************************************************************
+*
+* 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;
+}
+
index a9ea0f9..b2165a3 100644 (file)
@@ -72,7 +72,8 @@ if target_os not in ['windows', 'winrt']:
 
 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:
@@ -81,24 +82,27 @@ if target_os in ['android', 'linux', 'tizen']:
                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'])
@@ -114,6 +118,7 @@ if env.get('DTLS_WITH_X509') == '1':
 
 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'])
 
@@ -147,18 +152,22 @@ if with_tcp == True:
 
 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')
index d533f71..e4aa2eb 100644 (file)
@@ -35,6 +35,8 @@ if 'ALL' in transport:
                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"
index e725c44..1be743b 100644 (file)
 #include <sys/poll.h>
 #endif
 
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#include <mswsock.h>
+#endif
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -128,13 +133,19 @@ typedef char *CAURI_t;
  */
 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
@@ -250,7 +261,7 @@ typedef struct
     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. **/
@@ -501,24 +512,31 @@ typedef struct
 
     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
         {
index e829d4b..4e46270 100644 (file)
@@ -152,9 +152,9 @@ def __set_dir(env, dir):
                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)
@@ -176,6 +176,9 @@ def __installlib(ienv, targets, name):
        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')
index 79326e5..4db7d47 100644 (file)
@@ -29,7 +29,7 @@ ca_common_src = [
                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'
index d725980..08b1c1e 100644 (file)
 
 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;
 
 /**
@@ -57,7 +63,7 @@ static ca_cond_internal g_condInfo = { 0 };
 
 ca_mutex ca_mutex_new(void)
 {
-    return &g_mutexInfo;
+    return (ca_mutex)&g_mutexInfo;
 }
 
 bool ca_mutex_free(ca_mutex mutex)
@@ -77,7 +83,7 @@ void ca_mutex_unlock(ca_mutex mutex)
 
 ca_cond ca_cond_new(void)
 {
-    return &g_condInfo;
+    return (ca_cond)&g_condInfo;
 }
 
 void ca_cond_free(ca_cond cond)
index 834886c..aa77eb0 100644 (file)
 #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"
 
@@ -76,13 +90,21 @@ static const uint64_t NANOSECS_PER_SEC      = 1000000000L;
 
 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)
@@ -91,6 +113,10 @@ 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)
@@ -102,6 +128,11 @@ ca_mutex ca_mutex_new(void)
             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;
@@ -114,6 +145,11 @@ bool ca_mutex_free(ca_mutex mutex)
     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)
         {
@@ -124,6 +160,7 @@ bool ca_mutex_free(ca_mutex mutex)
         {
             OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
         }
+#endif
     }
     else
     {
@@ -138,12 +175,16 @@ void ca_mutex_lock(ca_mutex mutex)
     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
     {
@@ -157,6 +198,9 @@ void ca_mutex_unlock(ca_mutex mutex)
     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)
         {
@@ -164,11 +208,12 @@ void ca_mutex_unlock(ca_mutex mutex)
             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;
     }
 }
 
@@ -178,6 +223,10 @@ ca_cond ca_cond_new(void)
     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)
         {
@@ -187,14 +236,14 @@ ca_cond ca_cond_new(void)
             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!",
@@ -204,7 +253,7 @@ ca_cond ca_cond_new(void)
                 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)
         {
@@ -216,6 +265,11 @@ ca_cond ca_cond_new(void)
             pthread_condattr_destroy(&(eventInfo->condattr));
             OICFree(eventInfo);
         }
+#endif
+    }
+    else
+    {
+        OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
     }
 
     return retVal;
@@ -226,6 +280,9 @@ void ca_cond_free(ca_cond cond)
     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)
@@ -237,6 +294,7 @@ void ca_cond_free(ca_cond cond)
             OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
                     __func__, ret, ret2);
         }
+#endif
     }
     else
     {
@@ -249,11 +307,15 @@ void ca_cond_signal(ca_cond cond)
     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
     {
@@ -266,11 +328,15 @@ void ca_cond_broadcast(ca_cond cond)
     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
     {
@@ -283,6 +349,14 @@ void ca_cond_wait(ca_cond cond, ca_mutex mutex)
     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
@@ -308,6 +382,7 @@ void ca_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
     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)
 {
@@ -330,6 +405,25 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
 
     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;
 
@@ -367,14 +461,26 @@ CAWaitResult_t ca_cond_wait_for(ca_cond cond, ca_mutex mutex, uint64_t microseco
                 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;
 }
 
index 0fb57de..d17af9c 100644 (file)
 #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")
 
@@ -156,7 +162,6 @@ CAResult_t ca_thread_pool_add_task(ca_thread_pool_t thread_pool, ca_thread_func
     info->data = data;
 
     pthread_t threadHandle;
-
     int result = pthread_create(&threadHandle, NULL, ca_thread_pool_pthreads_delegate, info);
 
     if(result != 0)
@@ -194,11 +199,20 @@ void ca_thread_pool_free(ca_thread_pool_t thread_pool)
     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));
index d9f6e81..2e41cb9 100644 (file)
@@ -20,6 +20,7 @@
 #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"
index cd3f102..5f8c248 100644 (file)
 #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
 
index 03713c5..0623dbe 100644 (file)
@@ -29,7 +29,7 @@ if target_os == 'arduino':
                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'])
 
@@ -37,6 +37,10 @@ if target_os not in ['windows', 'winrt']:
        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'])
@@ -74,6 +78,6 @@ libcoap_src = [
        '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')
index bb44a99..c26784c 100644 (file)
 #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
@@ -76,7 +84,7 @@ typedef struct coap_address_t
 
 #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
@@ -91,7 +99,7 @@ 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)
 {
@@ -116,7 +124,7 @@ _coap_address_equals_impl(const coap_address_t *a,
     return 0;
 }
 
-static inline int
+INLINE_API int
 _coap_is_mcast_impl(const coap_address_t *a)
 {
     if (!a)
@@ -143,7 +151,7 @@ typedef struct coap_address_t
     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)
 {
@@ -163,7 +171,7 @@ _coap_address_equals_impl(const coap_address_t *a,
     return 1;
 }
 
-static inline int
+INLINE_API int
 _coap_is_mcast_impl(const coap_address_t *a)
 {
     if (!a)
@@ -182,7 +190,7 @@ _coap_is_mcast_impl(const coap_address_t *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));
@@ -197,7 +205,7 @@ static inline void coap_address_init(coap_address_t *addr)
  * @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);
@@ -208,7 +216,7 @@ static inline int coap_address_equals(const coap_address_t *a, const coap_addres
  * 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);
 }
index 879cb38..0319827 100644 (file)
@@ -136,7 +136,7 @@ coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id);
  *
  * @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);
 }
index 9add64f..3ac7fe1 100644 (file)
@@ -31,7 +31,7 @@
  *
  * @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;
@@ -51,7 +51,7 @@ inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
  *
  * @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;
@@ -70,7 +70,7 @@ inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
  *
  * @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;
index 2d5ef07..bd660ef 100644 (file)
@@ -71,13 +71,13 @@ unsigned int coap_opt_block_num(const coap_opt_t *block_opt);
  * 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;
index 6eb924b..64d1b26 100644 (file)
@@ -34,6 +34,9 @@ extern "C"
 #ifdef HAVE_TIME_H
 #include <time.h>
 #endif
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
 #ifdef WITH_LWIP
 
 #include <stdint.h>
@@ -44,12 +47,12 @@ extern "C"
 
     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)
     {
     }
 
@@ -75,7 +78,7 @@ extern "C"
     /** 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();
@@ -84,7 +87,7 @@ extern "C"
 
 #define coap_clock_init contiki_clock_init_impl
 
-    static inline void
+    INLINE_API void
     contiki_ticks_impl(coap_tick_t *t)
     {
         *t = clock_time();
@@ -93,7 +96,7 @@ extern "C"
 #define coap_ticks contiki_ticks_impl
 
 #endif /* WITH_CONTIKI */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(_WIN32)
     typedef unsigned int coap_tick_t;
 
     /**
@@ -107,7 +110,7 @@ extern "C"
 
     /** 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"
@@ -134,7 +137,7 @@ extern time_t clock_offset;
 #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);
@@ -159,7 +162,7 @@ extern time_t clock_offset;
 #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;
@@ -176,7 +179,12 @@ extern time_t clock_offset;
 #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 */
 }
@@ -187,7 +195,7 @@ extern time_t clock_offset;
      * 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;
@@ -197,7 +205,7 @@ extern time_t clock_offset;
      * 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);
index 71d396a..622e795 100644 (file)
@@ -4,11 +4,6 @@
 /* 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 */
 
index 027491d..fc4f1da 100644 (file)
@@ -53,7 +53,7 @@ static char *loglevels[] =
 
 #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);
@@ -63,7 +63,7 @@ static inline size_t print_timestamp(char *s, size_t len, coap_tick_t t)
 
 #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
@@ -89,7 +89,7 @@ print_timestamp(char *s, size_t len, coap_tick_t t)
  *
  * @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;
@@ -146,10 +146,12 @@ unsigned int print_readable(const unsigned char *data, unsigned int len, unsigne
 
 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
@@ -194,7 +196,11 @@ size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, si
             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 */
index b1b2e57..a7a8888 100644 (file)
@@ -12,7 +12,7 @@
 #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
index 580729b..48e0455 100644 (file)
 #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);
@@ -70,13 +79,13 @@ coap_free_node(coap_queue_t *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);
@@ -106,13 +115,13 @@ MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
 
 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);
@@ -321,7 +330,7 @@ is_wkc(coap_key_t k)
 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
@@ -386,7 +395,7 @@ coap_new_context(const coap_address_t *listen_addr)
     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 )
     {
@@ -396,7 +405,7 @@ coap_new_context(const coap_address_t *listen_addr)
         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");
@@ -451,7 +460,7 @@ coap_new_context(const coap_address_t *listen_addr)
 
 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;
@@ -468,7 +477,7 @@ void coap_free_context(coap_context_t *context)
     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)
     {
@@ -480,7 +489,7 @@ void coap_free_context(coap_context_t *context)
         }
 #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 );
@@ -538,7 +547,7 @@ void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap
     /* 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:
@@ -598,7 +607,7 @@ coap_send_impl(coap_context_t *context,
 }
 #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,
@@ -611,7 +620,7 @@ 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)
@@ -879,7 +888,7 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
  * 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)
     {
@@ -892,7 +901,7 @@ static inline int check_opt_size(coap_opt_t *opt, unsigned char *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)
@@ -916,7 +925,7 @@ int coap_read(coap_context_t *ctx)
 
     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 */
@@ -1067,7 +1076,7 @@ int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **n
 
 }
 
-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);
@@ -1229,7 +1238,7 @@ coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter
  * 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;
@@ -1504,7 +1513,7 @@ void handle_request(coap_context_t *context, coap_queue_t *node, const char* res
     }
 }
 
-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
@@ -1522,7 +1531,7 @@ static inline void handle_response(coap_context_t *context, coap_queue_t *sent,
     }
 }
 
-static inline int
+INLINE_API int
 #ifdef __GNUC__
 handle_locally(coap_context_t *context __attribute__ ((unused)),
         coap_queue_t *node __attribute__ ((unused)))
index 6e71da8..bd86b19 100644 (file)
@@ -113,7 +113,7 @@ extern "C"
      * 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
@@ -155,7 +155,7 @@ extern "C"
      * @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;
@@ -168,7 +168,7 @@ extern "C"
      * @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);
     }
@@ -197,7 +197,7 @@ extern "C"
  * @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)
@@ -317,7 +317,7 @@ static inline unsigned short coap_new_message_id(coap_context_t *context)
      * @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);
@@ -372,7 +372,7 @@ static inline unsigned short coap_new_message_id(coap_context_t *context)
      *
      * @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))
index ea60aab..60bb865 100644 (file)
@@ -208,7 +208,7 @@ coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
     return oi;
 }
 
-static inline int opt_finished(coap_opt_iterator_t *oi)
+INLINE_API int opt_finished(coap_opt_iterator_t *oi)
 {
     assert(oi);
 
index 9c33ac8..8441d5a 100644 (file)
@@ -112,7 +112,7 @@ typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1];
  *
  * @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));
 }
@@ -127,7 +127,7 @@ static inline void coap_option_filter_clear(coap_opt_filter_t f)
  *
  * @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);
 }
@@ -142,7 +142,7 @@ inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short 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);
 }
@@ -157,7 +157,7 @@ inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short 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);
 }
index 7708ab1..5a28696 100644 (file)
@@ -137,7 +137,7 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id,
 #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
index c375416..34b1b5c 100644 (file)
@@ -234,10 +234,10 @@ typedef union
 {
     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;
index 25e7720..8e2b85b 100644 (file)
@@ -29,7 +29,7 @@
  * 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;
@@ -43,7 +43,7 @@ static inline int coap_prng_impl(unsigned char *buf, size_t 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
 contiki_prng_impl(unsigned char *buf, size_t len)
 {
     unsigned short v = random_rand();
index 3954517..3af2f0c 100644 (file)
@@ -27,7 +27,7 @@
 #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"
 
@@ -64,7 +64,9 @@ coap_free_subscription(coap_subscription_t *subscription)
 }
 #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.
@@ -339,7 +341,7 @@ coap_resource_init(const unsigned char *uri, size_t len, int flags)
 {
     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
@@ -381,7 +383,7 @@ coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen,
     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
@@ -501,7 +503,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     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
@@ -514,7 +516,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     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
index 9382615..2349be1 100644 (file)
@@ -220,7 +220,7 @@ coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned ch
  * @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);
index 5f25f96..60fb972 100644 (file)
@@ -91,30 +91,30 @@ struct list
     (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;
@@ -125,7 +125,7 @@ list_pop(list_t the_list)
     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)
     {
@@ -138,7 +138,7 @@ static inline void list_insert(list_t the_list, void *previtem, void *newitem)
     }
 }
 
-static inline void *
+INLINE_API void *
 list_item_next(void *item)
 {
     return item == NULL ? NULL : ((struct list *) item)->next;
index 42dab60..d496e72 100644 (file)
@@ -32,7 +32,7 @@
  * @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)
@@ -493,7 +493,7 @@ coap_clone_uri(const coap_uri_t *uri)
 
 /* 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);
 }
index a1c739c..1889a8e 100644 (file)
@@ -62,7 +62,7 @@
  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
@@ -338,11 +338,11 @@ do {
     (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);                                                    \
index 3c671a3..1cf0fdb 100644 (file)
@@ -23,10 +23,10 @@ print"Reading ca script %s"%ca_transport
 
 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'])
@@ -38,25 +38,19 @@ if ca_os in ['darwin','ios']:
        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')])
@@ -157,11 +151,14 @@ if ca_os in ['linux', 'tizen', 'android', 'arduino', 'ios']:
 
 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'])
@@ -170,8 +167,14 @@ if ca_os in ['android', 'tizen']:
                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')
index 8caf45f..696ef01 100644 (file)
 #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)
@@ -491,7 +497,7 @@ static int32_t CASendSecureData(dtls_context_t *context,
     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.
index 83f24eb..9ddc7e8 100644 (file)
 #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
 
@@ -137,6 +148,7 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sock
                         NI_NUMERICHOST|NI_NUMERICSERV);
     if (r)
     {
+#if defined(EAI_SYSTEM)
         if (EAI_SYSTEM == r)
         {
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
@@ -147,6 +159,13 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sock
             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
@@ -165,6 +184,7 @@ void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storag
     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,
@@ -175,6 +195,13 @@ void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storag
             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
index 9a6c56a..5e62720 100644 (file)
 #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"
index 5fa8df9..5fa0ff3 100644 (file)
 #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>
@@ -77,6 +86,7 @@ typedef struct
 } CARetransmissionData_t;
 
 static const uint64_t USECS_PER_SEC = 1000000;
+static const uint64_t MSECS_PER_SEC = 1000;
 
 /**
  * @brief   getCurrent monotonic time
@@ -94,8 +104,13 @@ uint64_t getCurrentTimeInMicroSeconds();
  */
 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)
@@ -646,6 +661,10 @@ uint64_t getCurrentTimeInMicroSeconds()
     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);
index 5cc3798..8706ecf 100644 (file)
@@ -48,6 +48,9 @@ if target_os in ['linux','darwin','ios']:
     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)
index 98c7e5f..b014254 100644 (file)
@@ -367,7 +367,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
         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++;
     }
index 2ad25fe..48d52e2 100644 (file)
@@ -304,7 +304,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
 
         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++;
     }
index e310c92..c162a19 100644 (file)
@@ -1,4 +1,4 @@
-/*****************************************************************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
@@ -96,27 +117,46 @@ static char *ipv6mcnames[IPv6_DOMAINS] = {
     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) \
@@ -125,33 +165,19 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags);
         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()
 {
@@ -171,6 +197,7 @@ 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);
@@ -187,11 +214,12 @@ static void CAFindReadyMessage()
         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;
     }
@@ -215,7 +243,7 @@ static void CASelectReturned(fd_set *readFds, int ret)
         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)
@@ -239,12 +267,221 @@ static void CASelectReturned(fd_set *readFds, int ret)
         {
             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];
@@ -253,8 +490,9 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     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;
@@ -300,14 +538,60 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
             }
         }
     }
+#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);
@@ -332,7 +616,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
         }
     }
 
-    CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
+    CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);
 
     if (flags & CA_SECURE)
     {
@@ -352,6 +636,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
     }
 
     return CA_STATUS_OK;
+
 }
 
 void CAIPPullData()
@@ -369,11 +654,11 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
     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))
     {
@@ -382,7 +667,6 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
         return -1;
     }
 #endif
-
     struct sockaddr_storage sa = { .ss_family = family };
     socklen_t socklen;
 
@@ -390,16 +674,20 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
     {
         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);
             }
         }
 
@@ -408,12 +696,12 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
     }
     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);
             }
         }
 
@@ -421,30 +709,42 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
         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 ?
@@ -469,6 +769,7 @@ static int CACreateSocket(int family, uint16_t *port, bool isMulticast)
 
 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 };
@@ -495,13 +796,28 @@ static void CAInitializeNetlink()
 #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);
@@ -525,10 +841,12 @@ static void CAInitializePipe()
             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
     }
 }
@@ -541,7 +859,17 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
     {
         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);
@@ -587,10 +915,19 @@ CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
               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();
@@ -622,6 +959,7 @@ void CAIPStopServer()
     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]);
@@ -631,10 +969,17 @@ void CAIPStopServer()
     {
         // 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;
@@ -647,68 +992,95 @@ void CAWakeUpForChange()
             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()
@@ -716,7 +1088,7 @@ 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;
     }
 
@@ -731,21 +1103,19 @@ CAResult_t CAIPStartListenServer()
         {
             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);
         }
     }
 
@@ -773,25 +1143,20 @@ CAResult_t CAIPStopListenServer()
         {
             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);
         }
     }
@@ -806,14 +1171,14 @@ static void CAProcessNewInterface(CAInterface_t *ifitem)
         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);
     }
 }
 
@@ -844,31 +1209,28 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     }
 
     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);
@@ -879,6 +1241,45 @@ static void sendData(int fd, const CAEndpoint_t *endpoint,
     {
         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,
@@ -909,7 +1310,7 @@ 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;
         }
@@ -919,9 +1320,9 @@ static void sendMulticastData6(const u_arraylist_t *iflist,
         }
 
         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");
@@ -934,8 +1335,15 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
 {
     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;
 
@@ -947,7 +1355,7 @@ static void sendMulticastData4(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;
         }
@@ -955,14 +1363,15 @@ static void sendMulticastData4(const u_arraylist_t *iflist,
         {
             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");
     }
@@ -1062,7 +1471,7 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
         }
 
         eps[j].adapter = CA_ADAPTER_IP;
-        eps[j].interface = 0;
+        eps[j].ifindex = 0;
 
         if (ifitem->family == AF_INET6)
         {
@@ -1073,15 +1482,16 @@ CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
         {
             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)
         {
diff --git a/resource/csdk/connectivity/src/ip_adapter/windows/SConscript b/resource/csdk/connectivity/src/ip_adapter/windows/SConscript
new file mode 100644 (file)
index 0000000..f10999f
--- /dev/null
@@ -0,0 +1,12 @@
+#######################################################
+#       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')
diff --git a/resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/windows/caipnwmonitor.c
new file mode 100644 (file)
index 0000000..8c9490a
--- /dev/null
@@ -0,0 +1,282 @@
+/* *****************************************************************
+*
+* 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;
+}
index 688a04f..f4a6b3e 100644 (file)
@@ -29,7 +29,6 @@ src_dir = catest_env.get('SRC_DIR')
 # Build flags
 ######################################################################
 catest_env.PrependUnique(CPPPATH = [
-                '../../ocsocket/include',
                 '../../logger/include',
                 '../../stack/include',
                 '../../extlibs/cjson',
@@ -43,11 +42,9 @@ if '-lpthread' in tmplist:
     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',
@@ -55,15 +52,27 @@ catest_env.PrependUnique(LIBS = ['m',
 
 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
 ######################################################################
@@ -92,7 +101,8 @@ Alias("test", [catests])
 
 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',
index d413bb1..e8c1986 100644 (file)
@@ -18,6 +18,7 @@
  *
  ******************************************************************/
 
+#include "platform_features.h"
 #include "gtest/gtest.h"
 #include "cainterface.h"
 #include "cautilinterface.h"
@@ -159,12 +160,6 @@ int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
 }
 #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)
index 1c3f34e..54d9fb8 100644 (file)
 #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
 
@@ -68,6 +80,18 @@ uint64_t getAbsTime()
     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);
@@ -209,7 +233,12 @@ void condFunc(void *context)
     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;
@@ -372,7 +401,12 @@ TEST(ConditionTests, TC_03_BROADCAST)
     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();
 
@@ -518,7 +552,14 @@ TEST(ConditionTests, TC_07_WAITDURATION)
 
     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);
 
index b07eb6f..c701a2e 100644 (file)
@@ -20,6 +20,7 @@
 
 #include "gtest/gtest.h"
 
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 
 /**
@@ -41,6 +42,12 @@ void workaroundHook()
         pthread_key_delete(key);
     }
 }
+#else
+void workaroundHook()
+{
+    return;
+};
+#endif
 
 
 TEST(BaseTest, WorldIsSane)
index 40c60bb..b81fb7e 100644 (file)
@@ -1,13 +1,16 @@
 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'])
 
index 932221d..4bc391d 100644 (file)
@@ -67,6 +67,12 @@ typedef enum {
     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,
@@ -89,7 +95,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 
 #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
      *
@@ -196,7 +202,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 #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()
 
@@ -217,7 +223,7 @@ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint1
 #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
index cc30d58..7a32b46 100644 (file)
 #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
@@ -72,9 +74,10 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
     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"
@@ -98,7 +101,10 @@ static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1;
 #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
 
@@ -155,7 +161,7 @@ void OCLogInit()
 
 void OCLogShutdown()
 {
-#if defined(__linux__) || defined(__APPLE__)
+#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
     if (logCtx && logCtx->destroy)
     {
         logCtx->destroy(logCtx);
@@ -176,7 +182,7 @@ void OCLogv(LogLevel level, const char * tag, const char * format, ...)
     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);
@@ -207,7 +213,7 @@ void OCLog(LogLevel level, const char * tag, const char * logStr)
        __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);
@@ -230,6 +236,12 @@ void OCLog(LogLevel level, const char * tag, const char * 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))
index cabd07c..394401a 100644 (file)
@@ -320,7 +320,11 @@ OCStackResult RMCreateRouteOption(const RMRouteOption_t *optValue, CAHeaderOptio
     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");
index ccfcda0..96ae81c 100644 (file)
@@ -22,6 +22,7 @@
 ##
 
 Import('env')
+import os
 
 lib_env = env.Clone()
 SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
@@ -58,26 +59,26 @@ libocsrm_env.PrependUnique(CPPPATH = [
 
 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':
@@ -87,65 +88,48 @@ 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':
index c1900ac..ca185d6 100644 (file)
 #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;
@@ -166,5 +170,9 @@ extern char OIC_SEC_REST_QUERY_DELIMETER;
 //Security Version
 extern const char * DEFAULT_SEC_VERSION;
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif //IOTVT_SRM_RSRC_STRINGS_H
 
index 786658e..0cc68a4 100644 (file)
@@ -47,6 +47,8 @@
 #include "byte_array.h"
 #endif /* __WITH_X509__ */
 
+#include "platform_features.h"
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -139,7 +141,7 @@ typedef enum
 /**
  * Extract Reason Code from Access Response.
  */
-static inline SRMAccessResponseReasonCode_t GetReasonCode(
+INLINE_API SRMAccessResponseReasonCode_t GetReasonCode(
     SRMAccessResponse_t response)
 {
     SRMAccessResponseReasonCode_t reason =
@@ -150,7 +152,7 @@ static inline SRMAccessResponseReasonCode_t GetReasonCode(
 /**
  * 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))
     {
@@ -428,6 +430,9 @@ struct OicSecSacl
 {
     // <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
 };
 
 /**
index 329aaca..21686b5 100644 (file)
@@ -57,16 +57,26 @@ target_os = env.get('TARGET_OS')
 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'])
@@ -76,9 +86,12 @@ provisioning_env.AppendUnique(LIBS = ['tinydtls'])
 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')
 
@@ -108,14 +121,18 @@ provisioning_src = [
 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')
 
index a4f645d..f4951ac 100644 (file)
@@ -20,6 +20,7 @@
 #
 
 Import('env')
+import os.path
 
 provisioning_env = env.Clone()
 
@@ -46,19 +47,30 @@ provisioning_env.AppendUnique(CPPPATH = [
                '../../../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'])
 
index ab423b4..e1c6d5a 100644 (file)
 
 #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"
index 7047ae9..adec06f 100644 (file)
 #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"
 
index 5ca0e7a..06a5512 100644 (file)
 #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;
index e098886..61a51d3 100644 (file)
 #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>
 
index 38d1377..b52fe47 100644 (file)
 #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"
@@ -341,31 +352,68 @@ exit:
  */
 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;
@@ -428,8 +476,8 @@ uint16_t GetSecurePortFromJSON(char* jsonStr)
 }
 
 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)
index 7980e56..f77bf05 100644 (file)
@@ -20,7 +20,9 @@
 #include <stdio.h>
 #include <string.h>
 #include <stdint.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
 #include "ocprovisioningmanager.h"
 #include "secureresourceprovider.h"
index d2b9f4b..edd212a 100644 (file)
@@ -18,9 +18,9 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifdef WITH_ARDUINO
+#ifdef HAVE_STRING_H
 #include <string.h>
-#else
+#elif HAVE_STRINGS_H
 #include <strings.h>
 #endif
 #include <stdlib.h>
index 4ead7a3..76c2c38 100644 (file)
@@ -56,7 +56,7 @@ OCStackResult DiscoverAmsService(PEContext_t *context)
 
     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);
@@ -120,7 +120,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
         return OC_STACK_KEEP_TRANSACTION;
     }
 
-    OicUuid_t deviceId = {.id={}};
+    OicUuid_t deviceId = {.id={0}};
     memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
     OICFree(doxm);
 
@@ -151,7 +151,7 @@ OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *dev
 
     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);
 
@@ -226,9 +226,9 @@ OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivit
 {
     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;
@@ -400,7 +400,7 @@ bool FoundAmaclForRequest(PEContext_t *context)
 
 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)
     {
index 07bc8ea..ad37dc9 100644 (file)
 #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>
@@ -1207,7 +1208,7 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
         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) )
                 {
index 5606598..b22ca5b 100644 (file)
 #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
@@ -950,9 +956,6 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
     }\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
@@ -973,13 +976,17 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
     }\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
@@ -992,27 +999,38 @@ OCStackResult DPDeviceDiscovery(unsigned short waittime)
 \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
index 0c5c03f..8fcb6b0 100755 (executable)
@@ -42,9 +42,7 @@
 #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
 
index d3b6cb1..e31f3e8 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 //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
 
@@ -34,6 +38,16 @@ static const char UNTIL[] = "UNTIL";
 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))
index 02c984a..785234a 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <string.h>
 #include <math.h>
+#include "platform_features.h"
 #include "pbkdf2.h"
 #include "hmac.h"
 #include "debug.h"
index 921b249..d2491c4 100644 (file)
@@ -39,9 +39,7 @@
 #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
 
index 4a4694d..ee991fe 100644 (file)
@@ -214,9 +214,9 @@ bool IsRequestFromResourceOwner(PEContext_t *context)
     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)
     {
@@ -235,7 +235,7 @@ inline static bool IsRequestSubjectEmpty(PEContext_t *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))
@@ -253,7 +253,7 @@ static inline bool IsPermissionAllowingRequest(const uint16_t 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)
     {
@@ -476,7 +476,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
         // 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);
index c10b097..d263892 100644 (file)
 #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
index 26a9277..10b46a8 100644 (file)
@@ -183,7 +183,8 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     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
@@ -342,7 +343,7 @@ OCStackResult SRMInitPolicyEngine()
 
 void SRMDeInitPolicyEngine()
 {
-    return DeInitPolicyEngine(&g_policyEngineContext);
+    DeInitPolicyEngine(&g_policyEngineContext);
 }
 
 bool SRMIsSecurityResourceURI(const char* uri)
index 1cc5694..dd56ded 100644 (file)
@@ -92,7 +92,7 @@ OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
 
     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;
 
diff --git a/resource/csdk/security/src/strptime.c b/resource/csdk/security/src/strptime.c
new file mode 100644 (file)
index 0000000..5e2e7e2
--- /dev/null
@@ -0,0 +1,135 @@
+/** @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;
+}
index c431d77..61ebcf3 100644 (file)
@@ -25,6 +25,7 @@ import os.path
 srmtest_env = env.Clone()
 
 src_dir = srmtest_env.get('SRC_DIR')
+target_os = env.get('TARGET_OS')
 
 ######################################################################
 # Build flags
@@ -62,11 +63,18 @@ srmtest_env.PrependUnique(LIBS = ['ocsrm',
                                     '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
 ######################################################################
@@ -87,9 +95,9 @@ unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
 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'))
@@ -108,13 +116,14 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
 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')
index 558406a..a2e10af 100644 (file)
@@ -19,9 +19,6 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
 #include <sys/stat.h>
 #include "ocstack.h"
 #include "psinterface.h"
@@ -47,8 +44,8 @@ using namespace std;
 #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)
 
@@ -265,6 +262,11 @@ TEST(ACLResourceTest, ACLPostTest)
     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)
 {
index 6c1c20d..80eb186 100644 (file)
@@ -85,6 +85,31 @@ static void printRecur(IotvtICalRecur_t *recur)
     }
 }
 
+#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)
index 4806a96..b73881d 100644 (file)
@@ -19,9 +19,6 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
 #include "ocstack.h"
 #include "cainterface.h"
 #include "srmresourcestrings.h"
index d1c9396..b9e5ceb 100644 (file)
@@ -18,7 +18,9 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include "gtest/gtest.h"
 
 #include "ocpayload.h"
index 95cf63c..2917709 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #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"
@@ -119,6 +125,12 @@ TEST(PersistentStorageHandlerTest, RegisterValidHandler)
     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();
@@ -157,3 +169,5 @@ TEST(PersistentStorageHandlerTest, PersistentStorageValidHandlers)
     }
     psi->unlink(outFilePath);
 }
+#endif
+
index 1435ad5..5bfe64e 100644 (file)
@@ -28,7 +28,7 @@
 #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;
index ff5c453..8b81e91 100644 (file)
@@ -21,7 +21,7 @@
 #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);
 
index 052afad..8444694 100644 (file)
 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
 }
index bef3e98..a985d67 100644 (file)
@@ -289,9 +289,9 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         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);
 
index 4b62813..9857b2d 100644 (file)
@@ -60,33 +60,33 @@ extern "C"
 
 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.
@@ -97,7 +97,7 @@ bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, do
  *
  * @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.
@@ -108,7 +108,7 @@ bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCBy
  *
  * @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);
 
 /**
@@ -122,20 +122,19 @@ bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* nam
  *
  * @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.
@@ -147,7 +146,7 @@ bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OC
  *
  * @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]);
 
 /**
@@ -160,7 +159,7 @@ bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* na
  *
  * @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]);
 
 /**
@@ -176,82 +175,82 @@ bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
  *
  * @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
 }
index 9eeae7e..c774af6 100644 (file)
@@ -52,7 +52,7 @@ extern "C" {
  *
  * @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.
@@ -63,7 +63,7 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
  *
  * @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
 /**
@@ -85,7 +85,7 @@ OCStackResult OCSetRAInfo(const OCRAInfo_t *raInfo);
  *
  * @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
@@ -112,7 +112,7 @@ OCStackResult OCStopMulticastServer();
  *
  * @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
@@ -147,16 +147,16 @@ OCStackResult OCProcess();
  *
  * @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.
  *
@@ -168,8 +168,10 @@ OCStackResult OCDoResource(OCDoHandle *handle,
  *
  * @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.
@@ -179,7 +181,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
  *     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
 /**
@@ -198,7 +200,7 @@ OCStackResult OCRegisterPersistentStorageHandler(OCPersistentStorage* persistent
  *
  * @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
@@ -212,7 +214,7 @@ OCStackResult OCStartPresence(const uint32_t ttl);
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
 
-OCStackResult OCStopPresence();
+OC_EXPORT OCStackResult OCStopPresence();
 #endif
 
 
@@ -226,7 +228,7 @@ OCStackResult OCStopPresence();
  *
  * @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.
@@ -238,7 +240,7 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle
  *     ::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.
@@ -252,7 +254,7 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
  *     ::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.
@@ -271,13 +273,13 @@ OCStackResult OCSetPlatformInfo(OCPlatformInfo platformInfo);
  *
  * @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);
 
 
 /**
@@ -288,7 +290,7 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
  *
  * @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.
@@ -298,7 +300,7 @@ OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle
  *
  * @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.
@@ -308,8 +310,8 @@ OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHand
  *
  * @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.
  *
@@ -318,8 +320,8 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
  *
  * @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.
@@ -330,8 +332,9 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
  *
  * @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.
@@ -340,7 +343,7 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler ent
  *
  * @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.
@@ -349,7 +352,7 @@ OCStackResult OCGetNumberOfResources(uint8_t *numResources);
  *
  * @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
@@ -362,7 +365,7 @@ OCResourceHandle OCGetResourceHandle(uint8_t index);
  *
  * @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.
@@ -374,7 +377,7 @@ OCStackResult OCDeleteResource(OCResourceHandle handle);
  *
  * @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.
@@ -383,7 +386,7 @@ const char* OCGetServerInstanceIDString(void);
  *
  * @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.
@@ -395,7 +398,7 @@ const char *OCGetResourceUri(OCResourceHandle 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.
@@ -405,7 +408,7 @@ OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
  *
  * @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.
@@ -415,7 +418,7 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numRe
  *
  * @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.
@@ -425,7 +428,7 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+OC_EXPORT OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
         uint8_t *numResourceInterfaces);
 
 /**
@@ -436,7 +439,7 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
  *
  * @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.
@@ -446,7 +449,7 @@ const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index);
  *
  * @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.
@@ -456,7 +459,7 @@ uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t in
  *
  * @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);
 
 /**
@@ -466,7 +469,7 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
  *
  * @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
@@ -478,7 +481,7 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
  *
  * @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.
@@ -497,7 +500,7 @@ OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService q
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult
+OC_EXPORT OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                             OCObservationId  *obsIdList,
                             uint8_t          numberOfIds,
@@ -514,7 +517,7 @@ OCNotifyListOfObservers (OCResourceHandle handle,
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
+OC_EXPORT OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
 
 //#ifdef DIRECT_PAIRING
 /**
@@ -526,7 +529,7 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *response);
  *                    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
@@ -535,7 +538,7 @@ const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime);
  *
  * @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
@@ -547,8 +550,8 @@ const OCDPDev_t* OCGetDirectPairedDevices();
  * @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
index 7b706c2..073a965 100644 (file)
@@ -281,8 +281,11 @@ extern "C" {
 #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 */
@@ -477,7 +480,7 @@ typedef struct
     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
@@ -1201,7 +1204,7 @@ typedef struct
     char *type;
 
     /** Interface */
-    OCStringLL *interface;
+    OCStringLL *iface;
 
     /** This structure holds the old /oic/res response. */
     OCResourcePayload *resources;
index 2a9f091..12e6e3a 100644 (file)
@@ -46,10 +46,10 @@ extern "C"
 #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;
@@ -164,7 +164,7 @@ static inline void OCPayloadLogRep(LogLevel level, OCRepPayload* 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;
@@ -192,7 +192,7 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
         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);
     }
@@ -227,7 +227,7 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
     }
 }
 
-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);
@@ -252,7 +252,7 @@ static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
     }
 }
 
-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);
@@ -283,7 +283,7 @@ static inline void OCPayloadLogPlatform(LogLevel level, OCPlatformPayload* paylo
     }
 }
 
-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);
@@ -292,13 +292,13 @@ static inline void OCPayloadLogPresence(LogLevel level, OCPresencePayload* paylo
     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)
     {
@@ -321,7 +321,7 @@ static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *paylo
     }
 }
 
-static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
+INLINE_API void OCPayloadLog(LogLevel level, OCPayload* payload)
 {
     if(!payload)
     {
index 17c6417..82da858 100644 (file)
@@ -165,7 +165,7 @@ void OCDiscoveryCollectionPayloadDestroy(OCDiscoveryPayload* 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.
@@ -173,7 +173,7 @@ void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
  * @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
 }
index fe69612..5a3305b 100644 (file)
@@ -29,21 +29,26 @@ samples_env.PrependUnique(CPPPATH = [
                '../../../../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'])
 
index 3ebf005..cd47011 100644 (file)
@@ -21,6 +21,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <ocstack.h>
+#include <getopt.h>
 
 const char *getResult(OCStackResult result)
 {
diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/common.h b/resource/csdk/stack/samples/linux/SimpleClientServer/common.h
new file mode 100644 (file)
index 0000000..36a7456
--- /dev/null
@@ -0,0 +1,7 @@
+#ifndef COMMON_H_
+#define COMMON_H_
+
+const char *getResult(OCStackResult result);
+void StripNewLineChar(char* str);
+
+#endif
index 23053e7..123f969 100644 (file)
 #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
 /**
@@ -58,8 +66,6 @@ static OCDevAddr serverAddr;
 static char discoveryAddr[100];
 static std::string coapServerResource = "/a/light";
 
-void StripNewLineChar(char* str);
-
 #ifdef WITH_PRESENCE
 // The handle for observe registration
 OCDoHandle gPresenceHandle;
index 61622eb..988ce35 100644 (file)
 #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"
@@ -33,6 +39,7 @@
 #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)
index fee8870..f13c6bc 100644 (file)
 #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")
index 572b9e3..d15fdd4 100644 (file)
 #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;
@@ -41,10 +48,9 @@ static std::string coapServerResource = "/a/led";
 
 //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;
 
@@ -99,7 +105,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 
     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)
     {
@@ -292,12 +298,12 @@ int main(int argc, char* argv[])
 
     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();
index c3a7059..39627df 100644 (file)
@@ -30,6 +30,7 @@
 #include "ocpayload.h"
 #include "payload_logging.h"
 #include "ocremoteaccessclient.h"
+#include "common.h"
 
 #define SET_BUT_NOT_USED(x) (void) x
 // Tracking user input
@@ -43,7 +44,6 @@ static std::string coapServerResource = "/a/light";
 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
index 22f6810..13cf61b 100644 (file)
 #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
@@ -664,8 +674,7 @@ void *ChangeLightRepresentation (void *param)
     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)
     {
@@ -1113,12 +1122,16 @@ int main(int argc, char* argv[])
 
     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...");
 
index 9c4aef5..84d902c 100644 (file)
 #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"
index 792b7d2..b5408d0 100644 (file)
 #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")
 
@@ -542,8 +550,10 @@ int main(int argc, char* argv[])
     /*
      * 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...");
 
index e56e144..5f0ba4b 100644 (file)
 #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");
@@ -187,6 +197,21 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
     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*/)
 {
@@ -246,7 +271,9 @@ void handleSigInt(int signum)
 // 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())
@@ -299,8 +326,10 @@ int main(int /*argc*/, char** /*argv[]*/)
     // 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...");
index 3cd3cb4..2f338ea 100644 (file)
@@ -39,14 +39,17 @@ if target_os not in ['windows', 'winrt']:
        # 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'])
index 4a6b14e..4d0fdf0 100644 (file)
@@ -3,9 +3,17 @@
 #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"
index f531773..fdcf3cc 100644 (file)
 #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"
index fd7d8ee..bf49f2a 100644 (file)
 #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
@@ -405,19 +417,19 @@ FILE* client_fopen(const char *path, const char *mode)
 \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
@@ -625,7 +637,12 @@ int main(void)
             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
index 22bc674..9d83669 100644 (file)
 #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"
index 7e559c1..09d3093 100644 (file)
@@ -49,7 +49,7 @@ cp -f %{ROOTDIR}/resource/csdk/connectivity/src/libconnectivity_abstraction.so %
 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}/
index a24efed..cc2bfb4 100644 (file)
 #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"
index 896621f..f3648de 100755 (executable)
@@ -49,6 +49,8 @@
 #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)
index 2ad55b2..54182c9 100644 (file)
@@ -416,14 +416,14 @@ bool OCRepPayloadAddResourceTypeAsOwner(OCRepPayload* payload, char* resourceTyp
     }
 }
 
-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;
     }
@@ -441,7 +441,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
         {
             return false;
         }
-        cur->next->value = interface;
+        cur->next->value = iface;
         return true;
     }
     else
@@ -451,7 +451,7 @@ bool OCRepPayloadAddInterfaceAsOwner(OCRepPayload* payload, char* interface)
         {
             return false;
         }
-        payload->interfaces->value = interface;
+        payload->interfaces->value = iface;
         return true;
     }
 }
@@ -741,7 +741,7 @@ bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
 {
     if (!array)
     {
-        return NULL;
+        return false;
     }
 
     size_t dimTotal = calcDimTotal(dimensions);
@@ -1572,7 +1572,7 @@ void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload)
     OICFree(payload->uri);
     OICFree(payload->type);
     OICFree(payload->name);
-    OCFreeOCStringLL(payload->interface);
+    OCFreeOCStringLL(payload->iface);
     OCDiscoveryResourceDestroy(payload->resources);
     OICFree(payload);
 }
index 7eee7b9..477b9d7 100644 (file)
@@ -65,7 +65,7 @@ OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t*
     // 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
 
@@ -280,9 +280,9 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload *payload, uint8_t *o
         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");
         }
 
index 6373767..96f590c 100755 (executable)
@@ -35,6 +35,7 @@
 #include "ocstackinternal.h"
 #include "payload_logging.h"
 #include "rdpayload.h"
+#include "platform_features.h"
 
 #define TAG "OIC_RI_PAYLOADPARSE"
 
@@ -256,11 +257,11 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload **outPayload, CborValue *
         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;
             }
index e862549..50eaed9 100755 (executable)
 // 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
 
@@ -64,6 +65,8 @@
 #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};
@@ -783,9 +786,9 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
                         }
                         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)
index 8263100..592f27a 100644 (file)
@@ -526,7 +526,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
         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;
 
index d622944..eb3ed08 100644 (file)
 #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
 
@@ -441,7 +442,7 @@ void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
     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
@@ -459,7 +460,7 @@ void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
     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)
index 383d66a..fa67c28 100755 (executable)
@@ -32,9 +32,7 @@
 #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
@@ -100,9 +120,7 @@ void AddScheduledResource(ScheduledResourceInfo **head,
 {
     OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
 
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+    MUTEX_LOCK(&lock);
     ScheduledResourceInfo *tmp = NULL;
 
     if (*head != NULL)
@@ -119,25 +137,21 @@ void AddScheduledResource(ScheduledResourceInfo **head,
     {
         *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();
@@ -148,11 +162,7 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
         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)
             {
@@ -165,9 +175,9 @@ ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
     }
 
     exit:
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
     if (tmp == NULL)
     {
         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
@@ -179,9 +189,8 @@ ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo
 {
     OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
 
-#ifndef WITH_ARDUINO
-    pthread_mutex_lock(&lock);
-#endif
+    MUTEX_LOCK(&lock);
+
     ScheduledResourceInfo *tmp = NULL;
     tmp = head;
 
@@ -199,9 +208,9 @@ ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo
     }
 
 exit:
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
     if (tmp == NULL)
     {
         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
@@ -212,17 +221,17 @@ exit:
 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;
     }
 
@@ -244,9 +253,9 @@ void RemoveScheduledResource(ScheduledResourceInfo **head,
     }
 
     OCFREE(del)
-#ifndef WITH_ARDUINO
-    pthread_mutex_unlock(&lock);
-#endif
+
+    MUTEX_UNLOCK(&lock);
+
 }
 
 typedef struct aggregatehandleinfo
@@ -650,7 +659,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     // 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.
@@ -1096,13 +1105,13 @@ void DoScheduledGroupAction()
         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)
     {
@@ -1117,9 +1126,7 @@ void DoScheduledGroupAction()
 
             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;
@@ -1129,9 +1136,7 @@ void DoScheduledGroupAction()
                         &DoScheduledGroupAction);
 
                 OIC_LOG(INFO, TAG, "Reregisteration.");
-#ifndef WITH_ARDUINO
-                pthread_mutex_unlock(&lock);
-#endif
+                MUTEX_UNLOCK(&lock);
                 AddScheduledResource(&scheduleResourceList, schedule);
             }
             else
@@ -1159,6 +1164,16 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
     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)
@@ -1329,29 +1344,21 @@ OCStackResult BuildCollectionGroupActionCBORResponse(
                             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;
index 869e6ab..5f428b9 100644 (file)
@@ -659,7 +659,7 @@ KeepAliveEntry_t *AddKeepAliveEntry(const CAEndpoint_t *endpoint, OCMode mode,
     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));
 
index 507f011..2d52917 100644 (file)
@@ -43,11 +43,9 @@ stacktest_env.PrependUnique(CPPPATH = [
                ])
 
 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',
@@ -65,6 +63,12 @@ if env.get('SECURED') == '1':
 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
 ######################################################################
@@ -75,8 +79,9 @@ Alias("test", [stacktests, cbortests])
 
 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',
index 2e4a202..c17afc1 100644 (file)
@@ -33,7 +33,9 @@ extern "C"
 #include <sys/stat.h>
 #include <errno.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <stdlib.h>
 
 //-----------------------------------------------------------------------------
index b780369..beaa35e 100644 (file)
@@ -32,7 +32,9 @@ extern "C"
 #include <sys/stat.h>
 #include <errno.h>
 #include <fcntl.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <stdlib.h>
 
 //-----------------------------------------------------------------------------
index 5d84295..1484da4 100644 (file)
@@ -56,8 +56,14 @@ examples_env.AppendUnique(LIBS = ['oc_logger'])
 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'])
@@ -69,43 +75,57 @@ if target_os == 'android':
 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')
index dd207d5..2fd5bb3 100644 (file)
@@ -24,6 +24,7 @@
 /// (properties and methods) and host this resource on the server.
 ///
 
+#include <unistd.h>
 #include <functional>
 
 #include <pthread.h>
diff --git a/resource/examples/mediaserver.cpp b/resource/examples/mediaserver.cpp
new file mode 100644 (file)
index 0000000..4fc5fa5
--- /dev/null
@@ -0,0 +1,637 @@
+/* ****************************************************************
+ *
+ * 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(&currentVal);
+    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;
+}
+
index 3755b57..328e1e7 100644 (file)
@@ -25,7 +25,7 @@
 #include <pthread.h>
 #include <mutex>
 #include <condition_variable>
-
+#include <getopt.h>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
index e72c49d..eaeb83c 100644 (file)
 #include "OCPlatform.h"
 #include "OCApi.h"
 
+#ifdef HAVE_WINDOWS_H
+#include <Windows.h>
+#endif
+#include "platform_features.h"
+
 using namespace OC;
 using namespace std;
 
@@ -141,9 +146,9 @@ public:
         }
     }
 
-    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";
index 07d55f0..6bc6efe 100644 (file)
 
 // 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"
index 86081f8..17f04a1 100644 (file)
 #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
index 97a6074..752fc99 100644 (file)
 /// 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;
@@ -241,9 +249,9 @@ public:
         }
     }
 
-    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";
@@ -372,7 +380,12 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                                                             m_interestedObservers.end());
             }
 
+#if defined(_WIN32)
+            DWORD threadId;
+            HANDLE threadHandle;
+#else
             pthread_t threadId;
+#endif
 
             cout << "\t\trequestFlag : Observer\n";
             gObservation = 1;
@@ -382,7 +395,11 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             // 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;
index f9e439e..a0ac6e7 100644 (file)
 #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;
@@ -214,9 +219,9 @@ public:
         }
     }
 
-    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";
index 994858e..320cb06 100644 (file)
 
 #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;
diff --git a/resource/examples/winuiclient.cpp b/resource/examples/winuiclient.cpp
new file mode 100644 (file)
index 0000000..59e5d21
--- /dev/null
@@ -0,0 +1,439 @@
+/* ****************************************************************\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
diff --git a/resource/examples/winuiclient.h b/resource/examples/winuiclient.h
new file mode 100644 (file)
index 0000000..b052e4e
--- /dev/null
@@ -0,0 +1,89 @@
+/* ****************************************************************
+ *
+ * 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
+
diff --git a/resource/examples/winuiclientgui.cpp b/resource/examples/winuiclientgui.cpp
new file mode 100644 (file)
index 0000000..596bb4e
--- /dev/null
@@ -0,0 +1,370 @@
+/* ****************************************************************
+ *
+ * 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);
+}
+
index 2bfb10b..5b9ca83 100644 (file)
@@ -100,43 +100,43 @@ namespace OC
     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);
index d124502..875aace 100644 (file)
 #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"
@@ -45,6 +51,9 @@ namespace OC
 
 namespace OC
 {
+#if defined(_MSC_VER)
+    extern std::ostream& oclog();
+#else
     typedef boost::iostreams::stream<OC::oc_log_stream>     log_target_t;
 
     namespace detail
@@ -65,7 +74,7 @@ namespace OC
     {
         return detail::oclog_target();
     };
-
+#endif
 } // namespace OC
 
 namespace OC
index 519da78..78f9029 100644 (file)
@@ -80,11 +80,25 @@ 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
index 5f2071a..a7df3a0 100644 (file)
@@ -28,6 +28,9 @@
 #ifndef OC_REPRESENTATION_H_
 #define OC_REPRESENTATION_H_
 
+#define GCC_VERSION (__GNUC__ * 10000 \
+                   + __GNUC_MINOR__ * 100 \
+                   + __GNUC_PATCHLEVEL__)
 
 #include <string>
 #include <sstream>
@@ -99,13 +102,28 @@ namespace OC
             // 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(){}
 
@@ -302,12 +320,38 @@ namespace OC
                     // 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>();
index 3fe3a68..bc0bcdb 100644 (file)
@@ -60,7 +60,15 @@ namespace OC
 
             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;
 
@@ -103,8 +111,32 @@ namespace OC
     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
index e17e3a6..64ffa7e 100644 (file)
@@ -59,8 +59,36 @@ namespace OC
         {
         }
 
+#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
         */
index 474e90a..b4b8c9f 100644 (file)
@@ -57,8 +57,33 @@ namespace OC
         {
         }
 
+#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) {}
 
         /**
@@ -129,8 +154,8 @@ namespace OC
         *  @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;
         }
 
@@ -139,8 +164,8 @@ namespace OC
         *  @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);
         }
 
         /**
index 1c17c10..85039d0 100644 (file)
@@ -100,7 +100,7 @@ namespace OC
     template<typename T, typename = void>
     struct is_vector
     {
-        constexpr static bool value = false;
+        BOOST_STATIC_CONSTEXPR bool value = false;
     };
 
     template<typename T>
@@ -110,7 +110,7 @@ namespace OC
         >::type
     >
     {
-        constexpr static bool value = true;
+        BOOST_STATIC_CONSTEXPR bool value = true;
     };
 
     // type trait to remove the first type from a parameter-packed list
@@ -132,14 +132,14 @@ namespace OC
     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
index 33cb27d..e700739 100644 (file)
@@ -75,7 +75,7 @@ namespace OC
             return m_missingInterface;
         }
 
-        virtual const char* what() const noexcept
+        virtual const char* what() const BOOST_NOEXCEPT
         {
             std::string ret;
 
index 09c9486..edcf6f4 100644 (file)
 
 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";
index 16612dd..5e86cdc 100644 (file)
@@ -43,18 +43,27 @@ if target_os not in ['arduino', 'windows', 'winrt']:
        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')
index a3a4c91..7778b54 100644 (file)
@@ -33,7 +33,12 @@ examples_env = lib_env.Clone()
 ######################################################################
 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':
index f2e01ac..e6c8c2c 100644 (file)
@@ -55,9 +55,9 @@ class oc_log_stream : boost::iostreams::sink
  {}
 
  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)
index 740ded3..59cba9a 100644 (file)
@@ -33,8 +33,8 @@ using namespace OC;
 
 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)
index 23752b9..3de692b 100644 (file)
@@ -252,11 +252,10 @@ namespace OC
 
         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)
@@ -365,11 +364,11 @@ namespace OC
 
         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)
@@ -457,11 +456,11 @@ namespace OC
         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);
 
@@ -524,12 +523,15 @@ namespace OC
     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 << '?';
@@ -541,6 +543,12 @@ namespace OC
         }
 
         std::string queryString = paramsList.str();
+
+        if(queryString.empty())
+        {
+            return uri;
+        }
+
         if(queryString.back() == ';')
         {
             queryString.resize(queryString.size() - 1);
@@ -575,11 +583,11 @@ namespace OC
         }
         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);
 
@@ -621,11 +629,11 @@ namespace OC
         }
         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();
 
@@ -686,11 +694,11 @@ namespace OC
         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();
 
@@ -764,11 +772,11 @@ namespace OC
 
         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)
@@ -870,12 +878,11 @@ namespace OC
 
         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();
 
@@ -935,10 +942,11 @@ namespace OC
 
         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++;
         }
 
index 522ef82..ef9317f 100644 (file)
@@ -47,7 +47,7 @@ namespace OC
         std::mutex serverWrapperLock;
         std::map <OCResourceHandle, OC::EntityHandler>  entityHandlerMap;
         std::map <OCResourceHandle, std::string> resourceUriMap;
-        EntityHandler defaultDeviceEntityHandler = 0;
+        EntityHandler defaultDeviceEntityHandler;
     }
 }
 
index a5e82fc..7fdc9f5 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include "ocapi.h"
+#include "OCApi.h"
+
+#if defined(_MSC_VER)
+namespace OC
+{
+    std::ostream& oclog()
+    {
+        return std::cout;
+    }
+}
+#endif
index 8b0015b..09d1e16 100644 (file)
@@ -314,11 +314,13 @@ namespace OC
         ((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)
@@ -422,11 +424,11 @@ namespace OC
                     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);
@@ -891,13 +893,13 @@ namespace OC
         // 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>
@@ -911,10 +913,10 @@ namespace OC
     {
         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;
     };
 
@@ -924,9 +926,9 @@ namespace OC
     {
         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;
     };
 
 
index a3c8ec8..b381b9f 100644 (file)
 
 #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 {
 
@@ -67,15 +75,15 @@ OCResource::OCResource(std::weak_ptr<IClientWrapper> clientWrapper,
                         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();
 
@@ -456,7 +464,7 @@ OCStackResult OCResource::cancelObserve(QualityOfService QoS)
 
     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)
     {
index f1106a1..7a43499 100644 (file)
 ##
 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
 ######################################################################
@@ -43,8 +46,8 @@ oclib_env.AppendUnique(CPPPATH = [
 
 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':
@@ -67,6 +70,14 @@ if target_os == 'tizen':
 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
 ######################################################################
@@ -83,10 +94,14 @@ oclib_src = [
                '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')
index 94495ba..9d2cb21 100644 (file)
@@ -68,6 +68,10 @@ if target_os == 'android':
                # 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':
index 08a9ffb..b4be2de 100644 (file)
@@ -60,7 +60,7 @@ if target_os == 'linux':
                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')
@@ -69,4 +69,14 @@ elif target_os == 'darwin':
        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')
diff --git a/run.bat b/run.bat
new file mode 100644 (file)
index 0000000..2714376
--- /dev/null
+++ b/run.bat
@@ -0,0 +1,129 @@
+@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
index 832cc76..1b9e7f3 100644 (file)
@@ -244,7 +244,7 @@ Below is an example:
        # 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])
index da5062e..114be6e 100755 (executable)
@@ -26,7 +26,7 @@ Import('env')
 
 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')
 
@@ -47,9 +47,9 @@ if target_os not in ['arduino','darwin', 'ios']:
     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']:
index 20516e4..81cf79d 100644 (file)
@@ -16,9 +16,9 @@ linux_sample_env.AppendUnique(CPPPATH = ['include'])
 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'])
index ed94470..a72a7b4 100644 (file)
 #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>
index b6ef553..710245d 100755 (executable)
 ##
 
 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'])
@@ -64,7 +57,7 @@ if target_os == 'android':
 ######################################################################
 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',
          ]
@@ -74,12 +67,13 @@ if target_os in ['tizen'] :
 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')
index c4d2128..8229a61 100644 (file)
@@ -29,12 +29,14 @@ SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
 
 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'])
index cad3ef3..e9b72ff 100644 (file)
@@ -20,7 +20,9 @@
 #include "rd_server.h"
 
 #include <signal.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
 int g_quitFlag = 0;
 
index 2f6c922..c782560 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #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)
@@ -109,7 +136,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
     resources->publishedResource = storeResource;
     resources->devAddr = *address;
 
-    pthread_mutex_lock(&storageMutex);
+    MUTEX_LOCK(&storageMutex);
     if (g_rdStorage)
     {
         OCRDStorePublishResources *temp = g_rdStorage;
@@ -123,7 +150,7 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
     {
         g_rdStorage = resources;
     }
-    pthread_mutex_unlock(&storageMutex);
+    MUTEX_UNLOCK(&storageMutex);
 
     printStoragedResources(g_rdStorage);
     return OC_STACK_OK;
index a50bf2c..d444431 100644 (file)
@@ -24,6 +24,7 @@
 #include "oic_string.h"
 #include "oic_malloc.h"
 #include "payload_logging.h"
+#include "platform_features.h"
 
 #include "rdpayload.h"
 #include "ocpayload.h"
@@ -62,9 +63,9 @@ static OCStackResult sendRequest(OCMethod method, char *uri, OCDevAddr *addr,
     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.");
@@ -99,7 +100,7 @@ static void retreiveRDDetails(OCClientResponse *clientResponse, OCRDBiasFactorCB
 }
 
 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;
index e97fedf..3c4c922 100644 (file)
@@ -122,8 +122,13 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
  * 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;
 
index d82b5f5..f02d7d3 100644 (file)
@@ -93,8 +93,8 @@ client_src = [
 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')
@@ -119,4 +119,4 @@ if target_os == 'linux':
     SConscript('src/resourceBroker/unittest/SConscript')
 
 if target_os == 'android':
-    SConscript('android/SConscript')
\ No newline at end of file
+    SConscript('android/SConscript')
index 1ced6af..b2f7bd9 100644 (file)
@@ -30,6 +30,8 @@
 
 #include <octypes.h>
 
+#include "boost/config.hpp"
+
 namespace OIC
 {
     namespace Service
@@ -69,13 +71,13 @@ namespace OIC
              */
             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:
             /**
index 2901d78..6fcff21 100644 (file)
@@ -113,7 +113,7 @@ namespace OIC
             class KeyValueVisitorHelper: public boost::static_visitor< >
             {
             public:
-                KeyValueVisitorHelper(VISITOR& visitor) noexcept :
+                KeyValueVisitorHelper(VISITOR& visitor) BOOST_NOEXCEPT :
                         m_visitor( visitor )
                 {
                 }
@@ -186,7 +186,7 @@ namespace OIC
                  *
                  * @see getBaseTypeId
                  */
-                TypeId getId() const noexcept;
+                TypeId getId() const BOOST_NOEXCEPT;
 
                 /**
                  * Returns the type identifier of a base type of sequence.
@@ -198,7 +198,7 @@ namespace OIC
                  * @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.
@@ -207,7 +207,7 @@ namespace OIC
                  *
                  * @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.
@@ -219,7 +219,7 @@ namespace OIC
                  * @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 };
                 }
@@ -234,17 +234,17 @@ namespace OIC
                  * @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 }
                 {
                 }
@@ -299,7 +299,7 @@ namespace OIC
 
                 Value();
                 Value(const Value&);
-                Value(Value&&) noexcept;
+                Value(Value&&) BOOST_NOEXCEPT;
 
                 /**
                  * Constructs a Value if T is a supported type.<br/>
@@ -368,7 +368,7 @@ namespace OIC
                 /**
                  * 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;
@@ -420,32 +420,32 @@ namespace OIC
             /**
              * 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.
@@ -519,7 +519,7 @@ namespace OIC
             /**
              * Removes all elements.
              */
-            void clear() noexcept;
+            void clear() BOOST_NOEXCEPT;
 
             /**
              * Removes a single element.
@@ -553,14 +553,14 @@ namespace OIC
              *
              * @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 >
@@ -662,7 +662,7 @@ namespace OIC
          * @return true if the objects are equal, false otherwise.
          */
         bool operator==(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
-                noexcept;
+                BOOST_NOEXCEPT;
 
         /**
          * @relates RCSResourceAttributes::Type
@@ -672,7 +672,7 @@ namespace OIC
          * @return true if the objects are not equal, false otherwise.
          */
         bool operator!=(const RCSResourceAttributes::Type&, const RCSResourceAttributes::Type&)
-                noexcept;
+                BOOST_NOEXCEPT;
 
         /**
          * @relates RCSResourceAttributes::Value
@@ -763,32 +763,32 @@ namespace OIC
             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;
 
index 6e02574..1b92f13 100644 (file)
@@ -88,8 +88,8 @@ if target_os in ['tizen','android'] :
 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')
 
index 4ff3df8..a800415 100755 (executable)
 #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
 {
index 7c95953..de8c2c3 100755 (executable)
@@ -25,9 +25,7 @@
 #include <vector>
 #include <cstdio>
 #include <iostream>
-
 #include <ctime>
-
 #include <timer.h>
 
 using namespace std;
index 8bbe52f..1568447 100755 (executable)
@@ -25,7 +25,9 @@
 
 #include <algorithm>
 #include <thread>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 #include <string.h>
 
 #include "GroupManager.h"
index 1dfd837..163c58b 100644 (file)
@@ -94,6 +94,9 @@ elif target_os == 'ios':
 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'))
index 5ec0bad..1a429f6 100644 (file)
@@ -43,7 +43,11 @@ def run_test(env, xml_file, test):
 
     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 = ''
index 557e2a1..f0f0810 100644 (file)
@@ -346,7 +346,7 @@ def generate( env ) :
 
 
     # 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"