-<?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
- <component name="FacetManager">\r
- <facet type="java-gradle" name="Java-Gradle">\r
- <configuration>\r
- <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" inherit-compiler-output="true">\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <excludeFolder url="file://$MODULE_DIR$/.gradle" />\r
- </content>\r
- <orderEntry type="inheritedJdk" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- </component>\r
-</module>\r
-\r
+<?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>
+ </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
-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.simpleserver"\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
-\r
-dependencies {\r
- //compile fileTree(dir: 'libs', include: ['*.so'])\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.simpleserver"
+ 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=":simpleserver" />\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=":simpleserver" 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=":simpleserver" />
+ </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.simpleserver"
- 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"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
+
<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=".SimpleServer"
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 android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+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);
+ if(null != mContext && mContext instanceof SimpleServer) {
+ ((SimpleServer) mContext).createNewLightResource(newUri, "John's light " + sUriCounter);
+ }
+ OcRepresentation rep_post = getOcRepresentation();
+ try {
+ rep_post.setValue(OcResource.CREATED_URI_KEY, newUri);
+ } catch (OcException e) {
+ Log.e(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) {
+ Log.e(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(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) {
+ Log.e(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) {
+ Log.e(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) {
+ Log.e(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;
+ }
+
+ public void setContext(Context context) {
+ mContext = context;
+ }
+
+ @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();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void msg(String text) {
+ if (null != mContext) {
+ Intent intent = new Intent("org.iotivity.base.examples.simpleserver");
+ intent.putExtra("message", text);
+ mContext.sendBroadcast(intent);
+ }
+ }
+
+ 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;
+ private Context mContext;
+}
\ 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.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.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 extends Activity {
+
+ List<Light> lights = new LinkedList<>();
+
+ /**
+ * A local method to configure and initialize platform, and then create a light resource.
+ */
+ private void startSimpleServer() {
+ 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);
+
+ createNewLightResource("/a/light", "John's light");
+
+ msg("Waiting for the requests...");
+ printLine();
+
+ enableStartStopButton();
+ }
+
+ public 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());
+ light.setContext(this);
+
+ msg("Registering light as a resource");
+ try {
+ light.registerResource();
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to register a light resource");
+ }
+ lights.add(light);
+ }
+
+ private void stopSimpleServer() {
+ for (Light light : lights) {
+ try {
+ light.unregisterResource();
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unregister a light resource");
+ }
+ }
+ lights.clear();
+
+ msg("All created resources have been unregistered");
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = SimpleServer.class.getSimpleName();
+ private MessageReceiver mMessageReceiver = new MessageReceiver();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_simple_server);
+
+ registerReceiver(mMessageReceiver,
+ new IntentFilter("org.iotivity.base.examples.simpleserver"));
+
+ 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() {
+ startSimpleServer();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopSimpleServer();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ onStop();
+ }
+
+ @Override
+ protected void onStop() {
+ //unregisterReceiver(mMessageReceiver);
+ super.onStop();
+ }
+
+ @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);
+ }
+ });
+ }
+
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String message = intent.getStringExtra("message");
+ msg(message);
+ }
+ }
+}
+++ /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.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-/*
- * // Starts a new thread for OBSERVE. It increments the value of mPower by 10 every 3 seconds
- */
-package org.iotivity.base.examples.simpleserver;
-
-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.OcResourceResponse;
-
-import java.util.List;
-
-/**
- * LightRepThread
- *
- * Spawn a thread for OBSERVE. This increments the resource's power value by 10 every 3 seconds.
- * If there is an observationList, call notifyListOfObservers(). Otherwise, call notifyAllObservers()
- */
-public class LightRepThread extends Thread {
- private static String TAG = "LightRepThread: ";
-
- private LightResource mLightResource;
- private List<Byte> mObservationList;
- private static int count = 0;
-
- LightRepThread(Object lr, List<Byte> observationList) {
- mLightResource = (LightResource)lr;
- mObservationList = observationList;
- }
-
- public void run() {
- while(count < 20) {
- try {
- sleep(3000);
- } catch (InterruptedException e) {
- Log.e(TAG, e.getMessage());
- }
-
- // increment current power value by 10 every 3 seconds
- mLightResource.setPower(mLightResource.getPower() + 10);
- try {
- // if observationList is not empty, call notifyListOfObservers
- if (mObservationList.size() > 0) {
- OcResourceResponse ocResourceResponse = new OcResourceResponse();
- ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
- ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
- OcRepresentation r = mLightResource.get();
- ocResourceResponse.setResourceRepresentation
- (mLightResource.get(), OcPlatform.DEFAULT_INTERFACE);
- OcPlatform.notifyListOfObservers(mLightResource.getHandle(), mObservationList, ocResourceResponse);
- } else {
- // notify all observers if mObservationList is empty
- OcPlatform.notifyAllObservers(mLightResource.getHandle());
- }
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- ++count;
- }
- }
-}
+++ /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.simpleserver;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.ObservationInfo;
-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.RequestType;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-import java.util.LinkedList;
-import java.util.List;
-
-import base.iotivity.org.examples.message.IMessageLogger;
-
-/**
- * LightResource
- *
- * class LightResource is the main class of the simpleServer. This creates resources and handles incoming requests from the client.
- */
-public class LightResource implements IMessageLogger {
- private Context mContext;
- private static String TAG = "SimpleServer: ";
-
- private String mName;
- private Boolean mState;
- private Integer mPower;
- private OcRepresentation mLightRep;
- private OcResourceHandle mResourceHandle;
- private List<Byte> mObservationIds;
- private static boolean doOnce; // used in POST
- LightRepThread lightRepThread;
-
- // constructor
- LightResource(Context context) {
- mContext = context;
- mName = "John's light";
- mState = false;
- mPower = 0;
- mObservationIds = new LinkedList<>();
- mLightRep = new OcRepresentation();
- try {
- mLightRep.setValue(StringConstants.STATE, mState);
- mLightRep.setValue(StringConstants.POWER, mPower);
- mLightRep.setValue(StringConstants.NAME, mName);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- doOnce = true; // used in post
- lightRepThread = null;
- }
-
- //accessor methods
- protected int getPower() {
- return mPower;
- }
- protected void setPower(int power) {
- mPower = power;
- }
- protected OcResourceHandle getHandle() {
- return mResourceHandle;
- }
-
- /**
- * creates a resource. this method internally calls registerResource
- * @return returns the OcResourceHandle after creating and registering the resource
- */
- protected OcResourceHandle createResource0() {
- // entityhandler for registerResource
- OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
- @Override
- public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled
- return entityHandler(ocResourceRequest);
- }
- };
-
- try {
- mResourceHandle = OcPlatform.registerResource(StringConstants.RESOURCE_URI0, StringConstants.RESOURCE_TYPENAME,
- StringConstants.RESOURCE_INTERFACE, eh,
- EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
- } catch (OcException e) {
- logMessage(TAG + "RegisterResource error. " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "Successfully registered resource");
- return mResourceHandle;
- }
-
- /**
- * create another resource. this method internally calls registerResource
- */
- private void createResource1() {
- // entityhandler for registerResource
- OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
- @Override
- public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- // this is where the main logic of simpleserver is handled as different requests (GET, PUT, POST, OBSERVE, DELETE) are handled
- return entityHandler(ocResourceRequest);
- }
- };
-
- try {
- OcPlatform.registerResource(StringConstants.RESOURCE_URI1, StringConstants.RESOURCE_TYPENAME,
- StringConstants.RESOURCE_INTERFACE, eh,
- EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE));
- } catch (OcException e) {
- logMessage(TAG + "RegisterResource1 error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "Successfully registered resource1");
- }
-
- /**
- * post representation . Post can act like put or can create a new resource.
- * Gets value from the representation and updates the internal state
- * @param rep current OcRepresentation of the object
- * @return updated OcRepresentation
- */
- private OcRepresentation post(OcRepresentation rep) {
- //create a resource the first time
- if (true == doOnce) {
- createResource1();
- OcRepresentation representation = rep;
- try {
- representation.setValue(StringConstants.CREATED_URI, StringConstants.RESOURCE_URI1);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- doOnce = false;
- return representation;
- }
- // from second time onwards, put
- put(rep);
- return get();
- }
-
- /**
- * puts representation . Gets value from the representation and updates the internal state
- * @param rep current OcRepresentation of the object
- */
- private void put(OcRepresentation rep) {
- try {
- mState = rep.getValue(StringConstants.STATE);
- mPower = rep.getValue(StringConstants.POWER);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- logMessage(TAG + "Put State: " + mState + " Name: " + mName + " Power: " + mPower);
- }
-
- /**
- * gets the updated representation. Updates the representation with internal state before sending out
- * @return OcRepresentation after updating the values of the lightRepresentation
- */
- protected OcRepresentation get() {
- try {
- mLightRep.setValue(StringConstants.STATE, mState);
- mLightRep.setValue(StringConstants.POWER, mPower);
- mLightRep.setValue(StringConstants.NAME, mName);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- return mLightRep;
- }
-
- /**
- * this is the main method which handles different incoming requests appropriately.
- * Init is not supported currently.
- * @param request OcResourceRequest from the client
- * @return EntityHandlerResult depending on whether the request was handled successfully or not
- */
- private EntityHandlerResult entityHandler(OcResourceRequest request) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != request) {
- RequestType requestType = request.getRequestType();
- EnumSet<RequestHandlerFlag> requestFlag = request.getRequestHandlerFlagSet();
-
- if (requestFlag.contains(RequestHandlerFlag.INIT)) {
- logMessage(TAG + "Init");
- }
- if (requestFlag.contains(RequestHandlerFlag.REQUEST)) {
- try {
- logMessage(TAG + "Request");
- OcResourceResponse ocResourceResponse = new OcResourceResponse();
- ocResourceResponse.setRequestHandle(request.getRequestHandle());
- ocResourceResponse.setResourceHandle(request.getResourceHandle());
-
- switch (requestType) {
- // handle GET request
- case GET:
- logMessage("GET");
- ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
- ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
- ocResourceResponse.setResourceRepresentation(get());
- OcPlatform.sendResponse(ocResourceResponse);
- break;
- // handle PUT request
- case PUT:
- OcRepresentation rep = request.getResourceRepresentation();
- put(rep);
- ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
- ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
- ocResourceResponse.setResourceRepresentation(get());
- OcPlatform.sendResponse(ocResourceResponse);
- break;
- // handle POST request
- case POST:
- rep = request.getResourceRepresentation();
- OcRepresentation rep_post = post(rep);
- ocResourceResponse.setResourceRepresentation(rep_post);
- ocResourceResponse.setErrorCode(StringConstants.ERROR_CODE);
- if (rep_post.hasAttribute(StringConstants.CREATED_URI)) {
- String createdUri = rep_post.getValue(StringConstants.CREATED_URI);
- if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
- ocResourceResponse.setNewResourceUri(createdUri);
- ocResourceResponse.setResponseResult
- (EntityHandlerResult.RESOURCE_CREATED);
- } else {
- ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
- }
- }
- OcPlatform.sendResponse(ocResourceResponse);
- break;
- // handle DELETE request
- case DELETE:
- logMessage(TAG + "DELETE");
- OcPlatform.unregisterResource(getHandle());
- OcPlatform.unregisterResource(getHandle());
- break;
-
- }
-
- result = EntityHandlerResult.OK;
- } catch(OcException e) {
- logMessage(TAG + "Error in Request " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
- // handle OBSERVER request
- if (requestFlag.contains(RequestHandlerFlag.OBSERVER)) {
- logMessage(TAG + "OBSERVER");
- ObservationInfo observationInfo = request.getObservationInfo();
-
- switch (observationInfo.getObserveAction()) {
- case REGISTER:
- synchronized (mObservationIds) {
- mObservationIds.add(observationInfo.getOcObservationId());
- }
- break;
- case UNREGISTER:
- synchronized (mObservationIds) {
- mObservationIds.remove(observationInfo.getOcObservationId());
- }
- break;
- }
- if (null == lightRepThread) {
- lightRepThread = new LightRepThread(this, mObservationIds);
- lightRepThread.run();
- }
- result = EntityHandlerResult.OK;
- }
- }
- return result;
- }
-
- @Override
- public void logMessage(String msg) {
- logMsg(msg);
- }
-
- public void logMsg(final String text) {
- Intent intent = new Intent("org.iotivity.base.examples.simpleserver");
- intent.putExtra(StringConstants.MESSAGE, text);
- 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.simpleserver;
-
-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.support.v4.content.LocalBroadcastManager;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import android.content.SharedPreferences;
-import android.content.res.AssetManager;
-import android.preference.PreferenceManager;
-
-import org.iotivity.base.ModeType;
-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.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import base.iotivity.org.examples.message.IMessageLogger;
-
-/**
- * SimpleServer
- *
- * SimpleServer instantiates a TextView and creates and configures OICPlatform.
- * It also creates a LightResource and waits for the incoming client requests to handle specific scenarios.
- * This implements IMessageLogger to display messages on the screen
- */
-
-public class SimpleServer extends Activity implements IMessageLogger {
- private final static String TAG = "SimpleServer: ";
- private static final int BUFFER_SIZE = 1024;
- private String filePath = "";
- private TextView mEventsTextView;
- private MessageReceiver mMessageReceiver = new MessageReceiver();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- registerReceiver(mMessageReceiver, new IntentFilter("org.iotivity.base.examples.simpleserver"));
-
- 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));
-
- OcRepresentation rep = new OcRepresentation();
- rep.setValueBool("test", false);
- boolean result = rep.getValueBool("test");
- 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_SERVER_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_SERVER_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_SERVER_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);
- }
- }
- /**
- * configure OIC platform and call findResource
- */
- private void initOICStack() {
- //create platform config
- PlatformConfig cfg = new PlatformConfig(
- this,
- ServiceType.IN_PROC,
- ModeType.SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW,
- filePath + StringConstants.OIC_SERVER_JSON_DB_FILE);
- OcPlatform.Configure(cfg);
- // Create instance of lightResource
- LightResource myLight = new LightResource(this);
- // create and register a resource
- myLight.createResource0();
- }
-
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(StringConstants.MESSAGE);
- logMessage(message);
- }
- }
-
- public void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mEventsTextView.append("\n");
- mEventsTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- onStop();
- }
-
- @Override
- protected void onStop() {
- LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
- super.onStop();
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.iotivity.base.examples.simpleserver;
-
-import org.iotivity.base.OcPlatform;
-/**
- * StringConstants contains the simpleserver 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 RESOURCE_TYPENAME = "core.light";
- public static final String OIC_SERVER_JSON_DB_FILE = "oic_svr_db_server.json";
- public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE; //resource interface
- 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";
- public static final int ERROR_CODE = 200;
-}
+++ /dev/null
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
- android:layout_height="fill_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">
-
- <ScrollView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/scroll">
-
- <TextView android:text="@string/simpleServer" android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/textView"
- android:scrollbars="vertical"
- android:maxLines="10"/>
-
- </ScrollView>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_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:paddingLeft="@dimen/activity_horizontal_margin"
+ android:orientation="vertical"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".SimpleServer">
+ <ToggleButton
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/toggleButton"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true" />
+ <ScrollView
+ android:layout_below="@id/toggleButton"
+ 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 Server</string>
- <string name="app_name">SimpleServer</string>
- <string name="simpleServer">Starting Simple Server...</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>