if target_os == 'arduino':
SConscript('arduino.scons')
-if target_os == 'android':
- SConscript('android/android_api/SConscript')
-
# By default, src_dir is current dir, the build_dir is:
# ./out/<target_os>/<target_arch>/<release or debug>/
#
# Build "cloud" sub-project
SConscript(build_dir + 'cloud/SConscript')
+if env.get('BUILD_JAVA') == 'ON' or target_os == 'android':
+ if env.get('JAVA_HOME') != None:
+ SConscript(build_dir + 'java/SConscript')
+
# Append targets information to the help information, to see help info, execute command line:
# $ scon [options] -h
env.PrintTargets()
+++ /dev/null
-.gradle\r
-/local.properties\r
-/.idea/workspace.xml\r
-/.idea/libraries\r
-.DS_Store\r
-/build/*\r
-/base/build/*\r
-/base/obj/*\r
-/base/libs/*\r
-/sample/*\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.id="android_api" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
- <component name="FacetManager">
- <facet type="java-gradle" name="Java-Gradle">
- <configuration>
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
- <option name="BUILDABLE" value="false" />
- </configuration>
- </facet>
- <facet type="android-gradle" name="Android-Gradle">
- <configuration>
- <option name="GRADLE_PROJECT_PATH" value=":" />
- </configuration>
- </facet>
- <facet type="android" name="Android">
- <configuration>
- <option name="ALLOW_USER_CONFIGURATION" value="false" />
- </configuration>
- </facet>
- </component>
- <component name="NewModuleRootManager" inherit-compiler-output="true">
- <exclude-output />
- <content url="file://$MODULE_DIR$">
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />
- </content>
- <orderEntry type="inheritedJdk" />
- <orderEntry type="sourceFolder" forTests="false" />
- </component>
-</module>
\ No newline at end of file
+++ /dev/null
-.gradle/\r
-.idea/\r
-sample/\r
-base/build/\r
-base/obj/\r
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="android_api" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
- <component name="FacetManager">\r
- <facet type="android-gradle" name="Android-Gradle">\r
- <configuration>\r
- <option name="GRADLE_PROJECT_PATH" value=":base" />\r
- </configuration>\r
- </facet>\r
- <facet type="android" name="Android">\r
- <configuration>\r
- <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
- <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
- <option name="RES_FOLDERS_RELATIVE_PATH" value="" />\r
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
- <option name="LIBRARY_PROJECT" value="true" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" inherit-compiler-output="false">\r
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/native-libs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
- </content>\r
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- </component>\r
-</module>\r
-\r
+++ /dev/null
-LOCAL_PATH := $(call my-dir)\r
-TARGET_ARCH_ABI := $(APP_ABI)\r
-SECURED := $(SECURE)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-oc_logger\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-octbstack\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-oc\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-ca\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-\r
-ifeq ($(SECURED), 1)\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-ocprovision\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocprovision.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_LIB_PATH := ../../../../out/android/$(APP_ABI)/$(APP_OPTIM)\r
-LOCAL_MODULE := libandroid-ocpmapi\r
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocpmapi.so\r
-include $(PREBUILT_SHARED_LIBRARY)\r
-endif\r
-\r
-include $(CLEAR_VARS)\r
-OIC_SRC_PATH := ../../../resource\r
-LOCAL_MODULE := libca-interface\r
-LOCAL_SRC_FILES := JniCaInterface.c\r
-LOCAL_STATIC_LIBRARIES := libandroid-ca\r
-LOCAL_LDLIBS := -llog\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/connectivity/api\r
-include $(BUILD_SHARED_LIBRARY)\r
-\r
-include $(CLEAR_VARS)\r
-OIC_SRC_PATH := ../../../resource\r
-OIC_OUT_PATH := ../../../out\r
-LOCAL_MODULE := ocstack-jni\r
-LOCAL_SRC_FILES := JniOcStack.cpp \\r
- JniUtils.cpp \\r
- JniEntityHandler.cpp \\r
- JniOnResourceFoundListener.cpp \\r
- JniOnDeviceInfoListener.cpp \\r
- JniOnPlatformInfoListener.cpp \\r
- JniOnPresenceListener.cpp \\r
- JniOnGetListener.cpp \\r
- JniOnPutListener.cpp \\r
- JniOnPostListener.cpp \\r
- JniOnDeleteListener.cpp \\r
- JniOnObserveListener.cpp \\r
- JniOcRepresentation.cpp \\r
- JniOcResourceHandle.cpp \\r
- JniOcPresenceHandle.cpp \\r
- JniOcRequestHandle.cpp \\r
- JniOcResourceRequest.cpp \\r
- JniOcResourceResponse.cpp \\r
- JniOcPlatform.cpp \\r
- JniOcResource.cpp \\r
- JniOcResourceIdentifier.cpp \\r
- JniOcSecurity.cpp\r
-ifeq ($(SECURED), 1)\r
-LOCAL_SRC_FILES += JniOcSecureResource.cpp \\r
- JniOcProvisioning.cpp \\r
- JniSecureUtils.cpp \\r
- JniProvisionResultListner.cpp \\r
- JniPinCheckListener.cpp \\r
- JniDisplayPinListener.cpp\r
-endif\r
-\r
-LOCAL_LDLIBS := -llog\r
-LOCAL_STATIC_LIBRARIES := android-oc\r
-LOCAL_STATIC_LIBRARIES += android-octbstack\r
-LOCAL_STATIC_LIBRARIES += android-coap\r
-LOCAL_STATIC_LIBRARIES += android-oc_logger\r
-LOCAL_STATIC_LIBRARIES += android-ca\r
-LOCAL_STATIC_LIBRARIES += android_cpp11_compat\r
-ifeq ($(SECURED), 1)\r
-LOCAL_STATIC_LIBRARIES += android-ocprovision\r
-LOCAL_STATIC_LIBRARIES += android-ocpmapi\r
-endif\r
-\r
-LOCAL_CPPFLAGS += -std=c++0x\r
-LOCAL_CPP_FEATURES := rtti exceptions\r
-LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_string/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/c_common/oic_malloc/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../extlibs/boost/boost_1_58_0\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/../build_common/android/compatibility\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/oxm/\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/provisioning/include/internal\r
-LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/security/include\r
-include $(BUILD_SHARED_LIBRARY)\r
+++ /dev/null
-NDK_TOOLCHAIN_VERSION := 4.9\r
-APP_STL := gnustl_shared
\ No newline at end of file
build_linux_unsecured_with_rm $1 $2
build_linux_unsecured_with_rd $1 $2
build_linux_secured_with_rd $1 $2
+ build_linux_unsecured_with_java $1 $2
+ build_linux_secured_with_java $1 $2
build_simulator $1 $2
fi
scons RELEASE=$1 WITH_RD=1 SECURED=1 $2
}
+function build_linux_unsecured_with_java()
+{
+ echo "*********** Build for linux With Resource Directory & Security ************"
+ scons RELEASE=$1 BUILD_JAVA=ON TARGET_TRANSPORT=IP $2
+}
+
+function build_linux_secured_with_java()
+{
+ echo "*********** Build for linux With Resource Directory & Security ************"
+ scons RELEASE=$1 SECURED=1 BUILD_JAVA=ON TARGET_TRANSPORT=IP $2
+}
+
function build_android()
{
# Note: for android, as oic-resource uses C++11 feature stoi and to_string,
then
build_linux_secured_with_rd true
build_linux_secured_with_rd false
+ elif [ $1 = 'linux_unsecured_with_java' ]
+ then
+ build_linux_unsecured_with_java true
+ build_linux_unsecured_with_java false
+ elif [ $1 = 'linux_secured_with_java' ]
+ then
+ build_linux_secured_with_java true
+ build_linux_secured_with_java false
elif [ $1 = 'android' ]
then
build_android true
#ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with Soft AP or Mode 2 : Mediator with Soft AP)
help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))
+help_vars.Add(EnumVariable('BUILD_JAVA', 'Build Java bindings', 'OFF', allowed_values=('ON', 'OFF')))
+help_vars.Add(PathVariable('JAVA_HOME', 'JDK directory', os.environ.get('JAVA_HOME'), PathVariable.PathAccept))
+
AddOption('--prefix',
dest='prefix',
type='string',
# This script manages external libraries
#
# Some methods are added to manage external packages:
-# 'PrepareLib': Checks the existence of an external library, if it
+# 'PrepareLib': Checks the existence of an external library, if it
# doesn't exist, calls the script user provided to download(if required)
# and build the source code of the external library or notify user to
# install the library.
# 'InstallLib': Install library binaries(.so, .a etc)
#
# By default, assume the script for an exteranl library is:
-# <src_dir>/extlibs/<libname>/SConscript
+# <src_dir>/extlibs/<libname>/SConscript
#
# Note: After the external library is built:
# Head files should be installed to <src_dir>/deps/<target_os>/include
if target_os == 'android':
if target_arch == 'armeabi-v7a-hard':
target_arch = 'armeabi-v7a'
+ env.AppendUnique(CCFLAGS = ['-D__JAVA__'])
if target_os == 'darwin':
env.AppendUnique(CPPPATH = ['/usr/local/include'])
env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+if env.get('BUILD_JAVA') == 'ON' and target_os != 'android':
+ if env.get('JAVA_HOME') != None:
+ env.AppendUnique(CCFLAGS = ['-D__JAVA__'])
+ env.AppendUnique(CPPPATH = [
+ env.get('JAVA_HOME') + '/include',
+ env.get('JAVA_HOME') + '/include/' + target_os
+ ])
+ else:
+ raise SCons.Errors.StopError( 'BUILD_JAVA is ON, but JAVA_HOME is not set.')
+
+
# External library include files are in <src_dir>/deps/<target_os>/include
# the library binaries are in <src_dir>/deps/<target_os>/lib/<arch>
env.AppendUnique(CPPPATH = [os.path.join(env.get('SRC_DIR'), 'deps', target_os, 'include')])
# download the source code and build it
# @param libname - the name of the library try to prepare
# @param lib - the lib(.so, .a etc) to check (a library may include more then
-# one lib, e.g. boost, includes boost_thread, boost_system ...
+# one lib, e.g. boost, includes boost_thread, boost_system ...
# @param path - the directory of the library building script, if it's not set,
# by default, it's <src_dir>/extlibs/<libname>/
# @param script - the building script, by default, it's 'SConscript'
# This script set linux specific flags (GNU GCC)
#
##
+import os
Import('env')
print "Reading linux configuration script"
+SConscript('../external_libs.scons')
+help_vars = Variables()
+if env.get('BUILD_JAVA') == 'ON':
+ if not env.get('ANDROID_GRADLE'):
+ SConscript('../../extlibs/android/gradle/SConscript')
+ help_vars.Add(PathVariable('ANDROID_GRADLE', 'Android Gradle directory', os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1/bin/gradle')))
+
+ if env.get('ANDROID_GRADLE'):
+ android_gradle = env.get('ANDROID_GRADLE')
+ else:
+ print '''
+*************************************** Info **********************************
+* Android Gradle path isn't set, the default will be used. You can set *
+* environment variable ANDROID_GRADLE or add it in command line as: *
+* # scons ANDROID_GRADLE=<path to android GRADLE> ... *
+*******************************************************************************
+'''
+ android_gradle = os.path.join(env.get('SRC_DIR'), 'extlibs', 'android', 'gradle', 'gradle-2.2.1', 'bin', 'gradle')
+
+help_vars.Update(env)
+Help(help_vars.GenerateHelpText(env))
+
+
# Set release/debug flags
if env.get('RELEASE'):
env.AppendUnique(CCFLAGS = ['-Os'])
import platform
Import('env')
-android_home = env.get('ANDROID_HOME')
-
-ANDROID_TARGET_ARCH = env.get('TARGET_ARCH')
+TARGET_ARCH = env.get('TARGET_ARCH')
if env.get('RELEASE'):
- ANDROID_RELEASE="release"
+ RELEASE="release"
else:
- ANDROID_RELEASE="debug"
-ANDROID_SECURED = env.get('SECURED')
+ RELEASE="debug"
+SECURED = env.get('SECURED')
+
+target_os = env.get('TARGET_OS')
-os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
-os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
+if target_os == "android":
+ android_home = env.get('ANDROID_HOME')
+ os.environ['ANDROID_HOME'] = env.get('ANDROID_HOME')
+ os.environ['ANDROID_NDK_HOME'] = env.get('ANDROID_NDK')
-if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
- print '''
+ if not os.path.exists(android_home + '/platforms/android-21') or not os.path.exists(android_home + '/build-tools/20.0.0'):
+ print '''
***************************************** Info ********************************
* Either 'Android API 21' is not installed or 'Android SDK Build Tools *
* 20.0.0' is not installed. The Android SDK Manager will now open. Please *
...Opening Android SDK Manager now. Once you are finished, the build will continue.
'''
- os.system(android_home + '/tools/android')
+ os.system(android_home + '/tools/android')
def ensure_libs(target, source, env):
- return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
+ return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so', env.get('BUILD_DIR') + 'libocstack-jni.so']
+
+SConscript('jni/SConscript')
-# build android_api
jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED), emitter = ensure_libs)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + env.get('SRC_DIR') + '/java/iotivity-%s/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s -PBUILD_DIR=%s -PSRC_DIR=%s --stacktrace' %(target_os, TARGET_ARCH, RELEASE, SECURED, env.get('BUILD_DIR'), env.get('SRC_DIR')), emitter = ensure_libs)
jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-cmdBuildApi=jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
+cmdBuildApi=jdk_env.Gradle(target="base/objs", source="common/src/main/java/org/iotivity/base/OcResource.java")
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED))
-cmdBuildExamples=jdk_env.Gradle(target="../examples/devicediscoveryclient/apk", source="../examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java")
+examples_target = "java"
+if target_os == 'android':
+ examples_target = "android"
-# android examples require android api to be built before being invoked
-Depends(cmdBuildExamples, cmdBuildApi)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'java/examples-%s/build.gradle -PTARGET_OS=%s -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' % (examples_target, target_os, TARGET_ARCH, RELEASE, SECURED))
+cmdBuildExamples=jdk_env.Gradle(target="examples-%s/simpleclient/jar" % (examples_target, ), source="examples-%s/simpleclient/src/main/java/org/iotivity/base/examples/SimpleClient.java" % (examples_target, ))
+Depends(cmdBuildExamples, cmdBuildApi)
repositories {\r
jcenter()\r
}\r
- dependencies {\r
- classpath 'com.android.tools.build:gradle:1.3.0'\r
-\r
- // NOTE: Do not place your application dependencies here; they belong\r
- // in the individual module build.gradle files\r
- }\r
}\r
\r
allprojects {\r
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.devicediscoveryclient"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.devicediscoveryserver"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.fridgeclient"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.fridgegroupclient"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../iotivity-android/build/outputs/aar/"\r
+ }\r
+}\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
--- /dev/null
+apply plugin: 'com.android.application'\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.fridgegroupserver"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../iotivity-android/build/outputs/aar/"\r
+ }\r
+}\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
--- /dev/null
+apply plugin: 'com.android.application'
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.fridgeserver"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.groupclient"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.groupserver"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.presenceclient"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.presenceserver"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../iotivity-android/build/outputs/aar/"
+ }
+}
+
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
--- /dev/null
+apply plugin: 'com.android.application'\r
+\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.provisioningclient"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../iotivity-android/build/outputs/aar/"\r
+ }\r
+}\r
+\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
+\r
}
repositories {
flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
+ dirs "../../iotivity-android/build/outputs/aar/"
}
}
}
repositories {
flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
+ dirs "../../iotivity-android/build/outputs/aar/"
}
}
}
repositories {
flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
+ dirs "../../iotivity-android/build/outputs/aar/"
}
}
--- /dev/null
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+\r
+buildscript {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+\r
+ // NOTE: Do not place your application dependencies here; they belong\r
+ // in the individual module build.gradle files\r
+ }\r
+}\r
+\r
+allprojects {\r
+ apply plugin: 'java'\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+ compile fileTree(dir: "../../iotivity-$TARGET_OS/build/libs/", include: '*.jar')\r
+ }\r
+}\r
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This sample demonstrates the device discovery feature.
+ * The client queries for the device related information stored by the server.
+ */
+public class DeviceDiscoveryClient extends Activity implements
+ OcPlatform.OnDeviceFoundListener,
+ OcPlatform.OnPlatformFoundListener {
+ private void startDeviceDiscoveryClient() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+ sleep(1);
+
+ try {
+ msg("Querying for platform information...");
+ OcPlatform.getPlatformInfo("",
+ OcPlatform.WELL_KNOWN_PLATFORM_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to query for platform information");
+ }
+ sleep(2);
+
+ try {
+ msg("Querying for device information...");
+ OcPlatform.getDeviceInfo("",
+ OcPlatform.WELL_KNOWN_DEVICE_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to query for device information");
+ }
+ sleep(2);
+
+ enableStartButton();
+ printLine();
+ }
+
+ private final static Map<String, String> PLATFORM_INFO_KEYS = new HashMap<String, String>() {{
+ put("pi", "Platform ID: ");
+ put("mnmn", "Manufacturer name: ");
+ put("mnml", "Manufacturer url: ");
+ put("mnmo", "Manufacturer Model No: ");
+ put("mndt", "Manufactured Date: ");
+ put("mnpv", "Manufacturer Platform Version: ");
+ put("mnos", "Manufacturer OS version: ");
+ put("mnhw", "Manufacturer hardware version: ");
+ put("mnfv", "Manufacturer firmware version: ");
+ put("mnsl", "Manufacturer support url: ");
+ put("st", "Manufacturer system time: ");
+ }};
+
+ @Override
+ public synchronized void onPlatformFound(OcRepresentation ocRepresentation) {
+ msg("Platform Information received:");
+ try {
+ for (String key : PLATFORM_INFO_KEYS.keySet()) {
+ msg("\t" + PLATFORM_INFO_KEYS.get(key) + ocRepresentation.getValue(key));
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to read platform info values.");
+ }
+
+ printLine();
+ }
+
+ private final static Map<String, String> DEVICE_INFO_KEYS = new HashMap<String, String>() {{
+ put("di", "Device ID: ");
+ put("n", "Device name: ");
+ put("lcv", "Spec version url: ");
+ put("dmv", "Data Model: ");
+ }};
+
+ @Override
+ public synchronized void onDeviceFound(OcRepresentation ocRepresentation) {
+ msg("Device Information received:");
+ try {
+ for (String key : DEVICE_INFO_KEYS.keySet()) {
+ msg("\t" + DEVICE_INFO_KEYS.get(key) + ocRepresentation.getValue(key));
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to read device info values.");
+ }
+
+ printLine();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = DeviceDiscoveryClient.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_device_discovery_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setText("Re-start");
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startDeviceDiscoveryClient();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ private void enableStartButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ Button button = (Button) findViewById(R.id.button);
+ button.setEnabled(true);
+ }
+ });
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcDeviceInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPlatformInfo;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+/**
+ * This sample demonstrates platform and device discovery feature.
+ * The server sets the platform and device related info. which can be later retrieved by a client.
+ */
+public class DeviceDiscoveryServer extends Activity {
+
+ private void startDeviceDiscoveryServer() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ OcDeviceInfo deviceInfo = new OcDeviceInfo("myDeviceName");
+ try {
+ msg("Registering device info");
+ OcPlatform.registerDeviceInfo(deviceInfo);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register device info.");
+ }
+
+ OcPlatformInfo platformInfo = new OcPlatformInfo(
+ "myPlatformId", //Platform ID
+ "myManufactName", //Manufacturer Name
+ "www.myurl.com", //Manufacturer URL
+ "myModelNumber", //Model Number
+ "myDateOfManufacture", //Date of Manufacture
+ "myPlatformVersion", //Platform Version
+ "Manufacturer OS version", //Operating System Version
+ "myHardwareVersion", //Hardware Version
+ "myFirmwareVersion", //Firmware Version
+ "www.mysupporturl.com", //Support URL
+ String.valueOf(System.currentTimeMillis()) // System Time
+ );
+ try {
+ msg("Registering platform info");
+ OcPlatform.registerPlatformInfo(platformInfo);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register platform info.");
+ }
+
+ msg("Waiting for the requests...");
+ printLine();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = DeviceDiscoveryServer.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_device_discovery_server);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startDeviceDiscoveryServer();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * FridgeClient
+ * <p/>
+ * FridgeClient is a sample client app which should be started after the fridgeServer is started.
+ * It creates DeviceResource, DoorResources, LightResource and performs a GET operation on them.
+ */
+public class FridgeClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener {
+ public static final String DEVICE_URI = "/device";
+ public static final String LIGHT = "/light";
+ public static final String LEFT_DOOR = "/door/left";
+ public static final String RIGHT_DOOR = "/door/right";
+ public static final String RANDOM_DOOR = "/door/random";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_TOKEN_KEY = 3000;
+
+ private final List<OcResource> mResourceList = new LinkedList<OcResource>();
+ private OcResource mFridgeResource;
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void startFridgeClient() {
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ logMessage("Configuring platform");
+ OcPlatform.Configure(cfg);
+ logMessage("Initiating fridge discovery");
+ try {
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ logMessage(" Failed to discover resource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * An event handler to be executed whenever a "findResource" request completes successfully
+ *
+ * @param ocResource found resource
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource ocResource) {
+ if (null != mFridgeResource || !ocResource.getUri().equals(DEVICE_URI)) {
+ logMessage("Didn't find the correct fridge resource. Exiting");
+ return;
+ }
+ mFridgeResource = ocResource;
+ logMessage("Discovered a fridge with \nHost: " + mFridgeResource.getHost());
+
+ List<String> lightTypes = new LinkedList<>();
+ lightTypes.add("intel.fridge.light");
+ List<String> doorTypes = new LinkedList<>();
+ doorTypes.add("intel.fridge.door");
+ List<String> resourceInterfaces = new LinkedList<>();
+ resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+ logMessage("Creating child resource proxies for the previously known fridge components");
+ OcResource light = null;
+ OcResource leftDoor = null;
+ OcResource rightDoor = null;
+ OcResource randomDoor = null;
+ try {
+ light = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ LIGHT,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ lightTypes,
+ resourceInterfaces);
+ mResourceList.add(light);
+
+ leftDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ LEFT_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(leftDoor);
+
+ rightDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ RIGHT_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(rightDoor);
+
+ randomDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ RANDOM_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(randomDoor);
+ } catch (OcException e) {
+ logMessage("Error in constructResourceObject");
+ Log.e(TAG, e.getMessage());
+ }
+
+ List<OcHeaderOption> headerOptions = new LinkedList<>();
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY, API_VERSION);
+ OcHeaderOption clientToken = new OcHeaderOption(CLIENT_TOKEN_KEY, CLIENT_TOKEN);
+ headerOptions.add(apiVersion);
+ headerOptions.add(clientToken);
+ mFridgeResource.setHeaderOptions(headerOptions);
+
+ logMessage("Calling GET api on mFridgeResource and other component resources");
+ try {
+ mFridgeResource.get(new HashMap<String, String>(), this);
+ if (null != light) light.get(new HashMap<String, String>(), this);
+ if (null != leftDoor) leftDoor.get(new HashMap<String, String>(), this);
+ if (null != rightDoor) rightDoor.get(new HashMap<String, String>(), this);
+ if (null != randomDoor) randomDoor.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ logMessage("Error in GET calls");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request completes successfully
+ *
+ * @param headerOptionList list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ logMessage("Got a response from " + ocRepresentation.getUri());
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("GET request has failed");
+ Log.e(TAG, throwable.toString());
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeClient();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private static String TAG = "FridgeClient: ";
+ private TextView mConsoleTextView;
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * FridgeGroupClient
+ * <p/>
+ * FridgeGroupClient is a sample client app which should be started after the fridgeGroupServer is
+ * started. It discovers a fridge resource and then creates the proxy resources for each one of its
+ * children (light and door) and performs a GET on them.
+ */
+public class FridgeGroupClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener {
+ private static String TAG = "FridgeGroupClient: ";
+
+ private final List<OcResource> childResourceList = new LinkedList<>();
+ private OcResource fridgeResource;
+
+ private void startFridgeClient() {
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ logMessage("Configuring platform");
+ OcPlatform.Configure(cfg);
+ String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=intel.fridge.group";
+ logMessage("Initiating fridge discovery");
+ try {
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ logMessage("Failed to discover resource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * callback when a fridge resource is found.
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource ocResource) {
+ if ((null != fridgeResource) && !fridgeResource.getUri().equals("/fridge/group")) {
+ logMessage("Didn't find the correct fridge resource. Exiting");
+ return;
+ }
+ fridgeResource = ocResource;
+ logMessage("Discovered a fridge with \nHost: " + fridgeResource.getHost());
+ logMessage("Trying to call GET api on fridgeResource");
+ try {
+ fridgeResource.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ logMessage("Failed to call GET api");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * once the fridge resource is discovered, create proxy child resources of the fridge
+ * and call GET on each of the child resource proxies.
+ *
+ * @param list
+ * @param ocRepresentation parent resource
+ */
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ logMessage("Got a response from " + ocRepresentation.getUri());
+ for (OcRepresentation child : ocRepresentation.getChildren()) {
+ try {
+ logMessage("Creating child resource proxy from fridgeResource with uri " +
+ child.getUri());
+ OcResource childResource = OcPlatform.constructResourceObject(
+ fridgeResource.getHost(),
+ child.getUri(),
+ fridgeResource.getConnectivityTypeSet(),
+ false, // isObservable set to false
+ child.getResourceTypes(),
+ child.getResourceInterfaces());
+ childResourceList.add(childResource);
+ } catch (OcException e) {
+ logMessage("Error in creating child resource proxy");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ OcResource.OnGetListener childOnGetListener = new OcResource.OnGetListener() {
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ logMessage("Received a response from a child of the fridge with uri: " +
+ ocRepresentation.getUri());
+ for (String resType : ocRepresentation.getResourceTypes()) {
+ if (resType.equals("intel.fridge.door")) {
+ try {
+ logMessage(ocRepresentation.getValue(DOOR_SIDE_KEY) +
+ " door is " + ((ocRepresentation.getValue(DOOR_STATE_KEY)
+ ) ? "open" : "close"));
+ } catch (OcException e) {
+ logMessage("Failed to get the door resource representation");
+ Log.e(TAG, e.getMessage());
+ }
+ } else if (resType.equals("intel.fridge.light")) {
+ try {
+ logMessage("Fridge light is " +
+ ((ocRepresentation.getValue(LIGHT_STATUS_KEY)) ?
+ "on" : "off"));
+ } catch (OcException e) {
+ logMessage("Failed to get the light resource representation");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("OnGet failed for child of fridge");
+ Log.e(TAG, throwable.getMessage());
+ }
+ };
+
+ for (OcResource child : childResourceList) {
+ try {
+ logMessage("Trying to get a representation of " + child.getUri() +
+ " resource from server");
+ child.get(new HashMap<String, String>(), childOnGetListener);
+ } catch (OcException e) {
+ logMessage(e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("Failed to get representation of the fridge");
+ Log.e(TAG, throwable.toString());
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private TextView mConsoleTextView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeClient();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * DoorResource is a sample OIC server resource created by the refrigerator.
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(
+ resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for doorResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
+ response.setErrorCode(Resource.SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ response.setErrorCode(204);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private String mSide;
+ private boolean mDoorState;
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ private static String TAG = "DoorResource: ";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+/**
+ * FridgeGroupServer
+ * <p/>
+ * This is the main fridgeGroupServer class. This instantiates Refrigerator object
+ * which has different resources such as LightResource, DoorResource, etc.
+ */
+public class FridgeGroupServer extends Activity {
+ private Refrigerator refrigerator;
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void startFridgeServer() {
+ logMessage("Configuring platform config");
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+ OcPlatform.Configure(cfg);
+
+ logMessage("Creating refrigerator resources");
+ refrigerator = new Refrigerator(this);
+ logMessage("-----------------------------------------------------");
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private static String TAG = "FridgeServer: ";
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+ private BroadcastReceiver mMessageReceiver = new MessageReceiver();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_server);
+ registerReceiver(mMessageReceiver, new IntentFilter(Resource.INTENT));
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeServer();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String message = intent.getStringExtra(Resource.MESSAGE);
+ logMessage(message);
+ }
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * FridgeResource
+ * <p/>
+ * FridgeResource is a sample OIC server resource created by the refrigerator.
+ */
+public class FridgeResource extends Resource {
+ FridgeResource(Context context) {
+ mContext = context;
+ registerFridgeResource();
+ }
+
+ private void registerFridgeResource() {
+ try {
+ logMessage(TAG + "RegisterFridgeResource " + FRIDGE_URI +
+ " : " + FRIDGE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ FRIDGE_URI,
+ FRIDGE_TYPENAME,
+ OcPlatform.GROUP_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "FridgeResource register error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ public static final String FRIDGE_URI = "/fridge/group";
+ public static final String FRIDGE_TYPENAME = "intel.fridge.group";
+ private static String TAG = "FridgeResource: ";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra("message", msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * LightResource
+ * <p/>
+ * LightResource is a sample OIC server resource created by the refrigerator.
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ LightResource(Context context) {
+ mContext = context;
+
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(
+ LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for lightResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ response.setErrorCode(Resource.SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * update the value of light (ON/ OFF) from the representation
+ *
+ * @param representation new state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * helper function to update the current state of the light
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private boolean mIsLightOn = false;
+
+ private static String TAG = "LightResource: ";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+
+/**
+ * Refrigerator
+ * <p/>
+ * Refrigerator class has different objects (resources) which are instantiated when a
+ * Refrigerator object is created. Operations are performed on each of the individual resources.
+ */
+public class Refrigerator {
+ public static final String LEFT_SIDE = "left";
+ public static final String RIGHT_SIDE = "right";
+ public static final String RANDOM_SIDE = "random";
+
+ private FridgeResource mFridge;
+ private LightResource mLight;
+ private DoorResource mLeftDoor;
+ private DoorResource mRightDoor;
+ private DoorResource mRandomDoor;
+
+ /**
+ * constructor - creates resources of light and doors
+ *
+ * @param context needed by individual resources to be able to send broadcast
+ * messages to be displayed on the user screen
+ */
+ Refrigerator(Context context) {
+ mFridge = new FridgeResource(context);
+ mLight = new LightResource(context);
+ mLeftDoor = new DoorResource(LEFT_SIDE, context);
+ mRightDoor = new DoorResource(RIGHT_SIDE, context);
+ mRandomDoor = new DoorResource(RANDOM_SIDE, context);
+
+ mLight.bindTo(mFridge.getHandle());
+ mLeftDoor.bindTo(mFridge.getHandle());
+ mRightDoor.bindTo(mFridge.getHandle());
+ mRandomDoor.bindTo(mFridge.getHandle());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+
+/**
+ * Resource
+ * <p/>
+ * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource
+ */
+public abstract class Resource {
+ protected OcResourceHandle mResourceHandle;
+ protected OcRepresentation mRepresentation;
+
+ Resource() {
+ mResourceHandle = null;
+ mRepresentation = new OcRepresentation();
+ }
+
+ public void bindTo(OcResourceHandle collectionResourceHandle) {
+ try {
+ if (null != mResourceHandle && null != collectionResourceHandle) {
+ OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
+ }
+ } catch (OcException e) {
+ Log.e("Resource", e.getMessage());
+ }
+ }
+
+ public static final int SUCCESS = 200;
+ public static final String INTENT = "org.iotivity.base.examples.fridgegroupserver";
+ public static final String MESSAGE = "message";
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * DeviceResource
+ * <p/>
+ * Creates a device resource and performs action based on client requests
+ */
+public class DeviceResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DEVICE_URI = "/device";
+ public static final String RESOURCE_TYPENAME = "intel.fridge";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final String DEVICE_NAME = "device_name";
+ private static String TAG = "DeviceResource: ";
+ public static final int SUCCESS = 200;
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_VERSION_KEY = 3000;
+
+ private Context mContext;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DeviceResource(Context context) {
+ mContext = context;
+ registerDeviceResource();
+ }
+
+ private void registerDeviceResource() {
+ try {
+ logMessage("RegisterDeviceResource " + DEVICE_URI + " : " + RESOURCE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ DEVICE_URI,
+ RESOURCE_TYPENAME,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ List<OcHeaderOption> headerOptions = ocResourceRequest.getHeaderOptions();
+ String clientAPIVersion = "";
+ String clientToken = "";
+ // search for header options map and look for API version and client token
+ for (OcHeaderOption headerOption : headerOptions) {
+ int optionId = headerOption.getOptionId();
+ if (API_VERSION_KEY == optionId) {
+ clientAPIVersion = headerOption.getOptionData();
+ logMessage(TAG + " Client API Version: " + clientAPIVersion);
+ } else if (CLIENT_VERSION_KEY == optionId) {
+ clientToken = headerOption.getOptionData();
+ logMessage(TAG + " Client Token: " + clientToken);
+ }
+ }
+ if (clientAPIVersion.equals(API_VERSION) &&
+ clientToken.equals(CLIENT_TOKEN)) {
+ List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY,
+ API_VERSION);
+ serverHeaderOptions.add(apiVersion);
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ response.setHeaderOptions(serverHeaderOptions);
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * update state of device
+ *
+ * @return device representation
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DEVICE_NAME,
+ "Intel Powered 3 door, 1 light refrigerator");
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra("message", msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * Creates a door resource and performs actions based on the client requests
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ private boolean mDoorState;
+ private String mSide;
+
+ /**
+ * Constructor
+ *
+ * @param side side of the door
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
+ response.setErrorCode(SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ response.setErrorCode(204);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "DoorResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+/**
+ * FridgeServer
+ * <p/>
+ * This is the main fridgeServer class. This instantiates Refrigerator object
+ * which has different resources (DeviceResource, LightResource, DoorResources).
+ */
+public class FridgeServer extends Activity {
+ private Refrigerator refrigerator;
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void startFridgeServer() {
+ //create platform config
+ PlatformConfig cfg = new PlatformConfig(
+ this, //context
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+ logMessage("Configuring platform");
+ OcPlatform.Configure(cfg);
+ logMessage("Creating refrigerator resources");
+ refrigerator = new Refrigerator(this);
+ logMessage("-----------------------------------------------------");
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private static String TAG = "FridgeServer: ";
+ public static final String MESSAGE = "message";
+ public static final String INTENT = "org.iotivity.base.examples.fridgeserver";
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+ private MessageReceiver mMessageReceiver = new MessageReceiver();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_server);
+ registerReceiver(mMessageReceiver, new IntentFilter(INTENT));
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeServer();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String message = intent.getStringExtra(MESSAGE);
+ logMessage(message);
+ }
+ }
+
+ public void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * LightResource
+ * <p/>
+ * Creates a light resource and performs actions based on the client requests
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String LIGHT_STATUS_KEY = "light";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ private boolean mIsLightOn = false;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ LightResource(Context context) {
+ mContext = context;
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ response.setErrorCode(SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of LightResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * updates the current state of the light (on/ off)
+ *
+ * @return light is on or off
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of mIsOn from the representation
+ *
+ * @param representation get current state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "LightResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+
+/**
+ * Refrigerator
+ * <p/>
+ * Refrigerator class has different objects (resources) which are instantiated when a
+ * Refrigerator object is created.
+ */
+public class Refrigerator {
+ public static final String LEFT_SIDE = "left";
+ public static final String RIGHT_SIDE = "right";
+ public static final String RANDOM_SIDE = "random";
+
+ private LightResource mLight;
+ private DeviceResource mDevice;
+ private DoorResource mLeftDoor;
+ private DoorResource mRightDoor;
+ private DoorResource mRandomDoor;
+
+ /**
+ * constructor
+ *
+ * @param context needed by individual resources to be able to send broadcast
+ * messages to be displayed on the user screen
+ */
+ Refrigerator(Context context) {
+ mLight = new LightResource(context);
+ mDevice = new DeviceResource(context);
+ mLeftDoor = new DoorResource(LEFT_SIDE, context);
+ mRightDoor = new DoorResource(RIGHT_SIDE, context);
+ mRandomDoor = new DoorResource(RANDOM_SIDE, context);
+
+ mLight.bindTo(mDevice.getHandle());
+ mLeftDoor.bindTo(mDevice.getHandle());
+ mRightDoor.bindTo(mDevice.getHandle());
+ mRandomDoor.bindTo(mDevice.getHandle());
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples.fridgeserver;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+
+/**
+ * Resource
+ * <p/>
+ * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource
+ */
+public class Resource {
+ protected OcResourceHandle mResourceHandle;
+ protected OcRepresentation mRepresentation;
+
+ Resource() {
+ mResourceHandle = null;
+ mRepresentation = new OcRepresentation();
+ }
+
+ public void bindTo(OcResourceHandle collectionResourceHandle) {
+ try {
+ if (null != mResourceHandle && null != collectionResourceHandle) {
+ OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
+ }
+ } catch (OcException e) {
+ Log.e("Resource", e.getMessage());
+ }
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ public static final int SUCCESS = 200;
+}
\ No newline at end of file
--- /dev/null
+#
+# //******************************************************************
+# //
+# // Copyright 2015 Intel Corporation.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // Licensed under the Apache License, Version 2.0 (the "License");
+# // you may not use this file except in compliance with the License.
+# // You may obtain a copy of the License at
+# //
+# // http://www.apache.org/licenses/LICENSE-2.0
+# //
+# // Unless required by applicable law or agreed to in writing, software
+# // distributed under the License is distributed on an "AS IS" BASIS,
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# // See the License for the specific language governing permissions and
+# // limitations under the License.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+TARGET_ARCH=armeabi
+RELEASE=release
+SECURED=1
+ERROR_MSG="if building examples from android-studio, you might need to modify the default TARGET_ARCH\
+ and RELEASE in <iotivity>/android/examples/gradle.properties,\
+ if your aar file has different values for TARGET_ARCH and RELEASE"
+
--- /dev/null
+#Wed Apr 10 15:27:10 PDT 2013\r
+distributionBase=GRADLE_USER_HOME\r
+distributionPath=wrapper/dists\r
+zipStoreBase=GRADLE_USER_HOME\r
+zipStorePath=wrapper/dists\r
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip\r
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * GroupClient
+ */
+public class GroupClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener {
+
+ private OcResource mFoundCollectionResource;
+
+ /**
+ * A local method to configure and initialize platform and then search for the collection
+ * resources
+ */
+ private synchronized void startGroupClient() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", 0,
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ msg("Find all resources of type \"a.collection\".");
+ try {
+ OcPlatform.findResource(
+ "",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=a.collection",
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to invoke find resource API");
+ }
+
+ printLine();
+ }
+
+ /**
+ * An event handler to be executed whenever a "findResource" request completes successfully
+ *
+ * @param foundResource found resource
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource foundResource) {
+ if (null == foundResource) {
+ msg("Found resource is invalid");
+ return;
+ }
+ if (null != mFoundCollectionResource) {
+ msg("Found another resource, ignoring");
+ return;
+ }
+
+ // Get the resource URI
+ String resourceUri = foundResource.getUri();
+ // Get the resource host address
+ String hostAddress = foundResource.getHost();
+ msg("\tURI of the resource: " + resourceUri);
+ msg("\tHost address of the resource: " + hostAddress);
+ // Get the resource types
+ msg("\tList of resource types: ");
+ for (String resourceType : foundResource.getResourceTypes()) {
+ msg("\t\t" + resourceType);
+ }
+ msg("\tList of resource interfaces:");
+ for (String resourceInterface : foundResource.getResourceInterfaces()) {
+ msg("\t\t" + resourceInterface);
+ }
+ msg("\tList of resource connectivity types:");
+ for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
+ msg("\t\t" + connectivityType);
+ }
+
+ if (resourceUri.equals("/core/a/collection")) {
+ mFoundCollectionResource = foundResource;
+
+ msg("Getting representation of a collection resource...");
+
+ Map<String, String> queryParams = new HashMap<>();
+ try {
+ mFoundCollectionResource.get(
+ "",
+ OcPlatform.DEFAULT_INTERFACE,
+ queryParams,
+ this
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Error occurred while invoking \"get\" API");
+ }
+ }
+
+ printLine();
+ enableStartStopButton();
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request completes successfully
+ *
+ * @param list list of the header options
+ * @param representation representation of a resource
+ */
+ @Override
+ public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation representation) {
+ msg("Representation of a light collection resource:");
+ for (OcRepresentation childRepresentation : representation.getChildren()) {
+ msg("\t\tURI: " + childRepresentation.getUri());
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Failed to get representation of a found collection resource");
+ }
+
+ /**
+ * A local method to reset group client
+ */
+ private synchronized void stopGroupClient() {
+ mFoundCollectionResource = null;
+
+ msg("Group Client is reset.");
+ printLine();
+
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = GroupClient.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_group_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startGroupClient();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopGroupClient();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * GroupServer
+ */
+public class GroupServer extends Activity implements OcPlatform.OnResourceFoundListener {
+
+ private OcResourceHandle mCollectionResourceHandle;
+ private List<OcResourceHandle> mProxyResourceHandleList = new LinkedList<>();
+
+ /**
+ * A local method to configure and initialize platform, register a collection resource
+ * and then search for the light resources.In addition it creates a local light resource and
+ * adds it to the collection.
+ */
+ private synchronized void startGroupServer() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0", 0,
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ String resourceUri = "/core/a/collection";
+ String resourceTypeName = "a.collection";
+ msg("Registering a collection resource.");
+ try {
+ mCollectionResourceHandle = OcPlatform.registerResource(
+ resourceUri, //resource URI
+ resourceTypeName, //resource type name
+ OcPlatform.BATCH_INTERFACE, //using batch interface
+ null, //use default entity handler
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register a collection resource");
+ }
+
+ if (null != mCollectionResourceHandle) {
+ try {
+ OcPlatform.bindInterfaceToResource(
+ mCollectionResourceHandle,
+ OcPlatform.GROUP_INTERFACE);
+
+ OcPlatform.bindInterfaceToResource(
+ mCollectionResourceHandle,
+ OcPlatform.DEFAULT_INTERFACE);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ msg("Sending request to find all resources with \"core.light\" type name");
+ try {
+ OcPlatform.findResource(
+ "",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=core.light",
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to invoke find resource API");
+ }
+
+ OcResourceHandle localLightResourceHandle = null;
+ msg("Registering a local light resource");
+ try {
+ localLightResourceHandle = OcPlatform.registerResource(
+ "/a/light/local", //resource URI
+ "core.light", //resource type name
+ OcPlatform.DEFAULT_INTERFACE, //using default interface
+ null, //use default entity handler
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register a local ligh resource");
+ }
+
+ if (null != localLightResourceHandle) {
+ msg("Binding a found resource proxy handle to the collection resource");
+ try {
+ OcPlatform.bindResource(mCollectionResourceHandle, localLightResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to bind found resource proxy handle to the collection resource");
+ }
+ mProxyResourceHandleList.add(localLightResourceHandle);
+ }
+
+ printLine();
+ }
+
+ /**
+ * An event handler to be executed whenever a "findResource" request completes successfully
+ *
+ * @param foundResource found resource
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource foundResource) {
+ if (null == foundResource) {
+ msg("Found resource is invalid");
+ return;
+ }
+ msg("Found resource with \"core.light\" type name\".");
+ // Get the resource host address
+ String hostAddress = foundResource.getHost();
+ // Get the resource URI
+ String resourceUri = foundResource.getUri();
+ msg("\tHost address of the resource: " + hostAddress);
+ msg("\tURI of the resource: " + resourceUri);
+ // Get the resource types
+ msg("\tList of resource types: ");
+ for (String resourceType : foundResource.getResourceTypes()) {
+ msg("\t\t" + resourceType);
+ }
+ msg("\tList of resource interfaces:");
+ for (String resourceInterface : foundResource.getResourceInterfaces()) {
+ msg("\t\t" + resourceInterface);
+ }
+ msg("\tList of resource connectivity types:");
+ for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
+ msg("\t\t" + connectivityType);
+ }
+
+ //In this example we are only interested in the light resources
+ if (resourceUri.equals("/a/light")) {
+ msg("Registering a found resource as a local proxy resource");
+ OcResourceHandle proxyResourceHandle = null;
+ try {
+ proxyResourceHandle = OcPlatform.registerResource(foundResource);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register a found resource as a local proxy resource");
+ }
+
+ if (null != proxyResourceHandle) {
+ msg("Binding a found resource proxy handle to the collection resource");
+ try {
+ OcPlatform.bindResource(mCollectionResourceHandle, proxyResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to bind found resource proxy handle to the collection resource");
+ }
+ mProxyResourceHandleList.add(proxyResourceHandle);
+ }
+ }
+
+ printLine();
+ enableStartStopButton();
+ }
+
+ /**
+ * A local method to reset group server
+ */
+ private synchronized void stopGroupServer() {
+ msg("Unregistering resources");
+ for (OcResourceHandle proxyResourceHandle : mProxyResourceHandleList) {
+ try {
+ OcPlatform.unbindResource(mCollectionResourceHandle, proxyResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unbind a proxy resource");
+ }
+ try {
+ OcPlatform.unregisterResource(proxyResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unregister a proxy resource");
+ }
+ }
+ mProxyResourceHandleList.clear();
+
+ if (null != mCollectionResourceHandle) {
+ try {
+ OcPlatform.unregisterResource(mCollectionResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unregister a collection resource");
+ }
+ }
+ msg("Group Server is reset.");
+
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = GroupServer.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_group_server);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startGroupServer();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopGroupServer();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
\ No newline at end of file
--- /dev/null
+build
\ No newline at end of file
--- /dev/null
+//apply plugin: 'com.android.application'\r
+//\r
+//android {\r
+// compileSdkVersion 21\r
+// buildToolsVersion "21.1.1"\r
+//\r
+// defaultConfig {\r
+// applicationId "org.iotivity.guiclient"\r
+// minSdkVersion 19\r
+// targetSdkVersion 21\r
+// versionCode 1\r
+// versionName "1.0"\r
+// }\r
+// buildTypes {\r
+// release {\r
+// minifyEnabled false\r
+// proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+// }\r
+// }\r
+//}\r
+//\r
+//dependencies {\r
+// compile fileTree(dir: 'libs', include: ['*.jar'])\r
+// compile 'com.android.support:appcompat-v7:21.0.2'\r
+//}\r
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.content.Context;
+import android.media.Image;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.BaseExpandableListAdapter;
+import android.widget.CompoundButton;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+import android.widget.SeekBar;
+import android.widget.Switch;
+import android.widget.TextView;
+
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
+
+/**
+ * ExpandableResourceListAdapter knows how to render an ExpandableListView, using a
+ * List of OcResourceInfo objects as the parents of the ExpandableListView,
+ * and OcAttributeInfo objects as the children.
+ *
+ * @see org.iotivity.guiclient.OcAttributeInfo
+ */
+public class ExpandableResourceListAdapter extends BaseExpandableListAdapter {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "ExpandableResourceListAdapter";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ private List<OcResourceInfo> resourceList;
+ private Context ctx;
+
+ public ExpandableResourceListAdapter(List<OcResourceInfo> resourceList, Context ctx) {
+ this.resourceList = resourceList;
+ this.ctx = ctx;
+ }
+
+ @Override
+ public Object getChild(int groupPosition, int childPosition) {
+ return resourceList.get(groupPosition).getAttributes().get(childPosition);
+ }
+
+ @Override
+ public int getChildrenCount(int groupPosition) {
+ return resourceList.get(groupPosition).getAttributes().size();
+ }
+
+ @Override
+ public long getChildId(int groupPosition, int childPosition) {
+ return resourceList.get(groupPosition).getAttributes().get(childPosition).hashCode();
+ }
+
+ @Override
+ public int getChildType(int groupPosition, int childPosition) {
+ return this.resourceList.get(groupPosition).getAttributes().get(childPosition)
+ .getType().ordinal();
+ }
+
+ @Override
+ public int getChildTypeCount() {
+ return OC_ATTRIBUTE_TYPE.values().length;
+ }
+
+ @Override
+ public View getChildView(final int groupPosition, int childPosition,
+ boolean isLastChild, View convertView, ViewGroup parent) {
+ View v = convertView;
+ if (v == null) {
+ LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
+ (Context.LAYOUT_INFLATER_SERVICE);
+ switch(OC_ATTRIBUTE_TYPE.fromInt(getChildType(groupPosition, childPosition))) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ v = inflater.inflate(R.layout.attribute_layout_progress_bar, parent, false);
+ break;
+ case LIGHT_DIMMER:
+ v = inflater.inflate(R.layout.attribute_layout_slider, parent, false);
+ break;
+ case LIGHT_SWITCH:
+ case PLATFORM_LED_SWITCH:
+ v = inflater.inflate(R.layout.attribute_layout_on_off_switch, parent, false);
+ break;
+ }
+ }
+
+ OcAttributeInfo attribute =
+ resourceList.get(groupPosition).getAttributes().get(childPosition);
+
+ // All attribute icons and names are currently treated the same so we handle them outside
+ // the type-specific inflater functions
+ ImageView attributeIcon = (ImageView) v.findViewById(R.id.attribute_icon_id);
+ attributeIcon.setVisibility(View.VISIBLE);
+ TextView attributeName = (TextView) v.findViewById(R.id.attribute_name_id);
+ attributeName.setText(getAttributeLabelFromType(attribute.getType()));
+ attributeName.setVisibility(View.VISIBLE);
+
+ // Now inflate the rest of the layout in a type-specific way
+ switch(attribute.getType()){
+ case AMBIENT_LIGHT_SENSOR_READING:
+ this.renderAmbientLightSensorReading(v, groupPosition, attribute);
+ break;
+ case LIGHT_DIMMER:
+ this.renderLightDimmer(v, groupPosition, attribute);
+ break;
+ case LIGHT_SWITCH:
+ this.renderLightSwitch(v, groupPosition, attribute);
+ break;
+ case PLATFORM_LED_SWITCH:
+ this.renderPlatformLedSwitch(v, groupPosition, attribute);
+ break;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ this.renderRoomTemperatureSensorReading(v, groupPosition, attribute);
+ break;
+ }
+
+ return v;
+ }
+
+ @Override
+ public Object getGroup(int groupPosition) {
+ return resourceList.get(groupPosition);
+ }
+
+ @Override
+ public int getGroupCount() {
+ return resourceList.size();
+ }
+
+ @Override
+ public long getGroupId(int groupPosition) {
+ return resourceList.get(groupPosition).hashCode();
+ }
+
+ @Override
+ public View getGroupView(int groupPosition, boolean isExpanded,
+ View convertView, ViewGroup parent) {
+
+ View v = convertView;
+
+ if (v == null) {
+ LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
+ (Context.LAYOUT_INFLATER_SERVICE);
+ v = inflater.inflate(R.layout.resource_list_item_layout, parent, false);
+ }
+
+ TextView resourceName = (TextView) v.findViewById(R.id.resource_name_id);
+ TextView resourceDescription = (TextView) v.findViewById(R.id.resource_description_id);
+ ImageView resourceIcon = (ImageView) v.findViewById(R.id.resource_icon_id);
+
+ OcResourceInfo resource = resourceList.get(groupPosition);
+
+ resourceName.setText(this.getResourceLabelFromType(resource.getType()));
+ resourceDescription.setText(resource.getHost()+resource.getUri());
+ switch (resource.getType()) {
+ case AMBIENT_LIGHT_SENSOR:
+ resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
+ break;
+ case LIGHT:
+ resourceIcon.setImageResource(R.drawable.light_icon);
+ break;
+ case PLATFORM_LED:
+ resourceIcon.setImageResource(R.drawable.led_icon);
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ resourceIcon.setImageResource(R.drawable.thermometer_icon);
+ break;
+ default:
+ resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
+ break;
+ }
+
+ return v;
+ }
+
+ @Override
+ public boolean hasStableIds() {
+ return true;
+ }
+
+ @Override
+ public boolean isChildSelectable(int groupPosition, int childPosition) {
+ return true;
+ }
+
+ /**
+ * Type-specific layout render for Ambient Light Sensor reading attribute.
+ */
+ private void renderAmbientLightSensorReading(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ attributeValue.setText(String.valueOf(attribute.getValueInt()));
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render progressBar
+ ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.attribute_progress_bar);
+ progressBar.setMax(100); // display as percent from 0-100
+ progressBar.setProgress(attribute.getValueAsPercentOfMax());
+ progressBar.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Light Dimmer attribute.
+ */
+ private void renderLightDimmer(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ attributeValue.setText(String.valueOf(attribute.getValueInt()));
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render SeekBar
+ SeekBar slider = (SeekBar) view.findViewById(R.id.attribute_slider);
+ slider.setMax(attribute.getValueMax());
+ slider.setProgress(attribute.getValueInt());
+ slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
+ private int mSliderVal;
+ @Override
+ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onProgressChanged(%s)", progress));
+ this.mSliderVal = progress;
+ }
+ @Override
+ public void onStartTrackingTouch(SeekBar seekBar) {}
+ @Override
+ public void onStopTrackingTouch(SeekBar seekBar) {
+ if (LOCAL_LOGV) Log.v(TAG, "onStopTrackingTouch()");
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).setLightDimmerLevel(resourceList.get(groupPosition),
+ this.mSliderVal);
+ }
+ }
+ });
+ slider.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Light Switch attribute.
+ */
+ private void renderLightSwitch(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ if(false == attribute.getValueBool()) {
+ attributeValue.setText("off");
+ } else {
+ attributeValue.setText("on");
+ }
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render Switch
+ Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
+ toggleSwitch.setText(this.ctx.getString(R.string.oc_light_switch_toggle_text));
+ toggleSwitch.setChecked(attribute.getValueBool());
+ toggleSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).toggleLightSwitch(resourceList.get(groupPosition),
+ isChecked);
+ }
+ }
+ });
+ toggleSwitch.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for LED Switch attribute.
+ */
+ private void renderPlatformLedSwitch(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // Render attributeValue
+ TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
+ if(1 == attribute.getValueInt()) {
+ attributeValue.setText("on");
+ } else {
+ attributeValue.setText("off");
+ }
+ attributeValue.setVisibility(View.VISIBLE);
+
+ // Render Switch
+ Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
+ toggleSwitch.setText(this.ctx.getString(R.string.oc_led_switch_toggle_text));
+ toggleSwitch.setChecked(1 == attribute.getValueInt());
+ toggleSwitch.setOnCheckedChangeListener( new Switch.OnCheckedChangeListener() {
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
+ if(ctx instanceof MainActivity) {
+ // call MainActivity
+ ((MainActivity) ctx).toggleLedSwitch(resourceList.get(groupPosition),
+ isChecked);
+ }
+ }
+ });
+ toggleSwitch.setVisibility(View.VISIBLE);
+ }
+
+ /**
+ * Type-specific layout render for Room Temperature Sensor Reading attribute.
+ */
+ private void renderRoomTemperatureSensorReading(final View view,
+ final int groupPosition,
+ final OcAttributeInfo attribute) {
+ // this happens to have the same behavior as ambient light sensor, so just re-use
+ this.renderAmbientLightSensorReading(view, groupPosition, attribute);
+ }
+
+ private String getAttributeLabelFromType(OC_ATTRIBUTE_TYPE type) {
+ switch (type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ return ctx.getString(R.string.ui_attribute_label_ambient_light_sensor_reading);
+ case LIGHT_DIMMER:
+ return ctx.getString(R.string.ui_attribute_label_light_dimmer);
+ case LIGHT_SWITCH:
+ return ctx.getString(R.string.ui_attribute_label_light_switch);
+ case PLATFORM_LED_SWITCH:
+ return ctx.getString(R.string.ui_attribute_label_led_switch);
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return ctx.getString(R.string.ui_attribute_label_room_temperature_sensor_reading);
+ default:
+ Log.w(TAG, "getAttributeLabelFromType(): unrecognized attribute type.");
+ return "Attribute:";
+ }
+ }
+
+ private String getResourceLabelFromType(OcResourceInfo.OC_RESOURCE_TYPE type) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceLabelFromType()");
+
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR:
+ return ctx.getString(R.string.ui_resource_label_ambient_light_sensor);
+ case LIGHT:
+ return ctx.getString(R.string.ui_resource_label_light);
+ case PLATFORM_LED:
+ return ctx.getString(R.string.ui_resource_label_platform_led);
+ case ROOM_TEMPERATURE_SENSOR:
+ return ctx.getString(R.string.ui_resource_label_room_temperature_sensor);
+ default:
+ Log.w(TAG, "getResourceLabelFromType(): unrecognized resource type.");
+ return "Resource:";
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.app.AlertDialog;
+import android.content.DialogInterface;
+import android.support.v7.app.ActionBarActivity;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.ExpandableListView;
+import android.widget.ProgressBar;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH;
+import static org.iotivity.guiclient.R.id.expandableResourceListView;
+
+/**
+ * MainActivity instantiates a ExpandableListView of type ExpandableResourceListView, and
+ * also creates and starts a OcWorker object to handle the IoTivity specific work.
+ *
+ * @see org.iotivity.guiclient.OcWorker
+ * @see org.iotivity.guiclient.OcWorkerListener
+ * @see org.iotivity.guiclient.ExpandableResourceListAdapter
+ */
+public class MainActivity
+ extends ActionBarActivity
+ implements OcWorkerListener, View.OnClickListener, ExpandableListView.OnChildClickListener {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "MainActivity";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * The data structure behind the displayed List of resources and attributes.
+ */
+ private List<OcResourceInfo> mResourceList;
+
+ /**
+ * The custom adapter for displaying the ResourceListItem List
+ */
+ private ExpandableResourceListAdapter mResourceListAdapter;
+
+ /**
+ * The OIC-aware worker class which does all the OIC API interaction
+ * and handles the results, notifying MainActivity whenever an event
+ * requires a UI update.
+ */
+ private OcWorker mOcWorker;
+
+ /**
+ * Preserve a ref to Action Bar Menu for changing progress icon
+ */
+ private Menu optionsMenu;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onCreate()");
+
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.activity_main);
+
+ // start the OcWorker thread and register as a listener
+ if(null == this.mOcWorker) {
+ this.mOcWorker = new OcWorker(this);
+ this.mOcWorker.start(); // configures the OIC platform and wait for further calls
+ this.mOcWorker.registerListener(this);
+ }
+
+ // init the Resource display list
+ if(null == this.mResourceList) {
+ this.mResourceList = new ArrayList<>();
+ }
+
+ // init the ListView Adapter
+ if(null == this.mResourceListAdapter) {
+ this.mResourceListAdapter = new ExpandableResourceListAdapter(this.mResourceList,
+ this);
+ }
+
+ // init the Expandable List View
+ ExpandableListView exListView =
+ (ExpandableListView) findViewById(expandableResourceListView);
+ exListView.setIndicatorBounds(5, 5);
+ exListView.setIndicatorBounds(0, 20);
+ exListView.setAdapter(this.mResourceListAdapter);
+ exListView.setOnChildClickListener(this);
+ }
+
+ @Override
+ public void onRestoreInstanceState(Bundle savedInstanceState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onRestoreInstanceState()");
+ }
+
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ if (LOCAL_LOGV) Log.v(TAG, "onSaveInstanceState()");
+ }
+
+ @Override
+ public void onClick(View v) {
+ if (LOCAL_LOGV) Log.v(TAG, "onClick()");
+
+ this.setRefreshActionButtonState(false);
+ }
+
+ @Override
+ public boolean onChildClick(ExpandableListView parent,
+ View v,
+ int groupPosition,
+ int childPosition,
+ long id) {
+ if (LOCAL_LOGV) Log.v(TAG, "onChildClick()");
+
+ this.mOcWorker.doGetResource(mResourceList.get(groupPosition));
+
+ return false;
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ if (LOCAL_LOGV) Log.v(TAG, "onCreateOptionsMenu()");
+
+ // save a reference for use in controlling refresh icon later
+ this.optionsMenu = menu;
+
+ // Inflate the menu; this adds items to the action bar if it is present.
+ getMenuInflater().inflate(R.menu.menu_main, menu);
+
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("onOptionsItemSelected(%s)", item.toString()));
+ // Handle action bar item clicks here. The action bar will
+ // automatically handle clicks on the Home/Up button, so long
+ // as you specify a parent activity in AndroidManifest.xml.
+ int id = item.getItemId();
+
+ // Handle the "settings" icon/text click
+ if (id == R.id.action_settings) {
+ return true;
+ }
+
+ // Handle the "developer test" icon/text click
+ if (id == R.id.action_test) {
+ return true;
+ }
+
+ // Handle the trash can "discard" icon click
+ if (id == R.id.action_discard) {
+ AlertDialog diaBox = confirmDiscard();
+ diaBox.show();
+ }
+
+ // Handle the refresh/progress icon click
+ if (id == R.id.action_refresh) {
+ // show the indeterminate progress bar
+ this.setRefreshActionButtonState(true);
+ // use OcWorker to discover resources
+ this.mOcWorker.doDiscoverResources();
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ /**
+ * Handle a resource changed callback from OcWorker by posting a runnable to our
+ * own UI-safe looper/handler
+ */
+ @Override
+ public void onResourceChanged(final OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceChanged()");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ // in case we were waiting for a refresh, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+
+ mResourceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+
+ /**
+ * Handle a new resource found callback from OcWorker by posting a runnable to our
+ * own UI-safe looper/handler
+ */
+ @Override
+ public void onResourceFound(final OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
+
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ // in case we were waiting for a refresh, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+
+ // if resource not already in list, add it
+ if(!mResourceList.contains(resourceInfo)) {
+ mResourceList.add(resourceInfo);
+ }
+
+ mResourceListAdapter.notifyDataSetChanged();
+ }
+ });
+ }
+
+ public void toggleLedSwitch(OcResourceInfo resourceInfo, boolean onOff) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLedSwitch(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == PLATFORM_LED_SWITCH) {
+ if(onOff) {
+ ai.setValueInt(1);
+ } else {
+ ai.setValueInt(0);
+ }
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ public void toggleLightSwitch(OcResourceInfo resourceInfo, boolean onOff) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLightSwitch(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == LIGHT_SWITCH) {
+ ai.setValueBool(onOff);
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ public void setLightDimmerLevel(OcResourceInfo resourceInfo, int value) {
+ if (LOCAL_LOGV) Log.d(TAG, String.format("setLightDimmerLevel(%s, %s)",
+ resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(value)));
+
+ // send a msg to OcWorker to put the switch value
+ for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
+ if(ai.getType() == LIGHT_DIMMER) {
+ ai.setValueInt(value);
+ }
+ }
+ this.mOcWorker.doPutResource(resourceInfo);
+ }
+
+ /**
+ * Sets the Action Bar icon to "progress" (spinning circle), or returns it to refresh icon
+ *
+ * @param refreshing true sets icon to animated "progress" spinner; false to static
+ * refresh icon
+ */
+ private void setRefreshActionButtonState(final boolean refreshing) {
+ if (this.optionsMenu != null) {
+ final MenuItem refreshItem
+ = this.optionsMenu
+ .findItem(R.id.action_refresh);
+ if (refreshItem != null) {
+ if (refreshing) {
+ refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
+ ProgressBar progressBar =
+ (ProgressBar) findViewById(R.id.find_resource_progress_bar);
+ progressBar.setOnClickListener(this);
+
+ } else {
+ refreshItem.setActionView(null);
+ }
+ }
+ }
+ }
+
+ private AlertDialog confirmDiscard()
+ {
+ if (LOCAL_LOGV) Log.v(TAG, "confirmDiscard()");
+
+ return new AlertDialog.Builder(this)
+ .setTitle("Clear Resource List?")
+ .setIcon(R.drawable.ic_action_discard_dark)
+ .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ // clear OcWorker's list
+ mOcWorker.doClearResources();
+ // in case its running, hide the indeterminate progress bar
+ setRefreshActionButtonState(false);
+ // clear our local data model list
+ mResourceList.clear();
+ mResourceListAdapter.notifyDataSetChanged();
+ dialog.dismiss();
+ }
+ })
+
+ .setNegativeButton("No", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ dialog.dismiss();
+ }
+ })
+
+ .create();
+ }
+
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.util.Log;
+
+import java.io.Serializable;
+
+/**
+ * Created by nathanhs on 12/28/15.
+ */
+public class OcAttributeInfo implements Serializable {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcAttributeInfo";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ private static final int AMBIENT_LIGHT_SENSOR_READING_MAX = 4096;
+ private static final int LIGHT_DIMMER_MAX = 100;
+ private static final int LIGHT_SWITCH_MAX = 1;
+ private static final int PLATFORM_LED_SWITCH_MAX = 1;
+ // TODO: once the temp getValueInt works, figure out how to scale this properly
+ private static final int ROOM_TEMPERATURE_SENSOR_READING_MAX = 4096;
+
+ /**
+ * These are the resource types supported by OcResourceInfo.
+ */
+ public enum OC_ATTRIBUTE_TYPE {
+ AMBIENT_LIGHT_SENSOR_READING,
+ LIGHT_DIMMER,
+ LIGHT_SWITCH,
+ PLATFORM_LED_SWITCH,
+ ROOM_TEMPERATURE_SENSOR_READING;
+
+ private static final OC_ATTRIBUTE_TYPE[] values = OC_ATTRIBUTE_TYPE.values();
+
+ public static OC_ATTRIBUTE_TYPE fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private boolean mCurrentlyObserved;
+ private final int mId;
+ private static int mIdInitializer = 0;
+ private final boolean mObservable = true; //TODO BROKEN fix when implementing observe
+ private final OcResourceInfo mParentResource;
+ private final boolean mReadOnly;
+ private final OC_ATTRIBUTE_TYPE mType;
+ private boolean mValueBool; // used if attribute has a boolean value
+ private int mValueInt; // used if attribute has an int value
+ private String mValueString; // used if attribute has a String value
+ private final int mValueMax;
+
+ public OcAttributeInfo(OC_ATTRIBUTE_TYPE type, OcResourceInfo parent) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcAttributeInfo() constructor");
+
+ this.mId = OcAttributeInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
+ this.mParentResource = parent;
+ this.mReadOnly = this.getReadOnlyBasedOnType(type);
+ this.mType = type;
+ this.mValueBool = false;
+ this.mValueInt = 0;
+ this.mValueString = "error";
+ this.mValueMax = this.getMaxAttributeValueBasedOnType(type);
+ }
+
+ public int getId() {
+ return mId;
+ }
+
+ public OC_ATTRIBUTE_TYPE getType() {
+ return mType;
+ }
+
+ public boolean getValueBool() {
+ return this.mValueBool;
+ }
+
+ public int getValueInt() {
+ return this.mValueInt;
+ }
+
+ public int getValueMax() {
+ return mValueMax;
+ }
+
+ public String getValueString() {
+ return this.mValueString;
+ }
+
+ public int getValueAsPercentOfMax() {
+ return (this.mValueInt*100)/this.mValueMax;
+ }
+
+ public boolean isCurrentlyObserved() {
+ return this.mCurrentlyObserved;
+ }
+
+ public boolean isObservable() {
+ return this.mObservable;
+ }
+
+ public boolean isReadOnly() {
+ return mReadOnly;
+ }
+
+ public void setCurrentlyObserved(boolean currentlyObserved) {
+ this.mCurrentlyObserved = currentlyObserved;
+ }
+
+ public void setValueBool(boolean value) {
+ this.mValueBool = value;
+ }
+
+ public void setValueInt(int value) {
+ this.mValueInt = value;
+ }
+
+ public void setValueString(String value) {
+ this.mValueString = value;
+ }
+
+ private int getMaxAttributeValueBasedOnType(OC_ATTRIBUTE_TYPE type) {
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ return AMBIENT_LIGHT_SENSOR_READING_MAX;
+ case LIGHT_DIMMER:
+ return LIGHT_DIMMER_MAX;
+ case LIGHT_SWITCH:
+ return LIGHT_SWITCH_MAX;
+ case PLATFORM_LED_SWITCH:
+ return PLATFORM_LED_SWITCH_MAX;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return ROOM_TEMPERATURE_SENSOR_READING_MAX;
+ default:
+ Log.w(TAG, "getMaxAttributeValueBasedOnType(): unrecognized attribute type.");
+ return 0;
+ }
+ }
+
+ private boolean getReadOnlyBasedOnType(OC_ATTRIBUTE_TYPE type) {
+ switch(type) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ return true;
+ case LIGHT_DIMMER:
+ case LIGHT_SWITCH:
+ case PLATFORM_LED_SWITCH:
+ return false;
+ default:
+ Log.w(TAG, "getReadOnlyBasedOnType(): unrecognized attribute type.");
+ return false;
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+/**
+ * OcProtocolStrings contains the IoTivity-specific constant values. To add another supported
+ * Resource or Interface type to this app, begin by adding the new strings here, and then
+ * find the places throughout the app where Resource-specific case switches occur, and add
+ * the newly-supported type there.
+ */
+public interface OcProtocolStrings {
+ // OIC core protocol strings
+ public static final String COAP_CORE = "coap://224.0.1.187/oic/res";
+ public static final String RESOURCE_TYPE_QUERY = "?rt=";
+ public static final String INTERFACE_QUERY = "?if=";
+ // find resource queries
+ public static final String CORE_LIGHT = "core.light";
+ public static final String CORE_EDISON_RESOURCES = "core.edison.resources";
+ // resource URIs
+ public static final String LIGHT_RESOURCE_URI = "/a/light";
+ public static final String LIGHT_RESOURCE_URI2 = "/light0";
+ public static final String LIGHT_RESOURCE_URI3 = "/a/light1";
+ public static final String ROOM_TEMPERATURE_RESOURCE_URI = "/temperature";
+ public static final String AMBIENT_LIGHT_RESOURCE_URI = "/ambientlight";
+ public static final String PLATFORM_LED_RESOURCE_URI = "/led";
+ // attribute keys for set() calls
+ public static final String LIGHT_SWITCH_RESOURCE_KEY = "state";
+ public static final String LIGHT_DIMMER_RESOURCE_KEY = "power";
+ public static final String ROOM_TEMPERATURE_RESOURCE_KEY = "temperature";
+ public static final String AMBIENT_LIGHT_RESOURCE_KEY = "ambientlight";
+ public static final String PLATFORM_LED_RESOURCE_KEY = "switch";
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.util.Log;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.AMBIENT_LIGHT_SENSOR_READING;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
+import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_DIMMER_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI2;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI3;
+import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_SWITCH_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_KEY;
+import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
+import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
+
+/**
+ * OcResourceInfo is a wrapper object for the OcResource object. It implements the Resource-
+ * specific callbacks, and abstracts the IoTivity implementation details from the application.
+ *
+ * In order to use OcResourceInfo, an application should implement the OcResourceInfoListener
+ * interface, which is called when the OcResourceInfo changes in any meaningful way.
+ */
+public class OcResourceInfo
+ implements OcResource.OnGetListener, OcResource.OnPutListener, Serializable {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcResourceInfo";
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * These are the resource types supported by OcResourceInfo. They should have corresponding
+ * URI strings in the OcProtocolStrings interface.
+ */
+ public enum OC_RESOURCE_TYPE {
+ AMBIENT_LIGHT_SENSOR,
+ LIGHT,
+ PLATFORM_LED,
+ ROOM_TEMPERATURE_SENSOR;
+
+ private static final OC_RESOURCE_TYPE[] values = OC_RESOURCE_TYPE.values();
+
+ public static OC_RESOURCE_TYPE fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private List<OcAttributeInfo> mAttributes;
+ private final String mHost;
+ private final int mId;
+ private static int mIdInitializer = 0;
+ private List<OcResourceInfoListener> mListeners;
+ private final OcResource mResource;
+ private final OC_RESOURCE_TYPE mType;
+ private final String mUri;
+
+ public interface OcResourceInfoListener {
+ public void onResourceInfoChanged(OcResourceInfo resourceInfo);
+ }
+
+
+ public OcResourceInfo(OcResource resource, OcResourceInfoListener changeListener) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcResourceInfo() constructor");
+
+ this.mAttributes = new ArrayList<>();
+ this.mHost = resource.getHost();
+ this.mId = OcResourceInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
+ this.mListeners = new ArrayList<>();
+ this.mListeners.add(changeListener);
+ this.mResource = resource;
+ this.mType = this.getResourceTypeFromUri(resource.getUri());
+ this.mUri = resource.getUri();
+
+ }
+
+ public void registerListener(OcResourceInfoListener changeListener) {
+ if(null == this.mListeners) {
+ Log.e(TAG, "registerListener(): null mListeners List");
+ } else {
+ boolean alreadyRegistered = false;
+ for(OcResourceInfoListener rl : this.mListeners) {
+ if(changeListener == rl) {
+ alreadyRegistered = true;
+ }
+ }
+ if(!alreadyRegistered) {
+ this.mListeners.add(changeListener);
+ }
+ }
+ }
+
+ public OC_RESOURCE_TYPE getType() {
+ return this.mType;
+ }
+
+ public String getHost() {
+ return this.mHost;
+ }
+
+ public String getUri() {
+ return this.mUri;
+ }
+
+ @Override
+ public void onGetFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ }
+ Log.e(TAG, throwable.toString());
+ }
+
+ @Override
+ public void onPutFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ }
+ Log.e(TAG, throwable.toString());
+ }
+
+ public List<OcAttributeInfo> getAttributes() {
+ return this.mAttributes;
+ }
+
+ public void doOcGet() {
+ if(null != this.mResource) {
+ try {
+ this.mResource.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ } else {
+ Log.e(TAG, "doOcGet(): null mResource");
+ }
+ }
+
+ public void doOcPut(OcAttributeInfo attribute) {
+ if (LOCAL_LOGV) Log.v(TAG, "doOcPut()");
+
+ if(attribute.isReadOnly()) {
+ Log.w(TAG, String.format("doOcPut(): %s attribute is read only; skipping put!",
+ attribute.getType()));
+ } else {
+ if (null != this.mResource) {
+ try {
+ OcRepresentation representation = new OcRepresentation();
+ switch (attribute.getType()) {
+ case AMBIENT_LIGHT_SENSOR_READING:
+ break;
+ case LIGHT_DIMMER:
+ representation.setValueInt(LIGHT_DIMMER_RESOURCE_KEY,
+ attribute.getValueInt());
+ // This 'sw' logic is here because the current IoTivity Light forces
+ // the switch to "false" if the switch val is not specified.
+ boolean sw = true;
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if(ai.getType() == LIGHT_SWITCH) {
+ sw = ai.getValueBool();
+ }
+ }
+ representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY, sw);
+ break;
+ case LIGHT_SWITCH:
+ representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY,
+ attribute.getValueBool());
+ break;
+ case PLATFORM_LED_SWITCH:
+ representation.setValueInt(PLATFORM_LED_RESOURCE_KEY,
+ attribute.getValueInt());
+ break;
+ case ROOM_TEMPERATURE_SENSOR_READING:
+ break;
+ default:
+ break;
+ }
+ this.mResource.put(representation, new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ } else {
+ Log.e(TAG, "doOcGet(): null mResource");
+ }
+ }
+ }
+
+ private static Object onGetCompletedLock = new Object();
+ @Override
+// public void onGetCompleted(HeaderOptions headerOptions, OcRepresentation ocRepresentation) {
+ public void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ synchronized (onGetCompletedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "enter -> onGetCompleted()");
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
+
+ this.mAttributes.clear();
+ switch(this.mType) {
+ case AMBIENT_LIGHT_SENSOR:
+ int ambientLightVal = ocRepresentation.getValueInt(AMBIENT_LIGHT_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of %s attribute = %d",
+ mType, AMBIENT_LIGHT_RESOURCE_KEY, ambientLightVal));
+ OcAttributeInfo ambientAttribute = new OcAttributeInfo(
+ AMBIENT_LIGHT_SENSOR_READING, this);
+ ambientAttribute.setValueInt(ambientLightVal);
+ this.mAttributes.add(ambientAttribute);
+ break;
+ case LIGHT:
+ // do switch first
+ boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
+ OcAttributeInfo lightSwitchAttribute = new OcAttributeInfo(
+ LIGHT_SWITCH, this);
+ lightSwitchAttribute.setValueBool(lightSwitchVal);
+ this.mAttributes.add(lightSwitchAttribute);
+ // then dimmer
+ int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
+ OcAttributeInfo dimmerAttribute = new OcAttributeInfo(
+ LIGHT_DIMMER, this);
+ dimmerAttribute.setValueInt(dimmerVal);
+ this.mAttributes.add(dimmerAttribute);
+ break;
+ case PLATFORM_LED:
+ int ledVal = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of %s attribute = %d",
+ mType, PLATFORM_LED_RESOURCE_KEY, ledVal));
+ OcAttributeInfo ledAttribute = new OcAttributeInfo(
+ OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH, this);
+ ledAttribute.setValueInt(ledVal);
+ this.mAttributes.add(ledAttribute);
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ int temperatureVal = 98;
+ Log.w(TAG, "getting 'temperature' value is causing crash;" +
+ " skipping and using 98.");
+ // TODO This call crashes in the native JNI code. The example .cpp
+ // app receives a double for the Room Temp key, but the Java API
+ // doesn't support getValueDouble yet.
+ // Debug crash when API fixed?
+// temperatureVal = ocRepresentation.getValueInt(ROOM_TEMPERATURE_RESOURCE_KEY);
+ if (LOCAL_LOGV) Log.v(TAG,
+ String.format("%s int value of 'temperature' attribute = %d",
+ mType, temperatureVal));
+ OcAttributeInfo temperatureAttribute = new OcAttributeInfo(
+ OcAttributeInfo.OC_ATTRIBUTE_TYPE.ROOM_TEMPERATURE_SENSOR_READING,
+ this);
+ temperatureAttribute.setValueInt(temperatureVal);
+ this.mAttributes.add(temperatureAttribute);
+ break;
+ }
+ this.notifyListeners();
+ if (LOCAL_LOGV) Log.v(TAG, "exit <- onGetCompleted()");
+ }
+ }
+
+ /**
+ * Should be called whenever any Resource or Attribute values change on this object.
+ */
+ private void notifyListeners() {
+ if (LOCAL_LOGV) Log.v(TAG, "notifyListeners()");
+
+ for(OcResourceInfoListener l : this.mListeners) {
+ l.onResourceInfoChanged(this);
+ }
+ }
+
+ private Object onPutCompletedLock = new Object();
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ synchronized (onPutCompletedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "enter -> onPutCompleted()");
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
+ if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
+
+ switch(this.mType) {
+ case AMBIENT_LIGHT_SENSOR:
+ Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
+ this.mType));
+ break;
+ case LIGHT:
+ // do switch first
+ boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH) {
+ ai.setValueBool(lightSwitchVal);
+ }
+ }
+ // then dimmer
+ int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER) {
+ ai.setValueInt(dimmerVal);
+ }
+ }
+ break;
+ case PLATFORM_LED:
+ int value = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
+ for(OcAttributeInfo ai : this.mAttributes) {
+ if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH) {
+ ai.setValueInt(value);
+ }
+ }
+ break;
+ case ROOM_TEMPERATURE_SENSOR:
+ Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
+ this.mType));
+ break;
+ }
+ this.notifyListeners();
+ if (LOCAL_LOGV) Log.v(TAG, "exit <- onPutCompleted()");
+ }
+ }
+
+ private OC_RESOURCE_TYPE getResourceTypeFromUri(String uri) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceTypeFromUri()");
+
+ switch(uri) {
+ case LIGHT_RESOURCE_URI:
+ case LIGHT_RESOURCE_URI2:
+ case LIGHT_RESOURCE_URI3:
+ return OC_RESOURCE_TYPE.LIGHT;
+ case AMBIENT_LIGHT_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.AMBIENT_LIGHT_SENSOR;
+ case PLATFORM_LED_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.PLATFORM_LED;
+ case ROOM_TEMPERATURE_RESOURCE_URI:
+ return OC_RESOURCE_TYPE.ROOM_TEMPERATURE_SENSOR;
+ default:
+ Log.w(TAG, "getResourceTypeFromUri(): unsupported resource '" + uri + "'" );
+ }
+ return null;
+ }
+}
--- /dev/null
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.util.Log;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+
+import static org.iotivity.guiclient.OcProtocolStrings.COAP_CORE;
+import static org.iotivity.guiclient.OcProtocolStrings.CORE_EDISON_RESOURCES;
+import static org.iotivity.guiclient.OcProtocolStrings.CORE_LIGHT;
+import static org.iotivity.guiclient.OcProtocolStrings.INTERFACE_QUERY;
+import static org.iotivity.guiclient.OcProtocolStrings.RESOURCE_TYPE_QUERY;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_CLEAR_RESOURCES;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_DISCOVER_RESOURCES;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_GET_RESOURCE;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_PUT_RESOURCE;
+import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.fromInt;
+
+/**
+ * OcWorker
+ *
+ * A class designed to encapsulate the OIC API functionality. OcWorker has its own
+ * thread which is used to call all OIC APIs. To get results back from OcWorker,
+ * implement the interface OcWorkerListener, and call registerListener().
+ *
+ * @see org.iotivity.guiclient.OcWorkerListener
+ *
+ * Created by nathanhs on 12/22/15.
+ */
+public class OcWorker extends Thread
+ implements OcPlatform.OnResourceFoundListener, OcResourceInfo.OcResourceInfoListener {
+ /**
+ * Hardcoded TAG... if project never uses proguard then
+ * MyOcClient.class.getName() is the better way.
+ */
+ private static final String TAG = "OcWorker";
+ private Context mContext;
+
+ private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
+
+ /**
+ * NOTE: DO NOT assign non-default values to these enums!
+ * The correctness of "fromInt()" depends on the enum values not being
+ * overridden. For example DO_TEST = 100, RESULT_TEST = 101.. would BREAK the
+ * fromInt() function. There are designs which can account for arbitrary enum
+ * values, but they are less desirable for other reasons and since we do not
+ * need to use any specific value, this design is the best for this case.
+ */
+
+ /**
+ * These "IN" message types are for posting API-generated request actions
+ * to our OcWorker queue.
+ */
+ public enum OCW_IN_MSG {
+ DO_TEST, // developer testing only
+ DO_DISCOVER_RESOURCES,
+ DO_CLEAR_RESOURCES,
+ DO_GET_RESOURCE,
+ DO_PUT_RESOURCE,
+ DO_OBSERVE_RESOURCE,
+ DO_STOP_OBSERVING_RESOURCE;
+
+ private static final OCW_IN_MSG[] values = values();
+
+ public static OCW_IN_MSG fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ /**
+ * These events are for internally putting work on our thread's looper
+ * queue, usually in a callback where we don't want to do work on the
+ * callback thread.
+ */
+ private enum OC_EVENT {
+ OIC_RESOURCE_FOUND,
+ OIC_RESOURCE_CHANGED;
+
+ private static final OC_EVENT[] values = OC_EVENT.values();
+
+ public static OC_EVENT fromInt(int i) {
+ return values[i];
+ }
+ }
+
+ private Handler mDoMsgHandler;
+
+ private Handler mOcEventHandler;
+
+ /**
+ * The OcResourceInfo List
+ */
+ private ArrayList<OcResourceInfo> mOcResourceInfoList;
+
+ /**
+ * The types of OIC Resources included in "FindResource" calls by this object.
+ */
+ private final String[] mOcFindQueries = {
+ COAP_CORE + RESOURCE_TYPE_QUERY + CORE_LIGHT,
+ COAP_CORE + INTERFACE_QUERY + CORE_EDISON_RESOURCES
+ };
+
+ private List<OcWorkerListener> mListeners;
+
+ public OcWorker(Context context) {
+ if (LOCAL_LOGV) Log.v(TAG, "OcWorker() constructor");
+
+ mContext = context;
+ this.mListeners = new ArrayList<>();
+ }
+
+ /**
+ * Set up our Handler and Looper, then initialize the OIC platform and
+ * start processing messages as they arrive.
+ */
+ public void run() {
+ if (LOCAL_LOGV) Log.v(TAG, "run()");
+
+ Looper.prepare();
+ this.initHandlers(); // set up our message handler
+ this.ocInit(); // init the OIC layer including calling ConfigurePlatform
+ Looper.loop();
+ }
+
+ /**
+ * Registers a listener for OcWorker events.
+ *
+ * @see org.iotivity.guiclient.OcWorkerListener
+ */
+ public void registerListener(OcWorkerListener listener) {
+ if (LOCAL_LOGV) Log.v(TAG, "registerListener()");
+
+ if(null != this.mListeners) {
+ this.mListeners.add(listener);
+ } else {
+ Log.e(TAG, "registerListener(): null mListeners list; not adding listener!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The Resource discovery external API
+ */
+ public void doDiscoverResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "doDiscoverResources()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_DISCOVER_RESOURCES.ordinal()).sendToTarget();
+ } else {
+ Log.e(TAG, "doDiscoverResources(): null mDoMsgHandler; not discovering resources!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The GetResource external API
+ */
+ public void doGetResource(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "doGetResource()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_GET_RESOURCE.ordinal(), resourceInfo).sendToTarget();
+ } else {
+ Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The PutResource external API
+ */
+ public void doPutResource(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "doPutResource()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_PUT_RESOURCE.ordinal(), resourceInfo).sendToTarget();
+ } else {
+ Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * The Clear Resources external API
+ */
+ public void doClearResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "doClearResources()");
+
+ if(null != this.mDoMsgHandler) {
+ this.mDoMsgHandler.obtainMessage(
+ DO_CLEAR_RESOURCES.ordinal()).sendToTarget();
+ } else {
+ Log.e(TAG, "doClearResources(): null mDoMsgHandler; not clearing resources!");
+ Log.e(TAG, "OcWorker.run() must be called before using public methods.");
+ }
+ }
+
+ /**
+ * Set up handlers
+ */
+ private void initHandlers() {
+ if (LOCAL_LOGV) Log.v(TAG, "initHandler()");
+
+ this.mDoMsgHandler = new Handler() {
+ public void handleMessage(Message msg) {
+ Log.d(TAG, String.format("mDoMsgHandler.handleMessage(%s)", msg.toString()));
+ // process incoming messages here
+ OCW_IN_MSG type = fromInt(msg.what);
+ switch(type) {
+ case DO_TEST:
+ break;
+ case DO_DISCOVER_RESOURCES:
+ discoverResources();
+ break;
+ case DO_CLEAR_RESOURCES:
+ clearResourceInfoList();
+ break;
+ case DO_GET_RESOURCE:
+ getResourceAttributes((OcResourceInfo)msg.obj);
+ break;
+ case DO_PUT_RESOURCE:
+ putResourceAttributes((OcResourceInfo)msg.obj);
+ break;
+ case DO_OBSERVE_RESOURCE:
+ break;
+ case DO_STOP_OBSERVING_RESOURCE:
+ break;
+ default:
+ Log.e(TAG, "unknown msg.what in handler");
+ break;
+ }
+ }
+ };
+
+ this.mOcEventHandler = new Handler() {
+ public void handleMessage(Message msg) {
+ Log.d(TAG, String.format("mOcEventHandler.handleMessage(%s)", msg.toString()));
+ // process incoming messages here
+ OC_EVENT type = OC_EVENT.fromInt(msg.what);
+ switch(type) {
+ case OIC_RESOURCE_FOUND:
+ handleNewResourceFound((OcResource)msg.obj);
+ break;
+ case OIC_RESOURCE_CHANGED:
+ handleResourceInfoChange((OcResourceInfo)msg.obj);
+ break;
+ }
+ }
+ };
+ }
+
+ /**
+ * Get the attributes on resourceInfo.
+ *
+ * @param resourceInfo
+ */
+ private void getResourceAttributes(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "getResourceAttributes()");
+
+ // find the matching resource in our resourceList
+ OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
+ resourceInfo.getHost() + resourceInfo.getUri());
+ if(null != existingResource) {
+ existingResource.doOcGet();
+ } else {
+ Log.e(TAG, "getResourceAttributes(): could not find target resource.");
+ }
+ // Done. Later, the onGet listener in the OcResourceInfo object will notify us of a change
+ // via our onResourceChanged() method
+ }
+
+ /**
+ * For each attribute in the resourceInfo.mAttributes, put the attribute value to the
+ * Resource.
+ *
+ * @param resourceInfo
+ */
+ private void putResourceAttributes(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "putResourceAttributes()");
+
+ // find the matching resource in our resourceList
+ OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
+ resourceInfo.getHost() + resourceInfo.getUri());
+ if(null != existingResource) {
+ // for each attribute in resourceInfo, put that attribute to the resource
+ for(OcAttributeInfo attribute : resourceInfo.getAttributes()) {
+ if(false == attribute.isReadOnly()) {
+ existingResource.doOcPut(attribute);
+ }
+ }
+ } else {
+ Log.e(TAG, "putResourceAttributes(): could not find target resource.");
+ }
+ // Done. later, the onPut listener in the OcResourceInfo object will notify us of a change
+ // via our onResourceChanged() method
+ }
+
+ /**
+ * Because this callback is called on a JNI layer thread, don't do work here.
+ * Instead, create a "found resource" message and send to OcWorker's message queue,
+ * Our looper/handler then calls handleNewResource on our own worker thread.
+ *
+ * Also note that this method must be thread safe because it can be called by
+ * multiple concurrent native threads.
+ *
+ * @param resource
+ */
+ private Object onResourceFoundLock = new Object(); // not strictly necessary with this impl.,
+ // but clears up Log message readability.
+ @Override
+ public void onResourceFound(OcResource resource) {
+ synchronized (onResourceFoundLock) {
+ if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
+ if (LOCAL_LOGV) Log.v(TAG, "host: " + resource.getHost());
+ if (LOCAL_LOGV) Log.v(TAG, "uri: " + resource.getUri());
+ if (LOCAL_LOGV) Log.v(TAG, "is observable: " + resource.isObservable());
+
+ this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_FOUND.ordinal(),
+ resource).sendToTarget();
+ }
+ }
+
+ /**
+ * Handles the internal NEW_RESOURCE_FOUND event, typically engueued on "onResourceFound".
+ * Creates a new OcResourceInfo object to wrap the new OcResource and store other info.
+ *
+ * @param resource the OcResource object
+ */
+ private void handleNewResourceFound(OcResource resource) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("handleNewResourceFound(%s)",
+ resource.toString()));
+
+ OcResourceInfo ri =
+ this.selectResourceInfoByHostAndUri(resource.getHost() + resource.getUri());
+
+ // before notifying listeners, update our own internal OcResourceInfo list
+ if(null != mOcResourceInfoList) {
+ // check for pre-existing duplicate before adding
+ if(null == ri) {
+ if (LOCAL_LOGV) Log.v(TAG, "handleNewResourceFound(): ri is new; adding.");
+ // if not found, create new info object
+ ri = new OcResourceInfo(resource, this);
+ // register as a listener to the newly created OcResourceInfo
+ ri.registerListener(this);
+ // kick off a get to fill in attributes
+ ri.doOcGet();
+ // add the info object to our list
+ mOcResourceInfoList.add(ri);
+ }
+ }
+ // notify listeners
+ for(OcWorkerListener l : this.mListeners) {
+ l.onResourceFound(ri);
+ }
+ }
+
+ /**
+ * The "listener" callback from the OcResourceInfo class.
+ * Called by the OcResourceInfo object using the native callback thread.
+ * We use this callback to post an event to our queue so that the work
+ * is serialized with other incoming events, and executed on our worker thread.
+ *
+ * Also note that this method must be thread safe because it could be called by
+ * one of many OcResourceInfo objects on separate native threads.
+ *
+ * @param resourceInfo
+ */
+ private Object onResourceInfoChangedLock = new Object();
+ @Override
+ public void onResourceInfoChanged(OcResourceInfo resourceInfo) {
+
+ synchronized (onResourceInfoChangedLock) {
+ if (LOCAL_LOGV) Log.v(TAG, String.format("resourceInfoChanged(%s)",
+ resourceInfo.toString()));
+
+ // this is a result of a callback (i.e. onGetCompleted, onPut, onObserve)
+ // so we post a message to our queue to transfer the work to our own thread
+ this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_CHANGED.ordinal(),
+ resourceInfo).sendToTarget();
+ }
+ }
+
+ /**
+ * Handle our internal event that is enqueued when a resource is found.
+ *
+ * @param resourceInfo
+ */
+ private void handleResourceInfoChange(OcResourceInfo resourceInfo) {
+ if (LOCAL_LOGV) Log.v(TAG, "handleResourceInfoChange()");
+
+ // notify listeners
+ for(OcWorkerListener l : this.mListeners) {
+ l.onResourceChanged(resourceInfo);
+ }
+ }
+
+ /**
+ * Complete OIC-related initialization, including configuring the platform
+ */
+ private void ocInit() {
+ if (LOCAL_LOGV) Log.v(TAG, "ocInit()");
+
+ // OIC initialization
+ mOcResourceInfoList = new ArrayList<>();
+
+ this.configurePlatform();
+ }
+
+ /**
+ * Configures the OIC platform.
+ */
+ private void configurePlatform() {
+ if (LOCAL_LOGV) Log.v(TAG, "configurePlatform()");
+
+ PlatformConfig cfg = new PlatformConfig(
+ mContext,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ Log.d(TAG, "configurePlatform(): calling OcPlatform.Configure()");
+ OcPlatform.Configure(cfg);
+ }
+
+ /**
+ * Search mOcResourceInfo list for a resource whose Host and Uri concatenated
+ * matches the param passed, and return it.
+ *
+ * @param resourceHostAndUri
+ * @return OcResourceInfo with Host and Uri matching resourceHostAndUri, or null if
+ * no such OcResourceInfo exists in mOcResourceInfoList
+ */
+ private OcResourceInfo selectResourceInfoByHostAndUri(String resourceHostAndUri) {
+ if (LOCAL_LOGV) Log.v(TAG, "selectResourceByHostAndUri()");
+
+ boolean found = false;
+ OcResourceInfo retVal = null;
+
+ for(OcResourceInfo ri : mOcResourceInfoList) {
+ if(!found) {
+ String s = ri.getHost() + ri.getUri();
+ if (resourceHostAndUri.equalsIgnoreCase(s)) {
+ retVal = ri;
+ found = true;
+ }
+ }
+ }
+ if(!found) {
+ Log.v(TAG, "selectResourceByHostAndUri(): no resource found matching HostAndUri "
+ + resourceHostAndUri);
+ }
+
+ return retVal;
+ }
+
+ /**
+ * Finds OIC Resources matching known patterns.
+ *
+ * @see org.iotivity.guiclient.OcProtocolStrings
+ */
+ private void discoverResources() {
+ if (LOCAL_LOGV) Log.v(TAG, "discoverResources()");
+
+ try {
+ for (String s : mOcFindQueries) {
+ Log.d(TAG, String.format("discoverResources(): Calling OcPlatform.findResource(%s)", s));
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + s,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * Clear the ResourceInfoList
+ */
+ private void clearResourceInfoList() {
+ if (LOCAL_LOGV) Log.v(TAG, "clearResourceInfoList()");
+
+ this.mOcResourceInfoList.clear();
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2014 Intel Corporation.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.guiclient;
+
+import android.os.Handler;
+
+import java.util.List;
+
+/**
+ * Applications wishing to use the OcWorker object must implement this interface to
+ * receive notification of OcWorker's ResourceFound and ResourceChanged events.
+ *
+ * @see org.iotivity.guiclient.OcWorker
+ */
+public interface OcWorkerListener {
+
+ /**
+ * Called whenever a new Resource is discovered.
+ *
+ * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
+ * with UI functionality should post a message to their own UI thread, or similar action.
+ *
+ * @param resourceInfo
+ */
+ public void onResourceFound(final OcResourceInfo resourceInfo);
+
+ /**
+ * Called whenever a previously-discovered Resource changes, e.g. as a result of Put,
+ * or Observe callbacks.
+ *
+ * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
+ * with UI functionality should post a message to their own UI thread, or similar action.
+ *
+ * @param resourceInfo
+ */
+ public void onResourceChanged(final OcResourceInfo resourceInfo);
+
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPresenceHandle;
+import org.iotivity.base.OcPresenceStatus;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+
+/**
+ * A client example for presence notification
+ */
+public class PresenceClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcPlatform.OnPresenceListener {
+ private final static String TAG = PresenceClient.class.getSimpleName();
+ private OcResource mResource;
+ private OcPresenceHandle mPresenceHandle;
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ private void startPresenceClient() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ try {
+ msg("Finding Resource...");
+ OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to find resource(s). ");
+ }
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ @Override
+ public synchronized void onResourceFound(OcResource foundResource) {
+ String resourceUri = foundResource.getUri();
+ if (null != mResource || !resourceUri.equals("/a/light")) {
+ msg("Found resource, ignoring");
+ return;
+ }
+
+ msg("Found Resource");
+ String hostAddress = foundResource.getHost();
+ msg("\tResource URI : " + resourceUri);
+ msg("\tResource Host : " + hostAddress);
+ msg("\tResource Interfaces : ");
+ for (String resInterface : foundResource.getResourceInterfaces()) {
+ msg("\t\t" + resInterface);
+ }
+ msg("\tResource Type : ");
+ for (String resTypes : foundResource.getResourceTypes()) {
+ msg("\t\t" + resTypes);
+ }
+
+ try {
+ msg("Subscribing to unicast address:" + hostAddress);
+ OcPlatform.subscribePresence(hostAddress,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to subscribe to unicast address:" + hostAddress);
+ }
+ mResource = foundResource;
+ printLine();
+ }
+
+ @Override
+ public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress) {
+ msg("Received presence notification from : " + hostAddress);
+ switch (ocPresenceStatus) {
+ case OK:
+ msg("Nonce# " + nonce);
+ break;
+ case STOPPED:
+ msg("Presence Stopped");
+ break;
+ case TIMEOUT:
+ msg("Presence Timeout");
+ break;
+ case DO_NOT_HANDLE:
+ msg("Presence Do Not Handle");
+ break;
+ }
+ }
+
+ private void stopPresenceClient() {
+ if (null != mPresenceHandle) {
+ try {
+ msg("Unsubscribing from the presence notifications.");
+ OcPlatform.unsubscribePresence(mPresenceHandle);
+ mPresenceHandle = null;
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unsubscribe from the presence notifications" + e.toString());
+ }
+ }
+ mResource = null;
+ printLine();
+ enableStartStopButton();
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_presence_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startPresenceClient();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopPresenceClient();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+
+/**
+ * A server example for presence notification
+ */
+public class PresenceServer extends Activity {
+ private OcResourceHandle mResourceHandle;
+
+ private void startPresenceServer() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ try {
+ msg("Creating resource of type \"core.light\".");
+ createResource();
+ sleep(1);
+
+ msg("Starting presence notifications.");
+ OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
+ sleep(1);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Error: " + e.toString());
+ }
+ printLine();
+ enableStartStopButton();
+ }
+
+ /**
+ * This function internally calls registerResource API.
+ */
+ private void createResource() {
+ String resourceUri = "/a/light"; // URI of the resource
+ String resourceTypeName = "core.light"; // resource type name.
+ String resourceInterface = OcPlatform.DEFAULT_INTERFACE; // resource interface.
+
+ try {
+ // This will internally create and register the resource.
+ mResourceHandle = OcPlatform.registerResource(
+ resourceUri,
+ resourceTypeName,
+ resourceInterface,
+ null, //Use default entity handler
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ msg("Resource creation was unsuccessful.");
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void stopPresenceServer() {
+ try {
+ msg("Stopping presence notifications.");
+ OcPlatform.stopPresence();
+
+ msg("Unregister resource.");
+ if (null != mResourceHandle) OcPlatform.unregisterResource(mResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Error: " + e.toString());
+ }
+
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = PresenceServer.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_presence_server);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startPresenceServer();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopPresenceServer();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
\ No newline at end of file
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/d",
+ "/oic/p",
+ "/oic/res/types/d",
+ "/oic/ad",
+ "/oic/sec/amacl"
+ ],
+ "perms": 2,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat"
+ ],
+ "perms": 2,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
+ }
+ ],
+ "pstat": {
+ "isop": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
+ "ch": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
+ "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
+ }
+}
--- /dev/null
+package org.iotivity.base.examples.provisioningclient;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Message;
+import android.preference.PreferenceManager;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+import org.iotivity.base.OcProvisioning;
+import org.iotivity.base.OcSecureResource;
+import org.iotivity.base.ProvisionResult;
+import org.iotivity.base.OxmType;
+import org.iotivity.base.OicSecAcl;
+import org.iotivity.base.CredType;
+import org.iotivity.base.KeySize;
+import org.iotivity.base.DeviceStatus;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.List;
+
+public class ProvisioningClient extends Activity implements
+ OcSecureResource.DoOwnershipTransferListener,OcSecureResource.ProvisionPairwiseDevicesListener {
+
+ private static final String TAG = "Provisioning Client: ";
+ private static final int BUFFER_SIZE = 1024;
+ int unownedDevCount = StringConstants.NUMBER_ZERO;
+ private String filePath = "";
+ private OcSecureResource newSecureResource;
+ private List<OcSecureResource> deviceList;
+ private List<OcSecureResource> ownedDeviceList;
+ private TextView mEventsTextView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_secure_provision_client);
+ mEventsTextView = new TextView(this);
+ mEventsTextView.setGravity(Gravity.BOTTOM);
+ mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
+ LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
+ layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
+ );
+ filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
+ //copy json when application runs first time
+ SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
+ boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
+ if (isFirstRun) {
+ copyJsonFromAsset();
+ SharedPreferences.Editor editor = wmbPreference.edit();
+ editor.putBoolean("FIRSTRUN", false);
+ editor.commit();
+ }
+ initOICStack();
+ }
+
+ OcProvisioning.PinCallbackListener pinCallbackListener =
+ new OcProvisioning.PinCallbackListener() {
+ @Override
+ public String pinCallbackListener() {
+ Log.d(TAG, "Inside Pin Callback ");
+ return "";
+ }
+ };
+
+ OcSecureResource.ProvisionAclListener provisionAclListener =
+ new OcSecureResource.ProvisionAclListener() {
+ @Override
+ public void provisionAclListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ Log.d(TAG, "Inside ProvisionAclListener ");
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage("Error: ACL Provision failed !!");
+ } else {
+ logMessage("ACL Provision Done !!");
+ new DeviceRevocationAsyncTask().execute();
+ }
+ }
+ };
+
+ OcSecureResource.ProvisionCredentialsListener provisionCredentialsListener =
+ new OcSecureResource.ProvisionCredentialsListener() {
+ @Override
+ public void provisionCredentialsListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ Log.d(TAG, "Inside ProvisionCredentialsListener ");
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage("Error: Provision Credentials failed !!");
+ } else {
+ logMessage("Provision Credentials Done !!");
+ new ProvisionACLAsyncTask().execute();
+ }
+ }
+ };
+
+ OcSecureResource.UnlinkDevicesListener unlinkDevicesListener =
+ new OcSecureResource.UnlinkDevicesListener() {
+ @Override
+ public void unlinkDevicesListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ Log.d(TAG, "Inside unlinkDevicesListener ");
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage("Error: UnLinking device !!");
+ } else {
+ logMessage("Unlink Done !!");
+ new ProvisionCredentialAsyncTask().execute();
+ }
+ }
+ };
+
+ OcSecureResource.RemoveDeviceListener removeDeviceListener =
+ new OcSecureResource.RemoveDeviceListener() {
+ @Override
+ public void removeDeviceListener(List<ProvisionResult> provisionResults,
+ int hasError) {
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage("Error: Remove Fail !!");
+ } else {
+ logMessage("Remove Device done !!");
+ }
+ }
+ };
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void initOICStack() {
+ //create platform config
+ PlatformConfig cfg = new PlatformConfig(
+ this,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
+ OcPlatform.Configure(cfg);
+ try {
+ /*
+ * Initialize DataBase
+ */
+ String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
+ File.separator;
+ File file = new File(sqlDbPath);
+ //check files directory exists
+ if (!(file.isDirectory())) {
+ file.mkdirs();
+ Log.d(TAG, "Sql db directory created at " + sqlDbPath);
+ }
+ Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
+ OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
+ } catch (OcException e) {
+ logMessage(TAG + "provisionInit error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ new DiscoveryOTTransferAsyncTask().execute();
+ }
+
+ @Override
+ synchronized public void doOwnershipTransferListener(List<ProvisionResult> ProvisionResultList,
+ int hasError) {
+ ProvisionResult pResult = ProvisionResultList.get(0);
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage(TAG + "Ownership Transfer Failed for " + pResult.getDevId());
+ } else {
+ logMessage(TAG + "Ownership Transfer Successful for "
+ + pResult.getDevId());
+ unownedDevCount--;
+ }
+ if (unownedDevCount == 0) { //When done with Ownership Transfer
+ new OwnedDiscoveryAsyncTask().execute();
+ }
+ }
+
+ private void doPairwiseProvisioning() {
+ try {
+ logMessage(TAG + "Pairwise Provisioning b/w " + ownedDeviceList.get(0).getDeviceID()
+ + " and " + ownedDeviceList.get(1).getDeviceID());
+ newSecureResource = ownedDeviceList.get(0);
+ OcSecureResource newSecureResource2 = ownedDeviceList.get(1);
+ List<String> resources = new ArrayList<String>();
+ List<String> owners = new ArrayList<String>();
+ List<String> periods = new ArrayList<String>();
+ List<String> recurrences = new ArrayList<String>();
+ recurrences.add("Daily");
+ resources.add("*");
+ owners.add("adminDeviceUUID0");
+ periods.add("01-01-15");
+ OicSecAcl acl1 = new OicSecAcl(newSecureResource.getDeviceID(), recurrences, periods,
+ 31, resources, owners);
+ OicSecAcl acl2 = new OicSecAcl(newSecureResource2.getDeviceID(), recurrences, periods,
+ 31, resources, owners);
+ newSecureResource.provisionPairwiseDevices(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
+ KeySize.OWNER_PSK_LENGTH_128, acl1, newSecureResource2, acl2, this);
+ } catch (Exception e) {
+ logMessage(TAG + "Pairwise Provisioning error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ @Override
+ public void provisionPairwiseDevicesListener(List<ProvisionResult> ProvisionResultList,
+ int hasError) {
+ if (hasError == StringConstants.ERROR_CODE) {
+ logMessage(TAG + "provisionPairwiseDevices Failed");
+ } else {
+ for (int i = 0; i < ProvisionResultList.size(); i++) {
+ ProvisionResult pResult = ProvisionResultList.get(i);
+ logMessage(TAG + "provisionPairwiseDevices Result for "
+ + pResult.getDevId() + "is " + pResult.getResult());
+ }
+ new GetLinkedDevicesAsyncTask().execute();
+ }
+ }
+
+ /**
+ * Copy svr db json file from assets folder to app data files dir
+ */
+ private void copyJsonFromAsset() {
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+ int length;
+ byte[] buffer = new byte[BUFFER_SIZE];
+ try {
+ inputStream = getAssets().open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
+ File file = new File(filePath);
+ //check files directory exists
+ if (!(file.exists() && file.isDirectory())) {
+ file.mkdirs();
+ }
+ outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
+ while ((length = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, length);
+ }
+ } catch (NullPointerException e) {
+ logMessage(TAG + "Null pointer exception " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ } catch (FileNotFoundException e) {
+ logMessage(TAG + "Json svr db file not found " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ } catch (IOException e) {
+ logMessage(TAG + StringConstants.OIC_CLIENT_JSON_DB_FILE + " file copy failed");
+ Log.e(TAG, e.getMessage());
+ } finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ if (outputStream != null) {
+ try {
+ outputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ }
+
+ public void logMessage(String text) {
+ logMsg(text);
+ }
+
+ public void logMsg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ Message msg = new Message();
+ msg.obj = text;
+ mEventsTextView.append(text);
+ mEventsTextView.append("\n\n");
+ }
+ });
+ Log.i(TAG, text);
+ Intent intent = new Intent(getPackageName());
+ intent.putExtra(StringConstants.MESSAGE, text);
+ sendBroadcast(intent);
+ }
+
+ private class DiscoveryOTTransferAsyncTask extends AsyncTask<Void, String, String> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected String doInBackground(Void... params) {
+ try {
+ /**
+ * Discover Un-owned devices
+ */
+ publishProgress(TAG + "Discovering Unowned Devices");
+ deviceList = new ArrayList<OcSecureResource>(OcProvisioning.discoverUnownedDevices
+ (StringConstants.DISCOVERY_TIMEOUT_10));
+ if (deviceList.size() > 0) {
+ unownedDevCount = deviceList.size();
+ for (int i = 0; i < deviceList.size(); i++) {
+ publishProgress(TAG + "Un-owned Discovered Device " + (i + 1) + "= " +
+ deviceList.get(i).getDeviceID());
+ }
+ try {
+ OcProvisioning.SetownershipTransferCBdata(OxmType.OIC_JUST_WORKS,
+ pinCallbackListener);
+ for (int i = 0; i < deviceList.size(); i++) {
+ publishProgress(TAG + "Doing Ownership Transfer for " +
+ deviceList.get(i).getDeviceID());
+ deviceList.get(i).doOwnershipTransfer(ProvisioningClient.this);
+ }
+ } catch (OcException e) {
+ publishProgress(TAG + "Ownership Transfer error: " + e.getMessage());
+ return "Ownership Transfer error: " + e.getMessage();
+
+ }
+ } else {
+ publishProgress(TAG + "No un-owned devices present");
+ new OwnedDiscoveryAsyncTask().execute();
+ }
+ } catch (OcException e) {
+ publishProgress(TAG + "Un-owned discovery error: " + e.getMessage());
+ return "Un-owned discovery error: " + e.getMessage();
+ }
+ return "success";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+
+ @Override
+ protected void onPostExecute(String s) {
+ super.onPostExecute(s);
+ }
+ }
+
+ private class ProvisionACLAsyncTask extends AsyncTask<Void, String, Void> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ try {
+ if (ownedDeviceList.size() > 1) {
+ OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+ OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
+ publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID());
+ List<String> resources = new ArrayList<String>();
+ List<String> owners = new ArrayList<String>();
+ List<String> periods = new ArrayList<String>();
+ List<String> recurrences = new ArrayList<String>();
+ recurrences.add("Daily");
+ resources.add("*");
+ owners.add("adminDeviceUUID0");
+ periods.add("01-01-15");
+ OicSecAcl aclObject = new OicSecAcl(ocSecureResourceDest.getDeviceID(),
+ recurrences, periods, 31, resources, owners);
+ ocSecureResource.provisionACL(aclObject, provisionAclListener);
+ } else {
+ publishProgress(TAG + "No Owned devices present");
+ }
+ } catch (Exception e) {
+ publishProgress(TAG + "ProvisionACL error: " + e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+ }
+
+ private class ProvisionCredentialAsyncTask extends AsyncTask<Void, String, Void> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ try {
+ if (ownedDeviceList.size() > 1) {
+ OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+ OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
+ publishProgress(TAG + "ProvisionCredential for " +
+ ocSecureResource.getDeviceID() + " with " +
+ ocSecureResourceDest.getDeviceID());
+ ocSecureResource.provisionCredentials(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
+ KeySize.OWNER_PSK_LENGTH_128,
+ ocSecureResourceDest, provisionCredentialsListener);
+ } else {
+ publishProgress(TAG + "Cannot perform credentials between devices");
+ }
+ } catch (Exception e) {
+ publishProgress(TAG + "Provision credentials error: " + e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+ }
+
+ private class GetLinkedDevicesAsyncTask extends AsyncTask<Void, String, String> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected String doInBackground(Void... params) {
+ try {
+ if (ownedDeviceList.size() > 1) {
+ OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+ publishProgress(TAG + "Get linked devices of " + ocSecureResource.getDeviceID());
+ List<String> linkedDevices = ocSecureResource.getLinkedDevices();
+ if (linkedDevices.size() > 0) {
+ for (int i = 0; i < linkedDevices.size(); i++) {
+ publishProgress(TAG + "Linked Devices "+
+ (i + 1) + "= " + linkedDevices.get(i));
+ }
+ } else {
+ publishProgress(TAG + "No linked Devices found");
+ }
+ } else {
+ publishProgress(TAG + "Cannot perform linked devices");
+ }
+ } catch (Exception e) {
+ publishProgress(TAG + "getLinked device error: " + e.getMessage());
+ return "failed";
+ }
+ return "success";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+
+ @Override
+ protected void onPostExecute(String s) {
+ if ("success".equals(s)) {
+ new ProvisionUnlinkAsyncTask().execute();
+ }
+ }
+ }
+
+ private class ProvisionUnlinkAsyncTask extends AsyncTask<Void, String, Void> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ try {
+ if (ownedDeviceList.size() > 1) {
+ OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+ OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
+ publishProgress(TAG + "Un linking " + ocSecureResource.getDeviceID() +
+ " with " + ocSecureResourceDest.getDeviceID());
+ ocSecureResource.unlinkDevices(ocSecureResourceDest, unlinkDevicesListener);
+ } else {
+ publishProgress(TAG + "Cannot perform unlink devices");
+ }
+ } catch (Exception e) {
+ publishProgress(TAG + "Unlink error: " + e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+ }
+
+ private class DeviceRevocationAsyncTask extends AsyncTask<Void, String, Void> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected Void doInBackground(Void... params) {
+ try {
+ if (ownedDeviceList.size() > 0) {
+ OcSecureResource ocSecureResource = ownedDeviceList.get(0);
+ publishProgress(TAG + "Removing " + ocSecureResource.getDeviceID());
+ ocSecureResource.removeDevice(StringConstants.DISCOVERY_TIMEOUT_20,
+ removeDeviceListener);
+ } else {
+ publishProgress(TAG + "Cannot remove");
+ }
+ } catch (Exception e) {
+ publishProgress(TAG + "Remove Device error: " + e.getMessage());
+ }
+ return null;
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+ }
+
+ private class OwnedDiscoveryAsyncTask extends AsyncTask<Void, String, String> {
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ @Override
+ protected String doInBackground(Void... params) {
+ try {
+ publishProgress(TAG + "Initiate Owned device Discovery");
+ ownedDeviceList = OcProvisioning.discoverOwnedDevices
+ (StringConstants.DISCOVERY_TIMEOUT_10);
+ if (ownedDeviceList.size() > 0) {
+ for (int i = 0; i < ownedDeviceList.size(); i++) {
+ publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
+ ownedDeviceList.get(i).getDeviceID()
+ + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
+ + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
+ + "\nDevice Status= " + ((ownedDeviceList.get(i).
+ getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
+ );
+ }
+ } else {
+ publishProgress(TAG + "No Owned devices present");
+ }
+ } catch (OcException e) {
+ publishProgress(TAG + "Owned device Discovery error: " + e.getMessage());
+ return "Owned device Discovery error: " + e.getMessage();
+ }
+ return "success";
+ }
+
+ @Override
+ protected void onProgressUpdate(String... values) {
+ logMessage(values[0]);
+ }
+
+ @Override
+ protected void onPostExecute(String s) {
+ if (ownedDeviceList.size() > 1 && "success".equals(s)) {
+ doPairwiseProvisioning();
+ }
+ }
+ }
+
+ /**
+ * to display on Server Message on Client screen
+ */
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String message = intent.getStringExtra(StringConstants.MESSAGE);
+ logMessage(message);
+ }
+ }
+}
--- /dev/null
+package org.iotivity.base.examples.provisioningclient;
+
+public interface StringConstants {
+
+ public static final int NUMBER_ZERO = 0;
+ public static final int DISCOVERY_TIMEOUT_10 = 10;
+ public static final int DISCOVERY_TIMEOUT_20 = 20;
+ public static final int ERROR_CODE = 1;
+ public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.json";
+ public static final String MESSAGE = "message";
+ public static final String OIC_SQL_DB_FILE = "Pdm.db";
+ public static final int CREDENTIAL_TYPE=1;
+ public static final int OWNER_PSK_LENGTH_128=128/8;
+}
--- /dev/null
+include ':simpleserver', ':simpleclient'//, ':fridgeserver', ':fridgeclient', ':guiclient', ':provisioningclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver'
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/d",
+ "/oic/p",
+ "/oic/res/types/d",
+ "/oic/ad",
+ "/oic/sec/acl"
+ ],
+ "perms": 2,
+ "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat"
+ ],
+ "perms": 2,
+ "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+ }
+ ],
+ "pstat": {
+ "isop": true,
+ "deviceid": "ZGV2aWNlaWQAAAAAABhanw==",
+ "ch": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceid": "MjIyMjIyMjIyMjIyMjIyMg==",
+ "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
+ },
+ "cred": [{
+ "credid": 1,
+ "sub": "MTExMTExMTExMTExMTExMQ==",
+ "credtyp": 1,
+ "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
+ "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+ }]
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcRepresentation;
+
+/**
+ * Light
+ * <p/>
+ * This class is used by SimpleClient to create an object representation of a remote light resource
+ * and update the values depending on the server response
+ */
+public class Light {
+ public static final String NAME_KEY = "name";
+ public static final String STATE_KEY = "state";
+ public static final String POWER_KEY = "power";
+
+ private String mName;
+ private boolean mState;
+ private int mPower;
+
+ public Light() {
+ mName = "";
+ mState = false;
+ mPower = 0;
+ }
+
+ public void setOcRepresentation(OcRepresentation rep) throws OcException {
+ mName = rep.getValue(NAME_KEY);
+ mState = rep.getValue(Light.STATE_KEY);
+ mPower = rep.getValue(Light.POWER_KEY);
+ }
+
+ public OcRepresentation getOcRepresentation() throws OcException {
+ OcRepresentation rep = new OcRepresentation();
+ rep.setValue(NAME_KEY, mName);
+ rep.setValue(STATE_KEY, mState);
+ rep.setValue(POWER_KEY, mPower);
+ return rep;
+ }
+
+ public String getName() {
+ return mName;
+ }
+
+ public void setName(String name) {
+ this.mName = mName;
+ }
+
+ public boolean getState() {
+ return mState;
+ }
+
+ public void setState(boolean state) {
+ this.mState = state;
+ }
+
+ public int getPower() {
+ return mPower;
+ }
+
+ public void setPower(int power) {
+ this.mPower = power;
+ }
+
+ @Override
+ public String toString() {
+ return "\t" + NAME_KEY + ": " + mName +
+ "\n\t" + STATE_KEY + ": " + mState +
+ "\n\t" + POWER_KEY + ": " + mPower;
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceIdentifier;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * SimpleClient
+ * <p/>
+ * SimpleClient is a sample client app which should be started after the simpleServer is started.
+ * It finds resources advertised by the server and calls different operations on it (GET, PUT,
+ * POST, DELETE and OBSERVE).
+ */
+public class SimpleClient implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener,
+ OcResource.OnPutListener,
+ OcResource.OnPostListener,
+ OcResource.OnObserveListener {
+
+ private Map<OcResourceIdentifier, OcResource> mFoundResources = new HashMap<>();
+ private OcResource mFoundLightResource = null;
+ //local representation of a server's light resource
+ private Light mLight = new Light();
+
+ /**
+ * A local method to configure and initialize platform, and then search for the light resources.
+ */
+ private static void startSimpleClient() {
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ SimpleClient client = new SimpleClient();
+ try {
+ msg("Finding all resources of type \"core.light\".");
+ String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=core.light";
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ client
+ );
+ sleep(1);
+
+ /*Find resource is done twice so that we discover the original resources a second time.
+ These resources will have the same uniqueidentifier (yet be different objects),
+ so that we can verify/show the duplicate-checking code in foundResource(above);
+ */
+ msg("Finding all resources of type \"core.light\" for the second time");
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ client
+ );
+
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to invoke find resource API");
+ }
+
+ printLine();
+ }
+
+ /**
+ * An event handler to be executed whenever a "findResource" request completes successfully
+ *
+ * @param ocResource found resource
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource ocResource) {
+ if (null == ocResource) {
+ msg("Found resource is invalid");
+ return;
+ }
+
+ if (mFoundResources.containsKey(ocResource.getUniqueIdentifier())) {
+ msg("Found a previously seen resource again!");
+ } else {
+ msg("Found resource for the first time on server with ID: " + ocResource.getServerId());
+ mFoundResources.put(ocResource.getUniqueIdentifier(), ocResource);
+ }
+
+ if (null != mFoundLightResource) {
+ msg("Found another resource, ignoring");
+ return;
+ }
+ // Get the resource URI
+ String resourceUri = ocResource.getUri();
+ // Get the resource host address
+ String hostAddress = ocResource.getHost();
+ msg("\tURI of the resource: " + resourceUri);
+ msg("\tHost address of the resource: " + hostAddress);
+ // Get the resource types
+ msg("\tList of resource types: ");
+ for (String resourceType : ocResource.getResourceTypes()) {
+ msg("\t\t" + resourceType);
+ }
+ msg("\tList of resource interfaces:");
+ for (String resourceInterface : ocResource.getResourceInterfaces()) {
+ msg("\t\t" + resourceInterface);
+ }
+ msg("\tList of resource connectivity types:");
+ for (OcConnectivityType connectivityType : ocResource.getConnectivityTypeSet()) {
+ msg("\t\t" + connectivityType);
+ }
+ printLine();
+
+ //In this example we are only interested in the light resources
+ if (resourceUri.equals("/a/light")) {
+ //Assign resource reference to a global variable to keep it from being
+ //destroyed by the GC when it is out of scope.
+ mFoundLightResource = ocResource;
+
+ // Call a local method which will internally invoke "get" API on the foundLightResource
+ getLightResourceRepresentation();
+ }
+ }
+
+ /**
+ * Local method to get representation of a found light resource
+ */
+ private void getLightResourceRepresentation() {
+ msg("Getting Light Representation...");
+
+ Map<String, String> queryParams = new HashMap<>();
+ try {
+ // Invoke resource's "get" API with a OcResource.OnGetListener event
+ // listener implementation
+ sleep(1);
+ mFoundLightResource.get(queryParams, this);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"get\" API");
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request completes successfully
+ *
+ * @param list list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("GET request was successful");
+ msg("Resource URI: " + ocRepresentation.getUri());
+
+ try {
+ //Read attribute values into local representation of a light
+ mLight.setOcRepresentation(ocRepresentation);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to read the attributes of a light resource");
+ }
+ msg("Light attributes: ");
+ msg(mLight.toString());
+ printLine();
+
+ //Call a local method which will internally invoke put API on the foundLightResource
+ putLightRepresentation();
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ msgError(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Failed to get representation of a found light resource");
+ }
+
+ /**
+ * Local method to put a different state for this light resource
+ */
+ private void putLightRepresentation() {
+ //set new values
+ mLight.setState(true);
+ mLight.setPower(15);
+
+ msg("Putting light representation...");
+ OcRepresentation representation = null;
+ try {
+ representation = mLight.getOcRepresentation();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get OcRepresentation from a light");
+ }
+
+ Map<String, String> queryParams = new HashMap<>();
+
+ try {
+ sleep(1);
+ // Invoke resource's "put" API with a new representation, query parameters and
+ // OcResource.OnPutListener event listener implementation
+ mFoundLightResource.put(representation, queryParams, this);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"put\" API");
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "put" request completes successfully
+ *
+ * @param list list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
+ msg("PUT request was successful");
+ try {
+ mLight.setOcRepresentation(ocRepresentation);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to create Light representation");
+ }
+ msg("Light attributes: ");
+ msg(mLight.toString());
+ printLine();
+
+ //Call a local method which will internally invoke post API on the foundLightResource
+ postLightRepresentation();
+ }
+
+ /**
+ * An event handler to be executed whenever a "put" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onPutFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ msgError(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Failed to \"put\" a new representation");
+ }
+
+ /**
+ * Local method to post a different state for this light resource
+ */
+ private void postLightRepresentation() {
+ //set new values
+ mLight.setState(false);
+ mLight.setPower(105);
+
+ msg("Posting light representation...");
+ OcRepresentation representation = null;
+ try {
+ representation = mLight.getOcRepresentation();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get OcRepresentation from a light");
+ }
+
+ Map<String, String> queryParams = new HashMap<>();
+ try {
+ sleep(1);
+ // Invoke resource's "post" API with a new representation, query parameters and
+ // OcResource.OnPostListener event listener implementation
+ mFoundLightResource.post(representation, queryParams, this);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"post\" API");
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "post" request completes successfully
+ *
+ * @param list list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("POST request was successful");
+ try {
+ if (ocRepresentation.hasAttribute(OcResource.CREATED_URI_KEY)) {
+ msg("\tUri of the created resource: " +
+ ocRepresentation.getValue(OcResource.CREATED_URI_KEY));
+ } else {
+ mLight.setOcRepresentation(ocRepresentation);
+ msg(mLight.toString());
+ }
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ }
+
+ //setting new values
+ mLight.setState(true);
+ mLight.setPower(55);
+ msg("Posting again light representation...");
+ OcRepresentation representation2 = null;
+ try {
+ representation2 = mLight.getOcRepresentation();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get OcRepresentation from a light");
+ }
+
+ Map<String, String> queryParams = new HashMap<>();
+ try {
+ // Invoke resource's "post" API with a new representation, query parameters and
+ // OcResource.OnPostListener event listener implementation
+ mFoundLightResource.post(representation2, queryParams, onPostListener2);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"post\" API");
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "post" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ msgError(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Failed to \"post\" a new representation");
+ }
+
+ /**
+ * Declare and implement a second OcResource.OnPostListener
+ */
+ OcResource.OnPostListener onPostListener2 = new OcResource.OnPostListener() {
+ /**
+ * An event handler to be executed whenever a "post" request completes successfully
+ * @param list list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("Second POST request was successful");
+ try {
+ if (ocRepresentation.hasAttribute(OcResource.CREATED_URI_KEY)) {
+ msg("\tUri of the created resource: " +
+ ocRepresentation.getValue(OcResource.CREATED_URI_KEY));
+ } else {
+ mLight.setOcRepresentation(ocRepresentation);
+ msg(mLight.toString());
+ }
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ }
+
+ //Call a local method which will internally invoke observe API on the foundLightResource
+ observeFoundLightResource();
+ }
+
+ /**
+ * An event handler to be executed whenever a "post" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ msgError(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Failed to \"post\" a new representation");
+ }
+ };
+
+ /**
+ * Local method to start observing this light resource
+ */
+ private void observeFoundLightResource() {
+ try {
+ sleep(1);
+ // Invoke resource's "observe" API with a observe type, query parameters and
+ // OcResource.OnObserveListener event listener implementation
+ mFoundLightResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"observe\" API");
+ }
+ }
+
+ // holds current number of observations
+ private static int mObserveCount = 0;
+
+ /**
+ * An event handler to be executed whenever a "post" request completes successfully
+ *
+ * @param list list of the header options
+ * @param ocRepresentation representation of a resource
+ * @param sequenceNumber sequence number
+ */
+ @Override
+ public synchronized void onObserveCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation,
+ int sequenceNumber) {
+ if (OcResource.OnObserveListener.REGISTER == sequenceNumber) {
+ msg("Observe registration action is successful:");
+ } else if (OcResource.OnObserveListener.DEREGISTER == sequenceNumber) {
+ msg("Observe De-registration action is successful");
+ } else if (OcResource.OnObserveListener.NO_OPTION == sequenceNumber) {
+ msg("Observe registration or de-registration action is failed");
+ }
+
+ msg("OBSERVE Result:");
+ msg("\tSequenceNumber:" + sequenceNumber);
+ try {
+ mLight.setOcRepresentation(ocRepresentation);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get the attribute values");
+ }
+ msg(mLight.toString());
+
+ if ((++mObserveCount) == 11) {
+ msg("Cancelling Observe...");
+ try {
+ mFoundLightResource.cancelObserve();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Error occurred while invoking \"cancelObserve\" API");
+ }
+ msg("DONE");
+
+ //prepare for the next restart of the SimpleClient
+ resetGlobals();
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "observe" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onObserveFailed(Throwable throwable) {
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ msgError(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ //do something based on errorCode
+ msg("Error code: " + errCode);
+ }
+ msg("Observation of the found light resource has failed");
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = SimpleClient.class.getSimpleName();
+
+ public static void main(String[] args) {
+ startSimpleClient();
+ while (true)
+ sleep(1);
+ }
+
+ private static void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ msgError(TAG, e.toString());
+ }
+ }
+
+ private static void msg(final String text) {
+ System.out.println("[O]" + TAG + " | " + text);
+ }
+
+ private static void msg(final String tag, final String text) {
+ System.out.println("[O]" + tag + " | " + text);
+ }
+
+ private static void msgError(final String tag ,final String text) {
+ System.out.println("[E]" + tag + " | " + text);
+ }
+
+ private static void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private synchronized void resetGlobals() {
+ mFoundLightResource = null;
+ mFoundResources.clear();
+ mLight = new Light();
+ mObserveCount = 0;
+ }
+
+}
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/d",
+ "/oic/p",
+ "/oic/res/types/d",
+ "/oic/ad",
+ "/oic/sec/acl"
+ ],
+ "perms": 2,
+ "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat"
+ ],
+ "perms": 2,
+ "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": ["/light0", "/light1", "/a/light"],
+ "perms": 6,
+ "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+ }
+ ],
+ "pstat": {
+ "isop": true,
+ "deviceid": "ZGV2aWNlaWQAAAAAABhanw==",
+ "ch": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceid": "MTExMTExMTExMTExMTExMQ==",
+ "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
+ },
+ "cred": [{
+ "credid": 1,
+ "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
+ "credtyp": 1,
+ "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
+ "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+ }]
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+package org.iotivity.base.examples;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ObservationInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Light
+ * <p/>
+ * This class represents a light resource
+ */
+public class Light implements OcPlatform.EntityHandler {
+ private static final String NAME_KEY = "name";
+ private static final String STATE_KEY = "state";
+ private static final String POWER_KEY = "power";
+
+ private String mResourceUri; //resource URI
+ private String mResourceTypeName; //resource type name.
+ private String mResourceInterface; //resource interface.
+ private OcResourceHandle mResourceHandle; //resource handle
+
+ private String mName; //light name
+ private boolean mState; //light state
+ private int mPower; //light power
+
+ public Light(String resourceUri, String name, boolean state, int power) {
+ mResourceUri = resourceUri;
+ mResourceTypeName = "core.light";
+ mResourceInterface = OcPlatform.DEFAULT_INTERFACE;
+ mResourceHandle = null; //this is set when resource is registered
+
+ mName = name;
+ mState = state;
+ mPower = power;
+ }
+
+ public synchronized void registerResource() throws OcException {
+ if (null == mResourceHandle) {
+ mResourceHandle = OcPlatform.registerResource(
+ mResourceUri,
+ mResourceTypeName,
+ mResourceInterface,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+ }
+ }
+
+ /**
+ * NOTE: This is just a sample implementation of entity handler. Entity handler can be
+ * implemented in several ways by the manufacturer.
+ *
+ * @param request
+ * @return
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(final OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ if (null == request) {
+ msg("Server request is invalid");
+ return ehResult;
+ }
+ // Get the request flags
+ EnumSet<RequestHandlerFlag> requestFlags = request.getRequestHandlerFlagSet();
+ if (requestFlags.contains(RequestHandlerFlag.INIT)) {
+ msg("\t\tRequest Flag: Init");
+ ehResult = EntityHandlerResult.OK;
+ }
+ if (requestFlags.contains(RequestHandlerFlag.REQUEST)) {
+ msg("\t\tRequest Flag: Request");
+ ehResult = handleRequest(request);
+ }
+ if (requestFlags.contains(RequestHandlerFlag.OBSERVER)) {
+ msg("\t\tRequest Flag: Observer");
+ ehResult = handleObserver(request);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleRequest(OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ // Check for query params (if any)
+ Map<String, String> queries = request.getQueryParameters();
+ if (!queries.isEmpty()) {
+ msg("Query processing is up to entityHandler");
+ } else {
+ msg("No query parameters in this request");
+ }
+
+ for (Map.Entry<String, String> entry : queries.entrySet()) {
+ msg("Query key: " + entry.getKey() + " value: " + entry.getValue());
+ }
+
+ //Get the request type
+ RequestType requestType = request.getRequestType();
+ switch (requestType) {
+ case GET:
+ msg("\t\t\tRequest Type is GET");
+ ehResult = handleGetRequest(request);
+ break;
+ case PUT:
+ msg("\t\t\tRequest Type is PUT");
+ ehResult = handlePutRequest(request);
+ break;
+ case POST:
+ msg("\t\t\tRequest Type is POST");
+ ehResult = handlePostRequest(request);
+ break;
+ case DELETE:
+ msg("\t\t\tRequest Type is DELETE");
+ ehResult = handleDeleteRequest();
+ break;
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleGetRequest(final OcResourceRequest request) {
+ EntityHandlerResult ehResult;
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ if (mIsSlowResponse) { // Slow response case
+ new Thread(new Runnable() {
+ public void run() {
+ handleSlowResponse(request);
+ }
+ }).start();
+ ehResult = EntityHandlerResult.SLOW;
+ } else { // normal response case.
+ response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ ehResult = sendResponse(response);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handlePutRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ setOcRepresentation(request.getResourceRepresentation());
+ response.setResourceRepresentation(getOcRepresentation());
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setErrorCode(SUCCESS);
+ return sendResponse(response);
+ }
+
+ private static int sUriCounter = 1;
+ private EntityHandlerResult handlePostRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+ String newUri = "/a/light" + (++sUriCounter);
+ SimpleServer.createNewLightResource(newUri, "John's light " + sUriCounter);
+ OcRepresentation rep_post = getOcRepresentation();
+ try {
+ rep_post.setValue(OcResource.CREATED_URI_KEY, newUri);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ }
+ response.setResourceRepresentation(rep_post);
+ response.setErrorCode(SUCCESS);
+ response.setNewResourceUri(newUri);
+ response.setResponseResult(EntityHandlerResult.RESOURCE_CREATED);
+ return sendResponse(response);
+ }
+
+ private EntityHandlerResult handleDeleteRequest() {
+ try {
+ this.unregisterResource();
+ return EntityHandlerResult.RESOURCE_DELETED;
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to unregister a light resource");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ private void handleSlowResponse(OcResourceRequest request) {
+ sleep(10);
+ msg("Sending slow response...");
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ sendResponse(response);
+ }
+
+ private List<Byte> mObservationIds; //IDs of observes
+
+ private EntityHandlerResult handleObserver(final OcResourceRequest request) {
+ ObservationInfo observationInfo = request.getObservationInfo();
+ switch (observationInfo.getObserveAction()) {
+ case REGISTER:
+ if (null == mObservationIds) {
+ mObservationIds = new LinkedList<>();
+ }
+ mObservationIds.add(observationInfo.getOcObservationId());
+ break;
+ case UNREGISTER:
+ mObservationIds.remove((Byte)observationInfo.getOcObservationId());
+ break;
+ }
+ // Observation happens on a different thread in notifyObservers method.
+ // If we have not created the thread already, we will create one here.
+ if (null == mObserverNotifier) {
+ mObserverNotifier = new Thread(new Runnable() {
+ public void run() {
+ notifyObservers(request);
+ }
+ });
+ mObserverNotifier.start();
+ }
+ return EntityHandlerResult.OK;
+ }
+
+ private void notifyObservers(OcResourceRequest request) {
+ while (true) {
+ // increment current power value by 10 every 2 seconds
+ mPower += 10;
+ sleep(2);
+
+ msg("Notifying observers...");
+ msg(this.toString());
+ try {
+ if (mIsListOfObservers) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setErrorCode(SUCCESS);
+ response.setResourceRepresentation(getOcRepresentation());
+ OcPlatform.notifyListOfObservers(
+ mResourceHandle,
+ mObservationIds,
+ response);
+ } else {
+ OcPlatform.notifyAllObservers(mResourceHandle);
+ }
+ } catch (OcException e) {
+ ErrorCode errorCode = e.getErrorCode();
+ if (ErrorCode.NO_OBSERVERS == errorCode) {
+ msg("No more observers, stopping notifications");
+ }
+ return;
+ }
+ }
+ }
+
+ private EntityHandlerResult sendResponse(OcResourceResponse response) {
+ try {
+ OcPlatform.sendResponse(response);
+ return EntityHandlerResult.OK;
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to send response");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ public synchronized void unregisterResource() throws OcException {
+ if (null != mResourceHandle) {
+ OcPlatform.unregisterResource(mResourceHandle);
+ }
+ }
+
+ public void setOcRepresentation(OcRepresentation rep) {
+ try {
+ if (rep.hasAttribute(NAME_KEY)) mName = rep.getValue(NAME_KEY);
+ if (rep.hasAttribute(STATE_KEY)) mState = rep.getValue(STATE_KEY);
+ if (rep.hasAttribute(POWER_KEY)) mPower = rep.getValue(POWER_KEY);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get representation values");
+ }
+ }
+
+ public OcRepresentation getOcRepresentation() {
+ OcRepresentation rep = new OcRepresentation();
+ try {
+ rep.setValue(NAME_KEY, mName);
+ rep.setValue(STATE_KEY, mState);
+ rep.setValue(POWER_KEY, mPower);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to set representation values");
+ }
+ return rep;
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ public void setSlowResponse(boolean isSlowResponse) {
+ mIsSlowResponse = isSlowResponse;
+ }
+
+ public void useListOfObservers(boolean isListOfObservers) {
+ mIsListOfObservers = isListOfObservers;
+ }
+
+ @Override
+ public String toString() {
+ return "\t" + "URI" + ": " + mResourceUri +
+ "\n\t" + NAME_KEY + ": " + mName +
+ "\n\t" + STATE_KEY + ": " + mState +
+ "\n\t" + POWER_KEY + ": " + mPower;
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ msgError(TAG, e.toString());
+ }
+ }
+
+ private void msg(String text) {
+ SimpleServer.msg(text);
+ }
+
+ private void msgError(String tag, String text) {
+ SimpleServer.msgError(tag, text);
+ }
+
+ private final static String TAG = Light.class.getSimpleName();
+ private final static int SUCCESS = 200;
+ private boolean mIsSlowResponse = false;
+ private boolean mIsListOfObservers = false;
+ private Thread mObserverNotifier;
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * SimpleServer
+ * <p/>
+ * SimpleServer is a sample OIC server application.
+ * It creates a Light and waits for the incoming client calls to handle
+ * various request scenarios.
+ */
+public class SimpleServer {
+
+ static List<Light> lights = new LinkedList<>();
+
+ /**
+ * A local method to configure and initialize platform, and then create a light resource.
+ */
+ private static void startSimpleServer() {
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ createNewLightResource("/a/light", "John's light");
+
+ msg("Waiting for the requests...");
+ printLine();
+ }
+
+ public static void createNewLightResource(String resourceUri, String resourceName){
+ msg("Creating a light");
+ Light light = new Light(
+ resourceUri, //URI
+ resourceName, //name
+ false, //state
+ 0 //power
+ );
+ msg(light.toString());
+
+ msg("Registering light as a resource");
+ try {
+ light.registerResource();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to register a light resource");
+ }
+ lights.add(light);
+ }
+
+ private static void stopSimpleServer() {
+ for (Light light : lights) {
+ try {
+ light.unregisterResource();
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to unregister a light resource");
+ }
+ }
+ lights.clear();
+
+ msg("All created resources have been unregistered");
+ printLine();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = SimpleServer.class.getSimpleName();
+
+ public static void main(String[] args) {
+ startSimpleServer();
+ }
+
+ public void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ msgError(TAG, e.toString());
+ }
+ }
+
+ public static void msg(final String text) {
+ System.out.println("[O]" + TAG + " | " + text);
+ }
+
+ public static void msg(final String tag, final String text) {
+ System.out.println("[O]" + tag + " | " + text);
+ }
+
+ public static void msgError(final String tag ,final String text) {
+ System.out.println("[E]" + tag + " | " + text);
+ }
+
+ public static void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+}
--- /dev/null
+#!/usr/bin/env bash\r
+\r
+##############################################################################\r
+##\r
+## Gradle start up script for UN*X\r
+##\r
+##############################################################################\r
+\r
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
+DEFAULT_JVM_OPTS=""\r
+\r
+APP_NAME="Gradle"\r
+APP_BASE_NAME=`basename "$0"`\r
+\r
+# Use the maximum available, or set MAX_FD != -1 to use that value.\r
+MAX_FD="maximum"\r
+\r
+warn ( ) {\r
+ echo "$*"\r
+}\r
+\r
+die ( ) {\r
+ echo\r
+ echo "$*"\r
+ echo\r
+ exit 1\r
+}\r
+\r
+# OS specific support (must be 'true' or 'false').\r
+cygwin=false\r
+msys=false\r
+darwin=false\r
+case "`uname`" in\r
+ CYGWIN* )\r
+ cygwin=true\r
+ ;;\r
+ Darwin* )\r
+ darwin=true\r
+ ;;\r
+ MINGW* )\r
+ msys=true\r
+ ;;\r
+esac\r
+\r
+# For Cygwin, ensure paths are in UNIX format before anything is touched.\r
+if $cygwin ; then\r
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`\r
+fi\r
+\r
+# Attempt to set APP_HOME\r
+# Resolve links: $0 may be a link\r
+PRG="$0"\r
+# Need this for relative symlinks.\r
+while [ -h "$PRG" ] ; do\r
+ ls=`ls -ld "$PRG"`\r
+ link=`expr "$ls" : '.*-> \(.*\)$'`\r
+ if expr "$link" : '/.*' > /dev/null; then\r
+ PRG="$link"\r
+ else\r
+ PRG=`dirname "$PRG"`"/$link"\r
+ fi\r
+done\r
+SAVED="`pwd`"\r
+cd "`dirname \"$PRG\"`/" >&-\r
+APP_HOME="`pwd -P`"\r
+cd "$SAVED" >&-\r
+\r
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\r
+\r
+# Determine the Java command to use to start the JVM.\r
+if [ -n "$JAVA_HOME" ] ; then\r
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then\r
+ # IBM's JDK on AIX uses strange locations for the executables\r
+ JAVACMD="$JAVA_HOME/jre/sh/java"\r
+ else\r
+ JAVACMD="$JAVA_HOME/bin/java"\r
+ fi\r
+ if [ ! -x "$JAVACMD" ] ; then\r
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+ fi\r
+else\r
+ JAVACMD="java"\r
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
+\r
+Please set the JAVA_HOME variable in your environment to match the\r
+location of your Java installation."\r
+fi\r
+\r
+# Increase the maximum file descriptors if we can.\r
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then\r
+ MAX_FD_LIMIT=`ulimit -H -n`\r
+ if [ $? -eq 0 ] ; then\r
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then\r
+ MAX_FD="$MAX_FD_LIMIT"\r
+ fi\r
+ ulimit -n $MAX_FD\r
+ if [ $? -ne 0 ] ; then\r
+ warn "Could not set maximum file descriptor limit: $MAX_FD"\r
+ fi\r
+ else\r
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"\r
+ fi\r
+fi\r
+\r
+# For Darwin, add options to specify how the application appears in the dock\r
+if $darwin; then\r
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""\r
+fi\r
+\r
+# For Cygwin, switch paths to Windows format before running java\r
+if $cygwin ; then\r
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`\r
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`\r
+\r
+ # We build the pattern for arguments to be converted via cygpath\r
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\r
+ SEP=""\r
+ for dir in $ROOTDIRSRAW ; do\r
+ ROOTDIRS="$ROOTDIRS$SEP$dir"\r
+ SEP="|"\r
+ done\r
+ OURCYGPATTERN="(^($ROOTDIRS))"\r
+ # Add a user-defined pattern to the cygpath arguments\r
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then\r
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"\r
+ fi\r
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh\r
+ i=0\r
+ for arg in "$@" ; do\r
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`\r
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option\r
+\r
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition\r
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`\r
+ else\r
+ eval `echo args$i`="\"$arg\""\r
+ fi\r
+ i=$((i+1))\r
+ done\r
+ case $i in\r
+ (0) set -- ;;\r
+ (1) set -- "$args0" ;;\r
+ (2) set -- "$args0" "$args1" ;;\r
+ (3) set -- "$args0" "$args1" "$args2" ;;\r
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;\r
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;\r
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;\r
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;\r
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;\r
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;\r
+ esac\r
+fi\r
+\r
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\r
+function splitJvmOpts() {\r
+ JVM_OPTS=("$@")\r
+}\r
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\r
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"\r
+\r
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"\r
--- /dev/null
+@if "%DEBUG%" == "" @echo off\r
+@rem ##########################################################################\r
+@rem\r
+@rem Gradle startup script for Windows\r
+@rem\r
+@rem ##########################################################################\r
+\r
+@rem Set local scope for the variables with windows NT shell\r
+if "%OS%"=="Windows_NT" setlocal\r
+\r
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r
+set DEFAULT_JVM_OPTS=\r
+\r
+set DIRNAME=%~dp0\r
+if "%DIRNAME%" == "" set DIRNAME=.\r
+set APP_BASE_NAME=%~n0\r
+set APP_HOME=%DIRNAME%\r
+\r
+@rem Find java.exe\r
+if defined JAVA_HOME goto findJavaFromJavaHome\r
+\r
+set JAVA_EXE=java.exe\r
+%JAVA_EXE% -version >NUL 2>&1\r
+if "%ERRORLEVEL%" == "0" goto init\r
+\r
+echo.\r
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r
+echo.\r
+echo Please set the JAVA_HOME variable in your environment to match the\r
+echo location of your Java installation.\r
+\r
+goto fail\r
+\r
+:findJavaFromJavaHome\r
+set JAVA_HOME=%JAVA_HOME:"=%\r
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe\r
+\r
+if exist "%JAVA_EXE%" goto init\r
+\r
+echo.\r
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r
+echo.\r
+echo Please set the JAVA_HOME variable in your environment to match the\r
+echo location of your Java installation.\r
+\r
+goto fail\r
+\r
+:init\r
+@rem Get command-line arguments, handling Windowz variants\r
+\r
+if not "%OS%" == "Windows_NT" goto win9xME_args\r
+if "%@eval[2+2]" == "4" goto 4NT_args\r
+\r
+:win9xME_args\r
+@rem Slurp the command line arguments.\r
+set CMD_LINE_ARGS=\r
+set _SKIP=2\r
+\r
+:win9xME_args_slurp\r
+if "x%~1" == "x" goto execute\r
+\r
+set CMD_LINE_ARGS=%*\r
+goto execute\r
+\r
+:4NT_args\r
+@rem Get arguments from the 4NT Shell from JP Software\r
+set CMD_LINE_ARGS=%$\r
+\r
+:execute\r
+@rem Setup the command line\r
+\r
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar\r
+\r
+@rem Execute Gradle\r
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r
+\r
+:end\r
+@rem End local scope for the variables with windows NT shell\r
+if "%ERRORLEVEL%"=="0" goto mainEnd\r
+\r
+:fail\r
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r
+rem the _cmd.exe /c_ return code!\r
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1\r
+exit /b 1\r
+\r
+:mainEnd\r
+if "%OS%"=="Windows_NT" endlocal\r
+\r
+:omega\r
*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
*/\r
\r
-apply plugin: 'com.android.library'\r
\r
+\r
+buildscript {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+ classpath 'com.android.tools.build:gradle:1.3.0'\r
+\r
+ // NOTE: Do not place your application dependencies here; they belong\r
+ // in the individual module build.gradle files\r
+ }\r
+}\r
+\r
+allprojects {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+}\r
+\r
+\r
+apply plugin: 'com.android.library'\r
+ \r
android {\r
+ sourceSets {\r
+ main {\r
+ java {\r
+ srcDirs 'src/main/java', '../common/src/main/java'\r
+ }\r
+ manifest.srcFile 'src/main/AndroidManifest.xml'\r
+ jniLibs.srcDir "$buildDir/native-libs"\r
+ jni.srcDirs = [] //disable automatic ndk-build call\r
+ }\r
+ }\r
+\r
compileSdkVersion 21\r
buildToolsVersion "20.0.0"\r
archivesBaseName = "iotivity-base"\r
abortOnError false\r
}\r
\r
- sourceSets {\r
- main {\r
- manifest.srcFile 'src/main/AndroidManifest.xml'\r
- jniLibs.srcDir 'libs'\r
- jni.srcDirs = [] //disable automatic ndk-build call\r
- }\r
- }\r
}\r
\r
-\r
dependencies {\r
compile fileTree(dir: 'libs', include: ['*.jar'])\r
}\r
\r
-////////////////\r
-////NDK Support\r
-////////////////\r
-//If using this, Android studio will fail run the following to set the environment variable for android studio:\r
-//launchctl setenv ANDROID_NDK_HOME /Users/boos_patrick/Development/Android/android-ndk-r8e\r
-//otherwise remove the dependsOn part and run ./gradlew buildNative from the command line\r
-\r
-task copyNativeLibs(type: Copy, dependsOn: 'buildNative') {\r
- dependsOn 'buildNative'\r
- from(new File('libs')) { include '**/*.so' }\r
- into new File(buildDir, 'native-libs')\r
+task copyNativeLibs(type: Copy) {\r
+ String[] libraries = [\r
+ 'libca-interface.so',\r
+ 'libconnectivity_abstraction.so',\r
+ 'libgnustl_shared.so',\r
+ 'liboc_logger.so',\r
+ 'liboc.so',\r
+ 'libocstack-jni.so',\r
+ 'liboctbstack.so'\r
+ ]\r
+ if ("$SECURED" == '1')\r
+ libraries += [\r
+ 'libocprovision.so',\r
+ 'libocpmapi.so'\r
+ ]\r
+ from(new File("$BUILD_DIR")) { include libraries }\r
+ into new File(buildDir, "native-libs/$TARGET_ARCH")\r
}\r
\r
tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }\r
\r
-clean.dependsOn 'cleanCopyNativeLibs'\r
-\r
tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->\r
pkgTask.jniFolders = new HashSet<File>()\r
pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))\r
}\r
-\r
-task buildNative(type: Exec) {\r
- if (System.env.ANDROID_NDK_HOME != null) {\r
- //for windows use 'ndk-build.cmd'\r
- //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
- def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')\r
- commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED"\r
- } else {\r
- println '##################'\r
- println 'Skipping NDK build'\r
- println 'Reason: ANDROID_NDK_HOME not set.'\r
- println '##################'\r
- }\r
-}\r
--- /dev/null
+/*\r
+ * //******************************************************************\r
+ * //\r
+ * // Copyright 2015 Intel Corporation.\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
+\r
+apply plugin: 'java'\r
+\r
+sourceSets {\r
+ main {\r
+ java {\r
+ srcDirs 'src/main/java', '../common/src/main/java'\r
+ }\r
+ }\r
+}\r
+\r
+\r
+dependencies {\r
+ compile fileTree(dir: 'libs', include: ['*.jar'])\r
+}\r
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+import org.iotivity.ca.CaInterface;
+
+import java.util.EnumSet;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * This class contains the main entrance/functionality of the product. To set a custom
+ * configuration, the implementer must make a call to OcPlatform.Configure before the first usage
+ * of a method in this class.
+ */
+public final class OcPlatform {
+
+ static {
+ System.loadLibrary("oc_logger");
+ System.loadLibrary("octbstack");
+ System.loadLibrary("oc");
+ System.loadLibrary("ocstack-jni");
+ }
+
+ /**
+ * Default interface
+ */
+ public static final String DEFAULT_INTERFACE = "oic.if.baseline";
+
+ /**
+ * Used in discovering (GET) links to other resources of a collection
+ */
+ public static final String LINK_INTERFACE = "oic.if.ll";
+
+ /**
+ * Used in GET, PUT, POST, DELETE methods on links to other resources of a collection
+ */
+ public static final String BATCH_INTERFACE = "oic.if.b";
+
+ /**
+ * Used in GET, PUT, POST methods on links to other remote resources of a group
+ */
+ public static final String GROUP_INTERFACE = "oic.mi.grp";
+
+ public static final String WELL_KNOWN_QUERY = "/oic/res";
+ public static final String WELL_KNOWN_DEVICE_QUERY = "/oic/d";
+ public static final String WELL_KNOWN_PLATFORM_QUERY = "/oic/p";
+ public static final int DEFAULT_PRESENCE_TTL = 60;
+ public static final String PRESENCE_URI = "/oic/ad";
+
+ private static volatile boolean sIsPlatformInitialized = false;
+ private static QualityOfService sPlatformQualityOfService = QualityOfService.NA;
+
+ private OcPlatform() {
+ }
+
+ /**
+ * API for setting the configuration of the OcPlatform.
+ * <p>
+ * Note: Any calls made to this AFTER the first call to OcPlatform.Configure will have no affect
+ * </p>
+ *
+ * @param platformConfig platform configuration
+ */
+ public synchronized static void Configure(PlatformConfig platformConfig) {
+ if (!sIsPlatformInitialized) {
+ CaInterface.initialize();
+
+ sPlatformQualityOfService = platformConfig.getQualityOfService();
+
+ OcPlatform.configure(
+ platformConfig.getServiceType().getValue(),
+ platformConfig.getModeType().getValue(),
+ platformConfig.getIpAddress(),
+ platformConfig.getPort(),
+ platformConfig.getQualityOfService().getValue(),
+ platformConfig.getSvrDbPath()
+ );
+
+ sIsPlatformInitialized = true;
+ }
+ }
+
+ private static native void configure(int serviceType,
+ int modeType,
+ String ipAddress,
+ int port,
+ int qualityOfService,
+ String dbPath);
+
+ /**
+ * API for notifying base that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
+ *
+ * @param ocResourceHandle resource handle of the resource
+ * @throws OcException if failure
+ */
+ public static void notifyAllObservers(
+ OcResourceHandle ocResourceHandle) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.notifyAllObservers0(ocResourceHandle);
+ }
+
+ private static native void notifyAllObservers0(
+ OcResourceHandle ocResourceHandle) throws OcException;
+
+ /**
+ * API for notifying base that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
+ *
+ * @param ocResourceHandle resource handle of the resource
+ * @param qualityOfService the quality of communication
+ * @throws OcException if failure
+ */
+ public static void notifyAllObservers(
+ OcResourceHandle ocResourceHandle,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.notifyAllObservers1(ocResourceHandle, qualityOfService.getValue());
+ }
+
+ private static native void notifyAllObservers1(
+ OcResourceHandle ocResourceHandle,
+ int qualityOfService) throws OcException;
+
+ /**
+ * API for notifying only specific clients that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
+ *
+ * @param ocResourceHandle resource handle of the resource
+ * @param ocObservationIdList These set of ids are ones which which will be notified upon
+ * resource change.
+ * @param ocResourceResponse OcResourceResponse object used by app to fill the response for
+ * this resource change
+ * @throws OcException if failure
+ */
+ public static void notifyListOfObservers(
+ OcResourceHandle ocResourceHandle,
+ List<Byte> ocObservationIdList,
+ OcResourceResponse ocResourceResponse) throws OcException {
+ OcPlatform.initCheck();
+
+ byte[] idArr = new byte[ocObservationIdList.size()];
+ Iterator<Byte> it = ocObservationIdList.iterator();
+ int i = 0;
+ while (it.hasNext()) {
+ idArr[i++] = (byte) it.next();
+ }
+
+ OcPlatform.notifyListOfObservers2(
+ ocResourceHandle,
+ idArr,
+ ocResourceResponse);
+ }
+
+ private static native void notifyListOfObservers2(
+ OcResourceHandle ocResourceHandle,
+ byte[] ocObservationIdArray,
+ OcResourceResponse ocResourceResponse) throws OcException;
+
+ /**
+ * API for notifying only specific clients that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
+ *
+ * @param ocResourceHandle resource handle of the resource
+ * @param ocObservationIdList These set of ids are ones which which will be notified upon
+ * resource change.
+ * @param ocResourceResponse OcResourceResponse object used by app to fill the response for
+ * this resource change
+ * @param qualityOfService the quality of communication
+ * @throws OcException if failure
+ */
+ public static void notifyListOfObservers(
+ OcResourceHandle ocResourceHandle,
+ List<Byte> ocObservationIdList,
+ OcResourceResponse ocResourceResponse,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+
+ byte[] idArr = new byte[ocObservationIdList.size()];
+ Iterator<Byte> it = ocObservationIdList.iterator();
+ int i = 0;
+ while (it.hasNext()) {
+ idArr[i++] = (byte) it.next();
+ }
+
+ OcPlatform.notifyListOfObservers3(
+ ocResourceHandle,
+ idArr,
+ ocResourceResponse,
+ qualityOfService.getValue()
+ );
+ }
+
+ private static native void notifyListOfObservers3(
+ OcResourceHandle ocResourceHandle,
+ byte[] ocObservationIdArray,
+ OcResourceResponse ocResourceResponse,
+ int qualityOfService) throws OcException;
+
+ /**
+ * API for Service and Resource Discovery
+ * <p>
+ * Note: This API is for client side only.
+ * </p>
+ *
+ * @param host Host Address of a service to direct resource discovery query.
+ * If empty, performs multicast resource discovery query
+ * @param resourceUri name of the resource. If null or empty, performs search for all
+ * resource names
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onResourceFoundListener Handles events, success states and failure states.
+ * @throws OcException if failure
+ */
+ public static void findResource(
+ String host,
+ String resourceUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnResourceFoundListener onResourceFoundListener) throws OcException {
+ OcPlatform.initCheck();
+
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+
+ OcPlatform.findResource0(
+ host,
+ resourceUri,
+ connTypeInt,
+ onResourceFoundListener
+ );
+ }
+
+ private static native void findResource0(
+ String host,
+ String resourceUri,
+ int connectivityType,
+ OnResourceFoundListener onResourceFoundListener) throws OcException;
+
+ /**
+ * API for Service and Resource Discovery.
+ * <p>
+ * Note: This API is for client side only.
+ * </p>
+ *
+ * @param host Host IP Address of a service to direct resource discovery query.
+ * If empty, performs multicast resource discovery query
+ * @param resourceUri name of the resource. If null or empty, performs search for all
+ * resource names
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onResourceFoundListener Handles events, success states and failure states.
+ * @param qualityOfService the quality of communication
+ * @throws OcException if failure
+ */
+ public static void findResource(
+ String host,
+ String resourceUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnResourceFoundListener onResourceFoundListener,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+
+ OcPlatform.findResource1(host,
+ resourceUri,
+ connTypeInt,
+ onResourceFoundListener,
+ qualityOfService.getValue()
+ );
+ }
+
+ private static native void findResource1(
+ String host,
+ String resourceUri,
+ int connectivityType,
+ OnResourceFoundListener onResourceFoundListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * API for Device Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param deviceUri Uri containing address to the virtual device
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onDeviceFoundListener Handles events, success states and failure states.
+ * @throws OcException if failure
+ */
+ public static void getDeviceInfo(
+ String host,
+ String deviceUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnDeviceFoundListener onDeviceFoundListener) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ OcPlatform.getDeviceInfo0(
+ host,
+ deviceUri,
+ connTypeInt,
+ onDeviceFoundListener
+ );
+ }
+
+ private static native void getDeviceInfo0(
+ String host,
+ String deviceUri,
+ int connectivityType,
+ OnDeviceFoundListener onDeviceFoundListener) throws OcException;
+
+ /**
+ * API for Device Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param deviceUri Uri containing address to the virtual device
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onDeviceFoundListener Handles events, success states and failure states.
+ * @param qualityOfService the quality of communication
+ * @throws OcException if failure
+ */
+ public static void getDeviceInfo(
+ String host,
+ String deviceUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnDeviceFoundListener onDeviceFoundListener,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ OcPlatform.getDeviceInfo1(
+ host,
+ deviceUri,
+ connTypeInt,
+ onDeviceFoundListener,
+ qualityOfService.getValue()
+ );
+ }
+
+ private static native void getDeviceInfo1(
+ String host,
+ String deviceUri,
+ int connectivityType,
+ OnDeviceFoundListener onDeviceFoundListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * API for Platform Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param platformUri Uri containing address to the platform
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPlatformFoundListener Handles events, success states and failure states.
+ * @throws OcException if failure
+ */
+
+ public static void getPlatformInfo(
+ String host,
+ String platformUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnPlatformFoundListener onPlatformFoundListener) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ OcPlatform.getPlatformInfo0(
+ host,
+ platformUri,
+ connTypeInt,
+ onPlatformFoundListener
+ );
+ }
+
+ private static native void getPlatformInfo0(
+ String host,
+ String platformUri,
+ int connectivityType,
+ OnPlatformFoundListener onPlatformInfoFoundListener) throws OcException;
+
+ /**
+ * API for Platform Discovery
+ *
+ * @param host Host IP Address. If null or empty, Multicast is performed.
+ * @param platformUri Uri containing address to the platform
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPlatformFoundListener Handles events, success states and failure states.
+ * @param qualityOfService the quality of communication
+ * @throws OcException if failure
+ */
+
+ public static void getPlatformInfo(
+ String host,
+ String platformUri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnPlatformFoundListener onPlatformFoundListener,
+ QualityOfService qualityOfService) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ OcPlatform.getPlatformInfo1(
+ host,
+ platformUri,
+ connTypeInt,
+ onPlatformFoundListener,
+ qualityOfService.getValue()
+ );
+ }
+
+ private static native void getPlatformInfo1(
+ String host,
+ String platformUri,
+ int connectivityType,
+ OnPlatformFoundListener onPlatformFoundListener,
+ int qualityOfService) throws OcException;
+
+ /**
+ * This API registers a resource with the server
+ * <p/>
+ * Note: This API applies to server & client side.
+ * </P>
+ *
+ * @param ocResource The instance of OcResource with all data filled
+ * @return resource handle
+ * @throws OcException if failure
+ */
+ public static OcResourceHandle registerResource(
+ OcResource ocResource) throws OcException {
+ OcPlatform.initCheck();
+ return OcPlatform.registerResource0(ocResource);
+ }
+
+ private static native OcResourceHandle registerResource0(
+ OcResource ocResource) throws OcException;
+
+ /**
+ * This API registers a resource with the server NOTE: This API applies to server side only.
+ * <p/>
+ * Note: This API applies to server side only.
+ * </P>
+ *
+ * @param resourceUri The URI of the resource. Example: "a/light"
+ * @param resourceTypeName The resource type. Example: "light"
+ * @param resourceInterface The resource interface (whether it is collection etc).
+ * @param entityHandler entity handler.
+ * @param resourcePropertySet indicates the property of the resource
+ * @return resource handle
+ * @throws OcException if failure
+ */
+ public static OcResourceHandle registerResource(
+ String resourceUri,
+ String resourceTypeName,
+ String resourceInterface,
+ EntityHandler entityHandler,
+ EnumSet<ResourceProperty> resourcePropertySet) throws OcException {
+ OcPlatform.initCheck();
+
+ int resProperty = 0;
+
+ for (ResourceProperty prop : ResourceProperty.values()) {
+ if (resourcePropertySet.contains(prop))
+ resProperty |= prop.getValue();
+ }
+
+ return OcPlatform.registerResource1(resourceUri,
+ resourceTypeName,
+ resourceInterface,
+ entityHandler,
+ resProperty);
+ }
+
+ private static native OcResourceHandle registerResource1(
+ String resourceUri,
+ String resourceTypeName,
+ String resourceInterface,
+ EntityHandler entityHandler,
+ int resourceProperty) throws OcException;
+
+ /**
+ * Register Device Info
+ *
+ * @param ocDeviceInfo object containing all the device specific information
+ * @throws OcException if failure
+ */
+ public static void registerDeviceInfo(
+ OcDeviceInfo ocDeviceInfo) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.registerDeviceInfo0(
+ ocDeviceInfo.getDeviceName()
+ );
+ }
+
+ private static native void registerDeviceInfo0(
+ String deviceName
+ ) throws OcException;
+
+ /**
+ * Register Platform Info
+ *
+ * @param ocPlatformInfo object containing all the platform specific information
+ * @throws OcException if failure
+ */
+ public static void registerPlatformInfo(
+ OcPlatformInfo ocPlatformInfo) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.registerPlatformInfo0(
+ ocPlatformInfo.getPlatformId(),
+ ocPlatformInfo.getManufacturerName(),
+ ocPlatformInfo.getManufacturerUrl(),
+ ocPlatformInfo.getModelNumber(),
+ ocPlatformInfo.getDateOfManufacture(),
+ ocPlatformInfo.getPlatformVersion(),
+ ocPlatformInfo.getOperatingSystemVersion(),
+ ocPlatformInfo.getHardwareVersion(),
+ ocPlatformInfo.getFirmwareVersion(),
+ ocPlatformInfo.getSupportUrl(),
+ ocPlatformInfo.getSystemTime()
+ );
+ }
+
+ private static native void registerPlatformInfo0(
+ String platformId, String manufacturerName, String manufacturerUrl,
+ String modelNumber, String dateOfManufacture, String platformVersion,
+ String operatingSystemVersion, String hardwareVersion, String firmwareVersion,
+ String supportUrl, String systemTime
+ ) throws OcException;
+
+ /**
+ * This API unregisters a resource with the server NOTE: This API applies to server side only.
+ *
+ * @param ocResourceHandle This is the resource handle which we which to unregister from the
+ * server
+ * @throws OcException if failure
+ */
+ public static void unregisterResource(
+ OcResourceHandle ocResourceHandle) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.unregisterResource0(ocResourceHandle);
+ }
+
+ private static native void unregisterResource0(
+ OcResourceHandle ocResourceHandle) throws OcException;
+
+
+ /**
+ * Add a resource to a collection resource
+ *
+ * @param ocResourceCollectionHandle handle to the collection resource
+ * @param ocResourceHandle handle to resource to be added to the collection resource
+ * @throws OcException if failure
+ */
+ public static void bindResource(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle ocResourceHandle) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.bindResource0(ocResourceCollectionHandle, ocResourceHandle);
+ }
+
+ private static native void bindResource0(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle ocResourceHandle) throws OcException;
+
+ /**
+ * Add multiple resources to a collection resource.
+ *
+ * @param ocResourceCollectionHandle handle to the collection resource
+ * @param ocResourceHandleList reference to list of resource handles to be added to the
+ * collection resource
+ * @throws OcException if failure
+ */
+ public static void bindResources(
+ OcResourceHandle ocResourceCollectionHandle,
+ List<OcResourceHandle> ocResourceHandleList) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.bindResources0(
+ ocResourceCollectionHandle,
+ ocResourceHandleList.toArray(
+ new OcResourceHandle[ocResourceHandleList.size()])
+ );
+ }
+
+ private static native void bindResources0(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle[] ocResourceHandleArray) throws OcException;
+
+ /**
+ * Unbind a resource from a collection resource.
+ *
+ * @param ocResourceCollectionHandle handle to the collection resource
+ * @param ocResourceHandle resource handle to be unbound from the collection resource
+ * @throws OcException if failure
+ */
+ public static void unbindResource(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle ocResourceHandle) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.unbindResource0(ocResourceCollectionHandle, ocResourceHandle);
+ }
+
+ private static native void unbindResource0(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle ocResourceHandle) throws OcException;
+
+ /**
+ * Unbind resources from a collection resource.
+ *
+ * @param ocResourceCollectionHandle Handle to the collection resource
+ * @param ocResourceHandleList List of resource handles to be unbound from the collection
+ * resource
+ * @throws OcException if failure
+ */
+ public static void unbindResources(
+ OcResourceHandle ocResourceCollectionHandle,
+ List<OcResourceHandle> ocResourceHandleList) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.unbindResources0(
+ ocResourceCollectionHandle,
+ ocResourceHandleList.toArray(
+ new OcResourceHandle[ocResourceHandleList.size()])
+ );
+ }
+
+ private static native void unbindResources0(
+ OcResourceHandle ocResourceCollectionHandle,
+ OcResourceHandle[] ocResourceHandleArray) throws OcException;
+
+ /**
+ * Binds a type to a particular resource
+ *
+ * @param ocResourceHandle handle to the resource
+ * @param resourceTypeName new typename to bind to the resource
+ * @throws OcException if failure
+ */
+ public static void bindTypeToResource(
+ OcResourceHandle ocResourceHandle,
+ String resourceTypeName) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.bindTypeToResource0(ocResourceHandle, resourceTypeName);
+ }
+
+ private static native void bindTypeToResource0(
+ OcResourceHandle ocResourceHandle,
+ String resourceTypeName) throws OcException;
+
+ /**
+ * Binds an interface to a particular resource
+ *
+ * @param ocResourceHandle handle to the resource
+ * @param resourceInterfaceName new interface to bind to the resource
+ * @throws OcException if failure
+ */
+ public static void bindInterfaceToResource(
+ OcResourceHandle ocResourceHandle,
+ String resourceInterfaceName) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.bindInterfaceToResource0(ocResourceHandle, resourceInterfaceName);
+ }
+
+ private static native void bindInterfaceToResource0(
+ OcResourceHandle ocResourceHandle,
+ String resourceInterfaceName) throws OcException;
+
+ /**
+ * Start Presence announcements.
+ *
+ * @param ttl time to live in seconds
+ * @throws OcException if failure
+ */
+ public static void startPresence(int ttl) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.startPresence0(ttl);
+ }
+
+ private static native void startPresence0(int ttl) throws OcException;
+
+ /**
+ * Stop Presence announcements.
+ *
+ * @throws OcException if failure
+ */
+ public static void stopPresence() throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.stopPresence0();
+ }
+
+ private static native void stopPresence0() throws OcException;
+
+ /**
+ * Subscribes to a server's presence change events. By making this subscription, every time a
+ * server adds/removes/alters a resource, starts or is intentionally stopped
+ *
+ * @param host The IP address/addressable name of the server to subscribe to
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPresenceListener listener that will receive notifications/subscription events
+ * @return a handle object that can be used to identify this subscription request. It can be
+ * used to unsubscribe from these events in the future
+ * @throws OcException if failure
+ */
+ public static OcPresenceHandle subscribePresence(
+ String host,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnPresenceListener onPresenceListener) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ return OcPlatform.subscribePresence0(
+ host,
+ connTypeInt,
+ onPresenceListener
+ );
+ }
+
+ private static native OcPresenceHandle subscribePresence0(
+ String host,
+ int connectivityType,
+ OnPresenceListener onPresenceListener) throws OcException;
+
+ /**
+ * Subscribes to a server's presence change events. By making this subscription, every time a
+ * server adds/removes/alters a resource, starts or is intentionally stopped
+ *
+ * @param host The IP address/addressable name of the server to subscribe to
+ * @param resourceType a resource type specified as a filter for subscription events.
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPresenceListener listener that will receive notifications/subscription events
+ * @return a handle object that can be used to identify this subscription request. It can be
+ * used to unsubscribe from these events in the future
+ * @throws OcException if failure
+ */
+ public static OcPresenceHandle subscribePresence(
+ String host,
+ String resourceType,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ OnPresenceListener onPresenceListener) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ return OcPlatform.subscribePresence1(
+ host,
+ resourceType,
+ connTypeInt,
+ onPresenceListener);
+ }
+
+ private static native OcPresenceHandle subscribePresence1(
+ String host,
+ String resourceType,
+ int connectivityType,
+ OnPresenceListener onPresenceListener) throws OcException;
+
+ /**
+ * Unsubscribes from a previously subscribed server's presence events. Note that you may for
+ * a short time still receive events from the server since it may take time for the
+ * unsubscribe to take effect.
+ *
+ * @param ocPresenceHandle the handle object provided by the subscribePresence call that
+ * identifies this subscription
+ * @throws OcException if failure
+ */
+ public static void unsubscribePresence(
+ OcPresenceHandle ocPresenceHandle) throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.unsubscribePresence0(ocPresenceHandle);
+ }
+
+ private static native void unsubscribePresence0(
+ OcPresenceHandle ocPresenceHandle) throws OcException;
+
+ /**
+ * Creates a resource proxy object so that get/put/observe functionality can be used without
+ * discovering the object in advance. Note that the consumer of this method needs to provide
+ * all of the details required to correctly contact and observe the object. If the consumer
+ * lacks any of this information, they should discover the resource object normally.
+ * Additionally, you can only create this object if OcPlatform was initialized to be a Client
+ * or Client/Server.
+ *
+ * @param host a string containing a resolvable host address of the server holding
+ * the resource
+ * @param uri the rest of the resource's URI that will permit messages to be
+ * properly routed.
+ * Example: /a/light
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param isObservable a boolean containing whether the resource supports observation
+ * @param resourceTypeList a collection of resource types implemented by the resource
+ * @param interfaceList a collection of interfaces that the resource supports/implements
+ * @return new resource object
+ * @throws OcException if failure
+ */
+ public static OcResource constructResourceObject(
+ String host,
+ String uri,
+ EnumSet<OcConnectivityType> connectivityTypeSet,
+ boolean isObservable,
+ List<String> resourceTypeList,
+ List<String> interfaceList) throws OcException {
+ OcPlatform.initCheck();
+ int connTypeInt = 0;
+
+ for (OcConnectivityType connType : OcConnectivityType.values()) {
+ if (connectivityTypeSet.contains(connType))
+ connTypeInt |= connType.getValue();
+ }
+ return OcPlatform.constructResourceObject0(
+ host,
+ uri,
+ connTypeInt,
+ isObservable,
+ resourceTypeList.toArray(new String[resourceTypeList.size()]),
+ interfaceList.toArray(new String[interfaceList.size()])
+ );
+ }
+
+ private static native OcResource constructResourceObject0(
+ String host,
+ String uri,
+ int connectivityType,
+ boolean isObservable,
+ String[] resourceTypes,
+ String[] interfaces) throws OcException;
+
+ /**
+ * Allows application entity handler to send response to an incoming request.
+ *
+ * @param ocResourceResponse resource response
+ * @throws OcException if failure
+ */
+ public static void sendResponse(OcResourceResponse ocResourceResponse)
+ throws OcException {
+ OcPlatform.initCheck();
+ OcPlatform.sendResponse0(ocResourceResponse);
+ }
+
+ private static native void sendResponse0(OcResourceResponse ocResourceResponse)
+ throws OcException;
+
+ /**
+ * An OnResourceFoundListener can be registered via the OcPlatform.findResource call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnResourceFoundListener {
+ public void onResourceFound(OcResource resource);
+ }
+
+ /**
+ * An OnDeviceFoundListener can be registered via the OcPlatform.getDeviceInfo call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnDeviceFoundListener {
+ public void onDeviceFound(OcRepresentation ocRepresentation);
+ }
+
+ /**
+ * An OnPlatformFoundListener can be registered via the OcPlatform.getPlatformInfo call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnPlatformFoundListener {
+ public void onPlatformFound(OcRepresentation ocRepresentation);
+ }
+
+ /**
+ * An OnPresenceListener can be registered via the OcPlatform.subscribePresence call.
+ * Event listeners are notified asynchronously
+ */
+ public interface OnPresenceListener {
+ public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress);
+ }
+
+ /**
+ * An EntityHandler can be registered via the OcPlatform.registerResource call.
+ * Event listeners are notified asynchronously
+ */
+ public interface EntityHandler {
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest);
+ }
+
+ private static void initCheck() {
+ if (!sIsPlatformInitialized) {
+ throw new IllegalStateException("OcPlatform must be configured by making a call to " +
+ "OcPlatform.Configure before any other API calls are permitted");
+ }
+ }
+
+ /**
+ * Gets platform quality of service
+ *
+ * @return quality of service
+ */
+ public static QualityOfService getPlatformQualityOfService() {
+ OcPlatform.initCheck();
+ return sPlatformQualityOfService;
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base;
+
+/**
+ * Data structure to provide the configuration.
+ */
+public class PlatformConfig {
+ private ServiceType mServiceType;
+ private ModeType mModeType;
+ private String mIpAddress;
+ private int mPort;
+ private QualityOfService mQualityOfService;
+ private String mSvrDbPath; //TODO: Instead of SVRDB file, it should be Persistent Storage.
+ //this is only for 0.9.2
+ /**
+ * @param serviceType indicate IN_PROC or OUT_OF_PROC
+ * @param modeType indicate whether we want to do server, client or both
+ * @param ipAddress ip address of server
+ * if you specify 0.0.0.0 : it listens on any interface
+ * @param port port of server
+ * if you specifiy 0 : next available random port is used
+ * if you specify 5683 : client discovery can work even if they don't
+ * specify port
+ * @param qualityOfService quality of service
+ * @param dbPath Persistant storage file for SVR Database.
+ */
+ public PlatformConfig(
+ ServiceType serviceType,
+ ModeType modeType,
+ String ipAddress,
+ int port,
+ QualityOfService qualityOfService,
+ String dbPath) {
+ this.mServiceType = serviceType;
+ this.mModeType = modeType;
+ this.mIpAddress = ipAddress;
+ this.mPort = port;
+ this.mQualityOfService = qualityOfService;
+ this.mSvrDbPath = dbPath;
+ }
+
+ /**
+ * @param serviceType indicate IN_PROC or OUT_OF_PROC
+ * @param modeType indicate whether we want to do server, client or both
+ * @param ipAddress ip address of server
+ * if you specify 0.0.0.0 : it listens on any interface
+ * @param port port of server
+ * if you specifiy 0 : next available random port is used
+ * if you specify 5683 : client discovery can work even if they don't
+ * specify port
+ * @param qualityOfService quality of service
+ */
+ // Avoid breaking building java samples due to persistent storage SVR DB changes.
+ public PlatformConfig(
+ ServiceType serviceType,
+ ModeType modeType,
+ String ipAddress,
+ int port,
+ QualityOfService qualityOfService) {
+ this(serviceType,modeType,ipAddress,port,qualityOfService, "");
+ }
+
+ public ServiceType getServiceType() {
+ return mServiceType;
+ }
+
+ public ModeType getModeType() {
+ return mModeType;
+ }
+
+ public String getIpAddress() {
+ return mIpAddress;
+ }
+
+ public int getPort() {
+ return mPort;
+ }
+
+ public QualityOfService getQualityOfService() {
+ return mQualityOfService;
+ }
+
+ public String getSvrDbPath() {
+ return mSvrDbPath;
+ }
+
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.ca;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcConnectivityType;
+
+class BluetoothDevice {}
+
+public class CaInterface {
+ static {
+ }
+ private static volatile boolean isConnectionManagerInitialized = false;
+ private static volatile boolean isBtPairingInitialized = false;
+
+ public static void initialize() {}
+
+ /**
+ * Method start connection manager service.
+ * this method has to be called before other API call.
+ * @param context application context
+ * @param onConnectionManagerStateListener connection state callback listener
+ */
+ public synchronized static void startManagerService(
+ OnConnectionManagerStateListener onConnectionManagerStateListener) {
+ if (!isConnectionManagerInitialized) {
+ CaInterface.caManagerInitialize(onConnectionManagerStateListener);
+ isConnectionManagerInitialized = true;
+ }
+ }
+
+ /**
+ * Method stop connection manager service.
+ * this method must be called, when Application is destroied.
+ */
+ public synchronized static void stopManagerService() {
+ if (isConnectionManagerInitialized) {
+ CaInterface.caManagerTerminate();
+ isConnectionManagerInitialized = false;
+ }
+ }
+
+ /**
+ * Method set device information for Auto-Connection.
+ * this method has to be called before FindResource is called.
+ * @param address LE address of scanned bluetooth device.
+ */
+ public synchronized static void setAutoConnectionDevice(String address)
+ throws OcException {
+ CaInterface.initCheckForConnectionManager();
+ CaInterface.caManagerSetAutoConnectionDeviceInfo(address);
+ }
+
+ /**
+ * Method unset device information for Auto-Connection.
+ * @param address LE address of scanned bluetooth device.
+ */
+ public synchronized static void unsetAutoConnectionDevice(String address)
+ throws OcException {
+ CaInterface.initCheckForConnectionManager();
+ CaInterface.caManagerUnsetAutoConnectionDeviceInfo(address);
+ }
+
+ /**
+ * Interface for connection manager state listener.
+ * Event listeners are notified asynchronously.
+ */
+ public interface OnConnectionManagerStateListener {
+ public void onAdapterStateChanged(OcConnectivityType type, boolean enabled);
+ public void onConnectionStateChanged(OcConnectivityType type, String address,
+ boolean connected);
+ }
+
+ private static void initCheckForConnectionManager() {
+ if (!isConnectionManagerInitialized) {
+ throw new IllegalStateException("ConnectionManager must be started by making "
+ + "a call to CaInterface.startManagerService before any other API "
+ + "calls are permitted");
+ }
+ }
+
+ private static void caManagerInitialize(
+ OnConnectionManagerStateListener onConnectionManagerStateListener) {}
+ private static void caManagerTerminate() {}
+ private static void caManagerSetAutoConnectionDeviceInfo(String address) {}
+ private static void caManagerUnsetAutoConnectionDeviceInfo(String address) {}
+
+ /**
+ * start bluetooth pairing service.
+ * @param context application context
+ */
+ public synchronized static void startBtPairingService(
+ OnBtDeviceFoundListener listener) {
+ if (!isBtPairingInitialized) {
+ /* TODO */
+ CaInterface.caBtPairingInitialize(listener);
+
+ isBtPairingInitialized = true;
+ }
+ }
+
+ /**
+ * stop bluetooth pairing service.
+ */
+ public synchronized static void stopBtPairingService() {
+ if (isBtPairingInitialized) {
+ CaInterface.caBtPairingTerminate();
+
+ isBtPairingInitialized = false;
+ }
+ }
+
+ /**
+ * start bluetooth device scan.
+ */
+ public synchronized static void startScan()
+ throws OcException {
+ CaInterface.initCheckForBtPairingUtil();
+ CaInterface.caBtPairingStartScan();
+ }
+
+ /**
+ * stop bluetooth device scan.
+ */
+ public synchronized static void stopScan()
+ throws OcException {
+ CaInterface.initCheckForBtPairingUtil();
+ CaInterface.caBtPairingStopScan();
+ }
+
+ /**
+ * create bond
+ */
+ public synchronized static void createBond(BluetoothDevice device)
+ throws OcException {
+ CaInterface.initCheckForBtPairingUtil();
+ CaInterface.caBtPairingCreateBond(device);
+ }
+
+ public interface OnBtDeviceFoundListener {
+ public void onBtDeviceFound(BluetoothDevice device) throws OcException;
+ }
+
+ private static void initCheckForBtPairingUtil() {
+ if (!isBtPairingInitialized) {
+ throw new IllegalStateException("BT pairing Util must be started by making "
+ + "a call to CaInterface.startBtPairingService before any other API "
+ + "calls are permitted");
+ }
+ }
+
+ private static void caBtPairingInitialize(
+ OnBtDeviceFoundListener listener) {}
+ private static void caBtPairingTerminate() {}
+ private static void caBtPairingStartScan() {}
+ private static void caBtPairingStopScan() {}
+ private static void caBtPairingCreateBond(BluetoothDevice device) {}
+}
--- /dev/null
+/******************************************************************\r
+ *\r
+ * Copyright 2014 Samsung Electronics All Rights Reserved.\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
+package org.iotivity.ca;\r
+\r
+public class CaIpInterface {\r
+\r
+ public enum WifiAPState{\r
+ WIFI_AP_STATE_DISABLING (10),\r
+ WIFI_AP_STATE_DISABLED (11),\r
+ WIFI_AP_STATE_ENABLING (12),\r
+ WIFI_AP_STATE_ENABLED (13),\r
+ WIFI_AP_STATE_FAILED (14)\r
+ ; // semicolon needed when fields / methods follow\r
+\r
+\r
+ private final int apstate;\r
+\r
+ WifiAPState(int apstate)\r
+ {\r
+ this.apstate = apstate;\r
+ }\r
+ public int getIntValue() {\r
+ return this.apstate;\r
+ }\r
+ }\r
+\r
+ private CaIpInterface() {\r
+ registerIpStateReceiver();\r
+ }\r
+\r
+ private void registerIpStateReceiver() {\r
+ }\r
+\r
+ public static void destroyIpInterface() {\r
+ }\r
+\r
+ private native static void caIpStateEnabled();\r
+\r
+ private native static void caIpStateDisabled();\r
+}\r
*/
#include <jni.h>
-#include <android/log.h>
+#include "logger.h"
#include <stdio.h>
#include "cainterface.h"
#include "JniCaInterface.h"
#include "cacommon.h"
#define LOG_TAG "JNI_CA_INTERFACE"
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define LOGI(...) OIC_LOG_V(OC_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define LOGE(...) OIC_LOG_V(OC_LOG_ERROR, LOG_TAG, __VA_ARGS__)
static jobject g_foundDeviceListenerObject = NULL;
static jobject g_listenerObject = NULL;
return;
}
+#ifdef __ANDROID__
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_initialize
(JNIEnv *env, jclass clazz, jobject activity, jobject context)
CANativeSetActivity(env, activity);
CANativeJNISetContext(env, context);
}
+#else
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_initialize
+(JNIEnv *env, jclass clazz)
+{
+ LOGI("CaInterface_initialize");
+}
+#endif
void CAManagerConnectionStateChangedCB(CATransportAdapter_t adapter,
const char *remote_address,
LOGI("OUT - CAManagerAdapterStateChangedCB");
}
+#ifdef __ANDROID__
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
jobject context, jobject listener)
CARegisterNetworkMonitorHandler(CAManagerAdapterStateChangedCB,
CAManagerConnectionStateChangedCB);
}
+#else
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
+ jobject listener)
+{
+ LOGI("CaManagere_initialize");
+
+ g_listenerObject = (*env)->NewGlobalRef(env, listener);
+
+ CARegisterNetworkMonitorHandler(CAManagerAdapterStateChangedCB,
+ CAManagerConnectionStateChangedCB);
+}
+#endif
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caManagerTerminate(JNIEnv *env, jclass clazz)
(*env)->ReleaseStringUTFChars(env, jaddress, address);
}
+#ifdef __ANDROID__
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *env, jclass clazz,
jobject context, jobject listener)
g_foundDeviceListenerObject = (*env)->NewGlobalRef(env, listener);
CAUtilSetFoundDeviceListener(g_foundDeviceListenerObject);
}
+#else
+JNIEXPORT void JNICALL
+Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *env, jclass clazz,
+ jobject listener)
+{
+ LOGI("caBtPairingInitialize");
+ (void)clazz;
+
+ CAUtilClientInitialize(env, g_jvm);
+
+ g_foundDeviceListenerObject = (*env)->NewGlobalRef(env, listener);
+ CAUtilSetFoundDeviceListener(g_foundDeviceListenerObject);
+}
+#endif
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caBtPairingTerminate(JNIEnv *env, jclass clazz)
void CAManagerAdapterStateChangedCB(CATransportAdapter_t adapter, bool enabled);
+#ifdef __ANDROID__
/*
* Class: Java_org_iotivity_ca_CaInterface_caManagerInitialize
* Method: caManagerInitialize
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
jobject context, jobject listener);
+#else
+ /*
+ * Class: Java_org_iotivity_ca_CaInterface_caManagerInitialize
+ * Method: caManagerInitialize
+ * Signature: ()V
+ */
+ JNIEXPORT void JNICALL
+ Java_org_iotivity_ca_CaInterface_caManagerInitialize(JNIEnv *env, jclass clazz,
+ jobject listener);
+#endif
/*
* Class: Java_org_iotivity_ca_CaInterface_caManagerTerminate
jclass clazz,
jstring jaddress);
+#ifdef __ANDROID__
/*
* Class: Java_org_iotivity_ca_CaInterface_caBtPairingInitialize
* Method: caBtPairingInitialize
*/
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *, jclass, jobject, jobject);
+#else
+ /*
+ * Class: Java_org_iotivity_ca_CaInterface_caBtPairingInitialize
+ * Method: caBtPairingInitialize
+ * Signature: ()V
+ */
+ JNIEXPORT void JNICALL
+ Java_org_iotivity_ca_CaInterface_caBtPairingInitialize(JNIEnv *, jclass, jobject);
+#endif
/*
* Class: Java_org_iotivity_ca_CaInterface_caBtPairingTerminate
JNIEXPORT void JNICALL
Java_org_iotivity_ca_CaInterface_caBtPairingCreateBond(JNIEnv *, jclass, jobject);
+#ifdef __ANDROID__
/*
* Class: org_iotivity_ca_CaInterface_Initialize
* Method: Initialize
*/
JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
(JNIEnv *, jclass, jobject, jobject);
+#else
+ /*
+ * Class: org_iotivity_ca_CaInterface_Initialize
+ * Method: Initialize
+ * Signature: ()V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_ca_CaInterface_initialize
+ (JNIEnv *, jclass);
+#endif
#ifdef __cplusplus
}
return;
}
- // __android_log_print(ANDROID_LOG_INFO, "Rahul", "platformID = %s", platformID);
try
{
OCStackResult result = OCPlatform::registerPlatformInfo(platformInfo);
}
JniOcResource *jniOcResource = new JniOcResource(resource);
- jlong handle = reinterpret_cast<jlong>(jniOcResource);
jobject jResource = env->NewObject(g_cls_OcResource, g_mid_OcResource_ctor);
if (!jResource)
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
#include <jni.h>
-#include <android/log.h>
+#include "logger.h"
#include "OCApi.h"
#ifndef _Included_org_iotivity_base_ocstack
#define JNI_CURRENT_VERSION JNI_VERSION_1_6
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
-#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
+#define LOGI(...) OIC_LOG_V(INFO, TAG, __VA_ARGS__)
+#define LOGD(...) OIC_LOG_V(DEBUG, TAG, __VA_ARGS__)
+#define LOGE(...) OIC_LOG_V(ERROR, TAG, __VA_ARGS__)
#define JNI_EXCEPTION 1000
#define JNI_NO_NATIVE_POINTER 1001
case JNI_OK:
return env;
case JNI_EDETACHED:
+// AttachCurrentThread API changed in JNI 1.7 which is not a defined version
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-fpermissive"
if (g_jvm->AttachCurrentThread(&env, nullptr) < 0)
+#pragma GCC diagnostic push
{
LOGE("Failed to get the environment");
return nullptr;
strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
}
-#endif // _Included_org_iotivity_base_ocstack
\ No newline at end of file
+#endif // _Included_org_iotivity_base_ocstack
--- /dev/null
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Examples build script
+##
+Import('env')
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env')
+
+jni_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+jni_env.AppendUnique(CPPPATH = [
+ env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+ env.get('SRC_DIR') + '/resource/include',
+ env.get('SRC_DIR') + '/resource/c_common',
+ env.get('SRC_DIR') + '/resource/c_common/oic_string/include',
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
+ env.get('SRC_DIR') + '/resource/csdk/stack/include',
+ env.get('SRC_DIR') + '/resource/csdk/ocsocket/include',
+ env.get('SRC_DIR') + '/resource/oc_logger/include',
+ env.get('SRC_DIR') + '/resource/csdk/logger/include',
+ env.get('SRC_DIR') + '/resource/../extlibs/boost/boost_1_58_0',
+ env.get('SRC_DIR') + '/resource/../build_common/android/compatibility',
+ env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include',
+ env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm',
+ env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal',
+ env.get('SRC_DIR') + '/resource/csdk/security/include'
+ ])
+
+
+target_os = env.get('TARGET_OS')
+jni_env.AppendUnique(CCFLAGS = ['-Wno-error', '-Wno-comment', '-Wno-unused-function', '-Wno-unused-parameter'])
+if target_os not in ['windows', 'winrt']:
+ jni_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+
+ # Note: 'pthread' is in libc for android. On other platform, if use
+ # new gcc(>4.9?) it isn't required, otherwise, it's required
+ if target_os != 'android':
+ jni_env.AppendUnique(LIBS = ['-lpthread'])
+
+jni_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+jni_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+jni_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction'])
+if env.get('SECURED') == '1':
+ jni_env.AppendUnique(LIBS = ['tinydtls', 'ocprovision', 'ocpmapi'])
+
+if target_os == 'android':
+ jni_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ jni_env.AppendUnique(LIBS = ['gnustl_shared'])
+
+ if not env.get('RELEASE'):
+ jni_env.AppendUnique(LIBS = ['log'])
+
+if target_os in ['darwin', 'ios']:
+ jni_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+
+ca_interface = jni_env.SharedLibrary('ca-interface', ['JniCaInterface.c'])
+
+ocstack_files = [
+ 'JniOcStack.cpp',
+ 'JniUtils.cpp',
+ 'JniEntityHandler.cpp',
+ 'JniOnResourceFoundListener.cpp',
+ 'JniOnDeviceInfoListener.cpp',
+ 'JniOnPlatformInfoListener.cpp',
+ 'JniOnPresenceListener.cpp',
+ 'JniOnGetListener.cpp',
+ 'JniOnPutListener.cpp',
+ 'JniOnPostListener.cpp',
+ 'JniOnDeleteListener.cpp',
+ 'JniOnObserveListener.cpp',
+ 'JniOcRepresentation.cpp',
+ 'JniOcResourceHandle.cpp',
+ 'JniOcPresenceHandle.cpp',
+ 'JniOcRequestHandle.cpp',
+ 'JniOcResourceRequest.cpp',
+ 'JniOcResourceResponse.cpp',
+ 'JniOcPlatform.cpp',
+ 'JniOcResource.cpp',
+ 'JniOcResourceIdentifier.cpp',
+ 'JniOcSecurity.cpp'
+ ]
+if env.get('SECURED') == '1':
+ ocstack_files += [
+ 'JniOcSecureResource.cpp',
+ 'JniOcProvisioning.cpp',
+ 'JniSecureUtils.cpp',
+ 'JniProvisionResultListner.cpp',
+ 'JniPinCheckListener.cpp',
+ 'JniDisplayPinListener.cpp'
+ ]
+
+ocstack_jni = jni_env.SharedLibrary('ocstack-jni', ocstack_files)
+
+jni_env.InstallTarget(ocstack_jni, 'ocstack-jni')
+jni_env.InstallTarget(ca_interface, 'ca-interface')
+
+env.AppendTarget('ocstack-jni')
*\r
*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
*/\r
-\r
-include ':base'\r
#define CA_UTILS_INTERFACE_H_
#include "cacommon.h"
-#ifdef __ANDROID__
+#ifdef __JAVA__
#include "jni.h"
#endif
#ifdef __cplusplus
*/
CAResult_t CAUnsetAutoConnectionDeviceInfo(const char* address);
+#ifdef __JAVA__
#ifdef __ANDROID__
/**
* initialize util client for android
* @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
*/
CAResult_t CAUtilClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context);
+#else
+/**
+ * initialize util client for android
+ * @param[in] env JNI interface pointer.
+ * @param[in] jvm invocation inferface for JAVA virtual machine.
+ *
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
+ */
+CAResult_t CAUtilClientInitialize(JNIEnv *env, JavaVM *jvm);
+#endif
/**
* terminate util client for android
*/
CAResult_t CAUtilCreateBond(JNIEnv *env, jobject device);
-
/**
* set callback listener of found device.
* @param[in] listener callback listener
#define CA_ADAPTER_UTILS_H_
#include <stdbool.h>
-#ifdef __ANDROID__
+#ifdef __JAVA__
#include <jni.h>
#endif
void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storage *sockaddr);
#endif /* WITH_ARDUINO */
-#ifdef __ANDROID__
-/**
- * To set context of JNI Application.
- * This must be called by the Android API before CA Initialization.
- * @param[in] env JNI interface pointer.
- * @param[in] context context object.
- */
-void CANativeJNISetContext(JNIEnv *env, jobject context);
-
+#ifdef __JAVA__
/**
* To set jvm object.
* This must be called by the Android API before CA Initialization.
void CANativeJNISetJavaVM(JavaVM *jvm);
/**
- * To get context.
- * Called by adapters to get Application context.
- * @return context object.
- */
-jobject CANativeJNIGetContext();
-
-/**
* To get JVM object.
* Called from adapters to get JavaVM object.
* @return JVM object.
JavaVM *CANativeJNIGetJavaVM();
/**
- * To set Activity to JNI.
- * This must be called by the Android API before CA Initialization.
- * @param[in] env JNI Environment pointer.
- * @param[in] activity Activity object.
- */
-void CANativeSetActivity(JNIEnv *env, jobject activity);
-
-/**
- * To get Activity.
- * Called from adapters to get Activity.
- * @return Activity object.
- */
-jobject *CANativeGetActivity();
-
-/**
* get method ID for method Name and class
* @param[in] env JNI interface pointer.
* @param[in] className android class.
*/
void CADeleteGlobalReferences();
+#ifdef __ANDROID__
+/**
+ * To set context of JNI Application.
+ * This must be called by the Android API before CA Initialization.
+ * @param[in] env JNI interface pointer.
+ * @param[in] context context object.
+ */
+void CANativeJNISetContext(JNIEnv *env, jobject context);
+
+/**
+ * To set Activity to JNI.
+ * This must be called by the Android API before CA Initialization.
+ * @param[in] env JNI Environment pointer.
+ * @param[in] activity Activity object.
+ */
+void CANativeSetActivity(JNIEnv *env, jobject activity);
+
+/**
+ * To get context.
+ * Called by adapters to get Application context.
+ * @return context object.
+ */
+jobject CANativeJNIGetContext();
+
+/**
+ * To get Activity.
+ * Called from adapters to get Activity.
+ * @return Activity object.
+ */
+jobject *CANativeGetActivity();
+#endif
#endif
#ifdef __cplusplus
#include <netdb.h>
#endif
-#ifdef __ANDROID__
+#ifdef __JAVA__
#include <jni.h>
-#endif
-
-#define CA_ADAPTER_UTILS_TAG "OIC_CA_ADAP_UTILS"
-#ifdef __ANDROID__
/**
* @var g_jvm
* @brief pointer to store JavaVM
*/
static JavaVM *g_jvm = NULL;
+#ifdef __ANDROID__
/**
* @var gContext
* @brief pointer to store context for android callback interface
static jobject g_Context = NULL;
static jobject g_Activity = NULL;
#endif
+#endif
+
+#define CA_ADAPTER_UTILS_TAG "OIC_CA_ADAP_UTILS"
#ifdef WITH_ARDUINO
CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
}
#endif // WITH_ARDUINO
-#ifdef __ANDROID__
-void CANativeJNISetContext(JNIEnv *env, jobject context)
-{
- OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeJNISetContext");
-
- if (!context)
- {
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "context is null");
- return;
- }
-
- if (!g_Context)
- {
- g_Context = (*env)->NewGlobalRef(env, context);
- }
- else
- {
- OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "context is already set");
- }
-}
-
+#ifdef __JAVA__
void CANativeJNISetJavaVM(JavaVM *jvm)
{
OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeJNISetJavaVM");
g_jvm = jvm;
}
-jobject CANativeJNIGetContext()
-{
- return g_Context;
-}
-
JavaVM *CANativeJNIGetJavaVM()
{
return g_jvm;
}
-void CANativeSetActivity(JNIEnv *env, jobject activity)
+void CADeleteGlobalReferences(JNIEnv *env)
{
- OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeSetActivity");
-
- if (!activity)
+#ifdef __ANDROID__
+ if (g_Context)
{
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "activity is null");
- return;
+ (*env)->DeleteGlobalRef(env, g_Context);
+ g_Context = NULL;
}
- if (!g_Activity)
- {
- g_Activity = (*env)->NewGlobalRef(env, activity);
- }
- else
+ if (g_Activity)
{
- OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "activity is already set");
+ (*env)->DeleteGlobalRef(env, g_Activity);
+ g_Activity = NULL;
}
-}
-
-jobject *CANativeGetActivity()
-{
- return g_Activity;
+#endif
}
jmethodID CAGetJNIMethodID(JNIEnv *env, const char* className,
return jni_midID;
}
-void CADeleteGlobalReferences(JNIEnv *env)
+#ifdef __ANDROID__
+void CANativeJNISetContext(JNIEnv *env, jobject context)
{
- if (g_Context)
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeJNISetContext");
+
+ if (!context)
{
- (*env)->DeleteGlobalRef(env, g_Context);
- g_Context = NULL;
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "context is null");
+ return;
}
- if (g_Activity)
+ if (!g_Context)
{
- (*env)->DeleteGlobalRef(env, g_Activity);
- g_Activity = NULL;
+ g_Context = (*env)->NewGlobalRef(env, context);
+ }
+ else
+ {
+ OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "context is already set");
+ }
+}
+
+jobject CANativeJNIGetContext()
+{
+ return g_Context;
+}
+
+void CANativeSetActivity(JNIEnv *env, jobject activity)
+{
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "CANativeSetActivity");
+
+ if (!activity)
+ {
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "activity is null");
+ return;
+ }
+
+ if (!g_Activity)
+ {
+ g_Activity = (*env)->NewGlobalRef(env, activity);
+ }
+ else
+ {
+ OIC_LOG(INFO, CA_ADAPTER_UTILS_TAG, "activity is already set");
}
}
+
+jobject *CANativeGetActivity()
+{
+ return g_Activity;
+}
+#endif
#endif
#endif
}
+#ifdef __JAVA__
#ifdef __ANDROID__
/**
* initialize client connection manager
#endif
return res;
}
+#else
+/**
+ * initialize client connection manager
+ * @param[in] env JNI interface pointer.
+ * @param[in] jvm invocation inferface for JAVA virtual machine.
+ */
+CAResult_t CAUtilClientInitialize(JNIEnv *env, JavaVM *jvm)
+{
+ OIC_LOG(DEBUG, TAG, "CAUtilClientInitialize");
+
+ CAResult_t res = CA_STATUS_OK;
+#ifdef LE_ADAPTER
+ if (CA_STATUS_OK != CAManagerLEClientInitialize(env, jvm))
+ {
+ OIC_LOG(ERROR, TAG, "CAManagerLEClientInitialize has failed");
+ res = CA_STATUS_FAILED;
+ }
+#endif
+
+#ifdef EDR_ADAPTER
+ if (CA_STATUS_OK != CABTPairingInitialize(env, jvm))
+ {
+ OIC_LOG(ERROR, TAG, "CABTPairingInitialize has failed");
+ res = CA_STATUS_FAILED;
+ }
+#endif
+ return res;
+}
+
+#endif
/**
* terminate client connection manager