* one or more resources.
*/
public class OcResource {
+ public static final String CREATED_URI_KEY = "createduri";
private OcResource(long nativeHandle) {
this.mNativeHandle = nativeHandle;
* Event listeners are notified asynchronously
*/
public interface OnObserveListener {
+ /**
+ * To Register.
+ */
+ public static final int REGISTER = 0;
+ /**
+ * To Deregister.
+ */
+ public static final int DEREGISTER = 1;
+ /**
+ * Others.
+ */
+ public static final int NO_OPTION = 2;
+
public void onObserveCompleted(List<OcHeaderOption> headerOptionList,
OcRepresentation ocRepresentation,
int sequenceNumber);
return equalsN(other);
}
+ @Override
+ public int hashCode() {
+ //return the same hash code for every object to force dictionary objects to use equals() in
+ //key comparisons, since IoTivity wants to treat OcResourceIdentifier as a blob
+ return 0;
+ }
+
private native boolean equalsN(OcResourceIdentifier other);
private native void dispose();
<?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="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
+<module external.linked.project.id="examples" 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">\r
<component name="FacetManager">\r
<facet type="java-gradle" name="Java-Gradle">\r
<configuration>\r
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
+ <option name="BUILDABLE" value="false" />\r
</configuration>\r
</facet>\r
</component>\r
<orderEntry type="inheritedJdk" />\r
<orderEntry type="sourceFolder" forTests="false" />\r
</component>\r
-</module>\r
-\r
+</module>
\ No newline at end of file
-apply plugin: 'com.android.application'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "21.1.2"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.simpleclient"\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 project(':message')\r
- compile 'com.android.support:appcompat-v7:21.0.3'\r
-}\r
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 22
+ buildToolsVersion "22.0.1"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.simpleclient"
+ minSdkVersion 21
+ targetSdkVersion 22
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+}
+
+dependencies {
+ compile fileTree(dir: 'libs', include: ['*.jar'])
+}
--- /dev/null
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /home/rahul/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
-<?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="examples" 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=":simpleclient" />\r
- </configuration>\r
- </facet>\r
- <facet type="android" name="Android">\r
- <configuration>\r
- <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\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="file://$MODULE_DIR$/src/main/res" />\r
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\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/jni" 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/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
- <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
- <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
- <orderEntry type="module" module-name="message" exported="" />\r
- </component>\r
-</module>\r
-\r
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":simpleclient" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":simpleclient" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugTestSources" />
+ <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.iotivity.base.examples.simpleclient"
- xmlns:tools="http://schemas.android.com/tools">
+ package="org.iotivity.base.examples" >
- <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<application
android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
+ android:icon="@mipmap/iotivityicon"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
+ android:screenOrientation="portrait"
android:name=".SimpleClient"
android:label="@string/app_name" >
<intent-filter>
--- /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 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.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 extends Activity 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 void startSimpleClient() {
+ 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 all resources of type \"core.light\".");
+ String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=core.light";
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this
+ );
+ 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),
+ 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 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) {
+ Log.e(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) {
+ Log.e(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;
+ 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 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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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;
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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;
+ Log.e(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) {
+ Log.e(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;
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(TAG, e.toString());
+ msg("Error occurred while invoking \"cancelObserve\" API");
+ }
+ msg("DONE");
+
+ //prepare for the next restart of the SimpleClient
+ resetGlobals();
+ enableStartButton();
+ }
+ }
+
+ /**
+ * 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;
+ Log.e(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();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_simple_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() {
+ startSimpleClient();
+ }
+ }).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("------------------------------------------------------------------------");
+ }
+
+ private synchronized void resetGlobals() {
+ mFoundLightResource = null;
+ mFoundResources.clear();
+ mLight = new Light();
+ mObserveCount = 0;
+ }
+}
+++ /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.simpleclient;
-
-/**
- * Light
- *
- * This class is used by simpleclient to create an object and update the values depending on the server response
- */
-public class Light {
- private boolean mState;
- private int mPower;
- private String mName;
-
- // constructor
- Light() {
- mState = false;
- mPower = 0;
- mName = "";
- }
-
- // accessor methods
- public boolean getState() {
- return mState;
- }
- void setState(boolean state) {
- mState = state;
- }
- int getPower() {
- return mPower;
- }
- void setPower(int power) {
- mPower = power;
- }
- String getName() {
- return mName;
- }
- void setName(String name) {
- mName = name;
- }
-}
-
-
-
-
+++ /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.simpleclient;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.res.AssetManager;
-import android.os.Bundle;
-import android.os.Message;
-import android.preference.PreferenceManager;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-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.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-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.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-
-import base.iotivity.org.examples.message.IMessageLogger;
-
-/**
- * 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 and OBSERVE).
- * This implements IMessageLogger to display messages on the screen
- */
-public class SimpleClient extends Activity implements OcPlatform.OnResourceFoundListener,
- IMessageLogger {
- private static final String TAG = "SimpleClient: ";
-
- private static final int BUFFER_SIZE = 1024;
- private String filePath = "";
- private Light myLight;
- private OcResource curResource;
-
- //for display
- private TextView mEventsTextView;
- private static boolean printOnce = true;
-
- /**
- * 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 {
- /**
- * find all resources
- */
- OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "core.light",
- EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
- } catch (OcException e) {
- logMessage(TAG + "findResource error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- @Override
- /**
- * callback when a resource is found. This method calls doGetLightRepresentation to get the
- * current values of myLight
- */
- synchronized public void onResourceFound(OcResource ocResource) {
- /**
- * this may potentially be called by multiple threads at the same time
- */
- synchronized (this) {
- String resourceUri;
- String hostAddress;
- resourceUri = ocResource.getUri();
- hostAddress = ocResource.getHost();
- logMessage(TAG + "Discovered Resource\nUri: " + resourceUri + " \n Host: " + hostAddress);
- // get the resource types
- if (resourceUri.contains("light")) {
- curResource = ocResource;
- doGetLightRepresentation();
- }
- }
- }
-
- /**
- * get myLight values after observe
- */
- private void doObserveLightRepresentation() {
- // eventhandler for observe()
- OcResource.OnObserveListener onObserveListener = new OcResource.OnObserveListener() {
- @Override
- public void onObserveCompleted(List<OcHeaderOption> ocHeaderOptions,
- OcRepresentation ocRepresentation, int seqNum) {
- if (printOnce) {
- logMessage(TAG + "OBSERVE request was successful");
- printOnce = false;
- }
- try {
- boolean state = ocRepresentation.getValue(StringConstants.STATE);
- int power = ocRepresentation.getValue(StringConstants.POWER);
- String name = ocRepresentation.getValue(StringConstants.NAME);
- myLight.setState(state);
- myLight.setPower(power);
- myLight.setName(name);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "onObserve: Power: " + myLight.getPower());
- if (seqNum > 20) {
- try {
- curResource.cancelObserve();
- logMessage(TAG + "Successfully cancelled observe");
- } catch (OcException e) {
- logMessage(TAG + "cancelObserve error. " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- }
-
- @Override
- public void onObserveFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
- };
- try {
- curResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), onObserveListener);
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * get the current value of myLight after POST and call doObserveLightRepresentation
- *
- * @param ocRepresentation needed to invoke post()
- */
- private void doOnPost2(OcRepresentation ocRepresentation) {
- // eventhandler for post()
- OcResource.OnPostListener onPostListener2 = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation rep) {
- logMessage(TAG + "POST request was successful");
- String createdUri = rep.getUri();
- if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
- logMessage(TAG + "Uri of the created resource: " + createdUri);
- } else {
- try {
- boolean state = rep.getValue(StringConstants.STATE);
- int power = rep.getValue(StringConstants.POWER);
- String name = rep.getValue(StringConstants.NAME);
- myLight.setState(state);
- myLight.setPower(power);
- myLight.setName(name);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "onPost\nState: " + myLight.getState() + "\nPower: " +
- myLight.getPower() + "\nName: " + myLight.getName());
- }
- doObserveLightRepresentation();
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
- };
- try {
- curResource.post(ocRepresentation, new HashMap<String, String>(), onPostListener2);
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * create a new resource and update its value.
- */
- private void doPostLightRepresentation() {
- // eventhandler for post()
- OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
- @Override
- public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
- OcRepresentation ocRepresentation) {
- String createdUri = "";
- try {
- createdUri = ocRepresentation.getValue(StringConstants.CREATED_URI);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
- logMessage(TAG + "Uri of the created resource: " + createdUri);
- } else {
- boolean state = false;
- try {
- state = ocRepresentation.getValue(StringConstants.STATE);
- int power = ocRepresentation.getValue(StringConstants.POWER);
- String name = ocRepresentation.getValue(StringConstants.NAME);
- myLight.setState(state);
- myLight.setPower(power);
- myLight.setName(name);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
- OcRepresentation rep = new OcRepresentation();
- myLight.setState(true);
- myLight.setPower(55);
- try {
- rep.setValue(StringConstants.POWER, myLight.getPower());
- rep.setValue(StringConstants.STATE, myLight.getState());
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- doOnPost2(rep);
- }
-
- @Override
- public void onPostFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
- };
-
- OcRepresentation rep = new OcRepresentation();
- myLight.setState(false);
- myLight.setPower(105);
- try {
- rep.setValue(StringConstants.STATE, myLight.getState());
- rep.setValue(StringConstants.POWER, myLight.getPower());
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- try {
- curResource.post(rep, new HashMap<String, String>(), onPostListener);
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * modify the current value of myLight and call doPostLightRepresentation
- */
- private void doPutLightRepresentation() {
- // eventhandler for put()
- OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
- @Override
- public void onPutCompleted(List<OcHeaderOption> ocHeaderOptions,
- OcRepresentation ocRepresentation) {
- logMessage(TAG + "PUT resource was successful");
- try {
- boolean state = ocRepresentation.getValue(StringConstants.STATE);
- int power = ocRepresentation.getValue(StringConstants.POWER);
- String name = ocRepresentation.getValue(StringConstants.NAME);
- myLight.setState(state);
- myLight.setPower(power);
- myLight.setName(name);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
-
- logMessage(TAG + "onPutCompleted:\nState:" + myLight.getState() + "\nPower: " +
- myLight.getPower() + "\nName: " + myLight.getName());
- doPostLightRepresentation();
- }
-
- @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());
- }
- };
-
- OcRepresentation rep = new OcRepresentation();
- Log.d(TAG, "myLight settings: power = 15");
- myLight.setState(true);
- myLight.setPower(15);
- try {
- rep.setValue(StringConstants.STATE, myLight.getState());
- rep.setValue(StringConstants.POWER, myLight.getPower());
- rep.setValue(StringConstants.NAME, myLight.getName());
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- try {
- Log.d(TAG, "before calling put");
- curResource.put(rep, new HashMap<String, String>(), onPutListener);
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- Log.d(TAG, "end of put call");
- }
-
- /**
- * get the existing value of myLight and call doPutLightRepresentation() to modify the current values
- */
- private void doGetLightRepresentation() {
- // eventhandler for get()
- OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
- @Override
- public void onGetCompleted(List<OcHeaderOption> headerOptionList,
- OcRepresentation ocRepresentation) {
- logMessage(TAG + "GET resource was successful " + StringConstants.STATE);
- try {
- boolean state = ocRepresentation.getValue(StringConstants.STATE);
- int power = ocRepresentation.getValue(StringConstants.POWER);
- String name = ocRepresentation.getValue(StringConstants.NAME);
- myLight.setState(state);
- myLight.setPower(power);
- myLight.setName(name);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "onGetCompleted\nState: " + myLight.getState() + "\nPower: " +
- myLight.getPower() + "\nName: " + myLight.getName());
- doPutLightRepresentation();
- }
-
- @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());
- }
- };
-
- try {
- curResource.get(new HashMap<String, String>(), onGetListener);
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * to display on SimpleClient screen
- */
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(StringConstants.MESSAGE);
- logMessage(message);
- }
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mEventsTextView = new TextView(this);
- mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
- LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
- layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
- );
- myLight = new Light();
- 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();
- }
-/**
- * Copy svr db json file from assets folder to app data files dir
- */
- private void copyJsonFromAsset() {
- AssetManager assetManager = getAssets();
- InputStream in = null;
- OutputStream out = null;
- try {
- in = assetManager.open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
- File file = new File(filePath);
- //check files directory exists
- if (!(file.exists() && file.isDirectory())) {
- file.mkdirs();
- }
- out = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
- copyFile(in, out);
- } 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 (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- }
- }
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- }
- }
- }
- }
-
- private void copyFile(InputStream in, OutputStream out) throws IOException {
- byte[] buffer = new byte[BUFFER_SIZE];
- int read;
- while ((read = in.read(buffer)) != -1) {
- out.write(buffer, 0, read);
- }
- }
- @Override
- 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("\n");
- mEventsTextView.append(text);
- }
- });
- Log.i(TAG, text);
- //to print on SimpleServer screen
- Intent intent = new Intent("org.iotivity.base.examples.simpleclient");
- intent.putExtra(StringConstants.MESSAGE, text);
- sendBroadcast(intent);
- }
-}
+++ /dev/null
-package org.iotivity.base.examples.simpleclient;
-/**
- * StringConstant contains the simpleclient 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 StringConstants {
- public static final String RESOURCE_URI0 = "/a/light";
- public static final String RESOURCE_URI1 = "/a/light2";
- public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.json";
- public static final String CREATED_URI = "createduri";
- public static final String STATE = "state";
- public static final String NAME = "name";
- public static final String POWER = "power";
- public static final String MESSAGE = "message";
-}
+++ /dev/null
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
- android:label="@string/app_name">
-
- <TextView android:text="@string/app_name" android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- android:id="@+id/linearLayout" >
- </LinearLayout>
-</RelativeLayout>
--- /dev/null
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context=".SimpleClient">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/button"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:text="Start" />
+ <ScrollView
+ android:layout_below="@id/button"
+ android:layout_above="@+id/imageView"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:fillViewport="true"
+ android:id="@+id/scrollView">
+ <TextView android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/consoleTextView" />
+ </ScrollView>
+ <ImageView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/imageView"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:src="@drawable/iotivitylogo" />
+</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
- <item android:id="@+id/action_settings" android:title="@string/action_settings"
- android:orderInCategory="100" app:showAsAction="never" />
-</menu>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <style name="AppTheme" parent="android:Theme.Material.Light">
+ </style>
+</resources>
-<?xml version="1.0" encoding="utf-8"?>
<resources>
+ <string name="app_name">Simple Client</string>
- <string name="app_name">Starting Simple Client</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
-
</resources>
<resources>
<!-- Base application theme. -->
- <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>