Merge branch '1.3-rel' (1a2c9ee2) 01/21401/1
authorPhilippe Coval <philippe.coval@osg.samsung.com>
Wed, 12 Jul 2017 09:04:06 +0000 (11:04 +0200)
committerPhilippe Coval <philippe.coval@osg.samsung.com>
Wed, 12 Jul 2017 09:05:25 +0000 (11:05 +0200)
Relate-to: https://gerrit.iotivity.org/gerrit/21339

Change-Id: I1a2c9ee277023393e660b93ef49b19f7ef952974
Bug: https://jira.iotivity.org/browse/IOT-2453
Signed-off-by: Philippe Coval <philippe.coval@osg.samsung.com>
227 files changed:
.gitattributes
.gitignore
auto_build.py
bridging/SConscript
bridging/common/ConcurrentIotivityUtils.cpp
build_common/SConscript
build_common/arduino/SConscript
build_common/external_builders.scons
build_common/external_libs.scons
build_common/linux/SConscript
build_common/windows/SConscript
extlibs/android/sdk/SConscript
extlibs/arduino/SConscript
extlibs/mbedtls/SConscript
extlibs/wksxmppxep/SConscript
java/jni/SConscript
plugins/SConscript
plugins/samples/linux/SConscript
plugins/src/SConscript
plugins/unittests/SConscript
plugins/zigbee_wrapper/SConscript
plugins/zigbee_wrapper/src/SConscript
plugins/zigbee_wrapper/telegesis_wrapper/SConscript
plugins/zigbee_wrapper/telegesis_wrapper/src/SConscript
resource/IPCA/SConscript
resource/IPCA/samples/ElevatorClient/SConscript
resource/IPCA/samples/ElevatorServer/SConscript
resource/IPCA/samples/ipcaapp/SConscript
resource/IPCA/src/SConscript
resource/IPCA/unittests/SConscript
resource/SConscript
resource/android/SConscript
resource/c_common/SConscript
resource/c_common/iotivity_commontypes.h [new file with mode: 0644]
resource/c_common/ocatomic/include/ocatomic.h
resource/c_common/ocatomic/src/arduino/ocatomic.c
resource/c_common/ocatomic/src/others/ocatomic.c
resource/c_common/ocatomic/src/windows/ocatomic.c
resource/c_common/ocevent/include/ocevent.h [new file with mode: 0644]
resource/c_common/ocevent/src/others/ocevent.c [new file with mode: 0644]
resource/c_common/ocevent/src/windows/ocevent.c [new file with mode: 0644]
resource/c_common/ocevent/test/SConscript [new file with mode: 0644]
resource/c_common/ocevent/test/eventtest.cpp [new file with mode: 0644]
resource/c_common/octhread/include/octhread.h
resource/c_common/octhread/src/posix/octhread.c
resource/c_common/octhread/src/windows/octhread.c
resource/c_common/octimer/include/octimer.h
resource/c_common/octimer/src/octimer.c
resource/c_common/oic_time/include/oic_time.h
resource/c_common/platform_features.h
resource/c_common/unittests/SConscript
resource/csdk/connectivity/SConscript
resource/csdk/connectivity/api/cacommon.h
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/build/arduino/SConscript
resource/csdk/connectivity/build/arduino/arduino.scons
resource/csdk/connectivity/build/linux/SConscript
resource/csdk/connectivity/build/tizen/Makefile
resource/csdk/connectivity/build/tizen/SConscript
resource/csdk/connectivity/common/SConscript
resource/csdk/connectivity/common/src/caremotehandler.c
resource/csdk/connectivity/inc/cainterfacecontroller.h
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/ca_adapter_net_ssl.c
resource/csdk/connectivity/src/bt_edr_adapter/SConscript
resource/csdk/connectivity/src/bt_edr_adapter/android/SConscript
resource/csdk/connectivity/src/bt_edr_adapter/tizen/SConscript
resource/csdk/connectivity/src/bt_le_adapter/SConscript
resource/csdk/connectivity/src/bt_le_adapter/android/SConscript
resource/csdk/connectivity/src/bt_le_adapter/arduino/SConscript
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/linux/SConscript
resource/csdk/connectivity/src/bt_le_adapter/tizen/SConscript
resource/csdk/connectivity/src/cablockwisetransfer.c
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/ip_adapter/SConscript
resource/csdk/connectivity/src/ip_adapter/android/SConscript
resource/csdk/connectivity/src/ip_adapter/arduino/SConscript
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c
resource/csdk/connectivity/src/ip_adapter/tizen/SConscript
resource/csdk/connectivity/src/nfc_adapter/SConscript
resource/csdk/connectivity/src/nfc_adapter/android/SConscript
resource/csdk/connectivity/src/ra_adapter/SConscript
resource/csdk/connectivity/src/tcp_adapter/SConscript
resource/csdk/connectivity/src/tcp_adapter/arduino/SConscript
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/connectivity/test/SConscript
resource/csdk/connectivity/util/SConscript
resource/csdk/include/octypes.h
resource/csdk/resource-directory/src/rd_client.c
resource/csdk/resource-directory/src/rd_server.c
resource/csdk/routing/include/routingmanager.h
resource/csdk/routing/include/routingmanagerinterface.h
resource/csdk/routing/src/routingmanager.c
resource/csdk/routing/src/routingmanagerinterface.c
resource/csdk/security/SConscript
resource/csdk/security/provisioning/sample/autoprovisioningclient.c
resource/csdk/security/provisioning/sample/cloud/cloudResource.c
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_mfg.cpp
resource/csdk/security/provisioning/sample/sampleserver_mvjustworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_preconfpin.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/multipleownershiptransfermanager.c
resource/csdk/security/provisioning/src/ocprovisioningmanager.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/SConscript
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/provisioning/unittest/sampleserver.cpp
resource/csdk/security/provisioning/unittest/sampleserver2.cpp [new file with mode: 0644]
resource/csdk/security/src/credresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/stack/include/internal/occlientcb.h
resource/csdk/stack/include/internal/ocobserve.h
resource/csdk/stack/include/internal/ocresource.h
resource/csdk/stack/include/internal/ocserverrequest.h
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/ocpresence.h
resource/csdk/stack/octbstack_product_secured.def
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.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/ocserverbasicops.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/tizen/build/gbsbuild.sh
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocobserve.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/stacktests.cpp
resource/docs/c-doc/Doxyfile
resource/examples/SConscript
resource/include/StringConstants.h
resource/oc_logger/SConscript
resource/oc_logger/examples/SConscript
resource/provisioning/SConscript
resource/provisioning/examples/SConscript
resource/provisioning/unittests/SConscript
resource/src/InProcServerWrapper.cpp
resource/src/OCException.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons
resource/unittests/OCExceptionTest.cpp
resource/unittests/OCRepresentationTest.cpp
resource/unittests/SConscript
service/coap-http-proxy/src/CoapHttpHandler.c
service/easy-setup/enrollee/src/resourcehandler.c
service/easy-setup/enrollee/unittests/SConscript
service/notification/SConscript
service/notification/cpp-wrapper/consumer/SConscript
service/notification/cpp-wrapper/examples/linux/SConscript
service/notification/cpp-wrapper/provider/SConscript
service/notification/cpp-wrapper/unittest/SConscript
service/notification/examples/linux/SConscript
service/notification/examples/linux/notificationconsumer.c
service/notification/examples/linux/notificationprovider.c
service/notification/examples/tizen/NSSampleConsumerApp/.exportMap [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/edc_resource/ns_consumer_control.edc [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/inc/nsclient.h [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/inc/nsmain.h [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/lib/ResourceContainerConfig.xml [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/res/ui_controls.edc [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/shared/res/nssampleapp.png [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/src/nsclient.cpp [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/src/nsmain.cpp [new file with mode: 0644]
service/notification/examples/tizen/NSSampleConsumerApp/tizen-manifest.xml [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/.exportMap [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/edc_resource/ns_provider_control.edc [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/inc/nsmain.h [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/inc/nsserver.h [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/lib/ResourceContainerConfig.xml [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/res/ui_controls.edc [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/shared/res/nssampleapp.png [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/src/nsmain.cpp [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/src/nsserver.cpp [new file with mode: 0644]
service/notification/examples/tizen/NSSampleProviderApp/tizen-manifest.xml [new file with mode: 0644]
service/notification/src/provider/NSProviderCallbackResponse.c
service/notification/src/provider/NSProviderDiscovery.c
service/notification/src/provider/NSProviderInterface.c
service/notification/src/provider/NSProviderListener.c
service/notification/src/provider/NSProviderMemoryCache.c
service/notification/src/provider/NSProviderNotification.c
service/notification/src/provider/NSProviderScheduler.c
service/notification/src/provider/NSProviderSubscription.c
service/notification/src/provider/NSProviderSystem.c
service/notification/src/provider/NSProviderTopic.c
service/notification/unittest/SConscript
service/resource-container/unittests/SConscript
service/resource-encapsulation/examples/tizen/NestedAttributeClientApp/src/reclient.cpp
service/resource-encapsulation/examples/tizen/RESampleClientApp/src/reclient.cpp
service/resource-encapsulation/include/RCSException.h
service/resource-encapsulation/src/common/SConscript
service/resource-encapsulation/src/common/expiryTimer/unittests/ExpiryTimerTest.cpp
service/resource-encapsulation/src/common/primitiveResource/unittests/PresenceSubscriberTest.cpp
service/resource-encapsulation/src/common/primitiveResource/unittests/PrimitiveResourceTest.cpp
service/resource-encapsulation/src/common/primitiveResource/unittests/ResourceAttributesTest.cpp
service/resource-encapsulation/src/common/primitiveResource/unittests/SConscript
service/resource-encapsulation/src/common/utils/include/UnitTestHelperWithFakeOCPlatform.cpp [new file with mode: 0644]
service/resource-encapsulation/src/common/utils/include/UnitTestHelperWithFakeOCPlatform.h [new file with mode: 0644]
service/resource-encapsulation/src/resourceBroker/src/ResourceBroker.cpp
service/resource-encapsulation/src/resourceCache/src/ResourceCacheManager.cpp
service/resource-encapsulation/src/serverBuilder/SConscript
service/resource-encapsulation/src/serverBuilder/unittests/RCSResourceObjectTest.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResponseTest.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RequestHandlerTest.cpp
service/resource-encapsulation/unittests/DiscoveryManagerTest.cpp
service/resource-encapsulation/unittests/ResourceClientTest.cpp
service/resource-encapsulation/unittests/SConscript
service/simulator/SConscript
service/third_party_libs.scons
tools/generate_report.sh [new file with mode: 0755]
tools/tizen/iotivity.spec

index 6935b1e..d4a8d34 100644 (file)
@@ -1,2 +1,2 @@
-\r
-*.dat binary\r
+run.bat text eol=crlf
+*.dat binary
index fbf4bac..9c4f9fd 100644 (file)
@@ -38,19 +38,9 @@ resource/csdk/stack/samples/linux/SimpleClientServer/release/
 resource/csdk/connectivity/build/out/
 
 # Ignore autogenerated files
-resource/c_common/iotivity_config.h
-
-resource/oc_logger/bin/
-resource/oc_logger/lib/
-resource/oc_logger/samples/linux/release/
-resource/oc_logger/samples/linux/debug
-
-resource/unittests/release/
-resource/unittests/debug/
-
-service/things-manager/build/linux/release
-service/things-manager/build/linux/debug
-service/things-manager/sdk/build/linux/
+# better not to ignore this one:
+#resource/c_common/iotivity_config.h
+resource/csdk/connectivity/src/bt_le_adapter/linux/org.iotivity.gatt.service.conf
 
 service/notification/android/.gradle/
 service/notification/android/build/
@@ -100,32 +90,29 @@ iotivity.pc
 tmp/
 
 # Ignore downloaded dependencies
-extlibs/libcoap/libcoap
-extlibs/gtest/gtest-*
-extlibs/hippomocks-master/
-extlibs/hippomocks/hippomocks/
-extlibs/master.zip
-extlibs/cereal/cereal
-extlibs/cereal
-extlibs/android/gradle/gradle-2.2.1
-extlibs/android/ndk/android-ndk-r10d
-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/*
-extlibs/tinycbor/tinycbor
 *.tgz
 *.zip
-extlibs/arduino/arduino-1.5.8
-build_common/arduino/extlibs/arduino/arduino-1.5.8
-extlibs/tinydtls/dtls-client
-extlibs/tinydtls/dtls-server
+*.bin
+extlibs/android/gradle/gradle-*
+extlibs/android/ndk/android-ndk-*
+extlibs/android/sdk/android-sdk-*
+extlibs/arduino/arduino-*
 extlibs/bluez/bluez
+extlibs/boost/boost_*
+extlibs/cereal/cereal
+extlibs/gtest/googletest-*
+extlibs/hippomocks/hippomocks
+extlibs/hippomocks-master
+extlibs/libcoap/libcoap
+extlibs/libstrophe/libstrophe
 extlibs/mbedtls/mbedtls
+extlibs/rapidjson/rapidjson
 extlibs/raxmpp/raxmpp
+extlibs/sqlite3/sqlite3*
+extlibs/tinycbor/tinycbor
+extlibs/tinydtls/dtls-client
+extlibs/tinydtls/dtls-server
 extlibs/yaml/yaml
-extlibs/rapidjson/rapidjson
 
 # Ignore editor (e.g. Emacs) backup and autosave files
 *~
@@ -141,8 +128,11 @@ extlibs/rapidjson/rapidjson
 # Ignore Valgrind generated files.
 *.memcheck
 
-# Ignore  generated files
-*.dat
+# Ignore generated documentation files
+docs/c-doc/docs/
+docs/c-doc/doxygen.log
+docs/cpp-doc/docs/
+docs/cpp-doc/doxygen.log
 
 # Ignore debian generated files
 debian/files
index a9768a5..27c86aa 100755 (executable)
@@ -12,7 +12,8 @@ def helpmsg(script):
 Usage:
     build:
         python %s <targetbuild>
-        Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, linux_unsecured_with_rd, linux_secured_with_rd, android, arduino, tizen, simulator, darwin, windows, msys
+        Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, linux_unsecured_with_rd, linux_secured_with_rd,
+        android, android_unsecured, android_secured, arduino, tizen, tizen_unsecured, tizen_secured, simulator, darwin, windows, msys
         Note: \"linux\" will build \"linux_unsecured\", \"linux_secured\", \"linux_unsecured_with_ra\", \"linux_secured_with_ra\", \"linux_secured_with_rd\", \"linux_unsecured_with_mq\", \"linux_secured_with_tcp\" & \"linux_unsecured_with_tcp\" & \"linux_unsecured_with_rd\".
         Any selection will build both debug and release versions of all available targets in the scope you've selected.
         To choose any specific command, please use the SCons commandline directly. Please refer to [IOTIVITY_REPO]/Readme.scons.txt.
@@ -60,7 +61,8 @@ def build_all(flag, extra_option_str):
         build_linux_secured_with_java(flag, extra_option_str)
         build_simulator(flag, extra_option_str)
 
-        build_android(flag, extra_option_str)
+        build_android_unsecured(flag, extra_option_str)
+        build_android_secured(flag, extra_option_str)
         build_arduino(flag, extra_option_str)
         build_tizen(flag, extra_option_str)
 
@@ -202,6 +204,12 @@ def build_android(flag, extra_option_str):
                     }
     call_scons(build_options, extra_option_str)
 
+def build_android_secured(flag, extra_option_str):
+    build_android(flag, extra_option_str + " SECURED=1")
+
+def build_android_unsecured(flag, extra_option_str):
+    build_android(flag, extra_option_str + " SECURED=0")
+
 def build_android_x86(flag, extra_option_str):
     """ Build Android x86 Suite """
     build_android_x86_with_ip(flag, extra_option_str)
@@ -611,6 +619,14 @@ elif arg_num == 2:
         build_android("true", "")
         build_android("false", "")
 
+    elif str(sys.argv[1]) == "android_unsecured":
+        build_android_unsecured("true", "")
+        build_android_unsecured("false", "")
+
+    elif str(sys.argv[1]) == "android_secured":
+        build_android_secured("true", "")
+        build_android_secured("false", "")
+
     elif str(sys.argv[1]) == "android_x86":
         build_android_x86("true", "")
         build_android_x86("false", "")
index 24d00b7..5c555d6 100644 (file)
@@ -30,21 +30,21 @@ build_sample = 'ON'
 src_dir = env.get('SRC_DIR')
 
 # rapidjson fetch
-SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'rapidjson', 'SConscript'))
+SConscript('#extlibs/rapidjson/SConscript')
 
 if target_os not in [
     'android', 'arduino', 'darwin', 'ios', 'tizen', 'msys_nt', 'windows']:
 
-    SConscript(os.path.join('common', 'SConscript'))
+    SConscript('common/SConscript')
 
-    SConscript(os.path.join('mini_plugin_manager', 'SConscript'))
+    SConscript('mini_plugin_manager/SConscript')
 
-    SConscript(os.path.join('mpm_client', 'SConscript'))
+    SConscript('mpm_client/SConscript')
 
-    SConscript(os.path.join('plugins', 'lifx_plugin', 'SConscript'))
+    SConscript('plugins/lifx_plugin/SConscript')
 
-    SConscript(os.path.join('plugins', 'hue_plugin', 'SConscript'))
+    SConscript('plugins/hue_plugin/SConscript')
 
-    SConscript(os.path.join('plugins', 'nest_plugin', 'SConscript'))
+    SConscript('plugins/nest_plugin/SConscript')
 
-    SConscript(os.path.join('plugins', 'lyric_plugin', 'SConscript'))
+    SConscript('plugins/lyric_plugin/SConscript')
index 0c77e4b..3c23fa4 100644 (file)
@@ -72,7 +72,6 @@ OCStackResult ConcurrentIotivityUtils::respondToRequest(OCEntityHandlerRequest *
     std::unique_ptr<OCEntityHandlerResponse> response = make_unique<OCEntityHandlerResponse>();
 
     response->requestHandle = request->requestHandle;
-    response->resourceHandle = request->resource;
     response->ehResult = responseCode;
 
     // Clone a copy since this allocation is going across thread boundaries.
index 58c9f82..1e1a704 100755 (executable)
@@ -5,6 +5,7 @@
 ##
 import os
 import platform
+import re
 
 project_version = '1.3.0'
 
@@ -179,7 +180,6 @@ if target_os in targets_without_dtls_support:
                      '0',
                      allowed_values=('0', '1')))
 else:
-
     help_vars.Add(
         EnumVariable('SECURED',
                      'Build with DTLS',
@@ -409,6 +409,11 @@ if env['CONFIG_ENVIRONMENT_IMPORT'] == True:
     if os.environ['LDFLAGS'] != None:
         env.AppendUnique(LINKFLAGS=Split(os.environ['LDFLAGS']))
 
+if target_os in ['windows']:
+    # UnpackAll.py needs access to system PATH components that SCons
+    # does not include by default - e.g., the path to 7z.exe.
+    env.AppendUnique(PATH=os.environ['PATH'])
+
 # Ensure scons is able to change its working directory
 env.SConscriptChdir(1)
 
@@ -719,7 +724,7 @@ if ('PUB' in with_mq):
 if ('BROKER' in with_mq):
     env.AppendUnique(CPPDEFINES=['MQ_BROKER', 'WITH_MQ'])
 
-env.AppendUnique(CPPDEFINES = {'OC_LOG_LEVEL' : env.get('LOG_LEVEL')})
+env.AppendUnique(CPPDEFINES={'OC_LOG_LEVEL': env.get('LOG_LEVEL')})
 
 if env.get('LOGGING'):
     env.AppendUnique(CPPDEFINES=['TB_LOG'])
@@ -828,14 +833,47 @@ conf = Configure(
 # threading and mutexes.  This will set the environment variable
 # POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
 conf.CheckPThreadsSupport()
-
 env = conf.Finish()
+
+######################################################################
+# Generate Cbor from json files
 ######################################################################
+json2cbor = env.get('BUILD_DIR') + 'resource/csdk/security/tool/json2cbor' + env.get('PROGSUFFIX')
+
+def generate_actions(source, target, env, for_signature):
+    Depends(target, json2cbor)
+    return " %s %s %s" % (json2cbor, source[0], target[0])
+
+builder = Builder(generator = generate_actions,
+                  suffix = '.dat',
+                  src_suffix = '.json')
+
+env.Append(BUILDERS = {'Cbor' : builder})
+
+
+def ScanJSON(env, directory):
+    actions = []
+    if env.GetOption('clean') or env.get('SECURED') != '1':
+        return actions
+    dst_dir = env.get('BUILD_DIR') + '/' + directory + '/'
+    src_dir = env.get('SRC_DIR') + '/' + directory + '/'
+    for json_file in Glob('*.json'):
+        actions += env.Install(dst_dir, str(json_file))
+        if env.get('CROSS_COMPILE') != None:
+            cbor_file = src_dir + re.sub('\.json$', '.dat', str(json_file))
+            Install(dst_dir, cbor_file)
+        else:
+            cbor_file = env.Cbor(json_file)
+            cbor_file = Flatten(cbor_file)[0].name
+            src = dst_dir + cbor_file
+            dst = src_dir + cbor_file
+            Command(dst, src, Copy("$TARGET", "$SOURCE"))
+        actions += cbor_file
+    return actions
 
-# must call external_builders.scons second time to properly setup
-# UnpackAll builder this is due to the system path not being pulled
-# in for windows till after the windows target has run.
-env.SConscript('external_builders.scons')
+AddMethod(env, ScanJSON)
+
+######################################################################
 env.SConscript('external_libs.scons')
 
 Return('env')
index 65a2901..97bfb1d 100644 (file)
@@ -260,7 +260,7 @@ target_arch = env.get('TARGET_ARCH')
 
 # Verify that the arduino, time, red bear, and nordic libraries are
 # installed.  If not, get them and install them.
-SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'arduino', 'SConscript'))
+SConscript('#extlibs/arduino/SConscript')
 arduino_home = env.get('ARDUINO_HOME')
 print 'ARDUINO_HOME = ' + env.get('ARDUINO_HOME')
 
index eeae541..6ae62de 100644 (file)
@@ -44,19 +44,19 @@ def __prepare_lib(ienv, libname, lib=None, path=None, script=None):
         if path:
             dir = path
         else:
-            dir = os.path.join(env.get('SRC_DIR'), 'extlibs', libname)
+            dir = '#/extlibs/' + libname
 
         # Execute the script to download(if required) and build source code
         if script:
-            st = os.path.join(dir, script)
+            st = dir + '/' + script
         else:
-            st = os.path.join(dir, 'SConscript')
+            st = dir + 'SConscript'
 
         if os.path.exists(st):
             SConscript(st)
         else:
             if target_os in ['linux', 'darwin', 'tizen']:
-                print 'Don\'t find library(%s), please intall it, exit ...' % libname
+                print 'Library (%s) not found, please intall it, exit ...' % libname
             else:
                 print 'Library (%s) not found and cannot find the scons script (%s), exit ...' % (
                     libname, st)
index cbf2720..4fb176e 100644 (file)
@@ -51,18 +51,18 @@ if target_os not in ['windows']:
     env.AppendUnique(LIBPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'lib', target_arch)])
 
 # tinycbor build/fetch
-SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'tinycbor', 'SConscript'))
+SConscript('#extlibs/tinycbor/SConscript')
 
 #cJSON lib
-SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'cjson', 'SConscript'))
+SConscript('#extlibs/cjson/SConscript')
 
 with_ra = env.get('WITH_RA')
 if with_ra:
-    SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'raxmpp', 'SConscript'))
+    SConscript('#extlibs/raxmpp/SConscript')
 
 with_ra_ibb = env.get('WITH_RA_IBB')
 if with_ra_ibb:
-    SConscript(os.path.join(env.get('SRC_DIR'), 'extlibs', 'wksxmppxep', 'SConscript'))
+    SConscript('#extlibs/wksxmppxep/SConscript')
 
 if env.get('SECURED') == '1' or 'SERVER' in rd_mode:
     if target_os not in ['linux', 'tizen']:
index 331482a..85996cf 100644 (file)
@@ -8,6 +8,11 @@ Import('env')
 
 print "Reading linux configuration script"
 
+# Test Coverage Flags and Library (if RELEASE=0)
+if not env.get('RELEASE'):
+    env.AppendUnique(LIBS=['gcov'])
+    env.AppendUnique(CCFLAGS=['--coverage', '-fPIC', '-O0'])
+
 help_vars = Variables()
 if env.get('BUILD_JAVA') == True:
     if not env.get('ANDROID_GRADLE'):
index 68c124e..cd0fc4c 100644 (file)
@@ -89,7 +89,6 @@ if env['CC'] == 'cl':
     env.PrependUnique(LIBPATH=[os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk', 'resource-directory')])
     env.PrependUnique(LIBPATH=['#extlibs/mbedtls'])
 
-    env.AppendUnique(PATH=os.environ['PATH'])
     env['PDB'] = '${TARGET.base}.pdb'
     env.Append(LINKFLAGS=['/PDB:${TARGET.base}.pdb'])
 
index 980d7c6..ce4f7d6 100644 (file)
@@ -12,7 +12,7 @@ Import('env')
 target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 
-SConscript(src_dir + '/build_common/tools/UnpackAll.py')
+SConscript('#build_common/tools/UnpackAll.py')
 
 # Download
 if target_os == 'android':
index f086b31..72771f7 100644 (file)
@@ -14,7 +14,7 @@ Import('env')
 target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 
-SConscript(src_dir + '/build_common/tools/UnpackAll.py')
+SConscript('#build_common/tools/UnpackAll.py')
 
 # Download
 if target_os == 'arduino':
index 9517042..9c12a22 100644 (file)
@@ -34,7 +34,6 @@ mbedtls_config_file = 'config-iotivity.h' if target_os != 'windows' else 'config
 
 # The mbedtls_revision tag here must match the one in extlibs/mbedtls/prep.sh.
 mbedtls_revision = 'mbedtls-2.4.2'
-
 if not os.path.exists(mbedtls_dir):
     msg = '''
 *********************************** Error: ************************************
index 1b1956a..2345812 100644 (file)
@@ -23,7 +23,7 @@ LIB_PATH = SRC_PATH
 WJSXMPPXEP_LIBS = ['wksxmppxep', 'm', 'crypto']
 
 if with_ra_ibb:
-    env.SConscript(base_dir + '/extlibs/libstrophe/SConscript')
+    env.SConscript('#extlibs/libstrophe/SConscript')
     if not os.path.exists(SRC_NAME):
         raxmpp_env = Environment(ENV=os.environ)
         c = raxmpp_env.Action([
@@ -61,7 +61,6 @@ if with_ra_ibb:
                 print foo
                 foo = commands.getoutput('cp libwksxmppxep.a ' + build_dir)
                 print foo
-
             print 'Building with ' + SRC_NAME + ' Completely.'
 
         env.PrependUnique(
index 09559d2..91fe57e 100644 (file)
@@ -24,7 +24,7 @@
 Import('env')
 # Add third party libraries
 lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
+SConscript('#/resource/third_party_libs.scons', exports=['lib_env'])
 
 jni_env = lib_env.Clone()
 rd_mode = jni_env.get('RD_MODE')
index 8fc70bc..3decb72 100644 (file)
@@ -29,16 +29,16 @@ 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', 'msys_nt', 'windows']:
+if target_os not in [
+        'android', 'arduino', 'darwin', 'ios', 'tizen', 'msys_nt', 'windows'
+]:
 
-    SConscript(os.path.join('zigbee_wrapper', 'SConscript'))
+    SConscript('zigbee_wrapper/SConscript')
 
-    SConscript(os.path.join('src', 'SConscript'))
+    SConscript('src/SConscript')
 
-    SConscript(os.path.join('unittests', 'SConscript'))
+    SConscript('unittests/SConscript')
 
     if build_sample == 'ON':
-           if target_os in ['linux']:
-                   target_path = target_os
-                   SConscript(os.path.join('samples', target_path, 'SConscript'))
-
+        if target_os in ['linux']:
+            SConscript('samples/' + target_os + '/SConscript')
index 091c790..9fc158d 100644 (file)
@@ -30,55 +30,49 @@ pi_dir = os.path.join(src_dir, 'plugins')
 ######################################################################
 # Build flags
 ######################################################################
-samples_env.PrependUnique(CPPPATH = [
-               os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
-               os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-               os.path.join(src_dir, 'resource', 'csdk', 'include'),
-               os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
-                os.path.join(pi_dir, 'include')
-                ])
+samples_env.PrependUnique(CPPPATH=[
+    os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
+    os.path.join(pi_dir, 'include')
+])
 
-samples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
-samples_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-samples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+samples_env.AppendUnique(
+    CXXFLAGS=['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
+samples_env.AppendUnique(RPATH=[env.get('BUILD_DIR')])
+samples_env.AppendUnique(LIBPATH=[env.get('BUILD_DIR')])
 
 if target_os in ['darwin', 'ios']:
-       samples_env.PrependUnique(LIBS = ['m',
-                                          'octbstack',
-                                          'ocsrm',
-                                          'connectivity_abstraction',
-                                          'coap' ])
+    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',
-                                          'plugin_interface'])
-       samples_env.AppendUnique(LIBS = ['rt'])
-       if target_arch in ['x86_64', 'arm64']:
-               samples_env.AppendUnique(CPPFLAGS = ['-Llib64'])
-       else:
-               samples_env.AppendUnique(CPPFLAGS = ['-Llib'])
-       samples_env.AppendUnique(LIBS = ['pthread'])
+    samples_env.PrependUnique(LIBS=[
+        'm', 'octbstack', 'ocsrm', 'connectivity_abstraction', 'coap',
+        'plugin_interface'
+    ])
+    samples_env.AppendUnique(LIBS=['rt'])
+    if target_arch in ['x86_64', 'arm64']:
+        samples_env.AppendUnique(CPPFLAGS=['-Llib64'])
+    else:
+        samples_env.AppendUnique(CPPFLAGS=['-Llib'])
+    samples_env.AppendUnique(LIBS=['pthread'])
 
 if env.get('SECURED') == '1':
-    samples_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
+    samples_env.AppendUnique(LIBS=['mbedtls', 'mbedx509', 'mbedcrypto'])
 
-samples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+samples_env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
 ######################################################################
 # Source files and Targets
 ######################################################################
 iotivityandzigbeeserver = samples_env.Program('iotivityandzigbeeserver',
-        ['IotivityandZigbeeServer.c'])
+                                              ['IotivityandZigbeeServer.c'])
 iotivityandzigbeeclient = samples_env.Program('iotivityandzigbeeclient',
-        ['IotivityandZigbeeClient.c'])
+                                              ['IotivityandZigbeeClient.c'])
 
 list_of_samples = [iotivityandzigbeeserver, iotivityandzigbeeclient]
 
 Alias("samples", list_of_samples)
 
 env.AppendTarget('samples')
-
-
index fa9faa2..0c6189e 100644 (file)
@@ -29,62 +29,66 @@ target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 pi_path = os.path.join(src_dir, 'plugins')
 
-print"Reading PI script"
+print "Reading PI script"
 
 ######################################################################
 # Build flags
 ######################################################################
 with_unforked_libcoap = env.get('WITH_UNFORKED_LIBCOAP')
 if with_unforked_libcoap == '1':
-    env.PrependUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+    env.PrependUnique(CPPPATH=['#extlibs/libcoap/libcoap/include'])
 else:
-    env.PrependUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1', 'include')])
+    env.PrependUnique(CPPPATH=[
+        os.path.join(src_dir, 'resource', 'csdk', 'connectivity', 'lib',
+                     'libcoap-4.1.1', 'include')
+    ])
 
-env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
-                              os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
-                              os.path.join(src_dir, 'resource', 'c_common', 'oic_time', 'include'),
-                              os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'security', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'include')
-                            ])
-env.AppendUnique(CPPPATH = [ os.path.join(pi_path, 'include'),
-                             os.path.join(pi_path, 'include', 'internal'),
-                             os.path.join(pi_path, 'zigbee_wrapper', 'include'),
-                             os.path.join(pi_path, 'include', 'internal')
-                           ])
+env.PrependUnique(CPPPATH=[
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_time', 'include'),
+    os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'security', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'include')
+])
+env.AppendUnique(CPPPATH=[
+    os.path.join(pi_path, 'include'),
+    os.path.join(pi_path, 'include', 'internal'),
+    os.path.join(pi_path, 'zigbee_wrapper', 'include'),
+    os.path.join(pi_path, 'include', 'internal')
+])
 
 if target_os not in ['arduino', 'windows']:
-       env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
+    env.AppendUnique(CPPDEFINES=['WITH_POSIX'])
 
-if target_os in ['darwin','ios']:
-       env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+if target_os in ['darwin', 'ios']:
+    env.AppendUnique(CPPDEFINES=['_DARWIN_C_SOURCE'])
 
-env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
-env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+env.AppendUnique(CXXFLAGS=['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
+env.AppendUnique(RPATH=[env.get('BUILD_DIR')])
+env.AppendUnique(LIBPATH=[env.get('BUILD_DIR')])
 
-env.PrependUnique(LIBS = ['zigbee_wrapper'])
+env.PrependUnique(LIBS=['zigbee_wrapper'])
 
 if env.get('LOGGING'):
-       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
 #####################################################################
 # Source files and Target(s)
 ######################################################################
 pi_src = [
-         os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
-         'pluginlist.c',
-         'plugininterface.c',
-            ]
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
+    'pluginlist.c',
+    'plugininterface.c',
+]
 
-env.AppendUnique(PI_SRC = pi_src)
+env.AppendUnique(PI_SRC=pi_src)
 
 if target_os in ['android', 'tizen']:
-       calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))
+    calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))
 else:
-       calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))
+    calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))
 env.InstallTarget(calib, 'plugin_interface')
 env.UserInstallTargetLib(calib, 'plugin_interface')
-
index c1391df..8e1ade2 100644 (file)
@@ -20,6 +20,7 @@
 
 import os
 import os.path
+from tools.scons.RunTest import run_test
 
 # SConscript file for Local PKI google tests
 gtest_env = SConscript('#extlibs/gtest/SConscript')
@@ -32,22 +33,22 @@ target_os = unittests_env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
-unittests_env.PrependUnique(CPPPATH = [
-                os.path.join(pi_dir, 'include'),
-               ])
+unittests_env.PrependUnique(CPPPATH=[
+    os.path.join(pi_dir, 'include'),
+])
 
-unittests_env.AppendUnique(LIBPATH = [unittests_env.get('BUILD_DIR')])
-unittests_env.PrependUnique(LIBS = [
-               'plugin_interface',
-               'oc',
-               'octbstack',
-               'oc_logger',
-               'connectivity_abstraction',
-               'coap'
-               ])
+unittests_env.AppendUnique(LIBPATH=[unittests_env.get('BUILD_DIR')])
+unittests_env.PrependUnique(LIBS=[
+    'plugin_interface',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
+])
 
 if unittests_env.get('LOGGING'):
-       unittests_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    unittests_env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
 ######################################################################
 # Source files and Targets
@@ -58,10 +59,6 @@ Alias("piunittests", [piunittests])
 
 unittests_env.AppendTarget('piunittests')
 if unittests_env.get('TEST') == '1':
-       if target_os in ['linux']:
-                from tools.scons.RunTest import *
-                run_test(unittests_env,
-                         'plugins_unittests.memcheck',
-                         'plugins/unittests/piunittests',
-                         piunittests)
-
+    if target_os in ['linux']:
+        run_test(unittests_env, 'plugins_unittests.memcheck',
+                 'plugins/unittests/piunittests', piunittests)
index 6631faf..3ad6eaa 100644 (file)
@@ -27,6 +27,6 @@ Import('env')
 
 print "Reading top Zigbee Wrapper."
 
-env.SConscript(os.path.join('telegesis_wrapper', 'SConscript'))
+env.SConscript('telegesis_wrapper/SConscript')
 
-env.SConscript(os.path.join('src', 'SConscript'))
+env.SConscript('src/SConscript')
index 21b1bf2..108a448 100644 (file)
@@ -30,54 +30,57 @@ target_os = env.get('TARGET_OS')
 src_dir = env.get('SRC_DIR')
 zw_path = os.path.join(src_dir, 'plugins')
 
-print"Reading Zigbee Wrapper (ZW) script"
+print "Reading Zigbee Wrapper (ZW) script"
 
 ######################################################################
 # Build flags
 ######################################################################
 
-env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
-                              os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
-                              os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'include'),
-                              os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
-                              ])
-env.AppendUnique(CPPPATH = [ os.path.join(zw_path, 'include'),
-                             os.path.join(zw_path, 'include', 'internal'),
-                             os.path.join(zw_path, 'zigbee_wrapper', 'include')
-                             ])
+env.PrependUnique(CPPPATH=[
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
+    os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
+])
+env.AppendUnique(CPPPATH=[
+    os.path.join(zw_path, 'include'),
+    os.path.join(zw_path, 'include', 'internal'),
+    os.path.join(zw_path, 'zigbee_wrapper', 'include')
+])
 
 if target_os not in ['arduino', 'windows']:
-       env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
+    env.AppendUnique(CPPDEFINES=['WITH_POSIX'])
 
-if target_os in ['darwin','ios']:
-       env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+if target_os in ['darwin', 'ios']:
+    env.AppendUnique(CPPDEFINES=['_DARWIN_C_SOURCE'])
 
-env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
-env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
-env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+env.AppendUnique(CXXFLAGS=['-std=c++0x', '-Wall', '-Wextra', '-Werror'])
+env.AppendUnique(RPATH=[env.get('BUILD_DIR')])
+env.AppendUnique(LIBPATH=[env.get('BUILD_DIR')])
 
-env.PrependUnique(LIBS = ['telegesis_wrapper'])
+env.PrependUnique(LIBS=['telegesis_wrapper'])
 
 if env.get('LOGGING'):
-       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
 #####################################################################
 # Source files and Target(s)
 ######################################################################
 
 zw_src = [
-         os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'src', 'oic_malloc.c'),
-         os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
-            'zigbee_wrapper.c',
-         ]
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'src',
+                 'oic_malloc.c'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
+    'zigbee_wrapper.c',
+]
 
-env.AppendUnique(ZW_SRC = zw_src)
+env.AppendUnique(ZW_SRC=zw_src)
 
 if target_os in ['android', 'tizen']:
-       calib = env.SharedLibrary('zigbee_wrapper', env.get('ZW_SRC'))
+    calib = env.SharedLibrary('zigbee_wrapper', env.get('ZW_SRC'))
 else:
-       calib = env.StaticLibrary('zigbee_wrapper', env.get('ZW_SRC'))
+    calib = env.StaticLibrary('zigbee_wrapper', env.get('ZW_SRC'))
 env.InstallTarget(calib, 'libzigbee_wrapper')
 env.UserInstallTargetLib(calib, 'libzigbee_wrapper')
index 8b9a04d..391b0bb 100644 (file)
@@ -27,5 +27,4 @@ Import('env')
 
 print "Reading top Telegesis Wrapper."
 
-env.SConscript(os.path.join('src', 'SConscript'))
-
+env.SConscript('src/SConscript')
index b2d71b0..284405a 100644 (file)
@@ -33,37 +33,37 @@ tw_path = os.path.join(src_dir, 'plugins')
 # Source files and Target(s)
 ######################################################################
 
-print"Reading Telegesis Wrapper (TW) script"
+print "Reading Telegesis Wrapper (TW) script"
 
-env.AppendUnique(CPPPATH = [ os.path.join(tw_path, 'include'),
-                             os.path.join(tw_path, 'include', 'internal'),
-                             os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
-                             os.path.join(src_dir, 'resource', 'csdk', 'include'),
-                             os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
-                             os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-                             os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
-                             os.path.join(tw_path, 'zigbee_wrapper', 'telegesis_wrapper', 'include')
-                             ])
+env.AppendUnique(CPPPATH=[
+    os.path.join(tw_path, 'include'),
+    os.path.join(tw_path, 'include', 'internal'),
+    os.path.join(src_dir, 'resource', 'oc_logger', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),
+    os.path.join(tw_path, 'zigbee_wrapper', 'telegesis_wrapper', 'include')
+])
 
 if target_os not in ['arduino', 'windows']:
-       env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])
+    env.AppendUnique(CPPDEFINES=['WITH_POSIX'])
 
-if target_os in ['darwin','ios']:
-       env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+if target_os in ['darwin', 'ios']:
+    env.AppendUnique(CPPDEFINES=['_DARWIN_C_SOURCE'])
 
 tw_src = [
-         os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'src', 'oic_string.c'),
-         os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
-         'twsocketlist.c',
-         'telegesis_socket.c',
-         'telegesis_wrapper.c'
-         ]
+    os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'src',
+                 'oic_string.c'),
+    os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),
+    'twsocketlist.c', 'telegesis_socket.c', 'telegesis_wrapper.c'
+]
 
-env.AppendUnique(TW_SRC = tw_src)
+env.AppendUnique(TW_SRC=tw_src)
 
 if target_os in ['android', 'tizen']:
-       calib = env.SharedLibrary('telegesis_wrapper', env.get('TW_SRC'))
+    calib = env.SharedLibrary('telegesis_wrapper', env.get('TW_SRC'))
 else:
-       calib = env.StaticLibrary('telegesis_wrapper', env.get('TW_SRC'))
+    calib = env.StaticLibrary('telegesis_wrapper', env.get('TW_SRC'))
 env.InstallTarget(calib, 'libtelegesis_wrapper')
 env.UserInstallTargetLib(calib, 'libtelegesis_wrapper')
index 27ef034..aa3537d 100644 (file)
@@ -28,7 +28,7 @@ Import('env')
 ipca_env = env.Clone()
 
 # c_common calls into mbedcrypto and ipca calls into c_common
-ipca_env.AppendUnique(LIBS = ['mbedcrypto'])
+ipca_env.AppendUnique(LIBS=['mbedcrypto'])
 
 # Build ipca lib
 SConscript('src/SConscript', 'ipca_env')
index efee4ca..3f83e05 100644 (file)
@@ -28,27 +28,27 @@ elevator_client_env = ipca_env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
-elevator_client_env.PrependUnique(CPPPATH = [
-        '../../inc',
-        ])
+elevator_client_env.PrependUnique(CPPPATH=[
+    '../../inc',
+])
 
-elevator_client_env.PrependUnique(LIBS = ['ipca'])
+elevator_client_env.PrependUnique(LIBS=['ipca'])
 
 if target_os not in ['windows', 'msys_nt']:
-    elevator_client_env.AppendUnique(LIBS = ['dl'])
+    elevator_client_env.AppendUnique(LIBS=['dl'])
 
 if 'g++' in elevator_client_env.get('CXX'):
-    elevator_client_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+    elevator_client_env.AppendUnique(CXXFLAGS=['-Wall', '-std=c++0x'])
 
 if target_os in ['linux']:
     if not elevator_client_env.get('RELEASE'):
-        elevator_client_env.PrependUnique(LIBS = ['gcov'])
-        elevator_client_env.AppendUnique(CXXFLAGS = ['--coverage'])
+        elevator_client_env.PrependUnique(LIBS=['gcov'])
+        elevator_client_env.AppendUnique(CXXFLAGS=['--coverage'])
 
 elevator_client_src = [
     'ElevatorClient.cpp',
-    'OCFDevice.cpp'
-        ]
+     'OCFDevice.cpp'
+]
 ######################################################################
 # Source files and Targets
 ######################################################################
index a2144c1..51a90b0 100644 (file)
@@ -32,58 +32,56 @@ rd_mode = elevator_server_env.get('RD_MODE')
 ######################################################################
 # Build flags
 ######################################################################
-elevator_server_env.PrependUnique(CPPPATH = [
-        '#/resource/include',
-        '#/resource/oc_logger/include',
-        '#/resource/csdk/include',
-        '#/resource/csdk/stack/include',
-        '#/resource/csdk/security/include',
-        '#/resource/csdk/security/provisioning/include',
-        '#/resource/csdk/security/provisioning/include/internal',
-        '#/resource/csdk/connectivity/api',
-        '#/resource/csdk/connectivity/external/inc',
-        '#/resource/csdk/ocsocket/include',
-        '#/resource/c_common/ocrandom/include',
-        '#/resource/csdk/logger/include',
-        '#/extlibs/boost/boost',
-        '../../inc'
-        ])
-
-elevator_server_env.AppendUnique(LIBPATH = [ipca_env.get('BUILD_DIR')])
-
-elevator_server_env.PrependUnique(LIBS = [
-        'coap',
-        'octbstack'
-        ])
+elevator_server_env.PrependUnique(CPPPATH=[
+    '#/resource/include',
+    '#/resource/oc_logger/include',
+    '#/resource/csdk/include',
+    '#/resource/csdk/stack/include',
+    '#/resource/csdk/security/include',
+    '#/resource/csdk/security/provisioning/include',
+    '#/resource/csdk/security/provisioning/include/internal',
+    '#/resource/csdk/connectivity/api',
+    '#/resource/csdk/connectivity/external/inc',
+    '#/resource/csdk/ocsocket/include',
+    '#/resource/c_common/ocrandom/include',
+    '#/resource/csdk/logger/include',
+    '#/extlibs/boost/boost',
+    '../../inc'
+])
+
+elevator_server_env.AppendUnique(LIBPATH=[ipca_env.get('BUILD_DIR')])
+
+elevator_server_env.PrependUnique(LIBS=['coap', 'octbstack'])
 
 if target_os not in ['msys_nt', 'windows']:
-    elevator_server_env.PrependUnique(LIBS = [
-            'connectivity_abstraction'
-            ])
+    elevator_server_env.PrependUnique(LIBS=['connectivity_abstraction'])
 
-elevator_server_env.PrependUnique(LIBS = [
-        'oc'
-        ])
+elevator_server_env.PrependUnique(LIBS=['oc'])
 
 if elevator_server_env.get('SECURED') == '1':
-    elevator_server_env.AppendUnique(CPPDEFINES = ['SECURED'])
-    elevator_server_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto', 'ocprovision'])
+    elevator_server_env.AppendUnique(CPPDEFINES=['SECURED'])
+    elevator_server_env.AppendUnique(LIBS=[
+        'mbedtls',
+        'mbedx509',
+        'mbedcrypto',
+        'ocprovision'
+    ])
 
 if target_os in ['msys_nt', 'windows']:
-    elevator_server_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+    elevator_server_env.AppendUnique(LINKFLAGS=['/subsystem:CONSOLE'])
 else:
-    elevator_server_env.PrependUnique(LIBS = ['oc_logger'])
+    elevator_server_env.PrependUnique(LIBS=['oc_logger'])
 
 if target_os not in ['windows', 'msys_nt']:
-    elevator_server_env.AppendUnique(LIBS = ['dl'])
+    elevator_server_env.AppendUnique(LIBS=['dl'])
 
 if 'g++' in elevator_server_env.get('CXX'):
-    elevator_server_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+    elevator_server_env.AppendUnique(CXXFLAGS=['-Wall', '-std=c++0x'])
 
 if target_os in ['linux']:
     if not elevator_server_env.get('RELEASE'):
-        elevator_server_env.PrependUnique(LIBS = ['gcov'])
-        elevator_server_env.AppendUnique(CXXFLAGS = ['--coverage'])
+        elevator_server_env.PrependUnique(LIBS=['gcov'])
+        elevator_server_env.AppendUnique(CXXFLAGS=['--coverage'])
 
 ######################################################################
 # Source files and Targets
@@ -91,16 +89,21 @@ if target_os in ['linux']:
 elevator_server_src = [
     'ElevatorServerSample.cpp',
     'elevatorserver.cpp'
-        ]
-
-elevator_server_src_dir = os.path.join(elevator_server_env.get('SRC_DIR'),
-                              'resource', 'IPCA', 'samples', 'ElevatorServer') + os.sep
-elevator_server_build_dir = os.path.join(elevator_server_env.get('BUILD_DIR'),
-                              'resource', 'IPCA', 'samples', 'ElevatorServer') + os.sep
-
-elevator_server_env.Install(elevator_server_build_dir,
-                            elevator_server_src_dir + 'ElevatorServerSecurityDB.json')
-elevator_server_env.Install(elevator_server_build_dir,
-                            elevator_server_src_dir + 'ElevatorServerSecurityDB.dat')
-
-elevator_app = elevator_server_env.Program('ElevatorServer', elevator_server_src)
+]
+
+elevator_server_src_dir = os.path.join(
+    elevator_server_env.get('SRC_DIR'), 'resource', 'IPCA', 'samples',
+    'ElevatorServer') + os.sep
+elevator_server_build_dir = os.path.join(
+    elevator_server_env.get('BUILD_DIR'), 'resource', 'IPCA', 'samples',
+    'ElevatorServer') + os.sep
+
+elevator_server_env.Install(
+    elevator_server_build_dir,
+    elevator_server_src_dir + 'ElevatorServerSecurityDB.json')
+elevator_server_env.Install(
+    elevator_server_build_dir,
+    elevator_server_src_dir + 'ElevatorServerSecurityDB.dat')
+
+elevator_app = elevator_server_env.Program('ElevatorServer',
+                                           elevator_server_src)
index b67da55..0964b90 100644 (file)
@@ -28,28 +28,26 @@ ipcaapp_env = ipca_env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
-ipcaapp_env.PrependUnique(CPPPATH = [
-        '../../inc',
-        ])
+ipcaapp_env.PrependUnique(CPPPATH=[
+    '../../inc',
+])
 
-ipcaapp_env.PrependUnique(LIBS = ['ipca'])
+ipcaapp_env.PrependUnique(LIBS=['ipca'])
 
 if target_os not in ['windows', 'msys_nt']:
-    ipcaapp_env.AppendUnique(LIBS = ['dl'])
+    ipcaapp_env.AppendUnique(LIBS=['dl'])
 
 if 'g++' in ipcaapp_env.get('CXX'):
-    ipcaapp_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+    ipcaapp_env.AppendUnique(CXXFLAGS=['-Wall', '-std=c++0x'])
 
 if target_os in ['linux']:
     if not ipcaapp_env.get('RELEASE'):
-        ipcaapp_env.PrependUnique(LIBS = ['gcov'])
-        ipcaapp_env.AppendUnique(CXXFLAGS = ['--coverage'])
+        ipcaapp_env.PrependUnique(LIBS=['gcov'])
+        ipcaapp_env.AppendUnique(CXXFLAGS=['--coverage'])
 
 ######################################################################
 # Source files and Targets
 ######################################################################
-ipcapp_src = [
-    'ipcaapp.cpp'
-        ]
+ipcapp_src = ['ipcaapp.cpp']
 
 ipcaapp = ipcaapp_env.Program('ipcaapp', ipcapp_src)
index 0881eb9..1dc2bad 100644 (file)
@@ -30,68 +30,63 @@ ipca_lib_env = ipca_env.Clone()
 ######################################################################
 with_upstream_libcoap = ipca_lib_env.get('WITH_UPSTREAM_LIBCOAP')
 if with_upstream_libcoap == '1':
-    ipca_lib_env.PrependUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])
+    ipca_lib_env.PrependUnique(CPPPATH=[
+        '#extlibs/libcoap/libcoap/include'
+    ])
 else:
-    ipca_lib_env.PrependUnique(CPPPATH = ['#resource/csdk/connectivity/lib/libcoap-4.1.1/include'])
-
-ipca_lib_env.PrependUnique(CPPPATH = [
-        '../inc',
-        'inc',
-        '#/resource/include',
-        '#/resource/oc_logger/include',
-        '#/resource/csdk/include',
-        '#/resource/csdk/stack/include',
-        '#/resource/csdk/security/include',
-        '#/resource/csdk/security/provisioning/include',
-        '#/resource/csdk/security/provisioning/include/internal',
-        '#/resource/csdk/connectivity/api',
-        '#/resource/csdk/connectivity/external/inc',
-        '#/resource/csdk/ocsocket/include',
-        '#/resource/csdk/logger/include',
-        '#/resource/c_common/ocrandom/include',
-        '#/extlibs/boost/boost',
-        '#/extlibs/cjson',
-        ])
+    ipca_lib_env.PrependUnique(CPPPATH=[
+        '#resource/csdk/connectivity/lib/libcoap-4.1.1/include'
+    ])
+
+ipca_lib_env.PrependUnique(CPPPATH=[
+    '../inc',
+    'inc',
+    '#/resource/include',
+    '#/resource/oc_logger/include',
+    '#/resource/csdk/include',
+    '#/resource/csdk/stack/include',
+    '#/resource/csdk/security/include',
+    '#/resource/csdk/security/provisioning/include',
+    '#/resource/csdk/security/provisioning/include/internal',
+    '#/resource/csdk/connectivity/api',
+    '#/resource/csdk/connectivity/external/inc',
+    '#/resource/csdk/ocsocket/include',
+    '#/resource/csdk/logger/include',
+    '#/resource/c_common/ocrandom/include',
+    '#/extlibs/boost/boost',
+    '#/extlibs/cjson',
+])
 
 if target_os in ['windows', 'msys_nt']:
-    ipca_lib_env.Replace(WINDOWS_INSERT_DEF = ['1'])
+    ipca_lib_env.Replace(WINDOWS_INSERT_DEF=['1'])
 else:
-    ipca_lib_env.PrependUnique(LIBS = [
-        'oc_logger'
-        ])
+    ipca_lib_env.PrependUnique(LIBS=['oc_logger'])
 
-ipca_lib_env.PrependUnique(LIBS = [
-        'coap',
-        'octbstack'
-        ])
+ipca_lib_env.PrependUnique(LIBS=['coap', 'octbstack'])
 
 if target_os not in ['windows', 'msys_nt']:
-    ipca_lib_env.PrependUnique(LIBS = [
-            'connectivity_abstraction'
-            ])
+    ipca_lib_env.PrependUnique(LIBS=['connectivity_abstraction'])
 
-ipca_lib_env.PrependUnique(LIBS = [
-        'oc'
-        ])
+ipca_lib_env.PrependUnique(LIBS=['oc'])
 
 if ipca_lib_env.get('SECURED') == '1':
-    ipca_lib_env.PrependUnique(LIBS = [
-            'mbedtls',
-            'mbedx509',
-            'ocprovision'
-            ])
+    ipca_lib_env.PrependUnique(LIBS=[
+        'mbedtls',
+        'mbedx509',
+        'ocprovision'
+    ])
 
 if target_os not in ['windows', 'msys_nt']:
-    ipca_lib_env.AppendUnique(LIBS = ['dl'])
+    ipca_lib_env.AppendUnique(LIBS=['dl'])
 
 if 'g++' in ipca_lib_env.get('CXX'):
-    ipca_lib_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+    ipca_lib_env.AppendUnique(CXXFLAGS=['-Wall', '-std=c++0x'])
 
 if target_os in ['linux']:
-    ipca_lib_env.AppendUnique(LIBS = ['pthread'])
+    ipca_lib_env.AppendUnique(LIBS=['pthread'])
     if not ipca_lib_env.get('RELEASE'):
-        ipca_lib_env.PrependUnique(LIBS = ['gcov'])
-        ipca_lib_env.AppendUnique(CXXFLAGS = ['--coverage'])
+        ipca_lib_env.PrependUnique(LIBS=['gcov'])
+        ipca_lib_env.AppendUnique(CXXFLAGS=['--coverage'])
 
 ######################################################################
 # Source files and Targets
@@ -104,7 +99,7 @@ ipca_lib_src = [
     'device.cpp',
     'ipcavariant.cpp',
     'common.cpp'
-        ]
+]
 
 if ipca_lib_env.get('SECURED') != '1':
     ipca_lib_src.append('pretendocprovision.cpp')
index 351cce6..28cc4f7 100644 (file)
@@ -20,6 +20,7 @@
 
 import os
 import os.path
+from tools.scons.RunTest import run_test
 
 # Set to 1 for the test elevator client and elevator server to communicate through IoTivity stack.
 use_iotivity = 0
@@ -28,64 +29,71 @@ Import('test_env')
 ipcatest_env = test_env.Clone()
 src_dir = ipcatest_env.get('SRC_DIR')
 target_os = ipcatest_env.get('TARGET_OS')
+with_cloud = ipcatest_env.get('WITH_CLOUD')
 
 ######################################################################
 # Build flags
 ######################################################################
-ipcatest_env.AppendUnique(CPPPATH = [
-        '#/resource/include',
-        '#/resource/oc_logger/include',
-        '#/resource/csdk/include',
-        '#/resource/csdk/stack/include',
-        '#/resource/csdk/security/include',
-        '#/resource/csdk/security/provisioning/include',
-        '#/resource/csdk/security/provisioning/include/internal',
-        '#/resource/csdk/stack/include/internal',
-        '#/resource/csdk/connectivity/api',
-        '#/resource/csdk/connectivity/external/inc',
-        '#/resource/csdk/ocsocket/include',
-        '#/resource/csdk/logger/include',
-        '#/resource/c_common/ocrandom/include',
-        '#/extlibs/boost/boost',
-        '#/extlibs/libcoap/libcoap/include',
-        '../inc',
-        '../src/inc'
-        ])
-
-ipcatest_env.PrependUnique(LIBS = [
-        'oc_logger_internal',
-        'octbstack',
-        'ipca_static'
-        ])
+ipcatest_env.AppendUnique(CPPPATH=[
+    '#/resource/include',
+    '#/resource/oc_logger/include',
+    '#/resource/csdk/include',
+    '#/resource/csdk/stack/include',
+    '#/resource/csdk/security/include',
+    '#/resource/csdk/security/provisioning/include',
+    '#/resource/csdk/security/provisioning/include/internal',
+    '#/resource/csdk/stack/include/internal',
+    '#/resource/csdk/connectivity/api',
+    '#/resource/csdk/connectivity/external/inc',
+    '#/resource/csdk/ocsocket/include',
+    '#/resource/csdk/logger/include',
+    '#/resource/c_common/ocrandom/include',
+    '#/extlibs/boost/boost',
+    '#/extlibs/libcoap/libcoap/include',
+    '../inc',
+    '../src/inc'
+])
+
+ipcatest_env.PrependUnique(LIBS=[
+    'oc_logger_internal',
+    'octbstack',
+    'ipca_static'
+])
 
 if use_iotivity == 1:
-    ipcatest_env.PrependUnique(LIBS = [
+    ipcatest_env.PrependUnique(LIBS=[
         'oc',
         'connectivity_abstraction',
         'coap',
-        ])
+    ])
 
     if ipcatest_env.get('SECURED') == '1':
-        ipcatest_env.PrependUnique(LIBS = [
+        ipcatest_env.PrependUnique(LIBS=[
             'mbedtls',
             'mbedx509',
             'mbedcrypto',
             'ocprovision'
-            ])
+        ])
 
 if target_os in ['msys_nt', 'windows']:
-    ipcatest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE'])
+    ipcatest_env.AppendUnique(LINKFLAGS=['/subsystem:CONSOLE'])
+
+if ipcatest_env.get('MULTIPLE_OWNER') == '1':
+    ipcatest_env.AppendUnique(CPPDEFINES=['MULTIPLE_OWNER'])
+
+if with_cloud:
+    ipcatest_env.AppendUnique(CPPDEFINES=['WITH_CLOUD'])
 
 ######################################################################
 # Source files and Targets
 ######################################################################
 
 unittests_src = [
-        'ipcaunittests.cpp',
-        'IPCAElevatorClient.cpp',
-        'testelevatorserver.cpp',
-        'testelevatorclient.cpp'
-    ]
+    'ipcaunittests.cpp',
+    'IPCAElevatorClient.cpp',
+    'testelevatorserver.cpp',
+    'testelevatorclient.cpp'
+]
 
 if use_iotivity == 0:
     unittests_src += [
@@ -95,27 +103,31 @@ if use_iotivity == 0:
         'mockOCPlatform_impl.cpp',
         'mockOCProvision.cpp',
         '#/resource/src/OCRepresentation.cpp'
-        ]
+    ]
 
 if target_os not in ['windows', 'msys_nt']:
-    ipcatest_env.AppendUnique(LIBS = ['dl'])
+    ipcatest_env.AppendUnique(LIBS=['dl'])
 
 if 'g++' in ipcatest_env.get('CXX'):
-    ipcatest_env.AppendUnique(LIBS = ['pthread'])
+    ipcatest_env.AppendUnique(LIBS=['pthread'])
 
 if target_os in ['linux']:
     if not ipcatest_env.get('RELEASE'):
-        ipcatest_env.PrependUnique(LIBS = ['gcov'])
-        ipcatest_env.AppendUnique(CXXFLAGS = ['--coverage'])
+        ipcatest_env.PrependUnique(LIBS=['gcov'])
+        ipcatest_env.AppendUnique(CXXFLAGS=['--coverage'])
 
-ipcatest_src_dir = os.path.join(src_dir, 'resource', 'IPCA', 'unittests') + os.sep
+ipcatest_src_dir = os.path.join(src_dir, 'resource', 'IPCA',
+                                'unittests') + os.sep
 ipcatest_build_dir = os.path.join(
-                         ipcatest_env.get('BUILD_DIR'), 'resource', 'IPCA', 'unittests') + os.sep
+    ipcatest_env.get('BUILD_DIR'), 'resource', 'IPCA', 'unittests') + os.sep
 
-ipcatest_env.Alias("install", ipcatest_env.Install( ipcatest_build_dir,
-    ipcatest_src_dir + 'IPCAUnitTest.json'))
-ipcatest_env.Alias("install", ipcatest_env.Install( ipcatest_build_dir,
-    ipcatest_src_dir + 'IPCAUnitTest.dat'))
+ipcatest_env.Alias(
+    "install",
+    ipcatest_env.Install(ipcatest_build_dir,
+                         ipcatest_src_dir + 'IPCAUnitTest.json'))
+ipcatest_env.Alias("install",
+                   ipcatest_env.Install(ipcatest_build_dir,
+                                        ipcatest_src_dir + 'IPCAUnitTest.dat'))
 
 ipcatests = ipcatest_env.Program('ipcatests', unittests_src)
 
@@ -125,9 +137,5 @@ if target_os in ['windows']:
 
 if ipcatest_env.get('TEST') == '1':
     if target_os in ['windows']:
-        from tools.scons.RunTest import *
-        run_test(ipcatest_env,
-                 'resource_ipca_unittests.memcheck',
-                 'resource/ipca/unittests/ipcatests',
-                 ipcatests)
-
+        run_test(ipcatest_env, 'resource_ipca_unittests.memcheck',
+                 'resource/ipca/unittests/ipcatests', ipcatests)
index 3ec5999..90b163f 100644 (file)
@@ -30,7 +30,9 @@ target_os = env.get('TARGET_OS')
 # Build C Common dependencies
 SConscript('c_common/SConscript')
 
-if target_os not in ['arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows']:
+if target_os not in [
+        'arduino', 'darwin', 'ios', 'android', 'msys_nt', 'windows'
+]:
     env.AppendUnique(LIBS=['rt'])
 
 # Download (if not already present) & build libcoap
@@ -50,13 +52,14 @@ if target_os in ['windows', 'linux']:
     # Build IoTivity Procedural Client API
     SConscript('IPCA/SConscript')
 
-if target_os not in ['arduino','darwin','ios','android']:
+if target_os not in ['arduino', 'darwin', 'ios', 'android']:
     # Build examples
     SConscript('examples/SConscript')
 
 if target_os in ['linux', 'windows', 'darwin', 'msys_nt']:
     if target_os == 'darwin':
-        env.Command('#/out/darwin/iotivity-csdk.framework', None, '#/tools/darwin/mkfwk_osx.sh')
+        env.Command('#/out/darwin/iotivity-csdk.framework', None,
+                    '#/tools/darwin/mkfwk_osx.sh')
 
     # Build C/C++ unit tests
     SConscript('unit_tests.scons')
index d7bce9f..40c46c6 100644 (file)
@@ -7,13 +7,15 @@ compatibilitylib_env = env.Clone()
 ######################################################################
 # Build flags
 ######################################################################
-compatibilitylib_env.AppendUnique(CPPPATH = ['../include/'])
+compatibilitylib_env.AppendUnique(CPPPATH=[
+    '../include/'
+])
 
 target_os = env.get('TARGET_OS')
 
 if target_os == 'android':
-       compatibilitylib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
-       compatibilitylib_env.AppendUnique(LIBS = ['gnustl_shared'])
+    compatibilitylib_env.AppendUnique(CXXFLAGS=['-frtti', '-fexceptions'])
+    compatibilitylib_env.AppendUnique(LIBS=['gnustl_shared'])
 
 ######################################################################
 # Source files and Targets
@@ -21,5 +23,7 @@ if target_os == 'android':
 compatibilitylib_src = ['OCAndroid.cpp']
 
 if target_os == 'android':
-       static_compatibilitylib = compatibilitylib_env.StaticLibrary('compatibility', compatibilitylib_src)
-       compatibilitylib_env.InstallTarget(static_compatibilitylib, 'libcompatibility')
+    static_compatibilitylib = compatibilitylib_env.StaticLibrary(
+        'compatibility', compatibilitylib_src)
+    compatibilitylib_env.InstallTarget(
+        static_compatibilitylib, 'libcompatibility')
index e7e8581..2e6f10a 100644 (file)
@@ -150,6 +150,7 @@ env.AppendUnique(CPPPATH=[
     os.path.join(Dir('.').abspath, 'ocatomic', 'include'),
     os.path.join(Dir('.').abspath, 'ocrandom', 'include'),
     os.path.join(Dir('.').abspath, 'octhread', 'include'),
+    os.path.join(Dir('.').abspath, 'ocevent', 'include'),
     os.path.join(Dir('.').abspath, 'oic_platform', 'include'),
     os.path.join(Dir('.').abspath, 'octimer', 'include'),
     '#/extlibs/mbedtls/mbedtls/include'
@@ -197,8 +198,10 @@ else:
     common_src.append('ocatomic/src/others/ocatomic.c')
 
 if target_os in ['windows']:
+    common_src.append('ocevent/src/windows/ocevent.c')
     common_src.append('oic_platform/src/windows/oic_winplatform.cpp')
 else:
+    common_src.append('ocevent/src/others/ocevent.c')
     common_src.append('oic_platform/src/others/oic_otherplatforms.c')
 
 # C++ Arduino's <Timer.h> is included so use C++ compiler/flags
@@ -216,6 +219,9 @@ common_env.AppendUnique(CPPPATH=['#resource/csdk/logger/include'])
 commonlib = common_env.StaticLibrary('c_common', common_src)
 common_env.InstallTarget(commonlib, 'c_common')
 common_env.UserInstallTargetLib(commonlib, 'c_common')
+
+common_env.UserInstallTargetHeader(
+    'iotivity_commontypes.h', 'c_common', 'iotivity_commontypes.h')
 common_env.UserInstallTargetHeader(
     'iotivity_debug.h', 'c_common', 'iotivity_debug.h')
 common_env.UserInstallTargetHeader(
diff --git a/resource/c_common/iotivity_commontypes.h b/resource/c_common/iotivity_commontypes.h
new file mode 100644 (file)
index 0000000..02d84c0
--- /dev/null
@@ -0,0 +1,49 @@
+/* ****************************************************************\r
+ *\r
+ * Copyright 2017 Microsoft\r
+ *\r
+ *\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
+/**\r
+ * @file\r
+ *\r
+ * This file provides generic types used in the c_common layer.\r
+ */\r
+\r
+#ifndef IOTIVITY_COMMON_TYPES_H_\r
+#define IOTIVITY_COMMON_TYPES_H_\r
+\r
+#ifdef __cplusplus\r
+extern "C"\r
+{\r
+#endif /* __cplusplus */\r
+\r
+/**\r
+ * Enums for oc_cond_wait_for and oc_event_wait_for return values.\r
+ */\r
+typedef enum\r
+{\r
+   OC_WAIT_SUCCESS = 0,    /**< Condition or event is signaled. */\r
+   OC_WAIT_INVAL = -1,     /**< Condition or event is invalid. */\r
+   OC_WAIT_TIMEDOUT = -2   /**< Condition or event is timed out. */\r
+} OCWaitResult_t;\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* IOTIVITY_COMMON_TYPES_H_ */
\ No newline at end of file
index 48ea2ee..8947b4d 100644 (file)
@@ -20,6 +20,7 @@
 #define OC_ATOMIC_H\r
 \r
 #include <stdint.h>\r
+#include <stdbool.h>\r
 \r
 #ifdef __cplusplus\r
 extern "C"\r
@@ -38,10 +39,39 @@ int32_t oc_atomic_increment(volatile int32_t *addend);
  * Decrements (decreases by one) the value of the specified int32_t variable atomically.\r
  *\r
  * @param[in] addend  Pointer to the variable to be decremented.\r
- * @return int32_t  The resulting decremented value.\r
+ * @return int32_t    The resulting decremented value.\r
  */\r
 int32_t oc_atomic_decrement(volatile int32_t *addend);\r
 \r
+/**\r
+ * Increments (passed value) the value of the specified int32_t variable atomically.\r
+ *\r
+ * @param[in] value   The value to increment.\r
+ * @param[in] addend  Pointer to the target variable.\r
+ * @return int32_t    The resulting added value.\r
+ */\r
+int32_t oc_atomic_add(volatile int32_t *addend, int32_t value);\r
+\r
+/**\r
+ * Compare and swap atomically, if the current value is oldValue,\r
+ * then write newValue into *destination\r
+ *\r
+ * @param[in] destination    Pointer to the target variable.\r
+ * @param[in] oldValue       The value to compare against the current value(value in *destination).\r
+ * @param[in] newValue       The new value to write into *destination.\r
+ * @return bool              Returns true if the new value was successfully written.\r
+ */\r
+bool oc_atomic_cmpxchg(volatile int32_t *destination, int32_t oldValue, int32_t newValue);\r
+\r
+/**\r
+ * Or operation with the value of the specified int32_t variable atomically.\r
+ *\r
+ * @param[in] destination    Pointer to the target variable.\r
+ * @param[in] value          The value for "or" operation.\r
+ * @return int32_t           The resulting after "or" operation value.\r
+ */\r
+int32_t oc_atomic_or(volatile int32_t *destination, int32_t value);\r
+\r
 #ifdef __cplusplus\r
 } /* extern "C" */\r
 #endif /* __cplusplus */\r
index 5c5b6db..37b9a28 100644 (file)
@@ -36,3 +36,25 @@ int32_t oc_atomic_decrement(volatile int32_t *addend)
     (*addend)--;\r
     return *addend;\r
 }\r
+\r
+int32_t oc_atomic_add(volatile int32_t *addend, int32_t value)\r
+{\r
+    (*addend) += value;\r
+    return *addend;\r
+}\r
+\r
+bool oc_atomic_cmpxchg(volatile int32_t *destination, int32_t oldValue, int32_t newValue)\r
+{\r
+    if ((*destination) == oldValue)\r
+    {\r
+        *destination = newValue;\r
+        return true;\r
+    }\r
+    return false;\r
+}\r
+\r
+int32_t oc_atomic_or(volatile int32_t *destination, int32_t value)\r
+{\r
+    (*destination) |= value;\r
+    return *destination;\r
+}
\ No newline at end of file
index 8367cf0..9f2efb7 100644 (file)
@@ -33,3 +33,18 @@ int32_t oc_atomic_decrement(volatile int32_t *addend)
 {\r
     return __sync_sub_and_fetch(addend, 1);\r
 }\r
+\r
+int32_t oc_atomic_add(volatile int32_t *addend, int32_t value)\r
+{\r
+    return __sync_add_and_fetch(addend, value);\r
+}\r
+\r
+bool oc_atomic_cmpxchg(volatile int32_t *destination, int32_t oldValue, int32_t newValue)\r
+{\r
+    return __sync_bool_compare_and_swap(destination, oldValue, newValue);\r
+}\r
+\r
+int32_t oc_atomic_or(volatile int32_t *destination, int32_t value)\r
+{\r
+    return  __sync_or_and_fetch(destination, value);\r
+}
\ No newline at end of file
index 3dea8ff..289f1b3 100644 (file)
@@ -34,3 +34,22 @@ int32_t oc_atomic_decrement(volatile int32_t *addend)
 {\r
     return InterlockedDecrement((volatile long*)addend);\r
 }\r
+\r
+int32_t oc_atomic_add(volatile int32_t *addend, int32_t value)\r
+{\r
+    return InterlockedAdd((volatile long*)addend, value);\r
+}\r
+\r
+bool oc_atomic_cmpxchg(volatile int32_t *destination, int32_t oldValue, int32_t newValue)\r
+{\r
+    if (InterlockedCompareExchange((volatile long*)destination, newValue, oldValue) == oldValue)\r
+    {\r
+        return true;\r
+    }\r
+    return false;\r
+}\r
+\r
+int32_t oc_atomic_or(volatile int32_t *destination, int32_t value)\r
+{\r
+    return InterlockedOr((volatile long*)destination, value);\r
+}
\ No newline at end of file
diff --git a/resource/c_common/ocevent/include/ocevent.h b/resource/c_common/ocevent/include/ocevent.h
new file mode 100644 (file)
index 0000000..a13f623
--- /dev/null
@@ -0,0 +1,81 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2017 Microsoft\r
+ *\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
+/**\r
+ * @file\r
+ *\r
+ * This file defines the event object.\r
+ */\r
+\r
+#ifndef OC_EVENT_H_\r
+#define OC_EVENT_H_\r
+\r
+#include "iotivity_commontypes.h"\r
+#include <stdint.h>\r
+\r
+#ifdef __cplusplus\r
+extern "C"\r
+{\r
+#endif /* __cplusplus */\r
+\r
+typedef struct oc_event_t *oc_event;\r
+\r
+/**\r
+ * Creates a new event.\r
+ *\r
+ * @return  Reference to newly created event, NULL on allocation failure.\r
+ */\r
+oc_event oc_event_new();\r
+\r
+/**\r
+ * Frees the oc_event.\r
+ *\r
+ * @param[in]  event  Optional event to be freed.\r
+ */\r
+void oc_event_free(oc_event event);\r
+\r
+/**\r
+ * Waits infinitely for the event to be signaled.\r
+ *\r
+ * @param[in]  event  Event to wait on.\r
+ */\r
+void oc_event_wait(oc_event event);\r
+\r
+/**\r
+ * Waits for the event to be signaled or timed out.\r
+ *\r
+ * @param[in]  event         Event to wait on.\r
+ * @param[in]  milliseconds  Timeout in milliseconds.\r
+ * @return  OC_WAIT_SUCCESS  Event was signaled before timeout expired.\r
+ *          OC_WAIT_TIMEDOUT Timeout interval elapsed.\r
+ */\r
+OCWaitResult_t oc_event_wait_for(oc_event event, uint32_t milliseconds);\r
+\r
+/**\r
+ * Signals the event.\r
+ *\r
+ * @param[in]  event  Event to signal.\r
+ */\r
+void oc_event_signal(oc_event event);\r
+\r
+#ifdef __cplusplus\r
+} /* extern "C" */\r
+#endif /* __cplusplus */\r
+\r
+#endif /* OC_EVENT_H_ */\r
diff --git a/resource/c_common/ocevent/src/others/ocevent.c b/resource/c_common/ocevent/src/others/ocevent.c
new file mode 100644 (file)
index 0000000..c3bc1ef
--- /dev/null
@@ -0,0 +1,159 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2017 Microsoft\r
+ *\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
+/**\r
+ * @file\r
+ * This file implements Event object for allowing threads to wait on.\r
+ */\r
+\r
+#include "ocevent.h"\r
+#include "oic_malloc.h"\r
+#include "oic_time.h"\r
+#include "octhread.h"\r
+#include "logger.h"\r
+#include "iotivity_debug.h"\r
+\r
+#include <assert.h>\r
+#include <stdbool.h>\r
+#include <stdlib.h>\r
+\r
+/**\r
+ * TAG\r
+ * Logging tag for module name\r
+ */\r
+#define TAG "OIC_EVENT"\r
+\r
+typedef struct oc_event_t\r
+{\r
+    /* Mutex for protecting the members. */\r
+    oc_mutex mutex;\r
+    /* The conditional variable to wait on. */\r
+    oc_cond cond;\r
+    /* Whether the event is signaled. */\r
+    bool signaled;\r
+} oc_event_t;\r
+\r
+oc_event oc_event_new()\r
+{\r
+    oc_event event = (oc_event)OICCalloc(1, sizeof(oc_event_t));\r
+    if (!event)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to allocate oc_event");\r
+        return NULL;\r
+    }\r
+\r
+    event->mutex = oc_mutex_new();\r
+    event->cond = oc_cond_new();\r
+    event->signaled = false;\r
+\r
+    if (!event->mutex || !event->cond)\r
+    {\r
+        oc_event_free(event);\r
+        return NULL;\r
+    }\r
+\r
+    return event;\r
+}\r
+\r
+void oc_event_free(oc_event event)\r
+{\r
+    if (event)\r
+    {\r
+        oc_mutex_free(event->mutex);\r
+        oc_cond_free(event->cond);\r
+        OICFree(event);\r
+    }\r
+}\r
+\r
+void oc_event_wait(oc_event event)\r
+{\r
+    OC_VERIFY(OC_WAIT_SUCCESS == oc_event_wait_for(event, UINT32_MAX));\r
+}\r
+\r
+OCWaitResult_t oc_event_wait_for(oc_event event, uint32_t milliseconds)\r
+{\r
+    bool timedOut = false;\r
+    oc_mutex_assert_owner(event->mutex, false);\r
+    oc_mutex_lock(event->mutex);\r
+\r
+    if (!event->signaled)\r
+    {\r
+        if (0 != milliseconds)\r
+        {\r
+            const uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);\r
+            uint64_t remaining = milliseconds;\r
+            // This while loop is to filter spurious wakeups caused by conditional variable.\r
+            while (!event->signaled)\r
+            {\r
+                oc_mutex_assert_owner(event->mutex, true);\r
+                OCWaitResult_t waitResult = oc_cond_wait_for(event->cond, event->mutex,\r
+                                                             (remaining * US_PER_MS));\r
+                if (OC_WAIT_TIMEDOUT == waitResult)\r
+                {\r
+                    timedOut = true;\r
+                    break;\r
+                }\r
+                assert(OC_WAIT_SUCCESS == waitResult);\r
+\r
+                // Not timed out, see if the event is in signaled state and reset it.\r
+                if (event->signaled)\r
+                {\r
+                    timedOut = false;\r
+                    break;\r
+                }\r
+\r
+                // Not timed out and not signaled => spurious wakeup, see if we ran out of time.\r
+                const uint64_t elapsed = (OICGetCurrentTime(TIME_IN_MS) - startTime);\r
+                if (elapsed >= (uint64_t)milliseconds)\r
+                {\r
+                    timedOut = true;\r
+                    break;\r
+                }\r
+\r
+                // Encountered spurious wakeup and still has time to wait, recalculate the\r
+                // remaining time and wait again.\r
+                // Spurious wakeup: depending on the platform, waiting on a Condition Variable can\r
+                // occasionally (though rarely) return from the wait state even when the condition\r
+                // isn't set, so we always need to revalidate the state in a loop here.\r
+                remaining = (uint64_t)milliseconds - elapsed;\r
+            }\r
+        }\r
+        else\r
+        {\r
+            // Zero timeout provided and the event has not been signaled.\r
+            timedOut = true;\r
+        }\r
+    }\r
+    oc_mutex_assert_owner(event->mutex, true);\r
+    event->signaled = false;\r
+    oc_mutex_unlock(event->mutex);\r
+    return timedOut ? OC_WAIT_TIMEDOUT : OC_WAIT_SUCCESS;\r
+}\r
+\r
+void oc_event_signal(oc_event event)\r
+{\r
+    oc_mutex_assert_owner(event->mutex, false);\r
+    oc_mutex_lock(event->mutex);\r
+    if (!event->signaled)\r
+    {\r
+        event->signaled = true;\r
+        oc_cond_signal(event->cond);\r
+    }\r
+    oc_mutex_unlock(event->mutex);\r
+}\r
diff --git a/resource/c_common/ocevent/src/windows/ocevent.c b/resource/c_common/ocevent/src/windows/ocevent.c
new file mode 100644 (file)
index 0000000..084e792
--- /dev/null
@@ -0,0 +1,98 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2017 Microsoft\r
+ *\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
+/**\r
+ * @file\r
+ * This file implements Event object for allowing threads to wait on.\r
+ */\r
+\r
+#include "ocevent.h"\r
+#include "oic_malloc.h"\r
+#include "logger.h"\r
+#include "iotivity_debug.h"\r
+\r
+#include <assert.h>\r
+#include <stdbool.h>\r
+#include <stdlib.h>\r
+#include <windows.h>\r
+\r
+/**\r
+ * TAG\r
+ * Logging tag for module name\r
+ */\r
+#define TAG "OIC_EVENT"\r
+\r
+typedef struct oc_event_t\r
+{\r
+    /* The event handle */\r
+    HANDLE event;\r
+} oc_event_t;\r
+\r
+oc_event oc_event_new()\r
+{\r
+    oc_event event = (oc_event)OICCalloc(1, sizeof(oc_event_t));\r
+    if (!event)\r
+    {\r
+        OIC_LOG(ERROR, TAG, "Failed to allocate oc_event");\r
+        return NULL;\r
+    }\r
+\r
+    /* Create an auto-reset event */\r
+    event->event = CreateEvent(NULL, FALSE, FALSE, NULL);\r
+    if (!event->event)\r
+    {\r
+        oc_event_free(event);\r
+        return NULL;\r
+    }\r
+\r
+    return event;\r
+}\r
+\r
+void oc_event_free(oc_event event)\r
+{\r
+    if (event && event->event)\r
+    {\r
+        OC_VERIFY(0 != CloseHandle(event->event));\r
+    }\r
+    OICFree(event);\r
+}\r
+\r
+void oc_event_wait(oc_event event)\r
+{\r
+    OC_VERIFY(OC_WAIT_SUCCESS == WaitForSingleObject(event->event, INFINITE));\r
+}\r
+\r
+OCWaitResult_t oc_event_wait_for(oc_event event, uint32_t milliseconds)\r
+{\r
+    DWORD waitResult = WaitForSingleObject(event->event, milliseconds);\r
+    switch (waitResult)\r
+    {\r
+    case WAIT_OBJECT_0:\r
+        return OC_WAIT_SUCCESS;\r
+    case WAIT_TIMEOUT:\r
+        return OC_WAIT_TIMEDOUT;\r
+    default:\r
+        return OC_WAIT_INVAL;\r
+    }\r
+}\r
+\r
+void oc_event_signal(oc_event event)\r
+{\r
+    OC_VERIFY(0 != SetEvent(event->event));\r
+}
\ No newline at end of file
diff --git a/resource/c_common/ocevent/test/SConscript b/resource/c_common/ocevent/test/SConscript
new file mode 100644 (file)
index 0000000..8424a56
--- /dev/null
@@ -0,0 +1,53 @@
+#******************************************************************
+#
+# Copyright 2017  Microsoft
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+import os
+import os.path
+from tools.scons.RunTest import *
+
+Import('test_env')
+
+eventtests_env = test_env.Clone()
+target_os = eventtests_env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+eventtests_env.PrependUnique(CPPPATH=['#resource/c_common/ocevent/include'])
+
+eventtests_env.AppendUnique(LIBPATH=[eventtests_env.get('BUILD_DIR')])
+eventtests_env.Append(LIBS=['logger'])
+
+if eventtests_env.get('LOGGING'):
+    eventtests_env.AppendUnique(CPPDEFINES=['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+eventtests = eventtests_env.Program('eventtests', ['eventtest.cpp'])
+
+Alias("test", [eventtests])
+
+eventtests_env.AppendTarget('test')
+if eventtests_env.get('TEST') == '1':
+    if target_os in ['linux', 'windows']:
+        run_test(eventtests_env,
+                 'resource_c_common_event_test.memcheck',
+                 'resource/c_common/ocevent/test/eventtests')
diff --git a/resource/c_common/ocevent/test/eventtest.cpp b/resource/c_common/ocevent/test/eventtest.cpp
new file mode 100644 (file)
index 0000000..04d9381
--- /dev/null
@@ -0,0 +1,97 @@
+/* *****************************************************************\r
+ *\r
+ * Copyright 2017 Microsoft\r
+ *\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
+/**\r
+ * @file\r
+ *\r
+ * This file implement tests for the Event object.\r
+ */\r
+\r
+#include "ocevent.h"\r
+#include "gtest/gtest.h"\r
+#include <limits.h>\r
+#include <thread>\r
+\r
+class EventTester : public testing::Test\r
+{\r
+  protected:\r
+    virtual void SetUp()\r
+    {\r
+        m_event = oc_event_new();\r
+        ASSERT_TRUE(nullptr != m_event);\r
+    }\r
+    virtual void TearDown()\r
+    {\r
+        oc_event_free(m_event);\r
+    }\r
+    void TestSignalBeforeWait(uint32_t timeout);\r
+    oc_event m_event;\r
+};\r
+\r
+void EventTester::TestSignalBeforeWait(uint32_t timeout)\r
+{\r
+    std::thread thread([this]()\r
+    {\r
+        oc_event_signal(m_event);\r
+    });\r
+\r
+    // Make sure the signal occurs before the wait.\r
+    thread.join();\r
+\r
+    if (UINT_MAX == timeout)\r
+    {\r
+        oc_event_wait(m_event);\r
+    }\r
+    else\r
+    {\r
+        EXPECT_EQ(OC_WAIT_SUCCESS, oc_event_wait_for(m_event, timeout));\r
+    }\r
+}\r
+\r
+TEST_F(EventTester, InfiniteTimeout_SignaledAfterWait)\r
+{\r
+    std::thread thread([this]()\r
+    {\r
+        // This sleep allows the main thread to enter the wait state before the signal.\r
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));\r
+        oc_event_signal(m_event);\r
+    });\r
+    oc_event_wait(m_event);\r
+    thread.join();\r
+}\r
+\r
+TEST_F(EventTester, InfiniteTimeout_SignaledBeforeWait)\r
+{\r
+    TestSignalBeforeWait(UINT_MAX);\r
+}\r
+\r
+TEST_F(EventTester, ZeroTimeout_NotSignaled)\r
+{\r
+    EXPECT_EQ(OC_WAIT_TIMEDOUT, oc_event_wait_for(m_event, 0));\r
+}\r
+\r
+TEST_F(EventTester, ZeroTimeout_Signaled)\r
+{\r
+    TestSignalBeforeWait(0);\r
+}\r
+\r
+TEST_F(EventTester, TimedOut)\r
+{\r
+    EXPECT_EQ(OC_WAIT_TIMEDOUT, oc_event_wait_for(m_event, 10));\r
+}\r
index 142371b..feb51ac 100644 (file)
@@ -27,6 +27,7 @@
 #ifndef OC_THREAD_H_
 #define OC_THREAD_H_
 
+#include "iotivity_commontypes.h"
 #include <stdbool.h>
 #include <stdlib.h>
 #include <stdint.h>
@@ -46,16 +47,6 @@ typedef struct oc_mutex_internal *oc_mutex;
 typedef struct oc_cond_internal *oc_cond;
 typedef struct oc_thread_internal *oc_thread;
 
-/**
- * Enums for oc_cond_wait_for return values.
- */
-typedef enum
-{
-   OC_WAIT_SUCCESS = 0,    /**< Condition Signal. */
-   OC_WAIT_INVAL = -1,     /**< Invalid Condition. */
-   OC_WAIT_TIMEDOUT = -2   /**< Condition Timed Out. */
-} OCWaitResult_t;
-
 typedef enum
 {
     OC_THREAD_SUCCESS = 0,
index c87ee80..f7382c4 100644 (file)
@@ -286,10 +286,6 @@ bool oc_mutex_free(oc_mutex mutex)
             OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
         }
     }
-    else
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
-    }
 
     return bRet;
 }
@@ -306,23 +302,23 @@ void oc_mutex_lock(oc_mutex mutex)
             exit(ret);
         }
 
-#ifndef NDEBUG\r
-        /**\r
-         * Updating the recursionCount and owner fields must be performed\r
-         * while owning the lock, to solve race conditions with other\r
-         * threads using the same lock.\r
-         */\r
-        if (mutexInfo->recursionCount != 0)\r
-        {\r
-            oc_mutex_assert_owner(mutex, true);\r
-        }\r
-        else\r
-        {\r
-            mutexInfo->owner = oc_get_current_thread_id();\r
-        }\r
-\r
-        mutexInfo->recursionCount++;\r
-#endif\r
+#ifndef NDEBUG
+        /**
+         * Updating the recursionCount and owner fields must be performed
+         * while owning the lock, to solve race conditions with other
+         * threads using the same lock.
+         */
+        if (mutexInfo->recursionCount != 0)
+        {
+            oc_mutex_assert_owner(mutex, true);
+        }
+        else
+        {
+            mutexInfo->owner = oc_get_current_thread_id();
+        }
+
+        mutexInfo->recursionCount++;
+#endif
     }
     else
     {
@@ -335,21 +331,21 @@ void oc_mutex_unlock(oc_mutex mutex)
     oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
     if (mutexInfo)
     {
-#ifndef NDEBUG\r
-        oc_mutex_assert_owner(mutex, true);\r
-\r
-        /**\r
-         * Updating the recursionCount and owner fields must be performed\r
-         * while owning the lock, to solve race conditions with other\r
-         * threads using the same lock.\r
-         */\r
-        mutexInfo->recursionCount--;\r
-\r
-        if (mutexInfo->recursionCount == 0)\r
-        {\r
-            mutexInfo->owner = OC_INVALID_THREAD_ID;\r
-        }\r
-#endif\r
+#ifndef NDEBUG
+        oc_mutex_assert_owner(mutex, true);
+
+        /**
+         * Updating the recursionCount and owner fields must be performed
+         * while owning the lock, to solve race conditions with other
+         * threads using the same lock.
+         */
+        mutexInfo->recursionCount--;
+
+        if (mutexInfo->recursionCount == 0)
+        {
+            mutexInfo->owner = OC_INVALID_THREAD_ID;
+        }
+#endif
 
         int ret = pthread_mutex_unlock(&mutexInfo->mutex);
         if(ret != 0)
@@ -573,23 +569,23 @@ OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseco
              abstime = oc_get_current_time();
             oc_add_microseconds_to_timespec(&abstime, microseconds);
 
-#ifndef NDEBUG\r
-            // Recursively-acquired locks are not supported for use with condition variables.\r
-            oc_mutex_assert_owner(mutex, true);\r
-            assert(mutexInfo->recursionCount == 1);\r
-            mutexInfo->recursionCount = 0;\r
-            mutexInfo->owner = OC_INVALID_THREAD_ID;\r
-#endif\r
+#ifndef NDEBUG
+            // Recursively-acquired locks are not supported for use with condition variables.
+            oc_mutex_assert_owner(mutex, true);
+            assert(mutexInfo->recursionCount == 1);
+            mutexInfo->recursionCount = 0;
+            mutexInfo->owner = OC_INVALID_THREAD_ID;
+#endif
 
             // Wait for the given time
             ret = pthread_cond_timedwait(&(eventInfo->cond), &(mutexInfo->mutex), &abstime);
 
-#ifndef NDEBUG\r
-            oc_mutex_assert_owner(mutex, false);\r
-            assert(mutexInfo->recursionCount == 0);\r
-            mutexInfo->recursionCount = 1;\r
-            mutexInfo->owner = oc_get_current_thread_id();\r
-#endif\r
+#ifndef NDEBUG
+            oc_mutex_assert_owner(mutex, false);
+            assert(mutexInfo->recursionCount == 0);
+            mutexInfo->recursionCount = 1;
+            mutexInfo->owner = oc_get_current_thread_id();
+#endif
         }
 
         switch (ret)
@@ -613,24 +609,29 @@ OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseco
     }
     else
     {
-#ifndef NDEBUG\r
-        // Recursively-acquired locks are not supported for use with condition variables.\r
-        oc_mutex_assert_owner(mutex, true);\r
-        assert(mutexInfo->recursionCount == 1);\r
-        mutexInfo->recursionCount = 0;\r
-        mutexInfo->owner = OC_INVALID_THREAD_ID;\r
-#endif\r
+#ifndef NDEBUG
+        // Recursively-acquired locks are not supported for use with condition variables.
+        oc_mutex_assert_owner(mutex, true);
+        assert(mutexInfo->recursionCount == 1);
+        mutexInfo->recursionCount = 0;
+        mutexInfo->owner = OC_INVALID_THREAD_ID;
+#endif
 
         // Wait forever
+#ifndef NDEBUG
+        // The conditional variable wait API used will atomically release the mutex, but the
+        // best we can do here is to just clear the owner info before the API is called.
+        mutexInfo->owner = OC_INVALID_THREAD_ID;
+#endif
         int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
         retVal = (ret == 0) ? OC_WAIT_SUCCESS : OC_WAIT_INVAL;
 
-#ifndef NDEBUG\r
-        oc_mutex_assert_owner(mutex, false);\r
-        assert(mutexInfo->recursionCount == 0);\r
-        mutexInfo->recursionCount = 1;\r
-        mutexInfo->owner = oc_get_current_thread_id();\r
-#endif\r
+#ifndef NDEBUG
+        oc_mutex_assert_owner(mutex, false);
+        assert(mutexInfo->recursionCount == 0);
+        mutexInfo->recursionCount = 1;
+        mutexInfo->owner = oc_get_current_thread_id();
+#endif
     }
     return retVal;
 }
index cef1b06..2b450c5 100644 (file)
@@ -165,11 +165,7 @@ bool oc_mutex_free(oc_mutex mutex)
     {
         DeleteCriticalSection(&mutexInfo->mutex);
         OICFree(mutexInfo);
-        bRet=true;
-    }
-    else
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
+        bRet = true;
     }
 
     return bRet;
@@ -182,23 +178,23 @@ void oc_mutex_lock(oc_mutex mutex)
     {
         EnterCriticalSection(&mutexInfo->mutex);
 
-#ifndef NDEBUG\r
-        /**\r
-         * Updating the recursionCount and owner fields must be performed\r
-         * while owning the lock, to solve race conditions with other\r
-         * threads using the same lock.\r
-         */\r
-        if (mutexInfo->recursionCount != 0)\r
-        {\r
-            oc_mutex_assert_owner(mutex, true);\r
-        }\r
-        else\r
-        {\r
-            mutexInfo->owner = oc_get_current_thread_id();\r
-        }\r
-\r
-        mutexInfo->recursionCount++;\r
-#endif\r
+#ifndef NDEBUG
+        /**
+         * Updating the recursionCount and owner fields must be performed
+         * while owning the lock, to solve race conditions with other
+         * threads using the same lock.
+         */
+        if (mutexInfo->recursionCount != 0)
+        {
+            oc_mutex_assert_owner(mutex, true);
+        }
+        else
+        {
+            mutexInfo->owner = oc_get_current_thread_id();
+        }
+
+        mutexInfo->recursionCount++;
+#endif
     }
     else
     {
@@ -212,21 +208,21 @@ void oc_mutex_unlock(oc_mutex mutex)
 
     if (mutexInfo)
     {
-#ifndef NDEBUG\r
-        oc_mutex_assert_owner(mutex, true);\r
-\r
-        /**\r
-         * Updating the recursionCount and owner fields must be performed\r
-         * while owning the lock, to solve race conditions with other\r
-         * threads using the same lock.\r
-         */\r
-        mutexInfo->recursionCount--;\r
-\r
-        if (mutexInfo->recursionCount == 0)\r
-        {\r
-            mutexInfo->owner = OC_INVALID_THREAD_ID;\r
-        }\r
-#endif\r
+#ifndef NDEBUG
+        oc_mutex_assert_owner(mutex, true);
+
+        /**
+         * Updating the recursionCount and owner fields must be performed
+         * while owning the lock, to solve race conditions with other
+         * threads using the same lock.
+         */
+        mutexInfo->recursionCount--;
+
+        if (mutexInfo->recursionCount == 0)
+        {
+            mutexInfo->owner = OC_INVALID_THREAD_ID;
+        }
+#endif
 
         LeaveCriticalSection(&mutexInfo->mutex);
     }
@@ -348,13 +344,13 @@ OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseco
         milli = INFINITE;
     }
 
-#ifndef NDEBUG\r
-    // Recursively-acquired locks are not supported for use with condition variables.\r
-    oc_mutex_assert_owner(mutex, true);\r
-    assert(mutexInfo->recursionCount == 1);\r
-    mutexInfo->recursionCount = 0;\r
-    mutexInfo->owner = OC_INVALID_THREAD_ID;\r
-#endif\r
+#ifndef NDEBUG
+    // Recursively-acquired locks are not supported for use with condition variables.
+    oc_mutex_assert_owner(mutex, true);
+    assert(mutexInfo->recursionCount == 1);
+    mutexInfo->recursionCount = 0;
+    mutexInfo->owner = OC_INVALID_THREAD_ID;
+#endif
 
     // Wait for the given time        
     if (!SleepConditionVariableCS(&eventInfo->cond, &mutexInfo->mutex, milli))
@@ -374,12 +370,13 @@ OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseco
         retVal = OC_WAIT_SUCCESS;
     }
 
-#ifndef NDEBUG\r
-    oc_mutex_assert_owner(mutex, false);\r
-    assert(mutexInfo->recursionCount == 0);\r
-    mutexInfo->recursionCount = 1;\r
-    mutexInfo->owner = oc_get_current_thread_id();\r
-#endif\r
+
+#ifndef NDEBUG
+    oc_mutex_assert_owner(mutex, false);
+    assert(mutexInfo->recursionCount == 0);
+    mutexInfo->recursionCount = 1;
+    mutexInfo->owner = oc_get_current_thread_id();
+#endif
 
     return retVal;
 }
index 296ea0f..d832594 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+/**
+ * @file
+ * Time value functions.
+ */
+
 #ifndef OCTIMER_H_
 #define OCTIMER_H_
 
@@ -47,10 +52,12 @@ extern "C"
 #define SECS_YR_2000  (946684800L)
 #endif
 
-typedef void(*TimerCallback)();
+typedef void(*TimerCallback)(void *ctx);
 
 /**
- * This must be async-signal safe, so it cannot use difftime().
+ * Calculate time difference.
+ *
+ * Needs to be be async-signal safe, so cannot use difftime().
  * @param[in] after time to be substracted
  * @param[in] before reference time to be compared to
  * @return number of seconds between before and after, (after - before).
@@ -58,11 +65,14 @@ typedef void(*TimerCallback)();
 time_t timespec_diff(const time_t after, const time_t before);
 
 /**
- * Add positive seconds to a timespec, nothing if seconds is negative.
+ * Increase a time value by a specified amount.
+ *
+ * Adds positive seconds to a time value, nothing if seconds is negative.
  * @param[out] to time result to be added
  * @param[in] seconds amount of sec to add
  */
 void timespec_add(time_t *to, const time_t seconds);
+
 void checkTimeout();
 
 #ifndef WITH_ARDUINO
@@ -72,16 +82,15 @@ time_t getSecondsFromAbsTime(struct tm *tp);
 
 int initThread();
 void *loop(void *threadid);
-time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb);
+time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb, void *ctx);
 void OC_CALL unregisterTimer(int id);
 
 #else
 
 time_t timeToSecondsFromNow(tmElements_t *t);
-time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb);
+time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb, void *ctx);
 void OC_CALL unregisterTimer(int id);
 
-
 #endif
 
 #ifdef __cplusplus
index 9f1117f..6465329 100644 (file)
@@ -63,6 +63,7 @@ struct timelist_t
     time_t timeout_seconds;
     time_t timeout_time;
     TimerCallback cb;
+    void *ctx;
 } timeout_list[TIMEOUTS];
 
 time_t timespec_diff(const time_t after, const time_t before)
@@ -154,7 +155,7 @@ time_t getSecondsFromAbsTime(struct tm *tp)
     return delayed_time;
 }
 
-time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb)
+time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb, void *ctx)
 {
     time_t now, then;
     time_t next;
@@ -189,6 +190,7 @@ time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb)
 
     timeout_list[idx].timeout_time = then;
     timeout_list[idx].timeout_seconds = seconds;
+    timeout_list[idx].ctx = ctx;
 
     // printf( "\nbefore timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
     timeout_list[idx].cb = cb;
@@ -238,7 +240,7 @@ void checkTimeout()
                 timeout_list[i].timeout_state = TIMEOUT_UNUSED;
                 if (timeout_list[i].cb)
                 {
-                    timeout_list[i].cb();
+                    timeout_list[i].cb(timeout_list[i].ctx);
                 }
             }
         }
@@ -278,7 +280,7 @@ time_t timeToSecondsFromNow(tmElements_t *t_then)
     return (time_t) (then - t);
 }
 
-time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb)
+time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb, void *ctx)
 {
     time_t t, then;
     time_t next;
@@ -308,6 +310,7 @@ time_t OC_CALL registerTimer(const time_t seconds, int *id, TimerCallback cb)
 
     timeout_list[idx].timeout_time = then;
     timeout_list[idx].timeout_seconds = seconds;
+    timeout_list[idx].ctx = ctx;
 
     // printf( "\nbefore timeout_list[idx].cb = %X\n", timeout_list[idx].cb);
     timeout_list[idx].cb = cb;
@@ -361,7 +364,7 @@ void checkTimeout()
                 timeout_list[i].timeout_state = TIMEOUT_UNUSED;
                 if (timeout_list[i].cb)
                 {
-                    timeout_list[i].cb();
+                    timeout_list[i].cb(timeout_list[i].ctx);
                 }
             }
         }
index 6ca9e3e..cbf0924 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+/**
+ * @file
+ * Support for working with elapsed time.
+ */
+
 #ifndef OIC_TIME_H_
 #define OIC_TIME_H_
 
 #include <stdint.h>
 
+/**
+ * @name
+ * Useful constants for time unit conversions.
+ *
+ * @{
+ */
 #define MS_PER_SEC  (1000)
 #define US_PER_SEC  (1000000)
 #define US_PER_MS   (1000)
 #define NS_PER_US   (1000)
 #define NS_PER_MS   (1000000)
 #define HNS_PER_US  (10)
+/** @} */
 
 
 #ifdef __cplusplus
@@ -38,32 +50,40 @@ extern "C"
 
 typedef enum
 {
-    TIME_IN_MS = 0,
-    TIME_IN_US,
-}OICTimePrecision;
+    TIME_IN_MS = 0,     //!< milliseconds
+    TIME_IN_US,         //!< microseconds
+} OICTimePrecision;
 
-/*
- * If monotonic coarse/monotonic clock supported then gets current time as monotonic time
- * in milliseconds or microseconds as the elapsed time since some unspecified starting point
- * else gets current time in milliseconds or microseconds as the elapsed time since the epoch.
+/**
+ * Get the current time using the specified precision.
+ *
+ * Return the time in units of `precision`.
+ * If the implementation supports a monotonic clock, then
+ * the returned value will be from the monotonic clock,
+ * and the difference between two retrieved times can be considered
+ * an accurate elapsed time. The time base is unspecified
+ * in this case. If a monotonic clock is not supported,
+ * the time returned will be `precision` time units since the epoch,
+ * without adjustment for any external changes to the clock.
  *
- * For Arduino gets current time in milliseconds or microseconds since Arduino board begin
+ * For Arduino, returns the time since the Arduino board begin
  * running this program.
  *
- * @param     precision   based on this parameter, current time is returned in milliseconds or
- *                        microseconds
+ * @param     precision   based on this parameter, current time is
+ * returned in milliseconds or microseconds
  *
- * @warning   This function may be sensitive to system time changes on some platforms.
+ * @warning   This function may be sensitive to system time changes on
+ * platforms which do not support a monotonic clock.
  *
  * @note
- *            On Arduino platform:
- *            if the time precision is in milliseconds then the function will overflow
- *            (go back to 0) after approximately 50 days.
- *            if the time precision is in microseconds then the function will overflow
- *            (go back to 0) after approximately 70minutes.
+ * On the Arduino platform,
+ * if the time precision is in milliseconds then the function will
+ * overflow (go back to 0) after approximately 50 days.
+ * If the time precision is in microseconds then the function will
+ * overflow (go back to 0) after approximately 70 minutes.
  *
  * @return
- *         returns current time in milliseconds or microseconds.
+ *         Returns current time in milliseconds or microseconds.
  */
 uint64_t OICGetCurrentTime(OICTimePrecision precision);
 
index 3e6f0b0..cbe0f82 100644 (file)
 #  endif
 #endif
 
+/**
+ * Calling convention.
+ */
+#ifdef _WIN32
+/*
+ * Set to __stdcall for Windows, consistent with WIN32 APIs.
+ */
+#  define OC_CALL   __stdcall
+#else
+#  define OC_CALL
+#endif
+
 /**
  * Mark a parameter as unused. Used to prevent unused variable compiler warnings.
  */
index 1ed6b9b..6f9d79e 100644 (file)
@@ -27,9 +27,17 @@ Import('test_env')
 common_test_env = test_env.Clone()
 target_os = common_test_env.get('TARGET_OS')
 
-SConscript('../oic_string/test/SConscript', exports = { 'test_env' : common_test_env})
-SConscript('../oic_malloc/test/SConscript', exports = { 'test_env' : common_test_env})
-SConscript('../oic_time/test/SConscript', exports = { 'test_env' : common_test_env})
-SConscript('../ocrandom/test/SConscript', exports = { 'test_env' : common_test_env})
+# Enable treating all warnings as errors for Windows.
+if target_os in ['windows', 'msys_nt']:
+    common_test_env.AppendUnique(CCFLAGS=['/W4'])
+
+SConscript(exports={'test_env': common_test_env},
+           dirs=[
+               '../oic_string/test',
+               '../oic_malloc/test',
+               '../oic_time/test',
+               '../ocrandom/test',
+               '../ocevent/test',
+           ])
 if target_os == 'windows':
-    SConscript('../windows/test/SConscript', exports = { 'test_env' : common_test_env})
+    SConscript('../windows/test/SConscript', exports={'test_env': common_test_env})
index 58a1822..84d99e1 100644 (file)
@@ -22,7 +22,8 @@ targets_disallow_multitransport = ['arduino']
 if target_os in targets_disallow_multitransport:
     if ('ALL' in transport) or (len(transport) != 1):
         print "*** Error invalid option values: TARGET_TRANSPORT"
-        print "%s disallowed until testing can validate use of multiple transports on %s %d" % (transport, target_os, len(transport))
+        print "%s disallowed until testing can validate use of multiple transports on %s %d" % (
+            transport, target_os, len(transport))
         Exit(1)
 
-SConscript('src/SConscript', exports = 'connectivity_env')
+SConscript('src/SConscript', exports='connectivity_env')
index d62d2a8..a52326f 100644 (file)
@@ -397,6 +397,7 @@ typedef enum
     CA_REQUEST_ENTITY_TOO_LARGE = 413,      /**< Request Entity Too Large */
     CA_INTERNAL_SERVER_ERROR = 500,         /**< Internal Server Error */
     CA_BAD_GATEWAY = 502,
+    CA_SERVICE_UNAVAILABLE = 503,           /**< Server Unavailable */
     CA_RETRANSMIT_TIMEOUT = 504,            /**< Retransmit timeout */
     CA_PROXY_NOT_SUPPORTED = 505            /**< Proxy not enabled to service a request */
     /* Response status code - END HERE */
index a0455d3..2782721 100644 (file)
@@ -7,41 +7,51 @@ import platform
 
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
-               'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
-               'windows': ['windows', 'android', 'arduino'],
-               'darwin': ['darwin', 'ios', 'android', 'arduino'],
-               }
+    'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
+    'windows': ['windows', 'android', 'arduino'],
+    'darwin': ['darwin', 'ios', 'android', 'arduino'],
+}
 
 # Map of os and allowed archs (os: allowed archs)
 os_arch_map = {
-               'linux': ['x86', 'x86_64', 'arm', 'arm64', 'mips', 'mipsel', 'mips64', 'mips64el', 'i386', 'powerpc', 'sparc', 'aarch64'],
-               'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
-               'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
-               'windows': ['x86', 'amd64', 'arm'],
-               'darwin': ['i386', 'x86_64'],
-               'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
-               'arduino': ['avr', 'arm'],
-                'yocto': ['i586', 'i686', 'x86_64', 'arm', 'aarch64', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
-               }
+    'linux': [
+        'x86', 'x86_64', 'arm', 'arm64', 'mips', 'mipsel', 'mips64',
+        'mips64el', 'i386', 'powerpc', 'sparc', 'aarch64'
+    ],
+    'tizen': ['x86', 'x86_64', 'arm', 'arm64'],
+    'android': [
+        'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard',
+        'arm64-v8a'
+    ],
+    'windows': ['x86', 'amd64', 'arm'],
+    'darwin': ['i386', 'x86_64'],
+    'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
+    'arduino': ['avr', 'arm'],
+    'yocto': [
+        'i586', 'i686', 'x86_64', 'arm', 'aarch64', 'powerpc', 'powerpc64',
+        'mips', 'mipsel'
+    ],
+}
 
 host = platform.system().lower()
 
 if host not in host_target_map:
-       print "\nError: Current system (%s) isn't supported\n" % host
-       Exit(1)
+    print "\nError: Current system (%s) isn't supported\n" % host
+    Exit(1)
 
 ######################################################################
 # Get build options (the optins from command line)
 ######################################################################
-target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
+target_os = ARGUMENTS.get('TARGET_OS', host).lower()  # target os
 
 if target_os not in host_target_map[host]:
-       print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
-       Exit(1)
+    print "\nError: Unknown target os: %s (Allow values: %s)\n" % (
+        target_os, host_target_map[host])
+    Exit(1)
 
 default_arch = platform.machine()
 
-target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
+target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch)  # target arch
 
 # True if binary needs to be installed on board. (Might need root permissions)
 # set to 'no', 'false' or 0 for only compilation
@@ -54,27 +64,73 @@ device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
 # Common build options (release, target os, target arch)
 ######################################################################
 help_vars = Variables()
-help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
-help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
-help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
-help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
-help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
-help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '1', allowed_values=('0', '1')))
-help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
-help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
-help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
-help_vars.Add(BoolVariable('WITH_TCP', 'Enable TCP', False))
-help_vars.Add(ListVariable('WITH_MQ', 'Build with MQ publisher/subscriber/broker', 'OFF', ['OFF', 'SUB', 'PUB', 'BROKER']))
-
-help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
-
-AddOption('--prefix',
-                  dest='prefix',
-                  type='string',
-                  nargs=1,
-                  action='store',
-                  metavar='DIR',
-                  help='installation prefix')
+help_vars.Add(
+    BoolVariable('RELEASE',
+                 'Build for release?',
+                 True))  # set to 'no', 'false' or 0 for debug
+help_vars.Add(
+    BoolVariable('LOGGING',
+                 'Enable stack logging',
+                 False))
+help_vars.Add(
+    EnumVariable('TARGET_OS',
+                 'Target platform',
+                 host,
+                 allowed_values=host_target_map[host]))
+help_vars.Add(
+    ListVariable('TARGET_TRANSPORT',
+                 'Target transport',
+                 'ALL',
+                 ['ALL', 'BT', 'BLE', 'IP']))
+help_vars.Add(
+    EnumVariable('TARGET_ARCH',
+                 'Target architecture',
+                 default_arch,
+                 allowed_values=os_arch_map[target_os]))
+help_vars.Add(
+    EnumVariable('SECURED',
+                 'Build with DTLS',
+                 '1',
+                 allowed_values=('0', '1')))
+help_vars.Add(
+    BoolVariable('UPLOAD',
+                 'Upload binary ? (For Arduino)',
+                 require_upload))
+help_vars.Add(
+    EnumVariable('ROUTING',
+                 'Enable routing',
+                 'EP',
+                 allowed_values=('GW', 'EP')))
+help_vars.Add(
+    EnumVariable('BUILD_SAMPLE',
+                 'Build with sample',
+                 'ON',
+                 allowed_values=('ON', 'OFF')))
+help_vars.Add(
+    BoolVariable('WITH_TCP',
+                 'Enable TCP',
+                 False))
+help_vars.Add(
+    ListVariable('WITH_MQ',
+                 'Build with MQ publisher/subscriber/broker',
+                 'OFF',
+                 ['OFF', 'SUB', 'PUB', 'BROKER']))
+
+help_vars.AddVariables(
+    ('DEVICE_NAME',
+     'Network display name for device',
+     'OIC-DEVICE',
+     None,
+     None), )
+
+AddOption(
+    '--prefix',
+    dest='prefix',
+    type='string',
+    nargs=1,
+    action='store',
+    metavar='DIR',
+    help='installation prefix')
 
 ######################################################################
 # Platform(build target) specific options: SDK/NDK & toolchain
@@ -82,23 +138,33 @@ AddOption('--prefix',
 targets_support_cc = ['linux', 'arduino', 'tizen']
 
 if target_os in targets_support_cc:
-       # Set cross compile toolchain
-       help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
-       help_vars.Add(PathVariable('TC_PATH',
-                       'Toolchain path (Generally only be required for cross-compiling)',
-                       os.environ.get('TC_PATH')))
-
-if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
-       env = Environment(variables = help_vars,
-                       tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
-                       )
+    # Set cross compile toolchain
+    help_vars.Add('TC_PREFIX',
+                  "Toolchain prefix (Generally only required for cross-compiling)",
+                  os.environ.get('TC_PREFIX'))
+    help_vars.Add(
+        PathVariable(
+            'TC_PATH',
+            'Toolchain path (Generally only required for cross-compiling)',
+            os.environ.get('TC_PATH')))
+
+if target_os in [
+        'android', 'arduino'
+]:  # Android/Arduino always uses GNU compiler regardless of the host
+    env = Environment(
+        variables=help_vars, tools=['gnulink', 'gcc', 'g++', 'ar', 'as'])
 else:
-       env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os, PREFIX = GetOption('prefix'))
+    env = Environment(
+        variables=help_vars,
+        TARGET_ARCH=target_arch,
+        TARGET_OS=target_os,
+        PREFIX=GetOption('prefix'))
 
 Help(help_vars.GenerateHelpText(env))
 
 # Set device name to __OIC_DEVICE_NAME__
-env.AppendUnique(CPPDEFINES = ['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])
+env.AppendUnique(
+    CPPDEFINES=['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])
 
 tc_set_msg = '''
 ************************************ Warning **********************************
@@ -109,24 +175,24 @@ tc_set_msg = '''
 '''
 
 if target_os in targets_support_cc:
-       prefix = env.get('TC_PREFIX')
-       tc_path = env.get('TC_PATH')
-       if prefix:
-               env.Replace(CC = prefix + 'gcc')
-               env.Replace(CXX = prefix + 'g++')
-               env.Replace(AR = prefix + 'ar')
-               env.Replace(AS = prefix + 'as')
-               env.Replace(LINK = prefix + 'ld')
-               env.Replace(RANLIB = prefix + 'ranlib')
-
-       if tc_path:
-               env.PrependENVPath('PATH', tc_path)
-               sys_root = os.path.abspath(tc_path + '/../')
-               env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
-               env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
-
-       if prefix or tc_path:
-               print tc_set_msg
+    prefix = env.get('TC_PREFIX')
+    tc_path = env.get('TC_PATH')
+    if prefix:
+        env.Replace(CC=prefix + 'gcc')
+        env.Replace(CXX=prefix + 'g++')
+        env.Replace(AR=prefix + 'ar')
+        env.Replace(AS=prefix + 'as')
+        env.Replace(LINK=prefix + 'ld')
+        env.Replace(RANLIB=prefix + 'ranlib')
+
+    if tc_path:
+        env.PrependENVPath('PATH', tc_path)
+        sys_root = os.path.abspath(tc_path + '/../')
+        env.AppendUnique(CCFLAGS=['--sysroot=' + sys_root])
+        env.AppendUnique(LINKFLAGS=['--sysroot=' + sys_root])
+
+    if prefix or tc_path:
+        print tc_set_msg
 
 # Ensure scons be able to change its working directory
 env.SConscriptChdir(1)
@@ -139,67 +205,77 @@ env.SConscriptChdir(1)
 #   env.get('SRC_DIR')
 #   env.get('BUILD_DIR')
 
+
 def __set_dir(env, dir):
-       if not os.path.exists(dir + '/SConstruct'):
-               print '''
+    if not os.path.exists(dir + '/SConstruct'):
+        print '''
 *************************************** Error *********************************
 * The directory(%s) seems isn't a source code directory, no SConstruct file is
 * found. *
 *******************************************************************************
 ''' % dir
-               Exit(1)
+        Exit(1)
+
+    if env.get('RELEASE'):
+        build_dir = os.path.join(
+            dir, 'out', target_os, target_arch, 'release') + os.sep
+    else:
+        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)
+    env.Replace(SRC_DIR=dir)
 
-       if env.get('RELEASE'):
-               build_dir = os.path.join(dir, 'out', target_os, target_arch, 'release') + os.sep
-       else:
-               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)
-       env.Replace(SRC_DIR = dir)
+def __src_to_obj(env, src, home=''):
+    obj = env.get('BUILD_DIR') + src.replace(home, '')
+    if env.get('OBJSUFFIX'):
+        obj += env.get('OBJSUFFIX')
+    return env.Object(obj, src)
 
-def __src_to_obj(env, src, home = ''):
-       obj = env.get('BUILD_DIR') + src.replace(home, '')
-       if env.get('OBJSUFFIX'):
-               obj += env.get('OBJSUFFIX')
-       return env.Object(obj, src)
 
 def __install(ienv, targets, name):
-       i_n = ienv.Install(env.get('BUILD_DIR'), targets)
-       Alias(name, i_n)
-       env.AppendUnique(TS = [name])
+    i_n = ienv.Install(env.get('BUILD_DIR'), targets)
+    Alias(name, i_n)
+    env.AppendUnique(TS=[name])
+
 
 def __installlib(ienv, targets, name):
-       user_prefix = env.get('PREFIX')
-       if user_prefix:
-               install_lib_dir = os.path.join(user_prefix, 'lib')
-       else:
-               install_lib_dir = os.path.join(env.get('BUILD_DIR'), 'lib')
-       i_n = ienv.Install(install_lib_dir, targets)
-       ienv.Alias("install", i_n)
+    user_prefix = env.get('PREFIX')
+    if user_prefix:
+        install_lib_dir = os.path.join(user_prefix, 'lib')
+    else:
+        install_lib_dir = os.path.join(env.get('BUILD_DIR'), 'lib')
+    i_n = ienv.Install(install_lib_dir, targets)
+    ienv.Alias("install", i_n)
+
 
 def __installbin(ienv, targets, name):
-       user_prefix = env.get('PREFIX')
-       if user_prefix:
-               i_n = ienv.Install(user_prefix + '/bin', targets)
-               ienv.Alias("install", i_n)
+    user_prefix = env.get('PREFIX')
+    if user_prefix:
+        i_n = ienv.Install(user_prefix + '/bin', targets)
+        ienv.Alias("install", i_n)
+
 
 def __append_target(ienv, target):
-       env.AppendUnique(TS = [target])
+    env.AppendUnique(TS=[target])
+
 
 def __print_targets(env):
-       Help('''
+    Help('''
 ===============================================================================
 Targets:\n    ''')
-       for t in env.get('TS'):
-               Help(t + ' ')
-       Help('''
-\nDefault all targets will be built. You can specify the target to build:
+    for t in env.get('TS'):
+        Help(t + ' ')
+    Help('''
+\nBy default all targets will be built. You can specify the target to build:
 
     $ scons [options] [target]
 ===============================================================================
 ''')
 
+
 env.AddMethod(__set_dir, 'SetDir')
 env.AddMethod(__print_targets, 'PrintTargets')
 env.AddMethod(__src_to_obj, 'SrcToObj')
@@ -208,7 +284,7 @@ env.AddMethod(__install, 'InstallTarget')
 env.AddMethod(__installlib, 'UserInstallTargetLib')
 env.AddMethod(__installbin, 'UserInstallTargetBin')
 env.SetDir(env.GetLaunchDir())
-env['ROOT_DIR']=env.GetLaunchDir()+'/..'
+env['ROOT_DIR'] = env.GetLaunchDir() + '/..'
 
 Export('env')
 
@@ -225,20 +301,22 @@ if target_os == "yocto":
     try:
         CC = os.environ['CC']
         target_prefix = CC.split()[0]
-        target_prefix = target_prefix[:len(target_prefix)-3]
-        tools = {"CC" : target_prefix+"gcc",
-                "CXX" : target_prefix+"g++",
-                "AS" : target_prefix+"as",
-                "LD" : target_prefix+"ld",
-                "GDB" : target_prefix+"gdb",
-                "STRIP" : target_prefix+"strip",
-                "RANLIB" : target_prefix+"ranlib",
-                "OBJCOPY" : target_prefix+"objcopy",
-                "OBJDUMP" : target_prefix+"objdump",
-                "AR" : target_prefix+"ar",
-                "NM" : target_prefix+"nm",
-                "M4" : "m4",
-                "STRINGS": target_prefix+"strings"}
+        target_prefix = target_prefix[:len(target_prefix) - 3]
+        tools = {
+            "CC": target_prefix + "gcc",
+            "CXX": target_prefix + "g++",
+            "AS": target_prefix + "as",
+            "LD": target_prefix + "ld",
+            "GDB": target_prefix + "gdb",
+            "STRIP": target_prefix + "strip",
+            "RANLIB": target_prefix + "ranlib",
+            "OBJCOPY": target_prefix + "objcopy",
+            "OBJDUMP": target_prefix + "objdump",
+            "AR": target_prefix + "ar",
+            "NM": target_prefix + "nm",
+            "M4": "m4",
+            "STRINGS": target_prefix + "strings"
+        }
         PATH = os.environ['PATH'].split(os.pathsep)
         for tool in tools:
             if tool in os.environ:
@@ -259,19 +337,19 @@ if target_os == "yocto":
     We want to preserve debug symbols to allow BitBake to generate both DEBUG and
     RELEASE packages for OIC.
     '''
-    env.AppendUnique(CCFLAGS = ['-g'])
+    env.AppendUnique(CCFLAGS=['-g'])
     '''
     Additional flags to pass to the Yocto toolchain.
     '''
     if env.get('RELEASE'):
-        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+        env.AppendUnique(CPPDEFINES=['NDEBUG'])
     if env.get('LOGGING'):
-        env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-    env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
-    env.AppendUnique(CFLAGS = ['-std=gnu99'])
-    env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
+        env.AppendUnique(CPPDEFINES=['TB_LOG'])
+    env.AppendUnique(CPPDEFINES=['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
+    env.AppendUnique(CFLAGS=['-std=gnu99'])
+    env.AppendUnique(CCFLAGS=['-Wall', '-fPIC'])
     if target_os in ['linux']:
-        env.AppendUnique(LIBS = ['dl', 'pthread'])
+        env.AppendUnique(LIBS=['dl', 'pthread'])
     Export('env')
 else:
     '''
@@ -279,17 +357,17 @@ else:
     '''
     # Load config of target os
     if target_os in ['linux', 'tizen']:
-               env.SConscript('linux/SConscript')
+        env.SConscript('linux/SConscript')
     else:
-               env.SConscript(target_os + '/SConscript')
+        env.SConscript(target_os + '/SConscript')
 
 # Delete the temp files of configuration
 if env.GetOption('clean'):
-       dir = env.get('SRC_DIR')
+    dir = env.get('SRC_DIR')
 
-       if os.path.exists(dir + '/config.log'):
-               Execute(Delete(dir + '/config.log'))
-               Execute(Delete(dir + '/.sconsign.dblite'))
-               Execute(Delete(dir + '/.sconf_temp'))
+    if os.path.exists(dir + '/config.log'):
+        Execute(Delete(dir + '/config.log'))
+        Execute(Delete(dir + '/.sconsign.dblite'))
+        Execute(Delete(dir + '/.sconf_temp'))
 
 Return('env')
index d97d596..8c294f2 100644 (file)
@@ -6,293 +6,322 @@ import platform
 
 Import('env')
 
+
 def __parse_config(f):
-       dict = {}
+    dict = {}
+
+    if not os.path.isfile(f):
+        return dict
 
-       if not os.path.isfile(f):
-               return dict
+    file = open(f, 'r')
+    strs = file.readlines()
+    for str in strs:
+        str = str.strip()
+        if len(str) > 0 and str[0] == '#':
+            continue
 
-       file = open(f, 'r')
-       strs = file.readlines()
-       for str in strs:
-               str = str.strip()
-               if len(str) > 0 and str[0] == '#':
-                       continue
+        idx = str.find('=')
+        if idx > 0:
+            dict.setdefault(str[0:idx], str[idx + 1:])
 
-               idx = str.find('=')
-               if idx > 0:
-                       dict.setdefault(str[0:idx], str[idx + 1:])
+    return dict
 
-       return dict
 
 def __get_boards(dict):
-       boards = []
-       keys = dict.keys()
-       for key in keys:
-               idx = key.find('.name')
-               if idx > 0:
-                       if key.endswith('.name'):
-                               boards.append(key[0:idx])
-       return boards
+    boards = []
+    keys = dict.keys()
+    for key in keys:
+        idx = key.find('.name')
+        if idx > 0:
+            if key.endswith('.name'):
+                boards.append(key[0:idx])
+    return boards
+
 
 def __get_cpu(dict, board):
-       cpus = []
-       keys = dict.keys()
-       for key in keys:
-               idx = key.find(board + '.menu.cpu.')
-               start = len(board + '.menu.cpu.')
-               if idx >= 0:
-                       end = key.find('.', start)
-                       if end > 0:
-                               cpu = key[start:end]
-                               exist = False
-                               for c in cpus:
-                                       if c == cpu:
-                                               exist = True
-                                               break
-
-                               if not exist:
-                                       cpus.append(cpu)
-       return cpus
+    cpus = []
+    keys = dict.keys()
+    for key in keys:
+        idx = key.find(board + '.menu.cpu.')
+        start = len(board + '.menu.cpu.')
+        if idx >= 0:
+            end = key.find('.', start)
+            if end > 0:
+                cpu = key[start:end]
+                exist = False
+                for c in cpus:
+                    if c == cpu:
+                        exist = True
+                        break
+
+                if not exist:
+                    cpus.append(cpu)
+    return cpus
+
 
 def __get_board_info(board, key):
-       if cpu:
-               v = boards_info.get(board + '.menu.cpu.' + cpu + key)
-               if not v:
-                       v = boards_info.get(board + key)
-       else:
-               v = boards_info.get(board + key)
-       return v
-
-def __search_files(path, pattern, ondisk=True, source=True, strings=False, recursive=True):
-       if not recursive:
-               return Glob(pattern, ondisk, source, strings)
-
-       matches = []
-       for root, dirnames, filenames in os.walk(path):
-               #BLE library examples throw lot of errors. We dont need examples.
-               if 'examples' not in root:
-                       matches.extend(Glob(root + '/' + pattern, ondisk, source, strings))
-       return matches
+    if cpu:
+        v = boards_info.get(board + '.menu.cpu.' + cpu + key)
+        if not v:
+            v = boards_info.get(board + key)
+    else:
+        v = boards_info.get(board + key)
+    return v
+
+
+def __search_files(path,
+                   pattern,
+                   ondisk=True,
+                   source=True,
+                   strings=False,
+                   recursive=True):
+    if not recursive:
+        return Glob(pattern, ondisk, source, strings)
+
+    matches = []
+    for root, dirnames, filenames in os.walk(path):
+        #BLE library examples throw lot of errors. We dont need examples.
+        if 'examples' not in root:
+            matches.extend(Glob(root + '/' + pattern, ondisk, source, strings))
+    return matches
+
 
 # To make sure the src is built in 'BUILD_DIR' (by default it will be built at
 # the same directory as the .c .cpp .S)
 def __src_to_obj(env, srcs):
-       objs = []
-       prefix = env.get('BOARD') + '_'
-       if env.get('CPU'):
-               prefix += env.get('CPU') + '_'
-
-       build_dir = env.get('BUILD_DIR') + '/arduino/'
-       for src in srcs:
-               obj = src.path.replace(arduino_home, build_dir)
-               i = obj.rfind('.')
-               obj = obj[0:i]
-               if env.get('OBJSUFFIX'):
-                       obj += env.get('OBJSUFFIX')
-               objs.extend(env.Object(obj, src, OBJPREFIX=prefix))
-       return objs
+    objs = []
+    prefix = env.get('BOARD') + '_'
+    if env.get('CPU'):
+        prefix += env.get('CPU') + '_'
+
+    build_dir = env.get('BUILD_DIR') + '/arduino/'
+    for src in srcs:
+        obj = src.path.replace(arduino_home, build_dir)
+        i = obj.rfind('.')
+        obj = obj[0:i]
+        if env.get('OBJSUFFIX'):
+            obj += env.get('OBJSUFFIX')
+        objs.extend(env.Object(obj, src, OBJPREFIX=prefix))
+    return objs
+
 
 def __import_lib(env, lib):
-       lib_path = arduino_home + '/libraries/' + lib
-       if not os.path.exists(lib_path):
-               if target_arch == 'avr':
-                       lib_path = arduino_home + '/hardware/arduino/avr/libraries/' + lib
-               else:
-                       lib_path = arduino_home + '/hardware/arduino/sam/libraries/' + lib
-
-       if os.path.exists(lib_path + '/src'):
-               lib_path = lib_path + '/src'
-
-       env.AppendUnique(CPPPATH = [lib_path])
-
-       if os.path.exists(lib_path + '/utility'):
-               env.AppendUnique(CPPPATH = [lib_path + '/utility'])
-
-       lib_src = []
-       lib_src.extend(__search_files(lib_path, '*.S'))
-       lib_src.extend(__search_files(lib_path, '*.c'))
-       lib_src.extend(__search_files(lib_path, '*.cpp'))
-
-       lib_obj = __src_to_obj(env, lib_src)
-       build_dir = env.get('BUILD_DIR')
-       if build_dir:
-               lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
-       else:
-               lib_a = env.StaticLibrary(lib, lib_obj)
-
-       # If we link libSPI.a, the final binary is not getting launched
-       # on the board.  Which is not the case if we directly use SPI.o.
-
-       if env.get('TARGET_ARCH') == 'arm':
-               if lib == 'SPI':
-                       for obj in lib_obj:
-                               if obj.name.endswith('SPI.o'):
-                                       env.PrependUnique(LIBS = [File(obj)])
-               else:
-                       env.AppendUnique(LIBS = [File(lib_a[0])])
-       else:
-               env.PrependUnique(LIBS = [File(lib_a[0])])
+    lib_path = arduino_home + '/libraries/' + lib
+    if not os.path.exists(lib_path):
+        if target_arch == 'avr':
+            lib_path = arduino_home + '/hardware/arduino/avr/libraries/' + lib
+        else:
+            lib_path = arduino_home + '/hardware/arduino/sam/libraries/' + lib
+
+    if os.path.exists(lib_path + '/src'):
+        lib_path = lib_path + '/src'
+
+    env.AppendUnique(CPPPATH=[lib_path])
+
+    if os.path.exists(lib_path + '/utility'):
+        env.AppendUnique(CPPPATH=[lib_path + '/utility'])
+
+    lib_src = []
+    lib_src.extend(__search_files(lib_path, '*.S'))
+    lib_src.extend(__search_files(lib_path, '*.c'))
+    lib_src.extend(__search_files(lib_path, '*.cpp'))
+
+    lib_obj = __src_to_obj(env, lib_src)
+    build_dir = env.get('BUILD_DIR')
+    if build_dir:
+        lib_a = env.StaticLibrary(build_dir + lib, lib_obj)
+    else:
+        lib_a = env.StaticLibrary(lib, lib_obj)
+
+    # If we link libSPI.a, the final binary is not getting launched
+    # on the board.  Which is not the case if we directly use SPI.o.
+
+    if env.get('TARGET_ARCH') == 'arm':
+        if lib == 'SPI':
+            for obj in lib_obj:
+                if obj.name.endswith('SPI.o'):
+                    env.PrependUnique(LIBS=[File(obj)])
+        else:
+            env.AppendUnique(LIBS=[File(lib_a[0])])
+    else:
+        env.PrependUnique(LIBS=[File(lib_a[0])])
+
 
 def __build_core(env):
-       core_src = __search_files(core_folder, '*.S')
-       core_src.extend(__search_files(core_folder, '*.c'))
-       core_src.extend(__search_files(core_folder, '*.cpp'))
-
-       core_src.extend(__search_files(variant_folder, '*.S'))
-       core_src.extend(__search_files(variant_folder, '*.c'))
-       core_src.extend(__search_files(variant_folder, '*.cpp'))
-
-       core_obj = __src_to_obj(env, core_src)
-       build_dir = env.get('BUILD_DIR')
-       if build_dir:
-               s_core = env.StaticLibrary(build_dir + 'core', core_obj)
-       else:
-               s_core = env.StaticLibrary('core', core_obj)
-       env.AppendUnique(LIBS = [File(s_core[0])])
-
-       # To avoid compiler issue. Otherewise there may be warnings:
-       #       undefined reference to '_exit' '_close', '_getpid' ...
-       # Above functions are used in libc.a and implemented in syscalls_sam3.c
-       if env.get('TARGET_ARCH') == 'arm':
-               for obj in core_obj:
-                       if obj.name.endswith('syscalls_sam3.o'):
-                               env.AppendUnique(LIBS = [File(obj)])
+    core_src = __search_files(core_folder, '*.S')
+    core_src.extend(__search_files(core_folder, '*.c'))
+    core_src.extend(__search_files(core_folder, '*.cpp'))
+
+    core_src.extend(__search_files(variant_folder, '*.S'))
+    core_src.extend(__search_files(variant_folder, '*.c'))
+    core_src.extend(__search_files(variant_folder, '*.cpp'))
+
+    core_obj = __src_to_obj(env, core_src)
+    build_dir = env.get('BUILD_DIR')
+    if build_dir:
+        s_core = env.StaticLibrary(build_dir + 'core', core_obj)
+    else:
+        s_core = env.StaticLibrary('core', core_obj)
+    env.AppendUnique(LIBS=[File(s_core[0])])
+
+    # To avoid compiler issue. Otherewise there may be warnings:
+    #   undefined reference to '_exit' '_close', '_getpid' ...
+    # Above functions are used in libc.a and implemented in syscalls_sam3.c
+    if env.get('TARGET_ARCH') == 'arm':
+        for obj in core_obj:
+            if obj.name.endswith('syscalls_sam3.o'):
+                env.AppendUnique(LIBS=[File(obj)])
+
 
 def __create_bin(env, source):
-       name = source
-       if target_arch == 'avr':
-               eep = env.Command(name + '.eep', source, 'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET')
-               hex = env.Command(name + '.hex', source, 'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET')
-       else:
-               hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
+    name = source
+    if target_arch == 'avr':
+        eep = env.Command(
+            name + '.eep', source,
+            'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET'
+        )
+        hex = env.Command(name + '.hex', source,
+                          'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET')
+    else:
+        hex = env.Command(name + '.hex', source,
+                          'arm-none-eabi-objcopy -O binary $SOURCE $TARGET')
+
 
 #Currently Mega and Due build is supported.
 def __upload(env, binary):
-        if target_arch == 'avr':
-                protocol = __get_board_info(board, '.upload.protocol')
-                speed = __get_board_info(board, '.upload.speed')
-                port = '/dev/ttyACM0'
-                upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
-                + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
-
-                print "Upload command: %s" %upload_cmd
-                install_cmd = env.Command('install_cmd', None, upload_cmd)
-                env.Default('install_cmd')
-        else:
-               uu = __get_board_info(board, '.upload.native_usb')
-                port = 'ttyACM0'
-               upload_cmd = 'stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb \n' + arduino_home + '/hardware/tools/bossac -i -d --port=' + port + ' -U ' + uu + ' -e -w -v -b ' + binary + ' -R'
-                print "Upload command: %s" %upload_cmd
-                install_cmd = env.Command('install_cmd', None, upload_cmd)
-                env.Default('install_cmd')
+    if target_arch == 'avr':
+        protocol = __get_board_info(board, '.upload.protocol')
+        speed = __get_board_info(board, '.upload.speed')
+        port = '/dev/ttyACM0'
+        upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
+        + mcu + ' -c' + protocol + ' -P' + port + ' -b' + speed + ' -D -Uflash:w:' + binary + ':i'
+
+        print "Upload command: %s" % upload_cmd
+        install_cmd = env.Command('install_cmd', None, upload_cmd)
+        env.Default('install_cmd')
+    else:
+        uu = __get_board_info(board, '.upload.native_usb')
+        port = 'ttyACM0'
+        upload_cmd = 'stty -F /dev/' + port + ' speed 1200 cs8 -cstopb -parenb \n' + arduino_home + '/hardware/tools/bossac -i -d --port=' + port + ' -U ' + uu + ' -e -w -v -b ' + binary + ' -R'
+        print "Upload command: %s" % upload_cmd
+        install_cmd = env.Command('install_cmd', None, upload_cmd)
+        env.Default('install_cmd')
+
 
 # Print the command line that to upload binary to the board
 def __upload_help(env):
-       if target_arch == 'avr':
-               protocol = __get_board_info(board, '.upload.protocol')
-               speed = __get_board_info(board, '.upload.speed')
+    if target_arch == 'avr':
+        protocol = __get_board_info(board, '.upload.protocol')
+        speed = __get_board_info(board, '.upload.speed')
 
-               upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
-       + mcu + ' -c' + protocol + ' -P<serial_port>' + ' -b' + speed + ' -D -Uflash:w:<hex_file>:i'
-       else:
-               uu = __get_board_info(board, '.upload.native_usb')
-               upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port=<serial_port> -U ' + uu + ' -e -w -v -b <bin file> -R'
+        upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \
+       + mcu + ' -c' + protocol + ' -P<serial_port>' + ' -b' + speed + ' -D -Uflash:w:<hex_file>:i'
+    else:
+        uu = __get_board_info(board, '.upload.native_usb')
+        upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port=<serial_port> -U ' + uu + ' -e -w -v -b <bin file> -R'
 
-       Help('''
+    Help('''
 ===============================================================================
 You can upload the bin file with following command line:
 ''')
-       Help('\n   $ ' + upload_cmd)
-       Help('''
+    Help('\n   $ ' + upload_cmd)
+    Help('''
 \nPlease replace <xxx> according to the actual situation.
 ===============================================================================
 ''')
 
+
 # ARDUINO_HOME build option
 help_vars = Variables()
-help_vars.Add(PathVariable('ARDUINO_HOME', 'ARDUINO root directory', os.environ.get('ARDUINO_HOME')))
+help_vars.Add(
+    PathVariable('ARDUINO_HOME',
+                 'ARDUINO root directory',
+                 os.environ.get('ARDUINO_HOME')))
 help_vars.Update(env)
 Help(help_vars.GenerateHelpText(env))
 
 target_arch = env.get('TARGET_ARCH')
 arduino_home = env.get('ARDUINO_HOME')
 if not arduino_home:
-       print '''
+    print '''
 ************************************* Error ***********************************
 *   Arduino root directory isn't set, you can set enviornment variable        *
 * ARDUINO_HOME or add it in command line as:                                  *
 *      # scons ARDUINO_HOME=<path to arduino root directory> ...              *
 *******************************************************************************
 '''
-       Exit(1)
+    Exit(1)
 
 # Overwrite suffixes and prefixes
 if env['HOST_OS'] == 'win32':
-       env['OBJSUFFIX'] = '.o'
-       env['SHOBJSUFFIX'] = '.os'
-       env['LIBPREFIX'] = 'lib'
-       env['LIBSUFFIX'] = '.a'
-       env['SHLIBPREFIX'] = 'lib'
-       env['SHLIBSUFFIX'] = '.so'
-       env['LIBPREFIXES'] = ['lib']
-       env['LIBSUFFIXES'] = ['.a', '.so']
-       env['PROGSUFFIX'] = ''
+    env['OBJSUFFIX'] = '.o'
+    env['SHOBJSUFFIX'] = '.os'
+    env['LIBPREFIX'] = 'lib'
+    env['LIBSUFFIX'] = '.a'
+    env['SHLIBPREFIX'] = 'lib'
+    env['SHLIBSUFFIX'] = '.so'
+    env['LIBPREFIXES'] = ['lib']
+    env['LIBSUFFIXES'] = ['.a', '.so']
+    env['PROGSUFFIX'] = ''
 elif platform.system().lower() == 'darwin':
-       env['SHLIBSUFFIX'] = '.so'
-       env['LIBSUFFIXES'] = ['.a', '.so']
-       env['PROGSUFFIX'] = ''
+    env['SHLIBSUFFIX'] = '.so'
+    env['LIBSUFFIXES'] = ['.a', '.so']
+    env['PROGSUFFIX'] = ''
 
 # Debug/release relative flags
 if env.get('RELEASE'):
-       env.AppendUnique(CCFLAGS = ['-Os'])
-       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+    env.AppendUnique(CCFLAGS=['-Os'])
+    env.AppendUnique(CPPDEFINES=['NDEBUG'])
 else:
-       env.AppendUnique(CCFLAGS = ['-g'])
+    env.AppendUnique(CCFLAGS=['-g'])
 
 # BOARD / CPU option
 
 # Get IDE version
 if os.path.exists(arduino_home + '/lib/version.txt'):
-       vf = open(arduino_home + '/lib/version.txt', 'r')
-       version = vf.readline().replace('.', '')
+    vf = open(arduino_home + '/lib/version.txt', 'r')
+    version = vf.readline().replace('.', '')
 else:
-       print '''
+    print '''
 ************************************* Error ***********************************
 * Can't find version file (lib/version.txt), please check if (%s)
 * is arduino root directory.                                                  *
 *******************************************************************************
 ''' % arduino_home
-       Exit(1)
+    Exit(1)
 
 if version[0:2] == '10':
-       is_1_0_x = True
-       boards_info = __parse_config(arduino_home + '/hardware/arduino/boards.txt')
-       env.PrependENVPath('PATH', arduino_home + '/hardware/tools/avr/bin/')
-       env.Replace(CC = 'avr-gcc')
-       env.Replace(CXX = 'avr-gcc')
-       env.Replace(AR = 'avr-ar')
-       env.Replace(AS = 'avr-as')
-       env.Replace(LINK = 'avr-gcc')
-       env.Replace(RANLIB = 'avr-ranlib')
-       if target_arch != 'avr':
-               print '''
+    is_1_0_x = True
+    boards_info = __parse_config(arduino_home + '/hardware/arduino/boards.txt')
+    env.PrependENVPath('PATH', arduino_home + '/hardware/tools/avr/bin/')
+    env.Replace(CC='avr-gcc')
+    env.Replace(CXX='avr-gcc')
+    env.Replace(AR='avr-ar')
+    env.Replace(AS='avr-as')
+    env.Replace(LINK='avr-gcc')
+    env.Replace(RANLIB='avr-ranlib')
+    if target_arch != 'avr':
+        print '''
 ************************************* Error ***********************************
 * Arduino 1.0.x IDE only support 'avr', to support other arch at least 1.5.x  *
 * is required.
 *******************************************************************************
 '''
-               Exit(1)
+        Exit(1)
 else:
-       is_1_0_x = False
-       if target_arch == 'avr':
-               boards_info = __parse_config(arduino_home + '/hardware/arduino/avr/boards.txt')
-               platform_info = __parse_config(arduino_home + '/hardware/arduino/avr/platform.txt')
-       elif target_arch == 'arm':
-               boards_info = __parse_config(arduino_home + '/hardware/arduino/sam/boards.txt')
-               platform_info = __parse_config(arduino_home + '/hardware/arduino/sam/platform.txt')
-       else:
-               print '''
+    is_1_0_x = False
+    if target_arch == 'avr':
+        boards_info = __parse_config(arduino_home +
+                                     '/hardware/arduino/avr/boards.txt')
+        platform_info = __parse_config(arduino_home +
+                                       '/hardware/arduino/avr/platform.txt')
+    elif target_arch == 'arm':
+        boards_info = __parse_config(arduino_home +
+                                     '/hardware/arduino/sam/boards.txt')
+        platform_info = __parse_config(arduino_home +
+                                       '/hardware/arduino/sam/platform.txt')
+    else:
+        print '''
 ************************************* Error ***********************************
 * CPU arch %s isn't supported currently.
 *******************************************************************************
@@ -301,7 +330,11 @@ else:
 #Board option, let user to select the board
 boards = __get_boards(boards_info)
 help_vars = Variables()
-help_vars.Add(EnumVariable('BOARD', 'arduino board', boards[0], boards))
+help_vars.Add(
+    EnumVariable('BOARD',
+                 'arduino board',
+                 boards[0],
+                 allowed_values=boards))
 help_vars.Update(env)
 Help(help_vars.GenerateHelpText(env))
 
@@ -309,10 +342,14 @@ Help(help_vars.GenerateHelpText(env))
 board = env.get('BOARD')
 cpus = __get_cpu(boards_info, board)
 if len(cpus) > 0:
-       help_vars = Variables()
-       help_vars.Add(EnumVariable('CPU', 'arduino board cpu', cpus[0], cpus))
-       help_vars.Update(env)
-       Help(help_vars.GenerateHelpText(env))
+    help_vars = Variables()
+    help_vars.Add(
+        EnumVariable('CPU',
+                     'arduino board cpu',
+                     cpus[0],
+                     allowed_values=cpus))
+    help_vars.Update(env)
+    Help(help_vars.GenerateHelpText(env))
 
 # Arduino commom flags
 cpu = env.get('CPU')
@@ -324,115 +361,140 @@ usb_pid = __get_board_info(board, '.build.pid')
 variant = __get_board_info(board, '.build.variant')
 
 if not usb_vid:
-       usb_vid = __get_board_info(board, '.vid.0')
+    usb_vid = __get_board_info(board, '.vid.0')
 if not usb_pid:
-       usb_pid = __get_board_info(board, '.pid.0')
+    usb_pid = __get_board_info(board, '.pid.0')
 
 if is_1_0_x:
-       core_base = arduino_home + '/hardware/arduino/'
+    core_base = arduino_home + '/hardware/arduino/'
 else:
-       if target_arch == 'avr':
-               core_base = arduino_home + '/hardware/arduino/avr/'
-       else:
-               core_base = arduino_home + '/hardware/arduino/sam/'
+    if target_arch == 'avr':
+        core_base = arduino_home + '/hardware/arduino/avr/'
+    else:
+        core_base = arduino_home + '/hardware/arduino/sam/'
 
 variant_folder = core_base + 'variants/' + variant
-env.AppendUnique(CPPPATH = [variant_folder])
+env.AppendUnique(CPPPATH=[variant_folder])
 
 core = __get_board_info(board, '.build.core')
 core_folder = core_base + 'cores/' + core + '/'
-env.AppendUnique(CPPPATH = [core_folder])
+env.AppendUnique(CPPPATH=[core_folder])
 
 if is_1_0_x:
-       comm_flags = ['-std=c99']
-       if mcu:
-               comm_flags.extend(['-mmcu=' + mcu])
-       if f_cpu:
-               comm_flags.extend(['-DF_CPU=' + f_cpu])
-       comm_flags.extend(['-DARDUINO=' + version])
-       if usb_vid:
-               comm_flags.extend(['-DUSB_VID=' + usb_vid])
-       if usb_pid:
-               comm_flags.extend(['-DUSB_PID=' + usb_pid])
-
-       env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
-       env.AppendUnique(ASFLAGS = comm_flags)
-
-       env.AppendUnique(CFLAGS = ['-Os', '-ffunction-sections', '-fdata-sections', '-MMD'])
-       env.AppendUnique(CFLAGS = comm_flags)
-
-       env.AppendUnique(CXXFLAGS = ['-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections','-MMD'])
-       env.AppendUnique(CXXFLAGS = comm_flags)
-
-       env.AppendUnique(LINKFLAGS = ['-Os'])
-       if mcu == 'atmega2560':
-               env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections,--relax'])
-       else:
-               env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections'])
-       env.AppendUnique(LINKFLAGS = ['-mmcu=' + mcu])
+    comm_flags = ['-std=c99']
+    if mcu:
+        comm_flags.extend(['-mmcu=' + mcu])
+    if f_cpu:
+        comm_flags.extend(['-DF_CPU=' + f_cpu])
+    comm_flags.extend(['-DARDUINO=' + version])
+    if usb_vid:
+        comm_flags.extend(['-DUSB_VID=' + usb_vid])
+    if usb_pid:
+        comm_flags.extend(['-DUSB_PID=' + usb_pid])
+
+    env.AppendUnique(ASFLAGS=['-x', 'assembler-with-cpp'])
+    env.AppendUnique(ASFLAGS=comm_flags)
+
+    env.AppendUnique(
+        CFLAGS=['-Os', '-ffunction-sections', '-fdata-sections', '-MMD'])
+    env.AppendUnique(CFLAGS=comm_flags)
+
+    env.AppendUnique(CXXFLAGS=[
+        '-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections',
+        '-MMD'
+    ])
+    env.AppendUnique(CXXFLAGS=comm_flags)
+
+    env.AppendUnique(LINKFLAGS=['-Os'])
+    if mcu == 'atmega2560':
+        env.AppendUnique(LINKFLAGS=['-Wl,--gc-sections,--relax'])
+    else:
+        env.AppendUnique(LINKFLAGS=['-Wl,--gc-sections'])
+    env.AppendUnique(LINKFLAGS=['-mmcu=' + mcu])
 else:
-       if target_arch == 'avr':
-               cpu_flag = '-mmcu=' + mcu
-       else:
-               cpu_flag = '-mcpu=' + mcu
-
-       comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')]
-       if target_arch == 'arm':
-               # As of 1.5.8 the arduino headers had asm bugs with ARM and
-               # require gnu99 to be used.
-               comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
-       else:
-               comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
-
-       compiler_path = platform_info.get('compiler.path')
-       compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
-       env.PrependENVPath('PATH', compiler_path)
-       env.Replace(CC = platform_info.get('compiler.c.cmd'))
-       env.Replace(CXX = platform_info.get('compiler.cpp.cmd'))
-       env.Replace(AR = platform_info.get('compiler.ar.cmd'))
-       if target_arch == 'arm':
-               env.AppendUnique(CPPPATH = [arduino_home + '/hardware/arduino/sam/system/libsam',
-                                                       arduino_home + '/hardware/arduino/sam/system/CMSIS/CMSIS/Include/',
-                                                       arduino_home + '/hardware/arduino/sam/system//CMSIS/Device/ATMEL'])
-       env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp'])
-       env.AppendUnique(ASFLAGS = comm_flag)
-       env.AppendUnique(CFLAGS = Split(platform_info.get('compiler.c.flags')))
-       env.AppendUnique(CXXFLAGS = Split(platform_info.get('compiler.cpp.flags')))
-       env.AppendUnique(ARFLAGS = Split(platform_info.get('compiler.ar.flags')))
-       env.AppendUnique(CCFLAGS = comm_flag)
-
-       extra_flags = __get_board_info(board, '.build.extra_flags')
-       if extra_flags:
-               extra_flags = extra_flags.replace('{build.usb_flags}', '')
-               env.AppendUnique(CCFLAGS = Split(extra_flags))
-               usb_flags = ['-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON', '-DUSB_MANUFACTURER="Unknown"']
-               env.AppendUnique(CCFLAGS = usb_flags)
-
-       if target_arch == 'arm':
-               env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag,
-                                       '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript'),
-                                       '-Wl,-Map,' + env.get('BUILD_DIR') + 'arduino_prj.map'])
-               env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'))
-
-               variant_system_lib = __get_board_info(board, '.build.variant_system_lib')
-               if variant_system_lib:
-                       if variant_folder.find(' ') >= 0:
-                               variant_folder = '"' + variant_folder + '"'
-                       env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS '
-                                       + variant_folder + '/' + variant_system_lib + ' -Wl,--end-group')
-               else:
-                       env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group')
-       else:
-               env.AppendUnique(LINKFLAGS = Split(platform_info.get('compiler.c.elf.flags')))
-               env.AppendUnique(LINKFLAGS = [cpu_flag])
-               env.AppendUnique(LIBS = 'm')
-       env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES')
+    if target_arch == 'avr':
+        cpu_flag = '-mmcu=' + mcu
+    else:
+        cpu_flag = '-mcpu=' + mcu
+
+    comm_flag = [
+        cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version,
+        '-DARDUINO_' + __get_board_info(board, '.build.board')
+    ]
+    if target_arch == 'arm':
+        # As of 1.5.8 the arduino headers had asm bugs with ARM and
+        # require gnu99 to be used.
+        comm_flag.extend(['-std=gnu99', '-DARDUINO_ARCH_SAM'])
+    else:
+        comm_flag.extend(['-std=c99', '-DARDUINO_ARCH_AVR'])
+
+    compiler_path = platform_info.get('compiler.path')
+    compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home)
+    env.PrependENVPath('PATH', compiler_path)
+    env.Replace(CC=platform_info.get('compiler.c.cmd'))
+    env.Replace(CXX=platform_info.get('compiler.cpp.cmd'))
+    env.Replace(AR=platform_info.get('compiler.ar.cmd'))
+    if target_arch == 'arm':
+        env.AppendUnique(CPPPATH=[
+            arduino_home + '/hardware/arduino/sam/system/libsam',
+            arduino_home + '/hardware/arduino/sam/system/CMSIS/CMSIS/Include/',
+            arduino_home + '/hardware/arduino/sam/system//CMSIS/Device/ATMEL'
+        ])
+    env.AppendUnique(ASFLAGS=['-x', 'assembler-with-cpp'])
+    env.AppendUnique(ASFLAGS=comm_flag)
+    env.AppendUnique(CFLAGS=Split(platform_info.get('compiler.c.flags')))
+    env.AppendUnique(CXXFLAGS=Split(platform_info.get('compiler.cpp.flags')))
+    env.AppendUnique(ARFLAGS=Split(platform_info.get('compiler.ar.flags')))
+    env.AppendUnique(CCFLAGS=comm_flag)
+
+    extra_flags = __get_board_info(board, '.build.extra_flags')
+    if extra_flags:
+        extra_flags = extra_flags.replace('{build.usb_flags}', '')
+        env.AppendUnique(CCFLAGS=Split(extra_flags))
+        usb_flags = [
+            '-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON',
+            '-DUSB_MANUFACTURER="Unknown"'
+        ]
+        env.AppendUnique(CCFLAGS=usb_flags)
+
+    if target_arch == 'arm':
+        env.AppendUnique(LINKFLAGS=[
+            '-Os', '-Wl,--gc-sections', cpu_flag,
+            '-T' + variant_folder + '/' + __get_board_info(
+                board, '.build.ldscript'),
+            '-Wl,-Map,' + env.get('BUILD_DIR') + 'arduino_prj.map'
+        ])
+        env.AppendUnique(LINKFLAGS=Split(
+            '-lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group'
+        ))
+
+        variant_system_lib = __get_board_info(board,
+                                              '.build.variant_system_lib')
+        if variant_system_lib:
+            if variant_folder.find(' ') >= 0:
+                variant_folder = '"' + variant_folder + '"'
+            env.Replace(
+                LINKCOM=
+                '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS '
+                + variant_folder + '/' + variant_system_lib +
+                ' -Wl,--end-group')
+        else:
+            env.Replace(
+                LINKCOM=
+                '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group'
+            )
+    else:
+        env.AppendUnique(
+            LINKFLAGS=Split(platform_info.get('compiler.c.elf.flags')))
+        env.AppendUnique(LINKFLAGS=[cpu_flag])
+        env.AppendUnique(LIBS='m')
+    env.Replace(ARCOM='$AR ' + platform_info.get('compiler.ar.flags') +
+                ' $TARGET $SOURCES')
 
 __build_core(env)
 
-env.AddMethod(__import_lib, "ImportLib") #import arduino library
-#env.AddMethod(__build_core, "BuildCore") #build arduino core
-env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
-env.AddMethod(__upload, "Upload") #Upload binary to board
-env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf
-
+env.AddMethod(__import_lib, "ImportLib")  # import arduino library
+#env.AddMethod(__build_core, "BuildCore")  # build arduino core
+env.AddMethod(__create_bin, "CreateBin")  # create binary files (.eep and .hex)
+env.AddMethod(__upload, "Upload")  # Upload binary to board
+env.AddMethod(__upload_help, "UploadHelp")  # print cmdline to upload binary
index 4c13ebd..ef747f5 100644 (file)
@@ -6,24 +6,31 @@ Import('env')
 # Add 'SHIELD' build option, let user select board network connection type
 vars = Variables()
 if 'IP' in env.get('TARGET_TRANSPORT'):
-       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'WIFI', ['ETH', 'WIFI']))
+    vars.Add(
+        EnumVariable('SHIELD',
+                     'Network connection type',
+                     'WIFI',
+                     allowed_values=['ETH', 'WIFI']))
 elif 'BLE' in env.get('TARGET_TRANSPORT'):
-       vars.Add(EnumVariable('SHIELD', 'Network connection type', 'RBL_NRF8001', ['RBL_NRF8001']))
+    vars.Add(
+        EnumVariable('SHIELD',
+                     'Network connection type',
+                     'RBL_NRF8001',
+                     allowed_values=['RBL_NRF8001']))
 vars.Update(env)
 Help(vars.GenerateHelpText(env))
 
 env.ImportLib('SPI')
 if 'ETH' in env.get('SHIELD'):
-       env.ImportLib('Ethernet')
+    env.ImportLib('Ethernet')
 if 'WIFI' in env.get('SHIELD'):
-       env.ImportLib('WiFi')
+    env.ImportLib('WiFi')
 if 'RBL_NRF8001' in env.get('SHIELD'):
-       env.ImportLib('BLE')
-       env.ImportLib('RBL_nRF8001')
+    env.ImportLib('BLE')
+    env.ImportLib('RBL_nRF8001')
 
 env.ImportLib('Time/Time')
 # we have variety of macros for arduino!!
-env.AppendUnique(CPPDEFINES = ['WITH_ARDUINO', '__ARDUINO__'])
+env.AppendUnique(CPPDEFINES=['WITH_ARDUINO', '__ARDUINO__'])
 if env.get('LOGGING'):
-       env.AppendUnique(CPPDEFINES = ['TB_LOG'])
-
+    env.AppendUnique(CPPDEFINES=['TB_LOG'])
index 48e8dc6..181416b 100644 (file)
@@ -9,30 +9,30 @@ print "Reading linux configuration script"
 
 # Set release/debug flags
 if env.get('RELEASE'):
-       env.AppendUnique(CCFLAGS = ['-Os'])
-       env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+    env.AppendUnique(CCFLAGS=['-Os'])
+    env.AppendUnique(CPPDEFINES=['NDEBUG'])
 else:
-       env.AppendUnique(CCFLAGS = ['-g'])
+    env.AppendUnique(CCFLAGS=['-g'])
 
 if env.get('LOGGING'):
-    env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+    env.AppendUnique(CPPDEFINES=['TB_LOG'])
 
-env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__'])
-env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
-env.AppendUnique(LIBS = ['dl', 'pthread'])
+env.AppendUnique(CPPDEFINES=['WITH_POSIX', '__linux__'])
+env.AppendUnique(CCFLAGS=['-Wall', '-fPIC'])
+env.AppendUnique(LIBS=['dl', 'pthread'])
 
 # Set arch flags
 if not env.get('WITH_ENV'):
     target_arch = env.get('TARGET_ARCH')
     if target_arch in ['x86']:
-        env.AppendUnique(CCFLAGS = ['-m32'])
-        env.AppendUnique(LINKFLAGS = ['-m32'])
+        env.AppendUnique(CCFLAGS=['-m32'])
+        env.AppendUnique(LINKFLAGS=['-m32'])
     elif target_arch in ['x86_64']:
-        env.AppendUnique(CCFLAGS = ['-m64'])
-        env.AppendUnique(LINKFLAGS = ['-m64'])
+        env.AppendUnique(CCFLAGS=['-m64'])
+        env.AppendUnique(LINKFLAGS=['-m64'])
     elif target_arch in ['arm']:
-        env.AppendUnique(CPPFLAGS = ['-march=armv5te'])
+        env.AppendUnique(CPPFLAGS=['-march=armv5te'])
     elif target_arch in ['arm-v7a', 'armeabi-v7a']:
-        env.AppendUnique(CPPFLAGS = ['-march=armv7-a'])
+        env.AppendUnique(CPPFLAGS=['-march=armv7-a'])
     elif target_arch.find('arm64') > 0:
-        env.AppendUnique(CPPFLAGS = ['-march=armv8-a'])
+        env.AppendUnique(CPPFLAGS=['-march=armv8-a'])
index 287ec5f..10f5e06 100644 (file)
@@ -21,7 +21,7 @@ LIBCOAP_OBJ_DIR=./lib/libcoap-4.1.1/obj
 # TODO : Currently Hardcoded WIFI_ADAPTER. Change it to generic
 CFLAGS.debug = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -g -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
 CFLAGS.release = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
-COMPILEFLAG = `pkg-config --cflags --libs capi-network-wifi dlog ttrace capi-network-bluetooth glib-2.0`
+COMPILEFLAG = `pkg-config --cflags --libs dlog ttrace capi-network-bluetooth glib-2.0`
 
 # Include files will be copied into a single folder on gbsbuild.
 # NO NEED to mention the path explicitly.
index 57a4e90..0e9b7ed 100644 (file)
@@ -18,7 +18,8 @@ print "Given Transport is %s" % transport
 print "Given OS is %s" % target_os
 
 if target_os == 'tizen':
-       command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging, with_tcp)
-       print "Created Command is %s" % command
-       gbs_script = env.Command('gbs_build', None, command)
-       AlwaysBuild ('gbs_script')
\ No newline at end of file
+    command = "./resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s %s" % (
+        transport, secured, buildsample, release_mode, logging, with_tcp)
+    print "Created Command is %s" % command
+    gbs_script = env.Command('gbs_build', None, command)
+    AlwaysBuild('gbs_script')
index 2a25872..082ea7f 100644 (file)
@@ -10,24 +10,25 @@ print "Reading common folder script"
 target_os = connectivity_env.get('TARGET_OS')
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.AppendUnique(CPPPATH = [
-    '#resource/c_common/octhread/include/',
-    '#resource/csdk/connectivity/common/inc/',
-    '#resource/csdk/logger/include/',
-    ])
+connectivity_env.AppendUnique(CPPPATH=[
+    '#/resource/c_common/octhread/include/',
+    '#/resource/csdk/connectivity/common/inc/',
+    '#/resource/csdk/logger/include/',
+])
 
 ######################################################################
 # Source files
 ######################################################################
 ca_common_src_path = os.path.join(src_dir, 'src')
 ca_common_src = [
-        os.path.join(ca_common_src_path, 'uarraylist.c'),
-        os.path.join(ca_common_src_path, 'ulinklist.c'),
-        os.path.join(ca_common_src_path, 'uqueue.c'),
-        os.path.join(ca_common_src_path, 'caremotehandler.c')
-    ]
+    os.path.join(ca_common_src_path, 'uarraylist.c'),
+    os.path.join(ca_common_src_path, 'ulinklist.c'),
+    os.path.join(ca_common_src_path, 'uqueue.c'),
+    os.path.join(ca_common_src_path, 'caremotehandler.c')
+]
 
 if connectivity_env['POSIX_SUPPORTED'] or target_os in ['windows']:
-    ca_common_src.append(os.path.join(ca_common_src_path, 'cathreadpool_pthreads.c'))
+    ca_common_src.append(
+        os.path.join(ca_common_src_path, 'cathreadpool_pthreads.c'))
 
-connectivity_env.AppendUnique(CA_SRC = ca_common_src)
+connectivity_env.AppendUnique(CA_SRC=ca_common_src)
index 8ef9d52..5ff2b31 100644 (file)
@@ -119,6 +119,8 @@ CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
         case CA_REQUEST_ENTITY_INCOMPLETE:
         case CA_REQUEST_ENTITY_TOO_LARGE:
         case CA_INTERNAL_SERVER_ERROR:
+        case CA_BAD_GATEWAY:
+        case CA_SERVICE_UNAVAILABLE:
         case CA_RETRANSMIT_TIMEOUT:
             break;
         default:
index 56c3e5a..6d24968 100644 (file)
@@ -43,16 +43,21 @@ extern "C"
 #ifdef SINGLE_THREAD
 /**
  * Initializes different adapters based on the compilation flags.
+ *
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-void CAInitializeAdapters();
+CAResult_t CAInitializeAdapters();
 #else
 /**
  * Initializes different adapters based on the compilation flags.
  * @param[in]   handle           thread pool handle created by message handler
  *                               for different adapters.
  * @param[in]   transportType    transport type to initialize.
+ *
+ * @return  ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transportType);
+
+CAResult_t CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transportType);
 #endif
 
 /**
@@ -101,6 +106,13 @@ CAResult_t CAStartAdapter(CATransportAdapter_t transportType);
  */
 void CAStopAdapter(CATransportAdapter_t transportType);
 
+#ifndef SINGLE_THREAD
+/**
+ * Stop connectivity adapters all.
+ */
+void CAStopAdapters();
+#endif //SINGLE_THREAD
+
 #ifdef RA_ADAPTER
 /**
  * Set Remote Access information for XMPP Client.
index 78d5efb..b38108e 100644 (file)
@@ -9,7 +9,7 @@ ca_os = connectivity_env.get('TARGET_OS')
 ca_transport = connectivity_env.get('TARGET_TRANSPORT')
 secured = connectivity_env.get('SECURED')
 multiple_owner = connectivity_env.get('MULTIPLE_OWNER')
-with_ra = connectivity_env.get ('WITH_RA')
+with_ra = connectivity_env.get('WITH_RA')
 with_ra_ibb = connectivity_env.get('WITH_RA_IBB')
 with_tcp = connectivity_env.get('WITH_TCP')
 src_dir = connectivity_env.get('SRC_DIR')
@@ -20,61 +20,76 @@ ca_path = os.curdir
 # Source files and Target(s)
 ######################################################################
 
-print"Reading ca script %s"%ca_transport
+print "Reading ca script %s" % ca_transport
 
-connectivity_env.PrependUnique(CPPPATH = [ os.path.join(root_dir, 'api') ])
+connectivity_env.PrependUnique(CPPPATH=[os.path.join(root_dir, 'api')])
 
 with_upstream_libcoap = connectivity_env.get('WITH_UPSTREAM_LIBCOAP')
 if with_upstream_libcoap == '1':
-    connectivity_env.AppendUnique(CPPPATH = [os.path.join('#extlibs', 'libcoap', 'libcoap', 'include')])
+    connectivity_env.AppendUnique(
+        CPPPATH=[os.path.join('#extlibs', 'libcoap', 'libcoap', 'include')])
 else:
-    connectivity_env.AppendUnique(CPPPATH = [ os.path.join('#resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1', 'include')])
+    connectivity_env.AppendUnique(CPPPATH=[
+        os.path.join('#resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1', 'include')
+    ])
 
-connectivity_env.AppendUnique(CPPPATH = [
-        os.path.join(root_dir, 'inc'),
-        os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),
-        os.path.join(root_dir, 'common', 'inc'),
-        os.path.join(root_dir, 'util', 'inc'),
-        ])
+connectivity_env.AppendUnique(CPPPATH=[
+    os.path.join(root_dir, 'inc'),
+    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 ['darwin', 'ios', 'windows']:
-    connectivity_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+    connectivity_env.AppendUnique(LINKFLAGS=['-Wl,--no-undefined'])
 
 # Getting common source files
-connectivity_env.SConscript(os.path.join(root_dir, 'common', 'SConscript'), exports = 'connectivity_env')
+connectivity_env.SConscript(root_dir + '/common/SConscript',
+                            exports='connectivity_env')
 
 # Getting util source files
-connectivity_env.SConscript(os.path.join(root_dir, 'util', 'SConscript'), exports = 'connectivity_env')
+connectivity_env.SConscript(root_dir + '/util/SConscript',
+                            exports='connectivity_env')
 
 build_dir = connectivity_env.get('BUILD_DIR')
 
-connectivity_env.AppendUnique(CA_SRC = [os.path.join(ca_path,'adapter_util/caadapterutils.c')])
+connectivity_env.AppendUnique(
+    CA_SRC=[os.path.join(ca_path, 'adapter_util/caadapterutils.c')])
 
 if (('BLE' in ca_transport) or ('ALL' in ca_transport)):
-    connectivity_env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'adapter_util/cafragmentation.c')])
+    connectivity_env.AppendUnique(
+        CA_SRC=[os.path.join(ca_path, 'adapter_util/cafragmentation.c')])
 
 # Build mbedtls as ocstack uses hash functions from mbedcrypto.lib.
-tls_path = 'extlibs/mbedtls';
-tls_headers_path = 'mbedtls/include';
+tls_path = 'extlibs/mbedtls'
+tls_headers_path = 'mbedtls/include'
 if ca_os == 'tizen' and os.path.exists(root_dir + '/' + tls_path):
-    connectivity_env.SConscript(os.path.join(root_dir, tls_path + '/SConscript'))
-    connectivity_env.AppendUnique(CPPPATH = [os.path.join(root_dir, tls_path + '/' + tls_headers_path)])
+    connectivity_env.SConscript(
+        os.path.join(root_dir, tls_path + '/SConscript'))
+    connectivity_env.AppendUnique(
+        CPPPATH=[os.path.join(root_dir, tls_path + '/' + tls_headers_path)])
 else:
     if ca_os != 'android':
         connectivity_env.SConscript('#' + tls_path + '/SConscript')
-    connectivity_env.AppendUnique(CPPPATH = ['#' + tls_path + '/' + tls_headers_path])
+    connectivity_env.AppendUnique(
+        CPPPATH=['#' + tls_path + '/' + tls_headers_path])
 
 if connectivity_env.get('SECURED') == '1':
-    connectivity_env.AppendUnique(CPPPATH = ['#/resource/c_common/octimer/include'])
-    connectivity_env.AppendUnique(CPPPATH = [src_dir + '/resource/csdk/security/include'])
-    connectivity_env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'external/inc')])
+    connectivity_env.AppendUnique(
+        CPPPATH=['#/resource/c_common/octimer/include'])
+    connectivity_env.AppendUnique(
+        CPPPATH=[src_dir + '/resource/csdk/security/include'])
+    connectivity_env.AppendUnique(
+        CPPPATH=[os.path.join(root_dir, 'external/inc')])
     if ca_os != 'tizen' or os.path.exists(root_dir + '/' + tls_path) == False:
-        connectivity_env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'adapter_util/ca_adapter_net_ssl.c')])
+        connectivity_env.AppendUnique(CA_SRC=[
+            os.path.join(ca_path, 'adapter_util/ca_adapter_net_ssl.c')
+        ])
 
 ca_common_src = None
 
 if with_ra_ibb:
-    connectivity_env.SConscript('#extlibs/wksxmppxep/SConscript')
+    connectivity_env.SConscript('#/extlibs/wksxmppxep/SConscript')
 
 if ca_os == 'arduino':
     print "setting WITH_ARDUINO"
@@ -85,7 +100,7 @@ if ca_os == 'arduino':
         'canetworkconfigurator.c',
         'caprotocolmessage.c',
         'caretransmission.c',
-        ]
+    ]
 else:
     ca_common_src = [
         'caconnectivitymanager.c',
@@ -95,14 +110,14 @@ else:
         'caprotocolmessage.c',
         'caqueueingthread.c',
         'caretransmission.c',
-        ]
+    ]
     if (('IP' in ca_transport) or ('ALL' in ca_transport)):
-        connectivity_env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'cablockwisetransfer.c') ])
+        connectivity_env.AppendUnique(
+            CA_SRC=[os.path.join(ca_path, 'cablockwisetransfer.c')])
 
-ca_common_src = [
-        os.path.join(ca_path, d) for d in ca_common_src ]
+ca_common_src = [os.path.join(ca_path, d) for d in ca_common_src]
 
-connectivity_env.AppendUnique(CA_SRC = ca_common_src)
+connectivity_env.AppendUnique(CA_SRC=ca_common_src)
 
 transports = set()
 if 'ALL' in ca_transport:
@@ -121,15 +136,16 @@ if 'ALL' in ca_transport:
         transports.add('bt_edr_adapter')
         transports.add('bt_le_adapter')
         transports.add('nfc_adapter')
-    elif ca_os in['darwin','ios', 'msys_nt', 'windows']:
+    elif ca_os in ['darwin', 'ios', 'msys_nt', 'windows']:
         transports.add('ip_adapter')
     else:
         transports.add('ip_adapter')
         transports.add('bt_edr_adapter')
         transports.add('bt_le_adapter')
 
-    connectivity_env.SConscript(dirs = [
-        os.path.join(ca_path, d) for d in transports ], exports = 'connectivity_env')
+    connectivity_env.SConscript(
+        dirs=[os.path.join(ca_path, d) for d in transports],
+        exports='connectivity_env')
 
 if 'IP' in ca_transport:
     transports.add('ip_adapter')
@@ -148,30 +164,35 @@ if 'NFC' in ca_transport:
 if ca_os in ['linux', 'tizen', 'android', 'ios', 'windows'] and with_tcp:
     transports.add('tcp_adapter')
 
-SConscript(dirs = list(transports), exports='connectivity_env')
+SConscript(dirs=list(transports), exports='connectivity_env')
 
 if ca_os == 'android':
-    connectivity_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libca-interface.so'])
-    connectivity_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libconnectivity_abstraction.so'])
+    connectivity_env.AppendUnique(LINKFLAGS=['-Wl,-soname,libca-interface.so'])
+    connectivity_env.AppendUnique(
+        LINKFLAGS=['-Wl,-soname,libconnectivity_abstraction.so'])
 
 if connectivity_env.get('SECURED') == '1':
-    connectivity_env.AppendUnique(LIBS = ['mbedtls','mbedx509'])
+    connectivity_env.AppendUnique(LIBS=['mbedtls', 'mbedx509'])
 
 # c_common calls into mbedcrypto.
-connectivity_env.AppendUnique(LIBS = ['mbedcrypto'])
+connectivity_env.AppendUnique(LIBS=['mbedcrypto'])
 
-calib_internal = connectivity_env.StaticLibrary('connectivity_abstraction_internal', connectivity_env.get('CA_SRC'))
+calib_internal = connectivity_env.StaticLibrary(
+    'connectivity_abstraction_internal', connectivity_env.get('CA_SRC'))
 calib = Flatten(calib_internal)
 
 if ca_os in ['android', 'tizen', 'linux', 'yocto']:
-    connectivity_env.AppendUnique(LIBS = ['coap'])
+    connectivity_env.AppendUnique(LIBS=['coap'])
     if ca_os != 'android':
-        connectivity_env.AppendUnique(LIBS = ['rt'])
-    static_calib = connectivity_env.StaticLibrary('connectivity_abstraction', connectivity_env.get('CA_SRC'))
-    shared_calib = connectivity_env.SharedLibrary('connectivity_abstraction', connectivity_env.get('CA_SRC'))
+        connectivity_env.AppendUnique(LIBS=['rt'])
+    static_calib = connectivity_env.StaticLibrary(
+        'connectivity_abstraction', connectivity_env.get('CA_SRC'))
+    shared_calib = connectivity_env.SharedLibrary(
+        'connectivity_abstraction', connectivity_env.get('CA_SRC'))
     calib += Flatten([static_calib, shared_calib])
 elif ca_os not in ['msys_nt', 'windows']:
-    static_calib = connectivity_env.StaticLibrary('connectivity_abstraction', connectivity_env.get('CA_SRC'))
+    static_calib = connectivity_env.StaticLibrary(
+        'connectivity_abstraction', connectivity_env.get('CA_SRC'))
     calib += Flatten(static_calib)
 
 connectivity_env.InstallTarget(calib, 'connectivity_abstraction')
index 56bb853..b015a38 100644 (file)
@@ -1334,15 +1334,25 @@ static int InitPskIdentity(mbedtls_ssl_config * config)
     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
     return 0;
 }
-static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter,
+
+/**
+ * Select cipher suites for use with (D)TLS based on the credentials available.
+ *
+ * @param[in]  config     the (D)TLS configuration object
+ * @param[in]  adapter    the associated transport adapter
+ * @param[in]  deviceId   the device ID of the peer we will connect to
+ *
+ * @return  true on success or false on error
+ */
+static bool SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter,
                         const char* deviceId)
 {
     int index = 0;
     OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
 
-    VERIFY_NON_NULL_VOID(config, NET_SSL_TAG, "Invaild param");
-    VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL");
-    VERIFY_NON_NULL_VOID(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null");
+    VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Invailid param", false);
+    VERIFY_NON_NULL_RET(g_caSslContext, NET_SSL_TAG, "SSL Context is NULL", false);
+    VERIFY_NON_NULL_RET(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null", false);
 
     //Resetting cipherFlag
     g_caSslContext->cipherFlag[0] = false;
@@ -1351,7 +1361,8 @@ static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapte
     if (NULL == g_getCredentialTypesCallback)
     {
         OIC_LOG(ERROR, NET_SSL_TAG, "Param callback is null");
-        return;
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return false;
     }
 
     g_getCredentialTypesCallback(g_caSslContext->cipherFlag, deviceId);
@@ -1361,6 +1372,7 @@ static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapte
          true == g_caSslContext->cipherFlag[0]) && 0 != InitPskIdentity(config))
     {
         OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
+        /* Don't return error, the connection may work with another cred type */
     }
 
     // Retrieve the Cert credential from SRM
@@ -1370,6 +1382,7 @@ static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapte
         if (0 != ret)
         {
             OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
+            /* Don't return error, the connection may work with another cred type */
         }
     }
 
@@ -1414,7 +1427,15 @@ static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapte
 
     mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
 
+    if (0 == index)
+    {
+        OIC_LOG_V(ERROR, NET_SSL_TAG, "No ciphersuites configured, secure connections will fail");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return false;
+    }
+
     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return true;
 }
 /**
  * Initiate TLS handshake with endpoint.
@@ -1443,7 +1464,12 @@ static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
     }
 
     //Load allowed SVR suites from SVR DB
-    SetupCipher(config, endpoint->adapter, endpoint->remoteId);
+    if(!SetupCipher(config, endpoint->adapter, endpoint->remoteId))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Failed to set up cipher");
+        DeleteSslEndPoint(tep);
+        return NULL;
+    }
 
     oc_mutex_lock(g_sslContextMutex);
     ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
@@ -1586,11 +1612,12 @@ static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
 /**
  * Starts DTLS retransmission.
  */
-static void StartRetransmit()
+static void StartRetransmit(void *ctx)
 {
     size_t listIndex = 0;
     size_t listLength = 0;
     SslEndPoint_t *tep = NULL;
+    OC_UNUSED(ctx);
 
     oc_mutex_lock(g_sslContextMutex);
     if (NULL == g_caSslContext)
@@ -1620,7 +1647,7 @@ static void StartRetransmit()
             if (MBEDTLS_ERR_SSL_CONN_EOF != ret)
             {
                 //start new timer
-                registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit);
+                registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit, NULL);
                 //unlock & return
                 if (!checkSslOperation(tep,
                                        ret,
@@ -1634,7 +1661,7 @@ static void StartRetransmit()
         }
     }
     //start new timer
-    registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit);
+    registerTimer(RETRANSMISSION_TIME, &g_caSslContext->timerId, StartRetransmit, NULL);
     oc_mutex_unlock(g_sslContextMutex);
 }
 #endif
@@ -1779,7 +1806,7 @@ CAResult_t CAinitSslAdapter()
 
    oc_mutex_unlock(g_sslContextMutex);
 #ifdef __WITH_DTLS__
-    StartRetransmit();
+    StartRetransmit(NULL);
 #endif
 
     OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
@@ -2009,7 +2036,13 @@ CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, size_t dat
             return CA_STATUS_FAILED;
         }
         //Load allowed TLS suites from SVR DB
-        SetupCipher(config, sep->endpoint.adapter, NULL);
+        if(!SetupCipher(config, sep->endpoint.adapter, NULL))
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Failed to set up cipher");
+            DeleteSslEndPoint(peer);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
 
         ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
         if (!ret)
index 29474f7..cac9105 100644 (file)
@@ -1,5 +1,5 @@
 #######################################################
-#      Build BT EDR adapter
+# Build BT EDR adapter
 #######################################################
 
 Import('connectivity_env')
@@ -12,7 +12,8 @@ src_dir = os.path.abspath(os.curdir)
 
 # Source files to build common for all platforms
 if target_os != 'arduino':
-    connectivity_env.AppendUnique(CA_SRC = [os.path.join(src_dir, 'caedradapter.c')])
+    connectivity_env.AppendUnique(
+        CA_SRC=[os.path.join(src_dir, 'caedradapter.c')])
 
 # Check for the existence of the platform-specific SConscript file
 # relative to the top-level source directory, not the build (variant)
index 8293f4c..e6fb0f9 100644 (file)
@@ -7,11 +7,13 @@ Import('connectivity_env')
 
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.PrependUnique(CPPPATH = [ src_dir ])
+connectivity_env.PrependUnique(CPPPATH=[src_dir])
 
-src_files = [ os.path.join(src_dir, 'caedrclient.c'),
-              os.path.join(src_dir, 'caedrutils.c'),
-              os.path.join(src_dir, 'caedrnwmonitor.c'),
-              os.path.join(src_dir, 'caedrserver.c'), ]
+src_files = [
+    os.path.join(src_dir, 'caedrclient.c'),
+    os.path.join(src_dir, 'caedrutils.c'),
+    os.path.join(src_dir, 'caedrnwmonitor.c'),
+    os.path.join(src_dir, 'caedrserver.c'),
+]
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
index 1621326..af5ca46 100644 (file)
@@ -7,15 +7,18 @@ Import('connectivity_env')
 
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.PrependUnique(CPPPATH = [ src_dir ])
+connectivity_env.PrependUnique(CPPPATH=[src_dir])
 
-connectivity_env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+connectivity_env.ParseConfig(
+    "pkg-config --cflags --libs capi-network-bluetooth")
 
-src_files = [ os.path.join(src_dir, 'caedrclient.c'),
-              os.path.join(src_dir, 'caedrdevicelist.c'),
-              os.path.join(src_dir, 'caedrendpoint.c'),
-              os.path.join(src_dir, 'caedrnwmonitor.c'),
-              os.path.join(src_dir, 'caedrserver.c'),
-              os.path.join(src_dir, 'caedrutils.c') ]
+src_files = [
+    os.path.join(src_dir, 'caedrclient.c'),
+    os.path.join(src_dir, 'caedrdevicelist.c'),
+    os.path.join(src_dir, 'caedrendpoint.c'),
+    os.path.join(src_dir, 'caedrnwmonitor.c'),
+    os.path.join(src_dir, 'caedrserver.c'),
+    os.path.join(src_dir, 'caedrutils.c')
+]
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
index d73d6c2..0f5ff90 100644 (file)
@@ -12,12 +12,13 @@ target_os = connectivity_env.get('TARGET_OS')
 print "Reading BLE adapter script for", target_os
 
 # Source files common to all platforms.
-connectivity_env.AppendUnique(CA_SRC = [ os.path.join(src_dir, 'caleadapter.c') ])
+connectivity_env.AppendUnique(CA_SRC=[os.path.join(src_dir, 'caleadapter.c')])
 
 # Check for the existence of the platform-specific SConscript file
 # relative to the top-level source directory, not the build (variant)
 # directory, before calling that SConscript file to prevent a missing
 # file warning platforms that don't provide one.
-target_sconscript = File(os.path.join(target_os, 'SConscript')).srcnode().abspath
+target_sconscript = File(
+    os.path.join(target_os, 'SConscript')).srcnode().abspath
 if os.path.exists(target_sconscript):
     SConscript(target_sconscript, exports='connectivity_env')
index 7d71ac7..57eb5d9 100644 (file)
@@ -7,12 +7,14 @@ Import('connectivity_env')
 
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.PrependUnique(CPPPATH = [ src_dir ])
+connectivity_env.PrependUnique(CPPPATH=[src_dir])
 
-src_files = [ os.path.join(src_dir, 'caleclient.c'),
-              os.path.join(src_dir, 'caleserver.c'),
-              os.path.join(src_dir, 'calenwmonitor.c'),
-              os.path.join(src_dir, 'caleutils.c'),
-              os.path.join(src_dir, 'calestate.c') ]
+src_files = [
+    os.path.join(src_dir, 'caleclient.c'),
+    os.path.join(src_dir, 'caleserver.c'),
+    os.path.join(src_dir, 'calenwmonitor.c'),
+    os.path.join(src_dir, 'caleutils.c'),
+    os.path.join(src_dir, 'calestate.c')
+]
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
index e93464a..0889ec7 100644 (file)
@@ -7,10 +7,12 @@ Import('connectivity_env')
 
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.PrependUnique(CPPPATH = [ src_dir ])
+connectivity_env.PrependUnique(CPPPATH=[src_dir])
 
-src_files = [ os.path.join(src_dir, 'cableserver.cpp'),
-              os.path.join(src_dir, 'cablenwmonitor.cpp'),
-              os.path.join(src_dir, 'cableclient.cpp')]
+src_files = [
+    os.path.join(src_dir, 'cableserver.cpp'),
+    os.path.join(src_dir, 'cablenwmonitor.cpp'),
+    os.path.join(src_dir, 'cableclient.cpp')
+]
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
index 0e5273a..97761c9 100644 (file)
@@ -1243,7 +1243,10 @@ static void CALEServerSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1284,7 +1287,10 @@ static void CALEServerSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateHeader failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1297,7 +1303,10 @@ static void CALEServerSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1322,7 +1331,10 @@ static void CALEServerSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "Making data segment failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1343,11 +1355,13 @@ static void CALEServerSendDataThread(void *threadData)
                       CALEADAPTER_TAG,
                       "Update characteristics failed, result [%d]",
                       result);
-
-            g_errorHandler(bleData->remoteEndpoint,
-                           bleData->data,
-                           bleData->dataLen,
-                           result);
+            if (g_errorHandler)
+            {
+                g_errorHandler(bleData->remoteEndpoint,
+                               bleData->data,
+                               bleData->dataLen,
+                               result);
+            }
             return;
         }
 
@@ -1366,7 +1380,10 @@ static void CALEServerSendDataThread(void *threadData)
         {
             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                       "CAGenerateHeader failed, result [%d]", result);
-            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+            if (g_errorHandler)
+            {
+                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+            }
             return;
         }
 
@@ -1385,7 +1402,10 @@ static void CALEServerSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                             "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
 
@@ -1399,7 +1419,10 @@ static void CALEServerSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                             "Update characteristics failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
@@ -1422,7 +1445,10 @@ static void CALEServerSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                             "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
 
@@ -1437,10 +1463,13 @@ static void CALEServerSendDataThread(void *threadData)
                           CALEADAPTER_TAG,
                           "Update characteristics failed, result [%d]",
                           result);
-                g_errorHandler(bleData->remoteEndpoint,
-                               bleData->data,
-                               bleData->dataLen,
-                               result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint,
+                                   bleData->data,
+                                   bleData->dataLen,
+                                   result);
+                }
                 return;
             }
             OIC_LOG_V(DEBUG,
@@ -1451,111 +1480,8 @@ static void CALEServerSendDataThread(void *threadData)
      }
     else
     {
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
-#if defined(__TIZEN__)
-        // @todo
-        // tizen ble should also disabled when Tizen 3.0 is updated.
-        result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
-                      result);
-            CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-            return;
-        }
-
-        result = CAGenerateHeader(dataHeader,
-                                  CA_BLE_PACKET_NOT_START,
-                                  g_localBLESourcePort,
-                                  secureFlag,
-                                  CA_BLE_MULTICAST_PORT);
-
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                      "CAGenerateHeader failed, result [%d]", result);
-            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-            return;
-        }
-        OIC_LOG_V(DEBUG,
-                  CALEADAPTER_TAG,
-                  "Server Sent Multicast First Data - data length [%zu]",
-                  length);
-
-        for (index = 0; index < iter; index++)
-        {
-            // Send the remaining header.
-            result = CAMakeRemainDataSegment(dataSegment,
-                                             CA_BLE_NORMAL_SEGMENT_PAYLOAD_SIZE,
-                                             bleData->data,
-                                             bleData->dataLen,
-                                             index,
-                                             dataHeader);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                            "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-                return;
-            }
-
-            result = CAUpdateCharacteristicsToAllGattClients(
-                         dataSegment,
-                         CA_SUPPORTED_BLE_MTU_SIZE);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
-                          result);
-                CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-                return;
-            }
-            OIC_LOG_V(DEBUG,
-                      CALEADAPTER_TAG,
-                      "Server Sent Multicast %d Data - data length [%zu]",
-                      index + 1,
-                      CA_SUPPORTED_BLE_MTU_SIZE);
-        }
-
-        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
-        {
-            // send the last segment of the data (Ex: 22 bytes of 622
-            // bytes of data when MTU is 200)
-            result = CAMakeRemainDataSegment(dataSegment,
-                                             remainingLen,
-                                             bleData->data,
-                                             bleData->dataLen,
-                                             index,
-                                             dataHeader);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                            "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-                return;
-            }
-
-            result = CAUpdateCharacteristicsToAllGattClients(
-                         dataSegment,
-                         remainingLen + CA_BLE_HEADER_SIZE);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
-                          result);
-                CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-                return;
-            }
-            OIC_LOG_V(DEBUG,
-                      CALEADAPTER_TAG,
-                      "Server Sent Multicast Last Data - data length [%" PRIuPTR "]",
-                      remainingLen + CA_BLE_HEADER_SIZE);
-        }
-#else
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast Data");
         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
-#endif
     }
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
@@ -1592,11 +1518,13 @@ static void CALEClientSendDataThread(void *threadData)
                       CALEADAPTER_TAG,
                       "CALEClientSendNegotiationMessage has failed, result [%d]",
                       res);
-
-            g_errorHandler(bleData->remoteEndpoint,
-                           bleData->data,
-                           bleData->dataLen,
-                           res);
+            if (g_errorHandler)
+            {
+                g_errorHandler(bleData->remoteEndpoint,
+                               bleData->data,
+                               bleData->dataLen,
+                               res);
+            }
             return;
         }
     }
@@ -1619,7 +1547,10 @@ static void CALEClientSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateVariableForFragmentation failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1655,7 +1586,10 @@ static void CALEClientSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateHeader failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1668,7 +1602,10 @@ static void CALEClientSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "CAGenerateHeaderPayloadLength failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1693,7 +1630,10 @@ static void CALEClientSendDataThread(void *threadData)
     {
         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                   "Making data segment failed, result [%d]", result);
-        g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        if (g_errorHandler)
+        {
+            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+        }
         return;
     }
 
@@ -1717,10 +1657,13 @@ static void CALEClientSendDataThread(void *threadData)
                       CALEADAPTER_TAG,
                       "Update characteristics failed, result [%d]",
                       result);
-            g_errorHandler(bleData->remoteEndpoint,
-                           bleData->data,
-                           bleData->dataLen,
-                           result);
+            if (g_errorHandler)
+            {
+                g_errorHandler(bleData->remoteEndpoint,
+                               bleData->data,
+                               bleData->dataLen,
+                               result);
+            }
             return;
         }
         OIC_LOG_V(DEBUG,
@@ -1738,7 +1681,10 @@ static void CALEClientSendDataThread(void *threadData)
         {
             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                       "CAGenerateHeader failed, result [%d]", result);
-            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+            if (g_errorHandler)
+            {
+                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+            }
             return;
         }
 
@@ -1756,7 +1702,10 @@ static void CALEClientSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                             "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
 
@@ -1773,7 +1722,10 @@ static void CALEClientSendDataThread(void *threadData)
                           CALEADAPTER_TAG,
                           "Update characteristics failed, result [%d]",
                           result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
             OIC_LOG_V(DEBUG,
@@ -1799,7 +1751,10 @@ static void CALEClientSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
                             "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
 
@@ -1813,7 +1768,10 @@ static void CALEClientSendDataThread(void *threadData)
             {
                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
                                                    result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                if (g_errorHandler)
+                {
+                    g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
+                }
                 return;
             }
             OIC_LOG_V(DEBUG,
@@ -1824,114 +1782,8 @@ static void CALEClientSendDataThread(void *threadData)
     }
     else
     {
-#if defined(__TIZEN__)
-        // @todo
-        // tizen ble should also disabled when Tizen 3.0 is updated.
-        //Sending Mulitcast Data
-        // Send the first segment with the header.
-        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast Data");
-        result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                      "Update characteristics (all) failed, result [%d]", result);
-            CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-            return;
-        }
-
-        result = CAGenerateHeader(dataHeader,
-                                  CA_BLE_PACKET_NOT_START,
-                                  g_localBLESourcePort,
-                                  secureFlag,
-                                  0);
-
-        if (CA_STATUS_OK != result)
-        {
-            OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                      "CAGenerateHeader failed, result [%d]", result);
-            g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-            return;
-        }
-        OIC_LOG_V(DEBUG,
-                  CALEADAPTER_TAG,
-                  "Client Sent Multicast First Data - data length [%zu]",
-                  length);
-
-        for (index = 0; index < iter; index++)
-        {
-            // Send the remaining header.
-            result = CAMakeRemainDataSegment(dataSegment,
-                                             CA_BLE_NORMAL_SEGMENT_PAYLOAD_SIZE,
-                                             bleData->data,
-                                             bleData->dataLen,
-                                             index,
-                                             dataHeader);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                            "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-                return;
-            }
-
-            result = CAUpdateCharacteristicsToAllGattServers(
-                         dataSegment,
-                         CA_SUPPORTED_BLE_MTU_SIZE);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
-                          result);
-                CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-                return;
-            }
-            OIC_LOG_V(DEBUG,
-                      CALEADAPTER_TAG,
-                      "Client Sent Multicast %d Data - data length [%zu]",
-                      index + 1,
-                      CA_SUPPORTED_BLE_MTU_SIZE);
-        }
-
-        if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
-        {
-            // send the last segment of the data (Ex: 22 bytes of 622
-            // bytes of data when MTU is 200)
-            result = CAMakeRemainDataSegment(dataSegment,
-                                             remainingLen,
-                                             bleData->data,
-                                             bleData->dataLen,
-                                             index,
-                                             dataHeader);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                            "Making data segment failed, result [%d]", result);
-                g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
-                return;
-            }
-
-            result =
-                CAUpdateCharacteristicsToAllGattServers(
-                    dataSegment,
-                    remainingLen + CA_BLE_HEADER_SIZE);
-
-            if (CA_STATUS_OK != result)
-            {
-                OIC_LOG_V(ERROR, CALEADAPTER_TAG,
-                          "Update characteristics (all) failed, result [%d]", result);
-                CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
-                return;
-            }
-            OIC_LOG_V(DEBUG,
-                      CALEADAPTER_TAG,
-                      "Client Sent Multicast Last Data - data length [%" PRIuPTR "]",
-                      remainingLen + CA_BLE_HEADER_SIZE);
-        }
-#else
+        OIC_LOG(DEBUG, CALEADAPTER_TAG, "Client Sending Multicast data");
         OIC_LOG(DEBUG, CALEADAPTER_TAG, "BLE Multicast is not supported");
-#endif
     }
 
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
@@ -2804,7 +2656,7 @@ static void CALESecureReceiveDataCB(const CASecureEndpoint_t *sep,
 
     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Secure Data Receive - decrypted datalen = %d", dataLen);
 
-    if (dataLen <= 0)
+    if (dataLen == 0)
     {
         OIC_LOG(ERROR, CALEADAPTER_TAG, "incorrect dataLen, derecypt fail !");
         return;
@@ -3749,7 +3601,10 @@ static void CALEErrorHandler(const char *remoteAddress,
                                                0);
 
     // if required, will be used to build remote endpoint
-    g_errorHandler(rep, data, dataLen, result);
+    if (g_errorHandler)
+    {
+        g_errorHandler(rep, data, dataLen, result);
+    }
 
     CAFreeEndpoint(rep);
 
index e872c79..8ca8e70 100644 (file)
@@ -45,17 +45,17 @@ service_name = '\"org.iotivity.gatt.service\"'
 dbus_policy_in = 'org.iotivity.gatt.service.conf.in'
 
 conf_dict = {}
-subst_env = connectivity_env.Clone(tools = [ 'default', 'textfile' ],
-                      SUBST_DICT = conf_dict)
+subst_env = connectivity_env.Clone(
+    tools=['default', 'textfile'], SUBST_DICT=conf_dict)
 
-conf_dict = { '@service_name@' : service_name }
+conf_dict = {'@service_name@': service_name}
 
-subst_env.Substfile(dbus_policy_in, SUBST_DICT = conf_dict)
+subst_env.Substfile(dbus_policy_in, SUBST_DICT=conf_dict)
 
 # The resulting D-Bus policy file should go in to the appropriate
 # D-Bus configuration directory, such as /etc/dbus-1/system.d/.
 
-dbus_policy    = os.path.splitext(dbus_policy_in)[0]  # Drop '.in' extension.
+dbus_policy = os.path.splitext(dbus_policy_in)[0]  # Drop '.in' extension.
 generated_dbus_policy = os.path.join(this_build_dir, dbus_policy)
 connectivity_env.Clean(dbus_policy, generated_dbus_policy)
 
@@ -66,10 +66,8 @@ connectivity_env.Clean(dbus_policy, generated_dbus_policy)
 # Also add a minimum required version of GLib 2.32, which is what the
 # older GNU/Linux distributions supported by IoTivity shipped with.
 connectivity_env.AppendUnique(
-    CPPDEFINES = [
-        ('CA_DBUS_GATT_SERVICE_NAME', "'%s'" % service_name),
-        ('GLIB_VERSION_MIN_REQUIRED', 'GLIB_VERSION_2_32')
-    ])
+    CPPDEFINES=[('CA_DBUS_GATT_SERVICE_NAME', "'%s'" % service_name),
+                ('GLIB_VERSION_MIN_REQUIRED', 'GLIB_VERSION_2_32')])
 
 # The Linux BLE adapter implementation uses GDBus to make D-Bus based
 # method calls to BlueZ.  Pull in the necessary dependencies.
@@ -81,31 +79,32 @@ freedesktop_prefix = 'org.freedesktop.DBus.'
 bluez_prefix = 'org.bluez.'
 
 dbus_introspection_xml = {
-    'object_manager' : freedesktop_prefix,
-    'bluez'          : bluez_prefix,
+    'object_manager': freedesktop_prefix,
+    'bluez': bluez_prefix,
 }
 
 # The source files to be compiled as part of the connectivity
 # abstraction library.
-src_files = [ 'characteristic.c',
-              'descriptor.c',
-              'service.c',
-              'advertisement.c',
-              'utils.c',
-              'central.c',
-              'peripheral.c',
-              'client.c',
-              'server.c',
-              'recv.c',
-              'caleinterface.c'
-          ]
-src_files = [ os.path.join(this_src_dir, src_file) for src_file in src_files ]
+src_files = [
+    'characteristic.c',
+    'descriptor.c',
+    'service.c',
+    'advertisement.c',
+    'utils.c',
+    'central.c',
+    'peripheral.c',
+    'client.c',
+    'server.c',
+    'recv.c',
+    'caleinterface.c'
+]
+src_files = [os.path.join(this_src_dir, src_file) for src_file in src_files]
 
 glue_files = []
 
 for file, prefix in dbus_introspection_xml.items():
-    source_xml  = file + '.xml'
-    glue        = file + '-glue'
+    source_xml = file + '.xml'
+    glue = file + '-glue'
     glue_source = glue + '.c'
     glue_header = glue + '.h'
 
@@ -114,23 +113,20 @@ for file, prefix in dbus_introspection_xml.items():
     # A link to the generated GDBus glue header is also created in the
     # source directory to avoid having to explicitly add the variant
     # directory to the preprocessor include path.
-    glue_source_gen  = os.path.join(this_build_dir, glue_source)
-    glue_header_gen  = os.path.join(this_build_dir, glue_header)
+    glue_source_gen = os.path.join(this_build_dir, glue_source)
+    glue_header_gen = os.path.join(this_build_dir, glue_header)
     glue_header_copy = os.path.join(this_src_dir, glue_header)
-    targets     = [ glue_source_gen, glue_header_gen ]
+    targets = [glue_source_gen, glue_header_gen]
 
     glue_files.append(glue_source_gen)
 
-    gen = connectivity_env.Command(targets,
-                      source_xml,
-                      'cd %s '
-                      '&& gdbus-codegen --generate-c-code %s '
-                      '   --interface-prefix %s ${SOURCE.abspath} '
-                      '&& ln -sf %s %s '
-                      '&& cd -'
-                      % (this_build_dir,
-                         glue, prefix,
-                         glue_header_gen, glue_header_copy))
+    gen = connectivity_env.Command(
+        targets, source_xml, 'cd %s '
+        '&& gdbus-codegen --generate-c-code %s '
+        '   --interface-prefix %s ${SOURCE.abspath} '
+        '&& ln -sf %s %s '
+        '&& cd -' % (this_build_dir, glue, prefix, glue_header_gen,
+                     glue_header_copy))
 
     connectivity_env.Clean(gen, glue_header_copy)
 
@@ -140,7 +136,7 @@ for file, prefix in dbus_introspection_xml.items():
 
 src_files += glue_files
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
 
 # Local Variables:
 # mode:python
index 0e004cb..fca7cbd 100644 (file)
@@ -7,13 +7,16 @@ Import('connectivity_env')
 
 src_dir = os.path.abspath(os.curdir)
 
-connectivity_env.PrependUnique(CPPPATH = [ src_dir ])
+connectivity_env.PrependUnique(CPPPATH=[src_dir])
 
-connectivity_env.ParseConfig("pkg-config --cflags --libs capi-network-bluetooth")
+connectivity_env.ParseConfig(
+    "pkg-config --cflags --libs capi-network-bluetooth")
 
-src_files = [ os.path.join(src_dir, 'caleclient.c'),
-              os.path.join(src_dir, 'caleserver.c'),
-              os.path.join(src_dir, 'caleutil.c'),
-              os.path.join(src_dir, 'calenwmonitor.c')]
+src_files = [
+    os.path.join(src_dir, 'caleclient.c'),
+    os.path.join(src_dir, 'caleserver.c'),
+    os.path.join(src_dir, 'caleutil.c'),
+    os.path.join(src_dir, 'calenwmonitor.c')
+]
 
-connectivity_env.AppendUnique(CA_SRC = src_files)
+connectivity_env.AppendUnique(CA_SRC=src_files)
index 96a8c2b..dad66ca 100644 (file)
@@ -2809,7 +2809,6 @@ void CADestroyBlockID(CABlockDataID_t *blockID)
     VERIFY_NON_NULL_VOID(blockID, TAG, "blockID");
     OICFree(blockID->id);
     OICFree(blockID);
-    blockID = NULL;
 }
 
 bool CABlockidMatches(const CABlockData_t *currData, const CABlockDataID_t *blockID)
index df20a77..261732d 100644 (file)
@@ -23,6 +23,7 @@
 #include <string.h>
 #include <inttypes.h>
 
+#include "platform_features.h"
 #include "logger.h"
 #include "oic_malloc.h"
 #include "caadapterutils.h"
 #include "cainterface.h"
 #include <coap/utlist.h>
 
+#ifndef SINGLE_THREAD
+#include <assert.h>
+#include "caqueueingthread.h"
+#endif
+
 #ifdef RA_ADAPTER
 #include "caraadapter.h"
 #endif
 
 #define TAG "OIC_CA_INF_CTR"
 
+#if defined(TCP_ADAPTER) || defined(EDR_ADAPTER) || defined(LE_ADAPTER)
+#define STATEFUL_PROTOCOL_SUPPORTED
+#endif
+
 #define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
     {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} }
 
@@ -60,6 +70,10 @@ static CAErrorHandleCallback g_errorHandleCallback = NULL;
 
 static struct CANetworkCallback_t *g_networkChangeCallbackList = NULL;
 
+#ifndef SINGLE_THREAD
+static CAQueueingThread_t g_networkChangeCallbackThread;
+#endif
+
 /**
  * network callback structure is handling
  * for adapter state changed and connection state changed event.
@@ -78,6 +92,58 @@ typedef struct CANetworkCallback_t
 
 } CANetworkCallback_t;
 
+#ifndef SINGLE_THREAD
+/**
+ * struct to wrap the network change callback info.
+ */
+typedef struct CANetworkCallbackThreadInfo_t
+{
+    CAAdapterStateChangedCB adapterCB;
+    CATransportAdapter_t adapter;
+    bool isInterfaceUp;
+
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
+    CAConnectionStateChangedCB connectionCB;
+    CAEndpoint_t *endpoint;
+    bool isConnected;
+#endif
+} CANetworkCallbackThreadInfo_t;
+
+static void CANetworkChangeCallbackThreadProcess(void *threadData)
+{
+    assert(threadData);
+
+    CANetworkCallbackThreadInfo_t *info = (CANetworkCallbackThreadInfo_t *) threadData;
+    if (info->adapterCB)
+    {
+        info->adapterCB(info->adapter, info->isInterfaceUp);
+    }
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
+    else if(info->connectionCB)
+    {
+        info->connectionCB(info->endpoint, info->isConnected);
+    }
+#endif
+}
+
+static void CADestroyNetworkChangeCallbackData(void *data, uint32_t size)
+{
+    assert(data);
+    OC_UNUSED(size);
+
+    CANetworkCallbackThreadInfo_t *info = (CANetworkCallbackThreadInfo_t *) data;
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
+    if (info->endpoint)
+    {
+        CAFreeEndpoint(info->endpoint);
+        info->endpoint = NULL;
+    }
+#endif
+    OICFree(info);
+    info = NULL;
+}
+#endif // SINGLE_THREAD
+
 static CAResult_t CAGetAdapterIndex(CATransportAdapter_t cType, size_t *adapterIndex)
 {
     for (size_t index = 0 ; index < g_numberOfAdapters ; index++)
@@ -142,7 +208,7 @@ static CAResult_t AddNetworkStateChangedCallback(CAAdapterStateChangedCB adapter
         return CA_STATUS_INVALID_PARAM;
     }
 
-#if defined(TCP_ADAPTER) || defined(EDR_ADAPTER) || defined(LE_ADAPTER)
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
     if (!connCB)
     {
         OIC_LOG(ERROR, TAG, "connCB is null");
@@ -168,7 +234,7 @@ static CAResult_t AddNetworkStateChangedCallback(CAAdapterStateChangedCB adapter
     }
 
     callback->adapter = adapterCB;
-#if defined(TCP_ADAPTER) || defined(EDR_ADAPTER) || defined(LE_ADAPTER)
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
     // Since IP adapter(UDP) is the Connectionless Protocol, it doesn't need.
     callback->conn = connCB;
 #endif
@@ -245,12 +311,30 @@ static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
 
 static void CAAdapterChangedCallback(CATransportAdapter_t adapter, CANetworkStatus_t status)
 {
+    OIC_LOG_V(DEBUG, TAG, "[%d] adapter state is changed to [%d]", adapter, status);
+
     // Call the callback.
     CANetworkCallback_t *callback  = NULL;
     LL_FOREACH(g_networkChangeCallbackList, callback)
     {
         if (callback && callback->adapter)
         {
+#ifndef SINGLE_THREAD
+            CANetworkCallbackThreadInfo_t *info = (CANetworkCallbackThreadInfo_t *)
+                                        OICCalloc(1, sizeof(CANetworkCallbackThreadInfo_t));
+            if (!info)
+            {
+                OIC_LOG(ERROR, TAG, "OICCalloc to info failed!");
+                return;
+            }
+
+            info->adapterCB = callback->adapter;
+            info->adapter = adapter;
+            info->isInterfaceUp = (CA_INTERFACE_UP == status);
+
+            CAQueueingThreadAddData(&g_networkChangeCallbackThread, info,
+                                    sizeof(CANetworkCallbackThreadInfo_t));
+#else
             if (CA_INTERFACE_UP == status)
             {
                 callback->adapter(adapter, true);
@@ -259,26 +343,52 @@ static void CAAdapterChangedCallback(CATransportAdapter_t adapter, CANetworkStat
             {
                 callback->adapter(adapter, false);
             }
+#endif //SINGLE_THREAD
         }
     }
-    OIC_LOG_V(DEBUG, TAG, "[%d] adapter status is changed to [%d]", adapter, status);
 }
 
-#if defined(TCP_ADAPTER) || defined(EDR_ADAPTER) || defined(LE_ADAPTER)
-static void CAConnectionChangedCallback(const CAEndpoint_t *info, bool isConnected)
+#ifdef STATEFUL_PROTOCOL_SUPPORTED
+static void CAConnectionChangedCallback(const CAEndpoint_t *endpoint, bool isConnected)
 {
+    OIC_LOG_V(DEBUG, TAG, "[%s] connection state is changed to [%d]", endpoint->addr, isConnected);
+
     // Call the callback.
     CANetworkCallback_t *callback = NULL;
     LL_FOREACH(g_networkChangeCallbackList, callback)
     {
         if (callback && callback->conn)
         {
-            callback->conn(info, isConnected);
+#ifndef SINGLE_THREAD
+            CANetworkCallbackThreadInfo_t *info = (CANetworkCallbackThreadInfo_t *)
+                                        OICCalloc(1, sizeof(CANetworkCallbackThreadInfo_t));
+            if (!info)
+            {
+                OIC_LOG(ERROR, TAG, "OICCalloc to info failed!");
+                return;
+            }
+
+            CAEndpoint_t *cloneEp = CACloneEndpoint(endpoint);
+            if (!cloneEp)
+            {
+                OIC_LOG(ERROR, TAG, "CACloneEndpoint failed!");
+                OICFree(info);
+                return;
+            }
+
+            info->connectionCB = callback->conn;
+            info->endpoint = cloneEp;
+            info->isConnected = isConnected;
+
+            CAQueueingThreadAddData(&g_networkChangeCallbackThread, info,
+                                    sizeof(CANetworkCallbackThreadInfo_t));
+#else
+            callback->conn(endpoint, isConnected);
+#endif //SINGLE_THREAD
         }
     }
-    OIC_LOG_V(DEBUG, TAG, "[%s] connection status is changed to [%d]", info->addr, isConnected);
 }
-#endif
+#endif //STATEFUL_PROTOCOL_SUPPORTED
 
 static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
         const void *data, size_t dataLen,
@@ -293,14 +403,13 @@ static void CAAdapterErrorHandleCallback(const CAEndpoint_t *endpoint,
     }
 }
 
-void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transportType)
+CAResult_t CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transportType)
 {
     OIC_LOG_V(DEBUG, TAG, "initialize adapters %d", transportType);
 
     // Initialize adapters and register callback.
 #ifdef IP_ADAPTER
-    if ((transportType & CA_ADAPTER_IP) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType & CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_IP) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                        CAAdapterErrorHandleCallback, handle);
@@ -308,8 +417,7 @@ void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transpor
 #endif /* IP_ADAPTER */
 
 #ifdef EDR_ADAPTER
-    if ((transportType & CA_ADAPTER_RFCOMM_BTEDR) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType == CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_RFCOMM_BTEDR) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                         CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
@@ -317,8 +425,7 @@ void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transpor
 #endif /* EDR_ADAPTER */
 
 #ifdef LE_ADAPTER
-    if ((transportType & CA_ADAPTER_GATT_BTLE) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType == CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_GATT_BTLE) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                        CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
@@ -326,8 +433,7 @@ void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transpor
 #endif /* LE_ADAPTER */
 
 #ifdef RA_ADAPTER
-    if ((transportType & CA_ADAPTER_REMOTE_ACCESS) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType == CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_REMOTE_ACCESS) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeRA(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                        handle);
@@ -335,8 +441,7 @@ void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transpor
 #endif /* RA_ADAPTER */
 
 #ifdef TCP_ADAPTER
-    if ((transportType & CA_ADAPTER_TCP) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType == CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_TCP) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeTCP(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                         CAConnectionChangedCallback, CAAdapterErrorHandleCallback, handle);
@@ -344,13 +449,35 @@ void CAInitializeAdapters(ca_thread_pool_t handle, CATransportAdapter_t transpor
 #endif /* TCP_ADAPTER */
 
 #ifdef NFC_ADAPTER
-    if ((transportType & CA_ADAPTER_NFC) || (CA_DEFAULT_ADAPTER == transportType)
-        || (transportType == CA_ALL_ADAPTERS))
+    if ((transportType & CA_ADAPTER_NFC) || (CA_DEFAULT_ADAPTER == transportType))
     {
         CAInitializeNFC(CARegisterCallback, CAReceivedPacketCallback, CAAdapterChangedCallback,
                         CAAdapterErrorHandleCallback, handle);
     }
 #endif /* NFC_ADAPTER */
+
+#ifndef SINGLE_THREAD
+    CAResult_t res = CA_STATUS_OK;
+
+    // Initialize & Start network-change-callback-thread.
+    res = CAQueueingThreadInitialize(&g_networkChangeCallbackThread, handle,
+                                     CANetworkChangeCallbackThreadProcess,
+                                     CADestroyNetworkChangeCallbackData);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize callback queue thread");
+        return res;
+    }
+
+    res = CAQueueingThreadStart(&g_networkChangeCallbackThread);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread start error(callback thread).");
+        return res;
+    }
+#endif //SINGLE_THREAD
+
+    return CA_STATUS_OK;
 }
 
 void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
@@ -434,6 +561,30 @@ void CAStopAdapter(CATransportAdapter_t transportType)
     }
 }
 
+#ifndef SINGLE_THREAD
+void CAStopAdapters()
+{
+    CATransportAdapter_t connType;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    size_t length = u_arraylist_length(list);
+
+    for (size_t i = 0; i < length; i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
+
+        if (NULL == ptrType)
+        {
+            continue;
+        }
+
+        connType = *(CATransportAdapter_t *)ptrType;
+        CAStopAdapter(connType);
+    }
+
+    CAQueueingThreadStop(&g_networkChangeCallbackThread);
+}
+#endif //SINGLE_THREAD
+
 CAResult_t CAGetNetworkInfo(CAEndpoint_t **info, size_t *size)
 {
     VERIFY_NON_NULL(info, TAG, "info is null");
@@ -821,6 +972,10 @@ void CATerminateAdapters()
     g_adapterHandler = NULL;
     g_numberOfAdapters = 0;
 
+#ifndef SINGLE_THREAD
+    CAQueueingThreadDestroy(&g_networkChangeCallbackThread);
+#endif //SINGLE_THREAD
+
     RemoveAllNetworkStateChangedCallback();
 }
 
index 7d92e47..16d0536 100644 (file)
@@ -1145,7 +1145,12 @@ CAResult_t CAInitializeMessageHandler(CATransportAdapter_t transportType)
     }
 
     // initialize interface adapters by controller
-    CAInitializeAdapters(g_threadPoolHandle, transportType);
+    res = CAInitializeAdapters(g_threadPoolHandle, transportType);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize Adapters.");
+        return res;
+    }
 #else
     // retransmission initialize
     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
@@ -1165,22 +1170,8 @@ CAResult_t CAInitializeMessageHandler(CATransportAdapter_t transportType)
 void CATerminateMessageHandler()
 {
 #ifndef SINGLE_THREAD
-    CATransportAdapter_t connType;
-    u_arraylist_t *list = CAGetSelectedNetworkList();
-    size_t length = u_arraylist_length(list);
-
-    for (size_t i = 0; i < length; i++)
-    {
-        void* ptrType = u_arraylist_get(list, i);
-
-        if (NULL == ptrType)
-        {
-            continue;
-        }
-
-        connType = *(CATransportAdapter_t *)ptrType;
-        CAStopAdapter(connType);
-    }
+    // stop adapters
+    CAStopAdapters();
 
     // stop retransmission
     if (NULL != g_retransmissionContext.threadMutex)
index 1a1890f..b4abf21 100644 (file)
@@ -746,6 +746,7 @@ CAResult_t CAGetOptionCount(coap_opt_iterator_t opt_iter, uint8_t *optionCount)
 CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                             uint32_t *outCode, CAInfo_t *outInfo)
 {
+    OIC_LOG(INFO, TAG, "IN - CAGetInfoFromPDU");
     VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
     VERIFY_NON_NULL(outCode, TAG, "outCode");
@@ -816,7 +817,12 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
     }
 
     coap_opt_t *option = NULL;
-    char optionResult[CA_MAX_URI_LENGTH] = {0};
+    char *optionResult = (char *)OICCalloc(1, CA_MAX_URI_LENGTH * sizeof(char));
+    if (NULL == optionResult)
+    {
+        goto exit;
+    }
+
     uint32_t idx = 0;
     uint32_t optionLength = 0;
     bool isfirstsetflag = false;
@@ -825,10 +831,15 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
 
     while ((option = coap_option_next(&opt_iter)))
     {
-        char buf[COAP_MAX_PDU_SIZE] = {0};
+        char *buf = (char *)OICCalloc(1, COAP_MAX_PDU_SIZE * sizeof(char));
+        if (NULL == buf)
+        {
+            goto exit;
+        }
+
         uint32_t bufLength =
             CAGetOptionData(opt_iter.type, (uint8_t *)(COAP_OPT_VALUE(option)),
-                    COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf));
+                    COAP_OPT_LENGTH(option), (uint8_t *)buf, COAP_MAX_PDU_SIZE);
         if (bufLength)
         {
             OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
@@ -840,13 +851,14 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                     optionResult[optionLength] = '/';
                     optionLength++;
                     // Make sure there is enough room in the optionResult buffer
-                    if ((optionLength + bufLength) < sizeof(optionResult))
+                    if ((optionLength + bufLength) < CA_MAX_URI_LENGTH)
                     {
                         memcpy(&optionResult[optionLength], buf, bufLength);
                         optionLength += bufLength;
                     }
                     else
                     {
+                        OICFree(buf);
                         goto exit;
                     }
                 }
@@ -855,13 +867,14 @@ CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                     if (COAP_O