+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.devicediscoveryclient"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * This sample demonstrates the device discovery feature.
- * The client queries for the device related information stored by the server.
- */
-public class DeviceDiscoveryClient extends Activity implements
- OcPlatform.OnDeviceFoundListener,
- OcPlatform.OnPlatformFoundListener {
- private void startDeviceDiscoveryClient() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
- 0, // Uses randomly available port
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
- sleep(1);
-
- try {
- msg("Querying for platform information...");
- OcPlatform.getPlatformInfo("",
- OcPlatform.WELL_KNOWN_PLATFORM_QUERY,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to query for platform information");
- }
- sleep(2);
-
- try {
- msg("Querying for device information...");
- OcPlatform.getDeviceInfo("",
- OcPlatform.WELL_KNOWN_DEVICE_QUERY,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to query for device information");
- }
- sleep(2);
-
- enableStartButton();
- printLine();
- }
-
- private final static Map<String, String> PLATFORM_INFO_KEYS = new HashMap<String, String>() {{
- put("pi", "Platform ID: ");
- put("mnmn", "Manufacturer name: ");
- put("mnml", "Manufacturer url: ");
- put("mnmo", "Manufacturer Model No: ");
- put("mndt", "Manufactured Date: ");
- put("mnpv", "Manufacturer Platform Version: ");
- put("mnos", "Manufacturer OS version: ");
- put("mnhw", "Manufacturer hardware version: ");
- put("mnfv", "Manufacturer firmware version: ");
- put("mnsl", "Manufacturer support url: ");
- put("st", "Manufacturer system time: ");
- }};
-
- @Override
- public synchronized void onPlatformFound(OcRepresentation ocRepresentation) {
- msg("Platform Information received:");
- try {
- for (String key : PLATFORM_INFO_KEYS.keySet()) {
- msg("\t" + PLATFORM_INFO_KEYS.get(key) + ocRepresentation.getValue(key));
- }
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to read platform info values.");
- }
-
- printLine();
- }
-
- private final static Map<String, String> DEVICE_INFO_KEYS = new HashMap<String, String>() {{
- put("di", "Device ID: ");
- put("n", "Device name: ");
- put("lcv", "Spec version url: ");
- put("dmv", "Data Model: ");
- }};
-
- @Override
- public synchronized void onDeviceFound(OcRepresentation ocRepresentation) {
- msg("Device Information received:");
- try {
- for (String key : DEVICE_INFO_KEYS.keySet()) {
- msg("\t" + DEVICE_INFO_KEYS.get(key) + ocRepresentation.getValue(key));
- }
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to read device info values.");
- }
-
- printLine();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- private final static String TAG = DeviceDiscoveryClient.class.getSimpleName();
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_device_discovery_client);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setText("Re-start");
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startDeviceDiscoveryClient();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
-
- private void enableStartButton() {
- runOnUiThread(new Runnable() {
- public void run() {
- Button button = (Button) findViewById(R.id.button);
- button.setEnabled(true);
- }
- });
- }
-
- private void sleep(int seconds) {
- try {
- Thread.sleep(seconds * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- Log.e(TAG, e.toString());
- }
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-}
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.devicediscoveryserver"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcDeviceInfo;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcPlatformInfo;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-/**
- * This sample demonstrates platform and device discovery feature.
- * The server sets the platform and device related info. which can be later retrieved by a client.
- */
-public class DeviceDiscoveryServer extends Activity {
-
- private void startDeviceDiscoveryServer() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.SERVER,
- "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
- 0, // Uses randomly available port
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
-
- OcDeviceInfo deviceInfo = new OcDeviceInfo("myDeviceName");
- try {
- msg("Registering device info");
- OcPlatform.registerDeviceInfo(deviceInfo);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to register device info.");
- }
-
- OcPlatformInfo platformInfo = new OcPlatformInfo(
- "myPlatformId", //Platform ID
- "myManufactName", //Manufacturer Name
- "www.myurl.com", //Manufacturer URL
- "myModelNumber", //Model Number
- "myDateOfManufacture", //Date of Manufacture
- "myPlatformVersion", //Platform Version
- "Manufacturer OS version", //Operating System Version
- "myHardwareVersion", //Hardware Version
- "myFirmwareVersion", //Firmware Version
- "www.mysupporturl.com", //Support URL
- String.valueOf(System.currentTimeMillis()) // System Time
- );
- try {
- msg("Registering platform info");
- OcPlatform.registerPlatformInfo(platformInfo);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to register platform info.");
- }
-
- msg("Waiting for the requests...");
- printLine();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- private final static String TAG = DeviceDiscoveryServer.class.getSimpleName();
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_device_discovery_server);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startDeviceDiscoveryServer();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-}
+++ /dev/null
-apply plugin: 'com.android.application'
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.fridgeclient"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Message;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * FridgeClient
- * <p/>
- * FridgeClient is a sample client app which should be started after the fridgeServer is started.
- * It creates DeviceResource, DoorResources, LightResource and performs a GET operation on them.
- */
-public class FridgeClient extends Activity implements
- OcPlatform.OnResourceFoundListener,
- OcResource.OnGetListener {
- public static final String DEVICE_URI = "/device";
- public static final String LIGHT = "/light";
- public static final String LEFT_DOOR = "/door/left";
- public static final String RIGHT_DOOR = "/door/right";
- public static final String RANDOM_DOOR = "/door/random";
- public static final String API_VERSION = "v.1.0";
- public static final String CLIENT_TOKEN = "21ae43gf";
- public static final int API_VERSION_KEY = 2048;
- public static final int CLIENT_TOKEN_KEY = 3000;
-
- private final List<OcResource> mResourceList = new LinkedList<OcResource>();
- private OcResource mFridgeResource;
-
- /**
- * configure OIC platform and call findResource
- */
- private void startFridgeClient() {
- PlatformConfig cfg = new PlatformConfig(
- this, // context
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
-
- logMessage("Configuring platform");
- OcPlatform.Configure(cfg);
- logMessage("Initiating fridge discovery");
- try {
- OcPlatform.findResource("",
- OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
- } catch (OcException e) {
- logMessage(" Failed to discover resource");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * An event handler to be executed whenever a "findResource" request completes successfully
- *
- * @param ocResource found resource
- */
- @Override
- public synchronized void onResourceFound(OcResource ocResource) {
- if (null != mFridgeResource || !ocResource.getUri().equals(DEVICE_URI)) {
- logMessage("Didn't find the correct fridge resource. Exiting");
- return;
- }
- mFridgeResource = ocResource;
- logMessage("Discovered a fridge with \nHost: " + mFridgeResource.getHost());
-
- List<String> lightTypes = new LinkedList<>();
- lightTypes.add("intel.fridge.light");
- List<String> doorTypes = new LinkedList<>();
- doorTypes.add("intel.fridge.door");
- List<String> resourceInterfaces = new LinkedList<>();
- resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
- logMessage("Creating child resource proxies for the previously known fridge components");
- OcResource light = null;
- OcResource leftDoor = null;
- OcResource rightDoor = null;
- OcResource randomDoor = null;
- try {
- light = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
- LIGHT,
- mFridgeResource.getConnectivityTypeSet(),
- false, //isObservable
- lightTypes,
- resourceInterfaces);
- mResourceList.add(light);
-
- leftDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
- LEFT_DOOR,
- mFridgeResource.getConnectivityTypeSet(),
- false, //isObservable
- doorTypes,
- resourceInterfaces);
- mResourceList.add(leftDoor);
-
- rightDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
- RIGHT_DOOR,
- mFridgeResource.getConnectivityTypeSet(),
- false, //isObservable
- doorTypes,
- resourceInterfaces);
- mResourceList.add(rightDoor);
-
- randomDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
- RANDOM_DOOR,
- mFridgeResource.getConnectivityTypeSet(),
- false, //isObservable
- doorTypes,
- resourceInterfaces);
- mResourceList.add(randomDoor);
- } catch (OcException e) {
- logMessage("Error in constructResourceObject");
- Log.e(TAG, e.getMessage());
- }
-
- List<OcHeaderOption> headerOptions = new LinkedList<>();
- OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY, API_VERSION);
- OcHeaderOption clientToken = new OcHeaderOption(CLIENT_TOKEN_KEY, CLIENT_TOKEN);
- headerOptions.add(apiVersion);
- headerOptions.add(clientToken);
- mFridgeResource.setHeaderOptions(headerOptions);
-
- logMessage("Calling GET api on mFridgeResource and other component resources");
- try {
- mFridgeResource.get(new HashMap<String, String>(), this);
- if (null != light) light.get(new HashMap<String, String>(), this);
- if (null != leftDoor) leftDoor.get(new HashMap<String, String>(), this);
- if (null != rightDoor) rightDoor.get(new HashMap<String, String>(), this);
- if (null != randomDoor) randomDoor.get(new HashMap<String, String>(), this);
- } catch (OcException e) {
- logMessage("Error in GET calls");
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * An event handler to be executed whenever a "get" request completes successfully
- *
- * @param headerOptionList list of the header options
- * @param ocRepresentation representation of a resource
- */
- @Override
- public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
- OcRepresentation ocRepresentation) {
- logMessage("Got a response from " + ocRepresentation.getUri());
- }
-
- /**
- * An event handler to be executed whenever a "get" request fails
- *
- * @param throwable exception
- */
- @Override
- public synchronized void onGetFailed(Throwable throwable) {
- logMessage("GET request has failed");
- Log.e(TAG, throwable.toString());
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fridge_client);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startFridgeClient();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- private void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
-
- private static String TAG = "FridgeClient: ";
- private TextView mConsoleTextView;
-}
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "20.0.0"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.fridgegroupclient"\r
- minSdkVersion 21\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
- lintOptions {\r
- abortOnError false\r
- }\r
-}\r
-repositories {\r
- flatDir {\r
- dirs "../../android_api/base/build/outputs/aar/"\r
- }\r
-}\r
-try {\r
- dependencies {\r
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
- }\r
-} catch (all) {\r
- print "${ERROR_MSG}"\r
- assert all\r
-}\r
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Message;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * FridgeGroupClient
- * <p/>
- * FridgeGroupClient is a sample client app which should be started after the fridgeGroupServer is
- * started. It discovers a fridge resource and then creates the proxy resources for each one of its
- * children (light and door) and performs a GET on them.
- */
-public class FridgeGroupClient extends Activity implements
- OcPlatform.OnResourceFoundListener,
- OcResource.OnGetListener {
- private static String TAG = "FridgeGroupClient: ";
-
- private final List<OcResource> childResourceList = new LinkedList<>();
- private OcResource fridgeResource;
-
- private void startFridgeClient() {
- PlatformConfig cfg = new PlatformConfig(
- this, // context
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
-
- logMessage("Configuring platform");
- OcPlatform.Configure(cfg);
- String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=intel.fridge.group";
- logMessage("Initiating fridge discovery");
- try {
- OcPlatform.findResource("",
- requestUri,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
- } catch (OcException e) {
- logMessage("Failed to discover resource");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * callback when a fridge resource is found.
- */
- @Override
- public synchronized void onResourceFound(OcResource ocResource) {
- if ((null != fridgeResource) && !fridgeResource.getUri().equals("/fridge/group")) {
- logMessage("Didn't find the correct fridge resource. Exiting");
- return;
- }
- fridgeResource = ocResource;
- logMessage("Discovered a fridge with \nHost: " + fridgeResource.getHost());
- logMessage("Trying to call GET api on fridgeResource");
- try {
- fridgeResource.get(new HashMap<String, String>(), this);
- } catch (OcException e) {
- logMessage("Failed to call GET api");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * once the fridge resource is discovered, create proxy child resources of the fridge
- * and call GET on each of the child resource proxies.
- *
- * @param list
- * @param ocRepresentation parent resource
- */
- @Override
- public synchronized void onGetCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("Got a response from " + ocRepresentation.getUri());
- for (OcRepresentation child : ocRepresentation.getChildren()) {
- try {
- logMessage("Creating child resource proxy from fridgeResource with uri " +
- child.getUri());
- OcResource childResource = OcPlatform.constructResourceObject(
- fridgeResource.getHost(),
- child.getUri(),
- fridgeResource.getConnectivityTypeSet(),
- false, // isObservable set to false
- child.getResourceTypes(),
- child.getResourceInterfaces());
- childResourceList.add(childResource);
- } catch (OcException e) {
- logMessage("Error in creating child resource proxy");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- OcResource.OnGetListener childOnGetListener = new OcResource.OnGetListener() {
- public static final String DOOR_STATE_KEY = "state";
- public static final String DOOR_SIDE_KEY = "side";
- public static final String LIGHT_STATUS_KEY = "light";
-
- @Override
- public synchronized void onGetCompleted(List<OcHeaderOption> list,
- OcRepresentation ocRepresentation) {
- logMessage("Received a response from a child of the fridge with uri: " +
- ocRepresentation.getUri());
- for (String resType : ocRepresentation.getResourceTypes()) {
- if (resType.equals("intel.fridge.door")) {
- try {
- logMessage(ocRepresentation.getValue(DOOR_SIDE_KEY) +
- " door is " + ((ocRepresentation.getValue(DOOR_STATE_KEY)
- ) ? "open" : "close"));
- } catch (OcException e) {
- logMessage("Failed to get the door resource representation");
- Log.e(TAG, e.getMessage());
- }
- } else if (resType.equals("intel.fridge.light")) {
- try {
- logMessage("Fridge light is " +
- ((ocRepresentation.getValue(LIGHT_STATUS_KEY)) ?
- "on" : "off"));
- } catch (OcException e) {
- logMessage("Failed to get the light resource representation");
- Log.e(TAG, e.getMessage());
- }
- }
- }
- logMessage("-----------------------------------------------------");
- }
-
- @Override
- public synchronized void onGetFailed(Throwable throwable) {
- logMessage("OnGet failed for child of fridge");
- Log.e(TAG, throwable.getMessage());
- }
- };
-
- for (OcResource child : childResourceList) {
- try {
- logMessage("Trying to get a representation of " + child.getUri() +
- " resource from server");
- child.get(new HashMap<String, String>(), childOnGetListener);
- } catch (OcException e) {
- logMessage(e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- }
-
- @Override
- public synchronized void onGetFailed(Throwable throwable) {
- logMessage("Failed to get representation of the fridge");
- Log.e(TAG, throwable.toString());
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private TextView mConsoleTextView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fridge_client);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startFridgeClient();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
-
- private void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
-}
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "20.0.0"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.fridgegroupserver"\r
- minSdkVersion 21\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
- lintOptions {\r
- abortOnError false\r
- }\r
-}\r
-repositories {\r
- flatDir {\r
- dirs "../../android_api/base/build/outputs/aar/"\r
- }\r
-}\r
-try {\r
- dependencies {\r
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
- }\r
-} catch (all) {\r
- print "${ERROR_MSG}"\r
- assert all\r
-}\r
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcResourceResponse;
-import org.iotivity.base.RequestHandlerFlag;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-
-/**
- * DoorResource
- * <p/>
- * DoorResource is a sample OIC server resource created by the refrigerator.
- */
-public class DoorResource extends Resource implements OcPlatform.EntityHandler {
- DoorResource(String side, Context context) {
- mContext = context;
- mSide = side;
-
- registerDoorResource();
- }
-
- private void registerDoorResource() {
- String resourceURI = DOOR_URI + mSide;
- logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
- try {
- mResourceHandle = OcPlatform.registerResource(
- resourceURI,
- RESOURCE_TYPEDOOR,
- OcPlatform.DEFAULT_INTERFACE,
- this,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "Failed to register DoorResource");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * sample implementation of eventHandler for doorResource - this can be implemented in many
- * different ways
- *
- * @param ocResourceRequest OcResourceRequest from the client
- * @return EntityHandlerResult indicates whether the request was handled successfully or not
- */
- @Override
- public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != ocResourceRequest) {
- try {
- if (ocResourceRequest.getRequestHandlerFlagSet().contains(
- RequestHandlerFlag.REQUEST)) {
- OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(ocResourceRequest.getRequestHandle());
- response.setResourceHandle(ocResourceRequest.getResourceHandle());
-
- switch (ocResourceRequest.getRequestType()) {
- case GET:
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- break;
- case PUT:
- put(ocResourceRequest.getResourceRepresentation());
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- break;
- case DELETE:
- response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
- OcPlatform.sendResponse(response);
- break;
- }
- result = EntityHandlerResult.OK;
- }
- } catch (OcException e) {
- logMessage("Error in handleEntity of DoorResource");
- Log.e(TAG, e.getMessage());
- return EntityHandlerResult.ERROR;
- }
- }
- logMessage("-----------------------------------------------------");
- return result;
- }
-
- public OcResourceHandle getHandle() {
- return mResourceHandle;
- }
-
- /**
- * helper function to update the current value of the door resource
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
- mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
- logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
- " and door side is " + mSide);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * update the value of doorResource, depending on if door is open/ closed
- *
- * @param representation new state of a door
- */
- private void put(OcRepresentation representation) {
- try {
- mDoorState = representation.getValue(DOOR_STATE_KEY);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- // Note, we won't let the user change the door side!
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private Context mContext;
- private String mSide;
- private boolean mDoorState;
- public static final String DOOR_URI = "/door/";
- public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
- private static String TAG = "DoorResource: ";
- public static final String DOOR_STATE_KEY = "state";
- public static final String DOOR_SIDE_KEY = "side";
-
- private void logMessage(String msg) {
- Intent intent = new Intent(Resource.INTENT);
- intent.putExtra(Resource.MESSAGE, msg);
- mContext.sendBroadcast(intent);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.Message;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-/**
- * FridgeGroupServer
- * <p/>
- * This is the main fridgeGroupServer class. This instantiates Refrigerator object
- * which has different resources such as LightResource, DoorResource, etc.
- */
-public class FridgeGroupServer extends Activity {
- private Refrigerator refrigerator;
-
- /**
- * configure OIC platform and call findResource
- */
- private void startFridgeServer() {
- logMessage("Configuring platform config");
- PlatformConfig cfg = new PlatformConfig(
- this, // context
- ServiceType.IN_PROC,
- ModeType.SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
- OcPlatform.Configure(cfg);
-
- logMessage("Creating refrigerator resources");
- refrigerator = new Refrigerator(this);
- logMessage("-----------------------------------------------------");
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private static String TAG = "FridgeServer: ";
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
- private BroadcastReceiver mMessageReceiver = new MessageReceiver();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fridge_server);
- registerReceiver(mMessageReceiver, new IntentFilter(Resource.INTENT));
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startFridgeServer();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
-
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(Resource.MESSAGE);
- logMessage(message);
- }
- }
-
- private void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-
-
-/**
- * FridgeResource
- * <p/>
- * FridgeResource is a sample OIC server resource created by the refrigerator.
- */
-public class FridgeResource extends Resource {
- FridgeResource(Context context) {
- mContext = context;
- registerFridgeResource();
- }
-
- private void registerFridgeResource() {
- try {
- logMessage(TAG + "RegisterFridgeResource " + FRIDGE_URI +
- " : " + FRIDGE_TYPENAME);
- mResourceHandle = OcPlatform.registerResource(
- FRIDGE_URI,
- FRIDGE_TYPENAME,
- OcPlatform.GROUP_INTERFACE,
- null,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "FridgeResource register error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- public OcResourceHandle getHandle() {
- return mResourceHandle;
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private Context mContext;
- public static final String FRIDGE_URI = "/fridge/group";
- public static final String FRIDGE_TYPENAME = "intel.fridge.group";
- private static String TAG = "FridgeResource: ";
-
- private void logMessage(String msg) {
- Intent intent = new Intent(Resource.INTENT);
- intent.putExtra("message", msg);
- mContext.sendBroadcast(intent);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcResourceResponse;
-import org.iotivity.base.RequestHandlerFlag;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-
-
-/**
- * LightResource
- * <p/>
- * LightResource is a sample OIC server resource created by the refrigerator.
- */
-public class LightResource extends Resource implements OcPlatform.EntityHandler {
- LightResource(Context context) {
- mContext = context;
-
- registerLightResource();
- }
-
- private void registerLightResource() {
- try {
- logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
- mResourceHandle = OcPlatform.registerResource(
- LIGHT_URI,
- RESOURCE_TYPELIGHT,
- OcPlatform.DEFAULT_INTERFACE,
- this,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "Failed to register LightResource");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * sample implementation of eventHandler for lightResource - this can be implemented in many
- * different ways
- *
- * @param ocResourceRequest OcResourceRequest from the client
- * @return EntityHandlerResult indicates whether the request was handled successfully or not
- */
- @Override
- public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != ocResourceRequest) {
- try {
- if (ocResourceRequest.getRequestHandlerFlagSet().contains(
- RequestHandlerFlag.REQUEST)) {
- OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(ocResourceRequest.getRequestHandle());
- response.setResourceHandle(ocResourceRequest.getResourceHandle());
- switch (ocResourceRequest.getRequestType()) {
- case GET:
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- result = EntityHandlerResult.OK;
- break;
- case PUT:
- put(ocResourceRequest.getResourceRepresentation());
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- result = EntityHandlerResult.OK;
- break;
- }
- }
- } catch (OcException e) {
- logMessage("Error in handleEntity");
- Log.e(TAG, e.getMessage());
- return EntityHandlerResult.ERROR;
- }
- }
- logMessage("-----------------------------------------------------");
- return result;
- }
-
- public OcResourceHandle getHandle() {
- return mResourceHandle;
- }
-
- /**
- * update the value of light (ON/ OFF) from the representation
- *
- * @param representation new state of light
- */
- private void put(OcRepresentation representation) {
- try {
- mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * helper function to update the current state of the light
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private Context mContext;
- private boolean mIsLightOn = false;
-
- private static String TAG = "LightResource: ";
- public static final String LIGHT_URI = "/light";
- public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
- public static final String LIGHT_STATUS_KEY = "light";
-
- private void logMessage(String msg) {
- Intent intent = new Intent(Resource.INTENT);
- intent.putExtra(Resource.MESSAGE, msg);
- mContext.sendBroadcast(intent);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.content.Context;
-
-/**
- * Refrigerator
- * <p/>
- * Refrigerator class has different objects (resources) which are instantiated when a
- * Refrigerator object is created. Operations are performed on each of the individual resources.
- */
-public class Refrigerator {
- public static final String LEFT_SIDE = "left";
- public static final String RIGHT_SIDE = "right";
- public static final String RANDOM_SIDE = "random";
-
- private FridgeResource mFridge;
- private LightResource mLight;
- private DoorResource mLeftDoor;
- private DoorResource mRightDoor;
- private DoorResource mRandomDoor;
-
- /**
- * constructor - creates resources of light and doors
- *
- * @param context needed by individual resources to be able to send broadcast
- * messages to be displayed on the user screen
- */
- Refrigerator(Context context) {
- mFridge = new FridgeResource(context);
- mLight = new LightResource(context);
- mLeftDoor = new DoorResource(LEFT_SIDE, context);
- mRightDoor = new DoorResource(RIGHT_SIDE, context);
- mRandomDoor = new DoorResource(RANDOM_SIDE, context);
-
- mLight.bindTo(mFridge.getHandle());
- mLeftDoor.bindTo(mFridge.getHandle());
- mRightDoor.bindTo(mFridge.getHandle());
- mRandomDoor.bindTo(mFridge.getHandle());
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples;
-
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceHandle;
-
-/**
- * Resource
- * <p/>
- * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource
- */
-public abstract class Resource {
- protected OcResourceHandle mResourceHandle;
- protected OcRepresentation mRepresentation;
-
- Resource() {
- mResourceHandle = null;
- mRepresentation = new OcRepresentation();
- }
-
- public void bindTo(OcResourceHandle collectionResourceHandle) {
- try {
- if (null != mResourceHandle && null != collectionResourceHandle) {
- OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
- }
- } catch (OcException e) {
- Log.e("Resource", e.getMessage());
- }
- }
-
- public static final int SUCCESS = 200;
- public static final String INTENT = "org.iotivity.base.examples.fridgegroupserver";
- public static final String MESSAGE = "message";
-}
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.fridgeserver"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcResourceResponse;
-import org.iotivity.base.RequestHandlerFlag;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * DeviceResource
- * <p/>
- * Creates a device resource and performs action based on client requests
- */
-public class DeviceResource extends Resource implements OcPlatform.EntityHandler {
- public static final String DEVICE_URI = "/device";
- public static final String RESOURCE_TYPENAME = "intel.fridge";
- public static final String API_VERSION = "v.1.0";
- public static final String CLIENT_TOKEN = "21ae43gf";
- public static final String DEVICE_NAME = "device_name";
- private static String TAG = "DeviceResource: ";
- public static final int SUCCESS = 200;
- public static final int API_VERSION_KEY = 2048;
- public static final int CLIENT_VERSION_KEY = 3000;
-
- private Context mContext;
-
- /**
- * constructor
- *
- * @param context to enable sending of broadcast messages to be displayed on the user screen
- */
- DeviceResource(Context context) {
- mContext = context;
- registerDeviceResource();
- }
-
- private void registerDeviceResource() {
- try {
- logMessage("RegisterDeviceResource " + DEVICE_URI + " : " + RESOURCE_TYPENAME);
- mResourceHandle = OcPlatform.registerResource(
- DEVICE_URI,
- RESOURCE_TYPENAME,
- OcPlatform.DEFAULT_INTERFACE,
- this,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "Failed to register DeviceResource");
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * this is the main method which handles different incoming requests appropriately.
- *
- * @param ocResourceRequest OcResourceRequest from the client
- * @return EntityHandlerResult indicates whether the request was handled successfully or not
- */
- @Override
- public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != ocResourceRequest) {
- List<OcHeaderOption> headerOptions = ocResourceRequest.getHeaderOptions();
- String clientAPIVersion = "";
- String clientToken = "";
- // search for header options map and look for API version and client token
- for (OcHeaderOption headerOption : headerOptions) {
- int optionId = headerOption.getOptionId();
- if (API_VERSION_KEY == optionId) {
- clientAPIVersion = headerOption.getOptionData();
- logMessage(TAG + " Client API Version: " + clientAPIVersion);
- } else if (CLIENT_VERSION_KEY == optionId) {
- clientToken = headerOption.getOptionData();
- logMessage(TAG + " Client Token: " + clientToken);
- }
- }
- if (clientAPIVersion.equals(API_VERSION) &&
- clientToken.equals(CLIENT_TOKEN)) {
- List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();
- OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY,
- API_VERSION);
- serverHeaderOptions.add(apiVersion);
- try {
- if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
- OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(ocResourceRequest.getRequestHandle());
- response.setResourceHandle(ocResourceRequest.getResourceHandle());
- response.setHeaderOptions(serverHeaderOptions);
-
- switch (ocResourceRequest.getRequestType()) {
- case GET:
- response.setResponseResult(EntityHandlerResult.OK);
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- OcPlatform.sendResponse(response);
- break;
- }
- result = EntityHandlerResult.OK;
- }
- } catch (OcException e) {
- logMessage("Error in handleEntity of DeviceResource");
- Log.e(TAG, e.getMessage());
- }
- }
- }
- logMessage("-----------------------------------------------------");
- return result;
- }
-
- /**
- * update state of device
- *
- * @return device representation
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(DEVICE_NAME,
- "Intel Powered 3 door, 1 light refrigerator");
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- public void logMessage(String msg) {
- Intent intent = new Intent(FridgeServer.INTENT);
- intent.putExtra("message", msg);
- mContext.sendBroadcast(intent);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcResourceResponse;
-import org.iotivity.base.RequestHandlerFlag;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-
-/**
- * DoorResource
- * <p/>
- * Creates a door resource and performs actions based on the client requests
- */
-public class DoorResource extends Resource implements OcPlatform.EntityHandler {
- public static final String DOOR_URI = "/door/";
- public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
- public static final String DOOR_STATE_KEY = "state";
- public static final String DOOR_SIDE_KEY = "side";
- private boolean mDoorState;
- private String mSide;
-
- /**
- * Constructor
- *
- * @param side side of the door
- * @param context to enable sending of broadcast messages to be displayed on the user screen
- */
- DoorResource(String side, Context context) {
- mContext = context;
- mSide = side;
- registerDoorResource();
- }
-
- private void registerDoorResource() {
- String resourceURI = DOOR_URI + mSide;
- logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
- try {
- mResourceHandle = OcPlatform.registerResource(resourceURI,
- RESOURCE_TYPEDOOR,
- OcPlatform.DEFAULT_INTERFACE,
- this,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "Failed to register DoorResource");
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * this is the main method which handles different incoming requests appropriately.
- *
- * @param ocResourceRequest OcResourceRequest from the client
- * @return EntityHandlerResult indicates whether the request was handled successfully or not
- */
- @Override
- public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != ocResourceRequest) {
- try {
- if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
- OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(ocResourceRequest.getRequestHandle());
- response.setResourceHandle(ocResourceRequest.getResourceHandle());
-
- switch (ocResourceRequest.getRequestType()) {
- case GET:
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- break;
- case PUT:
- put(ocResourceRequest.getResourceRepresentation());
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- break;
- case DELETE:
- response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
- OcPlatform.sendResponse(response);
- break;
- }
- result = EntityHandlerResult.OK;
- }
- } catch (OcException e) {
- logMessage("Error in handleEntity of DoorResource");
- Log.e(TAG, e.getMessage());
- return EntityHandlerResult.ERROR;
- }
- }
- logMessage("-----------------------------------------------------");
- return result;
- }
-
- /**
- * helper function to update the current value of the door resource
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
- mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
- logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
- " and door side is " + mSide);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * update the value of doorResource, depending on if door is open/ closed
- *
- * @param representation new state of a door
- */
- private void put(OcRepresentation representation) {
- try {
- mDoorState = representation.getValue(DOOR_STATE_KEY);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- // Note, we won't let the user change the door side!
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private Context mContext;
- private static String TAG = "DoorResource: ";
-
- public void logMessage(String msg) {
- Intent intent = new Intent(FridgeServer.INTENT);
- intent.putExtra(FridgeServer.MESSAGE, msg);
- mContext.sendBroadcast(intent);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.Message;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-/**
- * FridgeServer
- * <p/>
- * This is the main fridgeServer class. This instantiates Refrigerator object
- * which has different resources (DeviceResource, LightResource, DoorResources).
- */
-public class FridgeServer extends Activity {
- private Refrigerator refrigerator;
-
- /**
- * configure OIC platform and call findResource
- */
- private void startFridgeServer() {
- //create platform config
- PlatformConfig cfg = new PlatformConfig(
- this, //context
- ServiceType.IN_PROC,
- ModeType.SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
- logMessage("Configuring platform");
- OcPlatform.Configure(cfg);
- logMessage("Creating refrigerator resources");
- refrigerator = new Refrigerator(this);
- logMessage("-----------------------------------------------------");
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private static String TAG = "FridgeServer: ";
- public static final String MESSAGE = "message";
- public static final String INTENT = "org.iotivity.base.examples.fridgeserver";
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
- private MessageReceiver mMessageReceiver = new MessageReceiver();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fridge_server);
- registerReceiver(mMessageReceiver, new IntentFilter(INTENT));
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final Button button = (Button) findViewById(R.id.button);
-
- if (null == savedInstanceState) {
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- button.setEnabled(false);
- new Thread(new Runnable() {
- public void run() {
- startFridgeServer();
- }
- }).start();
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- }
- }
-
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(MESSAGE);
- logMessage(message);
- }
- }
-
- public void logMessage(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import org.iotivity.base.EntityHandlerResult;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcResourceResponse;
-import org.iotivity.base.RequestHandlerFlag;
-import org.iotivity.base.ResourceProperty;
-
-import java.util.EnumSet;
-
-/**
- * LightResource
- * <p/>
- * Creates a light resource and performs actions based on the client requests
- */
-public class LightResource extends Resource implements OcPlatform.EntityHandler {
- public static final String LIGHT_STATUS_KEY = "light";
- public static final String LIGHT_URI = "/light";
- public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
- private boolean mIsLightOn = false;
-
- /**
- * constructor
- *
- * @param context to enable sending of broadcast messages to be displayed on the user screen
- */
- LightResource(Context context) {
- mContext = context;
- registerLightResource();
- }
-
- private void registerLightResource() {
- try {
- logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
- mResourceHandle = OcPlatform.registerResource(LIGHT_URI,
- RESOURCE_TYPELIGHT,
- OcPlatform.DEFAULT_INTERFACE,
- this,
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "Failed to register LightResource");
- Log.e(TAG, e.getMessage());
- }
- logMessage("-----------------------------------------------------");
- }
-
- /**
- * this is the main method which handles different incoming requests appropriately.
- *
- * @param ocResourceRequest OcResourceRequest from the client
- * @return EntityHandlerResult indicates whether the request was handled successfully or not
- */
- @Override
- public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != ocResourceRequest) {
- try {
- if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
- OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(ocResourceRequest.getRequestHandle());
- response.setResourceHandle(ocResourceRequest.getResourceHandle());
-
- switch (ocResourceRequest.getRequestType()) {
- case GET:
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- result = EntityHandlerResult.OK;
- break;
- case PUT:
- put(ocResourceRequest.getResourceRepresentation());
- updateRepresentationValues();
- response.setResourceRepresentation(mRepresentation);
- response.setResponseResult(EntityHandlerResult.OK);
- OcPlatform.sendResponse(response);
- result = EntityHandlerResult.OK;
- break;
- }
- }
- } catch (OcException e) {
- logMessage("Error in handleEntity of LightResource");
- Log.e(TAG, e.getMessage());
- return EntityHandlerResult.ERROR;
- }
- }
- logMessage("-----------------------------------------------------");
- return result;
- }
-
- /**
- * updates the current state of the light (on/ off)
- *
- * @return light is on or off
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * update the value of mIsOn from the representation
- *
- * @param representation get current state of light
- */
- private void put(OcRepresentation representation) {
- try {
- mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
- private Context mContext;
- private static String TAG = "LightResource: ";
-
- public void logMessage(String msg) {
- Intent intent = new Intent(FridgeServer.INTENT);
- intent.putExtra(FridgeServer.MESSAGE, msg);
- mContext.sendBroadcast(intent);
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.content.Context;
-
-/**
- * Refrigerator
- * <p/>
- * Refrigerator class has different objects (resources) which are instantiated when a
- * Refrigerator object is created.
- */
-public class Refrigerator {
- public static final String LEFT_SIDE = "left";
- public static final String RIGHT_SIDE = "right";
- public static final String RANDOM_SIDE = "random";
-
- private LightResource mLight;
- private DeviceResource mDevice;
- private DoorResource mLeftDoor;
- private DoorResource mRightDoor;
- private DoorResource mRandomDoor;
-
- /**
- * constructor
- *
- * @param context needed by individual resources to be able to send broadcast
- * messages to be displayed on the user screen
- */
- Refrigerator(Context context) {
- mLight = new LightResource(context);
- mDevice = new DeviceResource(context);
- mLeftDoor = new DoorResource(LEFT_SIDE, context);
- mRightDoor = new DoorResource(RIGHT_SIDE, context);
- mRandomDoor = new DoorResource(RANDOM_SIDE, context);
-
- mLight.bindTo(mDevice.getHandle());
- mLeftDoor.bindTo(mDevice.getHandle());
- mRightDoor.bindTo(mDevice.getHandle());
- mRandomDoor.bindTo(mDevice.getHandle());
- }
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeserver;
-
-import android.util.Log;
-
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResourceHandle;
-
-/**
- * Resource
- * <p/>
- * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource
- */
-public class Resource {
- protected OcResourceHandle mResourceHandle;
- protected OcRepresentation mRepresentation;
-
- Resource() {
- mResourceHandle = null;
- mRepresentation = new OcRepresentation();
- }
-
- public void bindTo(OcResourceHandle collectionResourceHandle) {
- try {
- if (null != mResourceHandle && null != collectionResourceHandle) {
- OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
- }
- } catch (OcException e) {
- Log.e("Resource", e.getMessage());
- }
- }
-
- public OcResourceHandle getHandle() {
- return mResourceHandle;
- }
-
- public static final int SUCCESS = 200;
-}
\ No newline at end of file
+++ /dev/null
-#Wed Apr 10 15:27:10 PDT 2013\r
-distributionBase=GRADLE_USER_HOME\r
-distributionPath=wrapper/dists\r
-zipStoreBase=GRADLE_USER_HOME\r
-zipStorePath=wrapper/dists\r
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip\r
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.groupclient"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.CompoundButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * GroupClient
- */
-public class GroupClient extends Activity implements
- OcPlatform.OnResourceFoundListener,
- OcResource.OnGetListener {
-
- private OcResource mFoundCollectionResource;
-
- /**
- * A local method to configure and initialize platform and then search for the collection
- * resources
- */
- private synchronized void startGroupClient() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", 0,
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
-
- msg("Find all resources of type \"a.collection\".");
- try {
- OcPlatform.findResource(
- "",
- OcPlatform.WELL_KNOWN_QUERY + "?rt=a.collection",
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this
- );
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to invoke find resource API");
- }
-
- printLine();
- }
-
- /**
- * An event handler to be executed whenever a "findResource" request completes successfully
- *
- * @param foundResource found resource
- */
- @Override
- public synchronized void onResourceFound(OcResource foundResource) {
- if (null == foundResource) {
- msg("Found resource is invalid");
- return;
- }
- if (null != mFoundCollectionResource) {
- msg("Found another resource, ignoring");
- return;
- }
-
- // Get the resource URI
- String resourceUri = foundResource.getUri();
- // Get the resource host address
- String hostAddress = foundResource.getHost();
- msg("\tURI of the resource: " + resourceUri);
- msg("\tHost address of the resource: " + hostAddress);
- // Get the resource types
- msg("\tList of resource types: ");
- for (String resourceType : foundResource.getResourceTypes()) {
- msg("\t\t" + resourceType);
- }
- msg("\tList of resource interfaces:");
- for (String resourceInterface : foundResource.getResourceInterfaces()) {
- msg("\t\t" + resourceInterface);
- }
- msg("\tList of resource connectivity types:");
- for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
- msg("\t\t" + connectivityType);
- }
-
- if (resourceUri.equals("/core/a/collection")) {
- mFoundCollectionResource = foundResource;
-
- msg("Getting representation of a collection resource...");
-
- Map<String, String> queryParams = new HashMap<>();
- try {
- mFoundCollectionResource.get(
- "",
- OcPlatform.DEFAULT_INTERFACE,
- queryParams,
- this
- );
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Error occurred while invoking \"get\" API");
- }
- }
-
- printLine();
- enableStartStopButton();
- }
-
- /**
- * An event handler to be executed whenever a "get" request completes successfully
- *
- * @param list list of the header options
- * @param representation representation of a resource
- */
- @Override
- public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation representation) {
- msg("Representation of a light collection resource:");
- for (OcRepresentation childRepresentation : representation.getChildren()) {
- msg("\t\tURI: " + childRepresentation.getUri());
- }
- }
-
- /**
- * An event handler to be executed whenever a "get" request fails
- *
- * @param throwable exception
- */
- @Override
- public synchronized void onGetFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- Log.e(TAG, ocEx.toString());
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- msg("Error code: " + errCode);
- }
- msg("Failed to get representation of a found collection resource");
- }
-
- /**
- * A local method to reset group client
- */
- private synchronized void stopGroupClient() {
- mFoundCollectionResource = null;
-
- msg("Group Client is reset.");
- printLine();
-
- enableStartStopButton();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- private final static String TAG = GroupClient.class.getSimpleName();
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_group_client);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
-
- if (null == savedInstanceState) {
- toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- toggleButton.setEnabled(false);
- if (isChecked) {
- new Thread(new Runnable() {
- public void run() {
- startGroupClient();
- }
- }).start();
- } else {
- new Thread(new Runnable() {
- public void run() {
- stopGroupClient();
- }
- }).start();
- }
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
-
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-
- private void sleep(int seconds) {
- try {
- Thread.sleep(seconds * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- Log.e(TAG, e.toString());
- }
- }
-
- private void enableStartStopButton() {
- runOnUiThread(new Runnable() {
- public void run() {
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- toggleButton.setEnabled(true);
- }
- });
- }
-}
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.groupserver"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.CompoundButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ResourceProperty;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * GroupServer
- */
-public class GroupServer extends Activity implements OcPlatform.OnResourceFoundListener {
-
- private OcResourceHandle mCollectionResourceHandle;
- private List<OcResourceHandle> mProxyResourceHandleList = new LinkedList<>();
-
- /**
- * A local method to configure and initialize platform, register a collection resource
- * and then search for the light resources.In addition it creates a local light resource and
- * adds it to the collection.
- */
- private synchronized void startGroupServer() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.CLIENT_SERVER,
- "0.0.0.0", 0,
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
-
- String resourceUri = "/core/a/collection";
- String resourceTypeName = "a.collection";
- msg("Registering a collection resource.");
- try {
- mCollectionResourceHandle = OcPlatform.registerResource(
- resourceUri, //resource URI
- resourceTypeName, //resource type name
- OcPlatform.BATCH_INTERFACE, //using batch interface
- null, //use default entity handler
- EnumSet.of(ResourceProperty.DISCOVERABLE)
- );
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to register a collection resource");
- }
-
- if (null != mCollectionResourceHandle) {
- try {
- OcPlatform.bindInterfaceToResource(
- mCollectionResourceHandle,
- OcPlatform.GROUP_INTERFACE);
-
- OcPlatform.bindInterfaceToResource(
- mCollectionResourceHandle,
- OcPlatform.DEFAULT_INTERFACE);
- } catch (OcException e) {
- e.printStackTrace();
- }
-
- }
-
- msg("Sending request to find all resources with \"core.light\" type name");
- try {
- OcPlatform.findResource(
- "",
- OcPlatform.WELL_KNOWN_QUERY + "?rt=core.light",
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
-
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to invoke find resource API");
- }
-
- OcResourceHandle localLightResourceHandle = null;
- msg("Registering a local light resource");
- try {
- localLightResourceHandle = OcPlatform.registerResource(
- "/a/light/local", //resource URI
- "core.light", //resource type name
- OcPlatform.DEFAULT_INTERFACE, //using default interface
- null, //use default entity handler
- EnumSet.of(ResourceProperty.DISCOVERABLE)
- );
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to register a local ligh resource");
- }
-
- if (null != localLightResourceHandle) {
- msg("Binding a found resource proxy handle to the collection resource");
- try {
- OcPlatform.bindResource(mCollectionResourceHandle, localLightResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to bind found resource proxy handle to the collection resource");
- }
- mProxyResourceHandleList.add(localLightResourceHandle);
- }
-
- printLine();
- }
-
- /**
- * An event handler to be executed whenever a "findResource" request completes successfully
- *
- * @param foundResource found resource
- */
- @Override
- public synchronized void onResourceFound(OcResource foundResource) {
- if (null == foundResource) {
- msg("Found resource is invalid");
- return;
- }
- msg("Found resource with \"core.light\" type name\".");
- // Get the resource host address
- String hostAddress = foundResource.getHost();
- // Get the resource URI
- String resourceUri = foundResource.getUri();
- msg("\tHost address of the resource: " + hostAddress);
- msg("\tURI of the resource: " + resourceUri);
- // Get the resource types
- msg("\tList of resource types: ");
- for (String resourceType : foundResource.getResourceTypes()) {
- msg("\t\t" + resourceType);
- }
- msg("\tList of resource interfaces:");
- for (String resourceInterface : foundResource.getResourceInterfaces()) {
- msg("\t\t" + resourceInterface);
- }
- msg("\tList of resource connectivity types:");
- for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
- msg("\t\t" + connectivityType);
- }
-
- //In this example we are only interested in the light resources
- if (resourceUri.equals("/a/light")) {
- msg("Registering a found resource as a local proxy resource");
- OcResourceHandle proxyResourceHandle = null;
- try {
- proxyResourceHandle = OcPlatform.registerResource(foundResource);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to register a found resource as a local proxy resource");
- }
-
- if (null != proxyResourceHandle) {
- msg("Binding a found resource proxy handle to the collection resource");
- try {
- OcPlatform.bindResource(mCollectionResourceHandle, proxyResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to bind found resource proxy handle to the collection resource");
- }
- mProxyResourceHandleList.add(proxyResourceHandle);
- }
- }
-
- printLine();
- enableStartStopButton();
- }
-
- /**
- * A local method to reset group server
- */
- private synchronized void stopGroupServer() {
- msg("Unregistering resources");
- for (OcResourceHandle proxyResourceHandle : mProxyResourceHandleList) {
- try {
- OcPlatform.unbindResource(mCollectionResourceHandle, proxyResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to unbind a proxy resource");
- }
- try {
- OcPlatform.unregisterResource(proxyResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to unregister a proxy resource");
- }
- }
- mProxyResourceHandleList.clear();
-
- if (null != mCollectionResourceHandle) {
- try {
- OcPlatform.unregisterResource(mCollectionResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to unregister a collection resource");
- }
- }
- msg("Group Server is reset.");
-
- printLine();
- enableStartStopButton();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- private final static String TAG = GroupServer.class.getSimpleName();
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_group_server);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
-
- if (null == savedInstanceState) {
- toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- toggleButton.setEnabled(false);
- if (isChecked) {
- new Thread(new Runnable() {
- public void run() {
- startGroupServer();
- }
- }).start();
- } else {
- new Thread(new Runnable() {
- public void run() {
- stopGroupServer();
- }
- }).start();
- }
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
-
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-
- private void enableStartStopButton() {
- runOnUiThread(new Runnable() {
- public void run() {
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- toggleButton.setEnabled(true);
- }
- });
- }
-}
\ No newline at end of file
+++ /dev/null
-build
\ No newline at end of file
+++ /dev/null
-//apply plugin: 'com.android.application'\r
-//\r
-//android {\r
-// compileSdkVersion 21\r
-// buildToolsVersion "21.1.1"\r
-//\r
-// defaultConfig {\r
-// applicationId "org.iotivity.guiclient"\r
-// minSdkVersion 19\r
-// targetSdkVersion 21\r
-// versionCode 1\r
-// versionName "1.0"\r
-// }\r
-// buildTypes {\r
-// release {\r
-// minifyEnabled false\r
-// proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
-// }\r
-// }\r
-//}\r
-//\r
-//dependencies {\r
-// compile fileTree(dir: 'libs', include: ['*.jar'])\r
-// compile 'com.android.support:appcompat-v7:21.0.2'\r
-//}\r
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.content.Context;
-import android.media.Image;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseExpandableListAdapter;
-import android.widget.CompoundButton;
-import android.widget.ImageView;
-import android.widget.ProgressBar;
-import android.widget.SeekBar;
-import android.widget.Switch;
-import android.widget.TextView;
-
-import java.util.List;
-
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE;
-import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
-
-/**
- * ExpandableResourceListAdapter knows how to render an ExpandableListView, using a
- * List of OcResourceInfo objects as the parents of the ExpandableListView,
- * and OcAttributeInfo objects as the children.
- *
- * @see org.iotivity.guiclient.OcAttributeInfo
- */
-public class ExpandableResourceListAdapter extends BaseExpandableListAdapter {
- /**
- * Hardcoded TAG... if project never uses proguard then
- * MyOcClient.class.getName() is the better way.
- */
- private static final String TAG = "ExpandableResourceListAdapter";
-
- private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
-
- private List<OcResourceInfo> resourceList;
- private Context ctx;
-
- public ExpandableResourceListAdapter(List<OcResourceInfo> resourceList, Context ctx) {
- this.resourceList = resourceList;
- this.ctx = ctx;
- }
-
- @Override
- public Object getChild(int groupPosition, int childPosition) {
- return resourceList.get(groupPosition).getAttributes().get(childPosition);
- }
-
- @Override
- public int getChildrenCount(int groupPosition) {
- return resourceList.get(groupPosition).getAttributes().size();
- }
-
- @Override
- public long getChildId(int groupPosition, int childPosition) {
- return resourceList.get(groupPosition).getAttributes().get(childPosition).hashCode();
- }
-
- @Override
- public int getChildType(int groupPosition, int childPosition) {
- return this.resourceList.get(groupPosition).getAttributes().get(childPosition)
- .getType().ordinal();
- }
-
- @Override
- public int getChildTypeCount() {
- return OC_ATTRIBUTE_TYPE.values().length;
- }
-
- @Override
- public View getChildView(final int groupPosition, int childPosition,
- boolean isLastChild, View convertView, ViewGroup parent) {
- View v = convertView;
- if (v == null) {
- LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
- (Context.LAYOUT_INFLATER_SERVICE);
- switch(OC_ATTRIBUTE_TYPE.fromInt(getChildType(groupPosition, childPosition))) {
- case AMBIENT_LIGHT_SENSOR_READING:
- case ROOM_TEMPERATURE_SENSOR_READING:
- v = inflater.inflate(R.layout.attribute_layout_progress_bar, parent, false);
- break;
- case LIGHT_DIMMER:
- v = inflater.inflate(R.layout.attribute_layout_slider, parent, false);
- break;
- case LIGHT_SWITCH:
- case PLATFORM_LED_SWITCH:
- v = inflater.inflate(R.layout.attribute_layout_on_off_switch, parent, false);
- break;
- }
- }
-
- OcAttributeInfo attribute =
- resourceList.get(groupPosition).getAttributes().get(childPosition);
-
- // All attribute icons and names are currently treated the same so we handle them outside
- // the type-specific inflater functions
- ImageView attributeIcon = (ImageView) v.findViewById(R.id.attribute_icon_id);
- attributeIcon.setVisibility(View.VISIBLE);
- TextView attributeName = (TextView) v.findViewById(R.id.attribute_name_id);
- attributeName.setText(getAttributeLabelFromType(attribute.getType()));
- attributeName.setVisibility(View.VISIBLE);
-
- // Now inflate the rest of the layout in a type-specific way
- switch(attribute.getType()){
- case AMBIENT_LIGHT_SENSOR_READING:
- this.renderAmbientLightSensorReading(v, groupPosition, attribute);
- break;
- case LIGHT_DIMMER:
- this.renderLightDimmer(v, groupPosition, attribute);
- break;
- case LIGHT_SWITCH:
- this.renderLightSwitch(v, groupPosition, attribute);
- break;
- case PLATFORM_LED_SWITCH:
- this.renderPlatformLedSwitch(v, groupPosition, attribute);
- break;
- case ROOM_TEMPERATURE_SENSOR_READING:
- this.renderRoomTemperatureSensorReading(v, groupPosition, attribute);
- break;
- }
-
- return v;
- }
-
- @Override
- public Object getGroup(int groupPosition) {
- return resourceList.get(groupPosition);
- }
-
- @Override
- public int getGroupCount() {
- return resourceList.size();
- }
-
- @Override
- public long getGroupId(int groupPosition) {
- return resourceList.get(groupPosition).hashCode();
- }
-
- @Override
- public View getGroupView(int groupPosition, boolean isExpanded,
- View convertView, ViewGroup parent) {
-
- View v = convertView;
-
- if (v == null) {
- LayoutInflater inflater = (LayoutInflater)ctx.getSystemService
- (Context.LAYOUT_INFLATER_SERVICE);
- v = inflater.inflate(R.layout.resource_list_item_layout, parent, false);
- }
-
- TextView resourceName = (TextView) v.findViewById(R.id.resource_name_id);
- TextView resourceDescription = (TextView) v.findViewById(R.id.resource_description_id);
- ImageView resourceIcon = (ImageView) v.findViewById(R.id.resource_icon_id);
-
- OcResourceInfo resource = resourceList.get(groupPosition);
-
- resourceName.setText(this.getResourceLabelFromType(resource.getType()));
- resourceDescription.setText(resource.getHost()+resource.getUri());
- switch (resource.getType()) {
- case AMBIENT_LIGHT_SENSOR:
- resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
- break;
- case LIGHT:
- resourceIcon.setImageResource(R.drawable.light_icon);
- break;
- case PLATFORM_LED:
- resourceIcon.setImageResource(R.drawable.led_icon);
- break;
- case ROOM_TEMPERATURE_SENSOR:
- resourceIcon.setImageResource(R.drawable.thermometer_icon);
- break;
- default:
- resourceIcon.setImageResource(R.drawable.iotivity_hex_icon);
- break;
- }
-
- return v;
- }
-
- @Override
- public boolean hasStableIds() {
- return true;
- }
-
- @Override
- public boolean isChildSelectable(int groupPosition, int childPosition) {
- return true;
- }
-
- /**
- * Type-specific layout render for Ambient Light Sensor reading attribute.
- */
- private void renderAmbientLightSensorReading(final View view,
- final int groupPosition,
- final OcAttributeInfo attribute) {
- // Render attributeValue
- TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
- attributeValue.setText(String.valueOf(attribute.getValueInt()));
- attributeValue.setVisibility(View.VISIBLE);
-
- // Render progressBar
- ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.attribute_progress_bar);
- progressBar.setMax(100); // display as percent from 0-100
- progressBar.setProgress(attribute.getValueAsPercentOfMax());
- progressBar.setVisibility(View.VISIBLE);
- }
-
- /**
- * Type-specific layout render for Light Dimmer attribute.
- */
- private void renderLightDimmer(final View view,
- final int groupPosition,
- final OcAttributeInfo attribute) {
- // Render attributeValue
- TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
- attributeValue.setText(String.valueOf(attribute.getValueInt()));
- attributeValue.setVisibility(View.VISIBLE);
-
- // Render SeekBar
- SeekBar slider = (SeekBar) view.findViewById(R.id.attribute_slider);
- slider.setMax(attribute.getValueMax());
- slider.setProgress(attribute.getValueInt());
- slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
- private int mSliderVal;
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("onProgressChanged(%s)", progress));
- this.mSliderVal = progress;
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {}
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- if (LOCAL_LOGV) Log.v(TAG, "onStopTrackingTouch()");
- if(ctx instanceof MainActivity) {
- // call MainActivity
- ((MainActivity) ctx).setLightDimmerLevel(resourceList.get(groupPosition),
- this.mSliderVal);
- }
- }
- });
- slider.setVisibility(View.VISIBLE);
- }
-
- /**
- * Type-specific layout render for Light Switch attribute.
- */
- private void renderLightSwitch(final View view,
- final int groupPosition,
- final OcAttributeInfo attribute) {
- // Render attributeValue
- TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
- if(false == attribute.getValueBool()) {
- attributeValue.setText("off");
- } else {
- attributeValue.setText("on");
- }
- attributeValue.setVisibility(View.VISIBLE);
-
- // Render Switch
- Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
- toggleSwitch.setText(this.ctx.getString(R.string.oc_light_switch_toggle_text));
- toggleSwitch.setChecked(attribute.getValueBool());
- toggleSwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
- if(ctx instanceof MainActivity) {
- // call MainActivity
- ((MainActivity) ctx).toggleLightSwitch(resourceList.get(groupPosition),
- isChecked);
- }
- }
- });
- toggleSwitch.setVisibility(View.VISIBLE);
- }
-
- /**
- * Type-specific layout render for LED Switch attribute.
- */
- private void renderPlatformLedSwitch(final View view,
- final int groupPosition,
- final OcAttributeInfo attribute) {
- // Render attributeValue
- TextView attributeValue = (TextView) view.findViewById(R.id.attribute_value_id);
- if(1 == attribute.getValueInt()) {
- attributeValue.setText("on");
- } else {
- attributeValue.setText("off");
- }
- attributeValue.setVisibility(View.VISIBLE);
-
- // Render Switch
- Switch toggleSwitch = (Switch) view.findViewById(R.id.attribute_switch);
- toggleSwitch.setText(this.ctx.getString(R.string.oc_led_switch_toggle_text));
- toggleSwitch.setChecked(1 == attribute.getValueInt());
- toggleSwitch.setOnCheckedChangeListener( new Switch.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("onCheckedChanged(%s)", isChecked));
- if(ctx instanceof MainActivity) {
- // call MainActivity
- ((MainActivity) ctx).toggleLedSwitch(resourceList.get(groupPosition),
- isChecked);
- }
- }
- });
- toggleSwitch.setVisibility(View.VISIBLE);
- }
-
- /**
- * Type-specific layout render for Room Temperature Sensor Reading attribute.
- */
- private void renderRoomTemperatureSensorReading(final View view,
- final int groupPosition,
- final OcAttributeInfo attribute) {
- // this happens to have the same behavior as ambient light sensor, so just re-use
- this.renderAmbientLightSensorReading(view, groupPosition, attribute);
- }
-
- private String getAttributeLabelFromType(OC_ATTRIBUTE_TYPE type) {
- switch (type) {
- case AMBIENT_LIGHT_SENSOR_READING:
- return ctx.getString(R.string.ui_attribute_label_ambient_light_sensor_reading);
- case LIGHT_DIMMER:
- return ctx.getString(R.string.ui_attribute_label_light_dimmer);
- case LIGHT_SWITCH:
- return ctx.getString(R.string.ui_attribute_label_light_switch);
- case PLATFORM_LED_SWITCH:
- return ctx.getString(R.string.ui_attribute_label_led_switch);
- case ROOM_TEMPERATURE_SENSOR_READING:
- return ctx.getString(R.string.ui_attribute_label_room_temperature_sensor_reading);
- default:
- Log.w(TAG, "getAttributeLabelFromType(): unrecognized attribute type.");
- return "Attribute:";
- }
- }
-
- private String getResourceLabelFromType(OcResourceInfo.OC_RESOURCE_TYPE type) {
- if (LOCAL_LOGV) Log.v(TAG, "getResourceLabelFromType()");
-
- switch(type) {
- case AMBIENT_LIGHT_SENSOR:
- return ctx.getString(R.string.ui_resource_label_ambient_light_sensor);
- case LIGHT:
- return ctx.getString(R.string.ui_resource_label_light);
- case PLATFORM_LED:
- return ctx.getString(R.string.ui_resource_label_platform_led);
- case ROOM_TEMPERATURE_SENSOR:
- return ctx.getString(R.string.ui_resource_label_room_temperature_sensor);
- default:
- Log.w(TAG, "getResourceLabelFromType(): unrecognized resource type.");
- return "Resource:";
- }
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.app.AlertDialog;
-import android.content.DialogInterface;
-import android.support.v7.app.ActionBarActivity;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.widget.ExpandableListView;
-import android.widget.ProgressBar;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH;
-import static org.iotivity.guiclient.R.id.expandableResourceListView;
-
-/**
- * MainActivity instantiates a ExpandableListView of type ExpandableResourceListView, and
- * also creates and starts a OcWorker object to handle the IoTivity specific work.
- *
- * @see org.iotivity.guiclient.OcWorker
- * @see org.iotivity.guiclient.OcWorkerListener
- * @see org.iotivity.guiclient.ExpandableResourceListAdapter
- */
-public class MainActivity
- extends ActionBarActivity
- implements OcWorkerListener, View.OnClickListener, ExpandableListView.OnChildClickListener {
- /**
- * Hardcoded TAG... if project never uses proguard then
- * MyOcClient.class.getName() is the better way.
- */
- private static final String TAG = "MainActivity";
-
- private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
-
- /**
- * The data structure behind the displayed List of resources and attributes.
- */
- private List<OcResourceInfo> mResourceList;
-
- /**
- * The custom adapter for displaying the ResourceListItem List
- */
- private ExpandableResourceListAdapter mResourceListAdapter;
-
- /**
- * The OIC-aware worker class which does all the OIC API interaction
- * and handles the results, notifying MainActivity whenever an event
- * requires a UI update.
- */
- private OcWorker mOcWorker;
-
- /**
- * Preserve a ref to Action Bar Menu for changing progress icon
- */
- private Menu optionsMenu;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- if (LOCAL_LOGV) Log.v(TAG, "onCreate()");
-
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.activity_main);
-
- // start the OcWorker thread and register as a listener
- if(null == this.mOcWorker) {
- this.mOcWorker = new OcWorker(this);
- this.mOcWorker.start(); // configures the OIC platform and wait for further calls
- this.mOcWorker.registerListener(this);
- }
-
- // init the Resource display list
- if(null == this.mResourceList) {
- this.mResourceList = new ArrayList<>();
- }
-
- // init the ListView Adapter
- if(null == this.mResourceListAdapter) {
- this.mResourceListAdapter = new ExpandableResourceListAdapter(this.mResourceList,
- this);
- }
-
- // init the Expandable List View
- ExpandableListView exListView =
- (ExpandableListView) findViewById(expandableResourceListView);
- exListView.setIndicatorBounds(5, 5);
- exListView.setIndicatorBounds(0, 20);
- exListView.setAdapter(this.mResourceListAdapter);
- exListView.setOnChildClickListener(this);
- }
-
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- if (LOCAL_LOGV) Log.v(TAG, "onRestoreInstanceState()");
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- if (LOCAL_LOGV) Log.v(TAG, "onSaveInstanceState()");
- }
-
- @Override
- public void onClick(View v) {
- if (LOCAL_LOGV) Log.v(TAG, "onClick()");
-
- this.setRefreshActionButtonState(false);
- }
-
- @Override
- public boolean onChildClick(ExpandableListView parent,
- View v,
- int groupPosition,
- int childPosition,
- long id) {
- if (LOCAL_LOGV) Log.v(TAG, "onChildClick()");
-
- this.mOcWorker.doGetResource(mResourceList.get(groupPosition));
-
- return false;
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- if (LOCAL_LOGV) Log.v(TAG, "onCreateOptionsMenu()");
-
- // save a reference for use in controlling refresh icon later
- this.optionsMenu = menu;
-
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
-
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("onOptionsItemSelected(%s)", item.toString()));
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
-
- // Handle the "settings" icon/text click
- if (id == R.id.action_settings) {
- return true;
- }
-
- // Handle the "developer test" icon/text click
- if (id == R.id.action_test) {
- return true;
- }
-
- // Handle the trash can "discard" icon click
- if (id == R.id.action_discard) {
- AlertDialog diaBox = confirmDiscard();
- diaBox.show();
- }
-
- // Handle the refresh/progress icon click
- if (id == R.id.action_refresh) {
- // show the indeterminate progress bar
- this.setRefreshActionButtonState(true);
- // use OcWorker to discover resources
- this.mOcWorker.doDiscoverResources();
- }
-
- return super.onOptionsItemSelected(item);
- }
-
- /**
- * Handle a resource changed callback from OcWorker by posting a runnable to our
- * own UI-safe looper/handler
- */
- @Override
- public void onResourceChanged(final OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "onResourceChanged()");
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // in case we were waiting for a refresh, hide the indeterminate progress bar
- setRefreshActionButtonState(false);
-
- mResourceListAdapter.notifyDataSetChanged();
- }
- });
- }
-
- /**
- * Handle a new resource found callback from OcWorker by posting a runnable to our
- * own UI-safe looper/handler
- */
- @Override
- public void onResourceFound(final OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
-
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // in case we were waiting for a refresh, hide the indeterminate progress bar
- setRefreshActionButtonState(false);
-
- // if resource not already in list, add it
- if(!mResourceList.contains(resourceInfo)) {
- mResourceList.add(resourceInfo);
- }
-
- mResourceListAdapter.notifyDataSetChanged();
- }
- });
- }
-
- public void toggleLedSwitch(OcResourceInfo resourceInfo, boolean onOff) {
- if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLedSwitch(%s, %s)",
- resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
-
- // send a msg to OcWorker to put the switch value
- for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
- if(ai.getType() == PLATFORM_LED_SWITCH) {
- if(onOff) {
- ai.setValueInt(1);
- } else {
- ai.setValueInt(0);
- }
- }
- }
- this.mOcWorker.doPutResource(resourceInfo);
- }
-
- public void toggleLightSwitch(OcResourceInfo resourceInfo, boolean onOff) {
- if (LOCAL_LOGV) Log.d(TAG, String.format("toggleLightSwitch(%s, %s)",
- resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(onOff)));
-
- // send a msg to OcWorker to put the switch value
- for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
- if(ai.getType() == LIGHT_SWITCH) {
- ai.setValueBool(onOff);
- }
- }
- this.mOcWorker.doPutResource(resourceInfo);
- }
-
- public void setLightDimmerLevel(OcResourceInfo resourceInfo, int value) {
- if (LOCAL_LOGV) Log.d(TAG, String.format("setLightDimmerLevel(%s, %s)",
- resourceInfo.getHost() + resourceInfo.getUri(), String.valueOf(value)));
-
- // send a msg to OcWorker to put the switch value
- for(OcAttributeInfo ai : resourceInfo.getAttributes()) {
- if(ai.getType() == LIGHT_DIMMER) {
- ai.setValueInt(value);
- }
- }
- this.mOcWorker.doPutResource(resourceInfo);
- }
-
- /**
- * Sets the Action Bar icon to "progress" (spinning circle), or returns it to refresh icon
- *
- * @param refreshing true sets icon to animated "progress" spinner; false to static
- * refresh icon
- */
- private void setRefreshActionButtonState(final boolean refreshing) {
- if (this.optionsMenu != null) {
- final MenuItem refreshItem
- = this.optionsMenu
- .findItem(R.id.action_refresh);
- if (refreshItem != null) {
- if (refreshing) {
- refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
- ProgressBar progressBar =
- (ProgressBar) findViewById(R.id.find_resource_progress_bar);
- progressBar.setOnClickListener(this);
-
- } else {
- refreshItem.setActionView(null);
- }
- }
- }
- }
-
- private AlertDialog confirmDiscard()
- {
- if (LOCAL_LOGV) Log.v(TAG, "confirmDiscard()");
-
- return new AlertDialog.Builder(this)
- .setTitle("Clear Resource List?")
- .setIcon(R.drawable.ic_action_discard_dark)
- .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- // clear OcWorker's list
- mOcWorker.doClearResources();
- // in case its running, hide the indeterminate progress bar
- setRefreshActionButtonState(false);
- // clear our local data model list
- mResourceList.clear();
- mResourceListAdapter.notifyDataSetChanged();
- dialog.dismiss();
- }
- })
-
- .setNegativeButton("No", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- })
-
- .create();
- }
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.util.Log;
-
-import java.io.Serializable;
-
-/**
- * Created by nathanhs on 12/28/15.
- */
-public class OcAttributeInfo implements Serializable {
- /**
- * Hardcoded TAG... if project never uses proguard then
- * MyOcClient.class.getName() is the better way.
- */
- private static final String TAG = "OcAttributeInfo";
-
- private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
-
- private static final int AMBIENT_LIGHT_SENSOR_READING_MAX = 4096;
- private static final int LIGHT_DIMMER_MAX = 100;
- private static final int LIGHT_SWITCH_MAX = 1;
- private static final int PLATFORM_LED_SWITCH_MAX = 1;
- // TODO: once the temp getValueInt works, figure out how to scale this properly
- private static final int ROOM_TEMPERATURE_SENSOR_READING_MAX = 4096;
-
- /**
- * These are the resource types supported by OcResourceInfo.
- */
- public enum OC_ATTRIBUTE_TYPE {
- AMBIENT_LIGHT_SENSOR_READING,
- LIGHT_DIMMER,
- LIGHT_SWITCH,
- PLATFORM_LED_SWITCH,
- ROOM_TEMPERATURE_SENSOR_READING;
-
- private static final OC_ATTRIBUTE_TYPE[] values = OC_ATTRIBUTE_TYPE.values();
-
- public static OC_ATTRIBUTE_TYPE fromInt(int i) {
- return values[i];
- }
- }
-
- private boolean mCurrentlyObserved;
- private final int mId;
- private static int mIdInitializer = 0;
- private final boolean mObservable = true; //TODO BROKEN fix when implementing observe
- private final OcResourceInfo mParentResource;
- private final boolean mReadOnly;
- private final OC_ATTRIBUTE_TYPE mType;
- private boolean mValueBool; // used if attribute has a boolean value
- private int mValueInt; // used if attribute has an int value
- private String mValueString; // used if attribute has a String value
- private final int mValueMax;
-
- public OcAttributeInfo(OC_ATTRIBUTE_TYPE type, OcResourceInfo parent) {
- if (LOCAL_LOGV) Log.v(TAG, "OcAttributeInfo() constructor");
-
- this.mId = OcAttributeInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
- this.mParentResource = parent;
- this.mReadOnly = this.getReadOnlyBasedOnType(type);
- this.mType = type;
- this.mValueBool = false;
- this.mValueInt = 0;
- this.mValueString = "error";
- this.mValueMax = this.getMaxAttributeValueBasedOnType(type);
- }
-
- public int getId() {
- return mId;
- }
-
- public OC_ATTRIBUTE_TYPE getType() {
- return mType;
- }
-
- public boolean getValueBool() {
- return this.mValueBool;
- }
-
- public int getValueInt() {
- return this.mValueInt;
- }
-
- public int getValueMax() {
- return mValueMax;
- }
-
- public String getValueString() {
- return this.mValueString;
- }
-
- public int getValueAsPercentOfMax() {
- return (this.mValueInt*100)/this.mValueMax;
- }
-
- public boolean isCurrentlyObserved() {
- return this.mCurrentlyObserved;
- }
-
- public boolean isObservable() {
- return this.mObservable;
- }
-
- public boolean isReadOnly() {
- return mReadOnly;
- }
-
- public void setCurrentlyObserved(boolean currentlyObserved) {
- this.mCurrentlyObserved = currentlyObserved;
- }
-
- public void setValueBool(boolean value) {
- this.mValueBool = value;
- }
-
- public void setValueInt(int value) {
- this.mValueInt = value;
- }
-
- public void setValueString(String value) {
- this.mValueString = value;
- }
-
- private int getMaxAttributeValueBasedOnType(OC_ATTRIBUTE_TYPE type) {
- switch(type) {
- case AMBIENT_LIGHT_SENSOR_READING:
- return AMBIENT_LIGHT_SENSOR_READING_MAX;
- case LIGHT_DIMMER:
- return LIGHT_DIMMER_MAX;
- case LIGHT_SWITCH:
- return LIGHT_SWITCH_MAX;
- case PLATFORM_LED_SWITCH:
- return PLATFORM_LED_SWITCH_MAX;
- case ROOM_TEMPERATURE_SENSOR_READING:
- return ROOM_TEMPERATURE_SENSOR_READING_MAX;
- default:
- Log.w(TAG, "getMaxAttributeValueBasedOnType(): unrecognized attribute type.");
- return 0;
- }
- }
-
- private boolean getReadOnlyBasedOnType(OC_ATTRIBUTE_TYPE type) {
- switch(type) {
- case AMBIENT_LIGHT_SENSOR_READING:
- case ROOM_TEMPERATURE_SENSOR_READING:
- return true;
- case LIGHT_DIMMER:
- case LIGHT_SWITCH:
- case PLATFORM_LED_SWITCH:
- return false;
- default:
- Log.w(TAG, "getReadOnlyBasedOnType(): unrecognized attribute type.");
- return false;
- }
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-/**
- * OcProtocolStrings contains the IoTivity-specific constant values. To add another supported
- * Resource or Interface type to this app, begin by adding the new strings here, and then
- * find the places throughout the app where Resource-specific case switches occur, and add
- * the newly-supported type there.
- */
-public interface OcProtocolStrings {
- // OIC core protocol strings
- public static final String COAP_CORE = "coap://224.0.1.187/oic/res";
- public static final String RESOURCE_TYPE_QUERY = "?rt=";
- public static final String INTERFACE_QUERY = "?if=";
- // find resource queries
- public static final String CORE_LIGHT = "core.light";
- public static final String CORE_EDISON_RESOURCES = "core.edison.resources";
- // resource URIs
- public static final String LIGHT_RESOURCE_URI = "/a/light";
- public static final String LIGHT_RESOURCE_URI2 = "/light0";
- public static final String LIGHT_RESOURCE_URI3 = "/a/light1";
- public static final String ROOM_TEMPERATURE_RESOURCE_URI = "/temperature";
- public static final String AMBIENT_LIGHT_RESOURCE_URI = "/ambientlight";
- public static final String PLATFORM_LED_RESOURCE_URI = "/led";
- // attribute keys for set() calls
- public static final String LIGHT_SWITCH_RESOURCE_KEY = "state";
- public static final String LIGHT_DIMMER_RESOURCE_KEY = "power";
- public static final String ROOM_TEMPERATURE_RESOURCE_KEY = "temperature";
- public static final String AMBIENT_LIGHT_RESOURCE_KEY = "ambientlight";
- public static final String PLATFORM_LED_RESOURCE_KEY = "switch";
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.util.Log;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.AMBIENT_LIGHT_SENSOR_READING;
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER;
-import static org.iotivity.guiclient.OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH;
-import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_KEY;
-import static org.iotivity.guiclient.OcProtocolStrings.AMBIENT_LIGHT_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_DIMMER_RESOURCE_KEY;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI2;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_RESOURCE_URI3;
-import static org.iotivity.guiclient.OcProtocolStrings.LIGHT_SWITCH_RESOURCE_KEY;
-import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_KEY;
-import static org.iotivity.guiclient.OcProtocolStrings.PLATFORM_LED_RESOURCE_URI;
-import static org.iotivity.guiclient.OcProtocolStrings.ROOM_TEMPERATURE_RESOURCE_URI;
-
-/**
- * OcResourceInfo is a wrapper object for the OcResource object. It implements the Resource-
- * specific callbacks, and abstracts the IoTivity implementation details from the application.
- *
- * In order to use OcResourceInfo, an application should implement the OcResourceInfoListener
- * interface, which is called when the OcResourceInfo changes in any meaningful way.
- */
-public class OcResourceInfo
- implements OcResource.OnGetListener, OcResource.OnPutListener, Serializable {
- /**
- * Hardcoded TAG... if project never uses proguard then
- * MyOcClient.class.getName() is the better way.
- */
- private static final String TAG = "OcResourceInfo";
-
- private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
-
- /**
- * These are the resource types supported by OcResourceInfo. They should have corresponding
- * URI strings in the OcProtocolStrings interface.
- */
- public enum OC_RESOURCE_TYPE {
- AMBIENT_LIGHT_SENSOR,
- LIGHT,
- PLATFORM_LED,
- ROOM_TEMPERATURE_SENSOR;
-
- private static final OC_RESOURCE_TYPE[] values = OC_RESOURCE_TYPE.values();
-
- public static OC_RESOURCE_TYPE fromInt(int i) {
- return values[i];
- }
- }
-
- private List<OcAttributeInfo> mAttributes;
- private final String mHost;
- private final int mId;
- private static int mIdInitializer = 0;
- private List<OcResourceInfoListener> mListeners;
- private final OcResource mResource;
- private final OC_RESOURCE_TYPE mType;
- private final String mUri;
-
- public interface OcResourceInfoListener {
- public void onResourceInfoChanged(OcResourceInfo resourceInfo);
- }
-
-
- public OcResourceInfo(OcResource resource, OcResourceInfoListener changeListener) {
- if (LOCAL_LOGV) Log.v(TAG, "OcResourceInfo() constructor");
-
- this.mAttributes = new ArrayList<>();
- this.mHost = resource.getHost();
- this.mId = OcResourceInfo.mIdInitializer++; // give a unique Id from other OcResourceInfos
- this.mListeners = new ArrayList<>();
- this.mListeners.add(changeListener);
- this.mResource = resource;
- this.mType = this.getResourceTypeFromUri(resource.getUri());
- this.mUri = resource.getUri();
-
- }
-
- public void registerListener(OcResourceInfoListener changeListener) {
- if(null == this.mListeners) {
- Log.e(TAG, "registerListener(): null mListeners List");
- } else {
- boolean alreadyRegistered = false;
- for(OcResourceInfoListener rl : this.mListeners) {
- if(changeListener == rl) {
- alreadyRegistered = true;
- }
- }
- if(!alreadyRegistered) {
- this.mListeners.add(changeListener);
- }
- }
- }
-
- public OC_RESOURCE_TYPE getType() {
- return this.mType;
- }
-
- public String getHost() {
- return this.mHost;
- }
-
- public String getUri() {
- return this.mUri;
- }
-
- @Override
- public void onGetFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
-
- @Override
- public void onPutFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
-
- public List<OcAttributeInfo> getAttributes() {
- return this.mAttributes;
- }
-
- public void doOcGet() {
- if(null != this.mResource) {
- try {
- this.mResource.get(new HashMap<String, String>(), this);
- } catch (OcException e) {
- e.printStackTrace();
- Log.e(TAG, e.getMessage());
- }
- } else {
- Log.e(TAG, "doOcGet(): null mResource");
- }
- }
-
- public void doOcPut(OcAttributeInfo attribute) {
- if (LOCAL_LOGV) Log.v(TAG, "doOcPut()");
-
- if(attribute.isReadOnly()) {
- Log.w(TAG, String.format("doOcPut(): %s attribute is read only; skipping put!",
- attribute.getType()));
- } else {
- if (null != this.mResource) {
- try {
- OcRepresentation representation = new OcRepresentation();
- switch (attribute.getType()) {
- case AMBIENT_LIGHT_SENSOR_READING:
- break;
- case LIGHT_DIMMER:
- representation.setValueInt(LIGHT_DIMMER_RESOURCE_KEY,
- attribute.getValueInt());
- // This 'sw' logic is here because the current IoTivity Light forces
- // the switch to "false" if the switch val is not specified.
- boolean sw = true;
- for(OcAttributeInfo ai : this.mAttributes) {
- if(ai.getType() == LIGHT_SWITCH) {
- sw = ai.getValueBool();
- }
- }
- representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY, sw);
- break;
- case LIGHT_SWITCH:
- representation.setValueBool(LIGHT_SWITCH_RESOURCE_KEY,
- attribute.getValueBool());
- break;
- case PLATFORM_LED_SWITCH:
- representation.setValueInt(PLATFORM_LED_RESOURCE_KEY,
- attribute.getValueInt());
- break;
- case ROOM_TEMPERATURE_SENSOR_READING:
- break;
- default:
- break;
- }
- this.mResource.put(representation, new HashMap<String, String>(), this);
- } catch (OcException e) {
- e.printStackTrace();
- Log.e(TAG, e.getMessage());
- }
- } else {
- Log.e(TAG, "doOcGet(): null mResource");
- }
- }
- }
-
- private static Object onGetCompletedLock = new Object();
- @Override
-// public void onGetCompleted(HeaderOptions headerOptions, OcRepresentation ocRepresentation) {
- public void onGetCompleted(List<OcHeaderOption> headerOptionList,
- OcRepresentation ocRepresentation) {
- synchronized (onGetCompletedLock) {
- if (LOCAL_LOGV) Log.v(TAG, "enter -> onGetCompleted()");
- if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
- if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
-
- this.mAttributes.clear();
- switch(this.mType) {
- case AMBIENT_LIGHT_SENSOR:
- int ambientLightVal = ocRepresentation.getValueInt(AMBIENT_LIGHT_RESOURCE_KEY);
- if (LOCAL_LOGV) Log.v(TAG,
- String.format("%s int value of %s attribute = %d",
- mType, AMBIENT_LIGHT_RESOURCE_KEY, ambientLightVal));
- OcAttributeInfo ambientAttribute = new OcAttributeInfo(
- AMBIENT_LIGHT_SENSOR_READING, this);
- ambientAttribute.setValueInt(ambientLightVal);
- this.mAttributes.add(ambientAttribute);
- break;
- case LIGHT:
- // do switch first
- boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
- OcAttributeInfo lightSwitchAttribute = new OcAttributeInfo(
- LIGHT_SWITCH, this);
- lightSwitchAttribute.setValueBool(lightSwitchVal);
- this.mAttributes.add(lightSwitchAttribute);
- // then dimmer
- int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
- OcAttributeInfo dimmerAttribute = new OcAttributeInfo(
- LIGHT_DIMMER, this);
- dimmerAttribute.setValueInt(dimmerVal);
- this.mAttributes.add(dimmerAttribute);
- break;
- case PLATFORM_LED:
- int ledVal = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
- if (LOCAL_LOGV) Log.v(TAG,
- String.format("%s int value of %s attribute = %d",
- mType, PLATFORM_LED_RESOURCE_KEY, ledVal));
- OcAttributeInfo ledAttribute = new OcAttributeInfo(
- OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH, this);
- ledAttribute.setValueInt(ledVal);
- this.mAttributes.add(ledAttribute);
- break;
- case ROOM_TEMPERATURE_SENSOR:
- int temperatureVal = 98;
- Log.w(TAG, "getting 'temperature' value is causing crash;" +
- " skipping and using 98.");
- // TODO This call crashes in the native JNI code. The example .cpp
- // app receives a double for the Room Temp key, but the Java API
- // doesn't support getValueDouble yet.
- // Debug crash when API fixed?
-// temperatureVal = ocRepresentation.getValueInt(ROOM_TEMPERATURE_RESOURCE_KEY);
- if (LOCAL_LOGV) Log.v(TAG,
- String.format("%s int value of 'temperature' attribute = %d",
- mType, temperatureVal));
- OcAttributeInfo temperatureAttribute = new OcAttributeInfo(
- OcAttributeInfo.OC_ATTRIBUTE_TYPE.ROOM_TEMPERATURE_SENSOR_READING,
- this);
- temperatureAttribute.setValueInt(temperatureVal);
- this.mAttributes.add(temperatureAttribute);
- break;
- }
- this.notifyListeners();
- if (LOCAL_LOGV) Log.v(TAG, "exit <- onGetCompleted()");
- }
- }
-
- /**
- * Should be called whenever any Resource or Attribute values change on this object.
- */
- private void notifyListeners() {
- if (LOCAL_LOGV) Log.v(TAG, "notifyListeners()");
-
- for(OcResourceInfoListener l : this.mListeners) {
- l.onResourceInfoChanged(this);
- }
- }
-
- private Object onPutCompletedLock = new Object();
- @Override
- public void onPutCompleted(List<OcHeaderOption> headerOptionList,
- OcRepresentation ocRepresentation) {
- synchronized (onPutCompletedLock) {
- if (LOCAL_LOGV) Log.v(TAG, "enter -> onPutCompleted()");
- if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis = %s", this.toString()));
- if (LOCAL_LOGV) Log.v(TAG, String.format("\tthis.mType = %s", this.mType));
-
- switch(this.mType) {
- case AMBIENT_LIGHT_SENSOR:
- Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
- this.mType));
- break;
- case LIGHT:
- // do switch first
- boolean lightSwitchVal = ocRepresentation.getValueBool(LIGHT_SWITCH_RESOURCE_KEY);
- for(OcAttributeInfo ai : this.mAttributes) {
- if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_SWITCH) {
- ai.setValueBool(lightSwitchVal);
- }
- }
- // then dimmer
- int dimmerVal = ocRepresentation.getValueInt(LIGHT_DIMMER_RESOURCE_KEY);
- for(OcAttributeInfo ai : this.mAttributes) {
- if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.LIGHT_DIMMER) {
- ai.setValueInt(dimmerVal);
- }
- }
- break;
- case PLATFORM_LED:
- int value = ocRepresentation.getValueInt(PLATFORM_LED_RESOURCE_KEY);
- for(OcAttributeInfo ai : this.mAttributes) {
- if (ai.getType() == OcAttributeInfo.OC_ATTRIBUTE_TYPE.PLATFORM_LED_SWITCH) {
- ai.setValueInt(value);
- }
- }
- break;
- case ROOM_TEMPERATURE_SENSOR:
- Log.w(TAG, String.format("onPutCompleted(): %s is a readonly attribute type.",
- this.mType));
- break;
- }
- this.notifyListeners();
- if (LOCAL_LOGV) Log.v(TAG, "exit <- onPutCompleted()");
- }
- }
-
- private OC_RESOURCE_TYPE getResourceTypeFromUri(String uri) {
- if (LOCAL_LOGV) Log.v(TAG, "getResourceTypeFromUri()");
-
- switch(uri) {
- case LIGHT_RESOURCE_URI:
- case LIGHT_RESOURCE_URI2:
- case LIGHT_RESOURCE_URI3:
- return OC_RESOURCE_TYPE.LIGHT;
- case AMBIENT_LIGHT_RESOURCE_URI:
- return OC_RESOURCE_TYPE.AMBIENT_LIGHT_SENSOR;
- case PLATFORM_LED_RESOURCE_URI:
- return OC_RESOURCE_TYPE.PLATFORM_LED;
- case ROOM_TEMPERATURE_RESOURCE_URI:
- return OC_RESOURCE_TYPE.ROOM_TEMPERATURE_SENSOR;
- default:
- Log.w(TAG, "getResourceTypeFromUri(): unsupported resource '" + uri + "'" );
- }
- return null;
- }
-}
+++ /dev/null
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.content.Context;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.util.Log;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-
-import static org.iotivity.guiclient.OcProtocolStrings.COAP_CORE;
-import static org.iotivity.guiclient.OcProtocolStrings.CORE_EDISON_RESOURCES;
-import static org.iotivity.guiclient.OcProtocolStrings.CORE_LIGHT;
-import static org.iotivity.guiclient.OcProtocolStrings.INTERFACE_QUERY;
-import static org.iotivity.guiclient.OcProtocolStrings.RESOURCE_TYPE_QUERY;
-import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_CLEAR_RESOURCES;
-import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_DISCOVER_RESOURCES;
-import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_GET_RESOURCE;
-import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.DO_PUT_RESOURCE;
-import static org.iotivity.guiclient.OcWorker.OCW_IN_MSG.fromInt;
-
-/**
- * OcWorker
- *
- * A class designed to encapsulate the OIC API functionality. OcWorker has its own
- * thread which is used to call all OIC APIs. To get results back from OcWorker,
- * implement the interface OcWorkerListener, and call registerListener().
- *
- * @see org.iotivity.guiclient.OcWorkerListener
- *
- * Created by nathanhs on 12/22/15.
- */
-public class OcWorker extends Thread
- implements OcPlatform.OnResourceFoundListener, OcResourceInfo.OcResourceInfoListener {
- /**
- * Hardcoded TAG... if project never uses proguard then
- * MyOcClient.class.getName() is the better way.
- */
- private static final String TAG = "OcWorker";
- private Context mContext;
-
- private static final boolean LOCAL_LOGV = true; // set to false to compile out verbose logging
-
- /**
- * NOTE: DO NOT assign non-default values to these enums!
- * The correctness of "fromInt()" depends on the enum values not being
- * overridden. For example DO_TEST = 100, RESULT_TEST = 101.. would BREAK the
- * fromInt() function. There are designs which can account for arbitrary enum
- * values, but they are less desirable for other reasons and since we do not
- * need to use any specific value, this design is the best for this case.
- */
-
- /**
- * These "IN" message types are for posting API-generated request actions
- * to our OcWorker queue.
- */
- public enum OCW_IN_MSG {
- DO_TEST, // developer testing only
- DO_DISCOVER_RESOURCES,
- DO_CLEAR_RESOURCES,
- DO_GET_RESOURCE,
- DO_PUT_RESOURCE,
- DO_OBSERVE_RESOURCE,
- DO_STOP_OBSERVING_RESOURCE;
-
- private static final OCW_IN_MSG[] values = values();
-
- public static OCW_IN_MSG fromInt(int i) {
- return values[i];
- }
- }
-
- /**
- * These events are for internally putting work on our thread's looper
- * queue, usually in a callback where we don't want to do work on the
- * callback thread.
- */
- private enum OC_EVENT {
- OIC_RESOURCE_FOUND,
- OIC_RESOURCE_CHANGED;
-
- private static final OC_EVENT[] values = OC_EVENT.values();
-
- public static OC_EVENT fromInt(int i) {
- return values[i];
- }
- }
-
- private Handler mDoMsgHandler;
-
- private Handler mOcEventHandler;
-
- /**
- * The OcResourceInfo List
- */
- private ArrayList<OcResourceInfo> mOcResourceInfoList;
-
- /**
- * The types of OIC Resources included in "FindResource" calls by this object.
- */
- private final String[] mOcFindQueries = {
- COAP_CORE + RESOURCE_TYPE_QUERY + CORE_LIGHT,
- COAP_CORE + INTERFACE_QUERY + CORE_EDISON_RESOURCES
- };
-
- private List<OcWorkerListener> mListeners;
-
- public OcWorker(Context context) {
- if (LOCAL_LOGV) Log.v(TAG, "OcWorker() constructor");
-
- mContext = context;
- this.mListeners = new ArrayList<>();
- }
-
- /**
- * Set up our Handler and Looper, then initialize the OIC platform and
- * start processing messages as they arrive.
- */
- public void run() {
- if (LOCAL_LOGV) Log.v(TAG, "run()");
-
- Looper.prepare();
- this.initHandlers(); // set up our message handler
- this.ocInit(); // init the OIC layer including calling ConfigurePlatform
- Looper.loop();
- }
-
- /**
- * Registers a listener for OcWorker events.
- *
- * @see org.iotivity.guiclient.OcWorkerListener
- */
- public void registerListener(OcWorkerListener listener) {
- if (LOCAL_LOGV) Log.v(TAG, "registerListener()");
-
- if(null != this.mListeners) {
- this.mListeners.add(listener);
- } else {
- Log.e(TAG, "registerListener(): null mListeners list; not adding listener!");
- Log.e(TAG, "OcWorker.run() must be called before using public methods.");
- }
- }
-
- /**
- * The Resource discovery external API
- */
- public void doDiscoverResources() {
- if (LOCAL_LOGV) Log.v(TAG, "doDiscoverResources()");
-
- if(null != this.mDoMsgHandler) {
- this.mDoMsgHandler.obtainMessage(
- DO_DISCOVER_RESOURCES.ordinal()).sendToTarget();
- } else {
- Log.e(TAG, "doDiscoverResources(): null mDoMsgHandler; not discovering resources!");
- Log.e(TAG, "OcWorker.run() must be called before using public methods.");
- }
- }
-
- /**
- * The GetResource external API
- */
- public void doGetResource(OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "doGetResource()");
-
- if(null != this.mDoMsgHandler) {
- this.mDoMsgHandler.obtainMessage(
- DO_GET_RESOURCE.ordinal(), resourceInfo).sendToTarget();
- } else {
- Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
- Log.e(TAG, "OcWorker.run() must be called before using public methods.");
- }
- }
-
- /**
- * The PutResource external API
- */
- public void doPutResource(OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "doPutResource()");
-
- if(null != this.mDoMsgHandler) {
- this.mDoMsgHandler.obtainMessage(
- DO_PUT_RESOURCE.ordinal(), resourceInfo).sendToTarget();
- } else {
- Log.e(TAG, "doPutResource(): null mDoMsgHandler; not putting resource!");
- Log.e(TAG, "OcWorker.run() must be called before using public methods.");
- }
- }
-
- /**
- * The Clear Resources external API
- */
- public void doClearResources() {
- if (LOCAL_LOGV) Log.v(TAG, "doClearResources()");
-
- if(null != this.mDoMsgHandler) {
- this.mDoMsgHandler.obtainMessage(
- DO_CLEAR_RESOURCES.ordinal()).sendToTarget();
- } else {
- Log.e(TAG, "doClearResources(): null mDoMsgHandler; not clearing resources!");
- Log.e(TAG, "OcWorker.run() must be called before using public methods.");
- }
- }
-
- /**
- * Set up handlers
- */
- private void initHandlers() {
- if (LOCAL_LOGV) Log.v(TAG, "initHandler()");
-
- this.mDoMsgHandler = new Handler() {
- public void handleMessage(Message msg) {
- Log.d(TAG, String.format("mDoMsgHandler.handleMessage(%s)", msg.toString()));
- // process incoming messages here
- OCW_IN_MSG type = fromInt(msg.what);
- switch(type) {
- case DO_TEST:
- break;
- case DO_DISCOVER_RESOURCES:
- discoverResources();
- break;
- case DO_CLEAR_RESOURCES:
- clearResourceInfoList();
- break;
- case DO_GET_RESOURCE:
- getResourceAttributes((OcResourceInfo)msg.obj);
- break;
- case DO_PUT_RESOURCE:
- putResourceAttributes((OcResourceInfo)msg.obj);
- break;
- case DO_OBSERVE_RESOURCE:
- break;
- case DO_STOP_OBSERVING_RESOURCE:
- break;
- default:
- Log.e(TAG, "unknown msg.what in handler");
- break;
- }
- }
- };
-
- this.mOcEventHandler = new Handler() {
- public void handleMessage(Message msg) {
- Log.d(TAG, String.format("mOcEventHandler.handleMessage(%s)", msg.toString()));
- // process incoming messages here
- OC_EVENT type = OC_EVENT.fromInt(msg.what);
- switch(type) {
- case OIC_RESOURCE_FOUND:
- handleNewResourceFound((OcResource)msg.obj);
- break;
- case OIC_RESOURCE_CHANGED:
- handleResourceInfoChange((OcResourceInfo)msg.obj);
- break;
- }
- }
- };
- }
-
- /**
- * Get the attributes on resourceInfo.
- *
- * @param resourceInfo
- */
- private void getResourceAttributes(OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "getResourceAttributes()");
-
- // find the matching resource in our resourceList
- OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
- resourceInfo.getHost() + resourceInfo.getUri());
- if(null != existingResource) {
- existingResource.doOcGet();
- } else {
- Log.e(TAG, "getResourceAttributes(): could not find target resource.");
- }
- // Done. Later, the onGet listener in the OcResourceInfo object will notify us of a change
- // via our onResourceChanged() method
- }
-
- /**
- * For each attribute in the resourceInfo.mAttributes, put the attribute value to the
- * Resource.
- *
- * @param resourceInfo
- */
- private void putResourceAttributes(OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "putResourceAttributes()");
-
- // find the matching resource in our resourceList
- OcResourceInfo existingResource = this.selectResourceInfoByHostAndUri(
- resourceInfo.getHost() + resourceInfo.getUri());
- if(null != existingResource) {
- // for each attribute in resourceInfo, put that attribute to the resource
- for(OcAttributeInfo attribute : resourceInfo.getAttributes()) {
- if(false == attribute.isReadOnly()) {
- existingResource.doOcPut(attribute);
- }
- }
- } else {
- Log.e(TAG, "putResourceAttributes(): could not find target resource.");
- }
- // Done. later, the onPut listener in the OcResourceInfo object will notify us of a change
- // via our onResourceChanged() method
- }
-
- /**
- * Because this callback is called on a JNI layer thread, don't do work here.
- * Instead, create a "found resource" message and send to OcWorker's message queue,
- * Our looper/handler then calls handleNewResource on our own worker thread.
- *
- * Also note that this method must be thread safe because it can be called by
- * multiple concurrent native threads.
- *
- * @param resource
- */
- private Object onResourceFoundLock = new Object(); // not strictly necessary with this impl.,
- // but clears up Log message readability.
- @Override
- public void onResourceFound(OcResource resource) {
- synchronized (onResourceFoundLock) {
- if (LOCAL_LOGV) Log.v(TAG, "onResourceFound()");
- if (LOCAL_LOGV) Log.v(TAG, "host: " + resource.getHost());
- if (LOCAL_LOGV) Log.v(TAG, "uri: " + resource.getUri());
- if (LOCAL_LOGV) Log.v(TAG, "is observable: " + resource.isObservable());
-
- this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_FOUND.ordinal(),
- resource).sendToTarget();
- }
- }
-
- /**
- * Handles the internal NEW_RESOURCE_FOUND event, typically engueued on "onResourceFound".
- * Creates a new OcResourceInfo object to wrap the new OcResource and store other info.
- *
- * @param resource the OcResource object
- */
- private void handleNewResourceFound(OcResource resource) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("handleNewResourceFound(%s)",
- resource.toString()));
-
- OcResourceInfo ri =
- this.selectResourceInfoByHostAndUri(resource.getHost() + resource.getUri());
-
- // before notifying listeners, update our own internal OcResourceInfo list
- if(null != mOcResourceInfoList) {
- // check for pre-existing duplicate before adding
- if(null == ri) {
- if (LOCAL_LOGV) Log.v(TAG, "handleNewResourceFound(): ri is new; adding.");
- // if not found, create new info object
- ri = new OcResourceInfo(resource, this);
- // register as a listener to the newly created OcResourceInfo
- ri.registerListener(this);
- // kick off a get to fill in attributes
- ri.doOcGet();
- // add the info object to our list
- mOcResourceInfoList.add(ri);
- }
- }
- // notify listeners
- for(OcWorkerListener l : this.mListeners) {
- l.onResourceFound(ri);
- }
- }
-
- /**
- * The "listener" callback from the OcResourceInfo class.
- * Called by the OcResourceInfo object using the native callback thread.
- * We use this callback to post an event to our queue so that the work
- * is serialized with other incoming events, and executed on our worker thread.
- *
- * Also note that this method must be thread safe because it could be called by
- * one of many OcResourceInfo objects on separate native threads.
- *
- * @param resourceInfo
- */
- private Object onResourceInfoChangedLock = new Object();
- @Override
- public void onResourceInfoChanged(OcResourceInfo resourceInfo) {
-
- synchronized (onResourceInfoChangedLock) {
- if (LOCAL_LOGV) Log.v(TAG, String.format("resourceInfoChanged(%s)",
- resourceInfo.toString()));
-
- // this is a result of a callback (i.e. onGetCompleted, onPut, onObserve)
- // so we post a message to our queue to transfer the work to our own thread
- this.mOcEventHandler.obtainMessage(OC_EVENT.OIC_RESOURCE_CHANGED.ordinal(),
- resourceInfo).sendToTarget();
- }
- }
-
- /**
- * Handle our internal event that is enqueued when a resource is found.
- *
- * @param resourceInfo
- */
- private void handleResourceInfoChange(OcResourceInfo resourceInfo) {
- if (LOCAL_LOGV) Log.v(TAG, "handleResourceInfoChange()");
-
- // notify listeners
- for(OcWorkerListener l : this.mListeners) {
- l.onResourceChanged(resourceInfo);
- }
- }
-
- /**
- * Complete OIC-related initialization, including configuring the platform
- */
- private void ocInit() {
- if (LOCAL_LOGV) Log.v(TAG, "ocInit()");
-
- // OIC initialization
- mOcResourceInfoList = new ArrayList<>();
-
- this.configurePlatform();
- }
-
- /**
- * Configures the OIC platform.
- */
- private void configurePlatform() {
- if (LOCAL_LOGV) Log.v(TAG, "configurePlatform()");
-
- PlatformConfig cfg = new PlatformConfig(
- mContext,
- ServiceType.IN_PROC,
- ModeType.CLIENT_SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
-
- Log.d(TAG, "configurePlatform(): calling OcPlatform.Configure()");
- OcPlatform.Configure(cfg);
- }
-
- /**
- * Search mOcResourceInfo list for a resource whose Host and Uri concatenated
- * matches the param passed, and return it.
- *
- * @param resourceHostAndUri
- * @return OcResourceInfo with Host and Uri matching resourceHostAndUri, or null if
- * no such OcResourceInfo exists in mOcResourceInfoList
- */
- private OcResourceInfo selectResourceInfoByHostAndUri(String resourceHostAndUri) {
- if (LOCAL_LOGV) Log.v(TAG, "selectResourceByHostAndUri()");
-
- boolean found = false;
- OcResourceInfo retVal = null;
-
- for(OcResourceInfo ri : mOcResourceInfoList) {
- if(!found) {
- String s = ri.getHost() + ri.getUri();
- if (resourceHostAndUri.equalsIgnoreCase(s)) {
- retVal = ri;
- found = true;
- }
- }
- }
- if(!found) {
- Log.v(TAG, "selectResourceByHostAndUri(): no resource found matching HostAndUri "
- + resourceHostAndUri);
- }
-
- return retVal;
- }
-
- /**
- * Finds OIC Resources matching known patterns.
- *
- * @see org.iotivity.guiclient.OcProtocolStrings
- */
- private void discoverResources() {
- if (LOCAL_LOGV) Log.v(TAG, "discoverResources()");
-
- try {
- for (String s : mOcFindQueries) {
- Log.d(TAG, String.format("discoverResources(): Calling OcPlatform.findResource(%s)", s));
- OcPlatform.findResource("",
- OcPlatform.WELL_KNOWN_QUERY + "?rt=" + s,
- EnumSet.of(OcConnectivityType.CT_DEFAULT),
- this);
- }
- } catch (OcException e) {
- e.printStackTrace();
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * Clear the ResourceInfoList
- */
- private void clearResourceInfoList() {
- if (LOCAL_LOGV) Log.v(TAG, "clearResourceInfoList()");
-
- this.mOcResourceInfoList.clear();
- }
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.guiclient;
-
-import android.os.Handler;
-
-import java.util.List;
-
-/**
- * Applications wishing to use the OcWorker object must implement this interface to
- * receive notification of OcWorker's ResourceFound and ResourceChanged events.
- *
- * @see org.iotivity.guiclient.OcWorker
- */
-public interface OcWorkerListener {
-
- /**
- * Called whenever a new Resource is discovered.
- *
- * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
- * with UI functionality should post a message to their own UI thread, or similar action.
- *
- * @param resourceInfo
- */
- public void onResourceFound(final OcResourceInfo resourceInfo);
-
- /**
- * Called whenever a previously-discovered Resource changes, e.g. as a result of Put,
- * or Observe callbacks.
- *
- * Note that the calling thread for this callback is not a UI thread. OcWorkerListeners
- * with UI functionality should post a message to their own UI thread, or similar action.
- *
- * @param resourceInfo
- */
- public void onResourceChanged(final OcResourceInfo resourceInfo);
-
-}
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.presenceclient"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.CompoundButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcPresenceHandle;
-import org.iotivity.base.OcPresenceStatus;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-
-/**
- * A client example for presence notification
- */
-public class PresenceClient extends Activity implements
- OcPlatform.OnResourceFoundListener,
- OcPlatform.OnPresenceListener {
- private final static String TAG = PresenceClient.class.getSimpleName();
- private OcResource mResource;
- private OcPresenceHandle mPresenceHandle;
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- private void startPresenceClient() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
- 0, // Uses randomly available port
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
-
- try {
- msg("Finding Resource...");
- OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY,
- EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to find resource(s). ");
- }
- printLine();
- enableStartStopButton();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- @Override
- public synchronized void onResourceFound(OcResource foundResource) {
- String resourceUri = foundResource.getUri();
- if (null != mResource || !resourceUri.equals("/a/light")) {
- msg("Found resource, ignoring");
- return;
- }
-
- msg("Found Resource");
- String hostAddress = foundResource.getHost();
- msg("\tResource URI : " + resourceUri);
- msg("\tResource Host : " + hostAddress);
- msg("\tResource Interfaces : ");
- for (String resInterface : foundResource.getResourceInterfaces()) {
- msg("\t\t" + resInterface);
- }
- msg("\tResource Type : ");
- for (String resTypes : foundResource.getResourceTypes()) {
- msg("\t\t" + resTypes);
- }
-
- try {
- msg("Subscribing to unicast address:" + hostAddress);
- OcPlatform.subscribePresence(hostAddress,
- EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to subscribe to unicast address:" + hostAddress);
- }
- mResource = foundResource;
- printLine();
- }
-
- @Override
- public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress) {
- msg("Received presence notification from : " + hostAddress);
- switch (ocPresenceStatus) {
- case OK:
- msg("Nonce# " + nonce);
- break;
- case STOPPED:
- msg("Presence Stopped");
- break;
- case TIMEOUT:
- msg("Presence Timeout");
- break;
- case DO_NOT_HANDLE:
- msg("Presence Do Not Handle");
- break;
- }
- }
-
- private void stopPresenceClient() {
- if (null != mPresenceHandle) {
- try {
- msg("Unsubscribing from the presence notifications.");
- OcPlatform.unsubscribePresence(mPresenceHandle);
- mPresenceHandle = null;
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Failed to unsubscribe from the presence notifications" + e.toString());
- }
- }
- mResource = null;
- printLine();
- enableStartStopButton();
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_presence_client);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
-
- if (null == savedInstanceState) {
- toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- toggleButton.setEnabled(false);
- if (isChecked) {
- new Thread(new Runnable() {
- public void run() {
- startPresenceClient();
- }
- }).start();
- } else {
- new Thread(new Runnable() {
- public void run() {
- stopPresenceClient();
- }
- }).start();
- }
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
-
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-
- private void enableStartStopButton() {
- runOnUiThread(new Runnable() {
- public void run() {
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- toggleButton.setEnabled(true);
- }
- });
- }
-}
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'
-
-android {
- compileSdkVersion 21
- buildToolsVersion "20.0.0"
-
- defaultConfig {
- applicationId "org.iotivity.base.examples.presenceserver"
- minSdkVersion 21
- targetSdkVersion 21
- versionCode 1
- versionName "1.0"
- }
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
- lintOptions {
- abortOnError false
- }
-}
-repositories {
- flatDir {
- dirs "../../android_api/base/build/outputs/aar/"
- }
-}
-
-try {
- dependencies {
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
- }
-} catch (all) {
- print "${ERROR_MSG}"
- assert all
-}
+++ /dev/null
-/*
- *******************************************************************
- *
- * Copyright 2015 Intel Corporation.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-package org.iotivity.base.examples;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.View;
-import android.widget.CompoundButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcResourceHandle;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ResourceProperty;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-
-/**
- * A server example for presence notification
- */
-public class PresenceServer extends Activity {
- private OcResourceHandle mResourceHandle;
-
- private void startPresenceServer() {
- Context context = this;
-
- PlatformConfig platformConfig = new PlatformConfig(
- context,
- ServiceType.IN_PROC,
- ModeType.SERVER,
- "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
- 0, // Uses randomly available port
- QualityOfService.LOW
- );
-
- msg("Configuring platform.");
- OcPlatform.Configure(platformConfig);
-
- try {
- msg("Creating resource of type \"core.light\".");
- createResource();
- sleep(1);
-
- msg("Starting presence notifications.");
- OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
- sleep(1);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Error: " + e.toString());
- }
- printLine();
- enableStartStopButton();
- }
-
- /**
- * This function internally calls registerResource API.
- */
- private void createResource() {
- String resourceUri = "/a/light"; // URI of the resource
- String resourceTypeName = "core.light"; // resource type name.
- String resourceInterface = OcPlatform.DEFAULT_INTERFACE; // resource interface.
-
- try {
- // This will internally create and register the resource.
- mResourceHandle = OcPlatform.registerResource(
- resourceUri,
- resourceTypeName,
- resourceInterface,
- null, //Use default entity handler
- EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- msg("Resource creation was unsuccessful.");
- Log.e(TAG, e.toString());
- }
- }
-
- private void stopPresenceServer() {
- try {
- msg("Stopping presence notifications.");
- OcPlatform.stopPresence();
-
- msg("Unregister resource.");
- if (null != mResourceHandle) OcPlatform.unregisterResource(mResourceHandle);
- } catch (OcException e) {
- Log.e(TAG, e.toString());
- msg("Error: " + e.toString());
- }
-
- printLine();
- enableStartStopButton();
- }
-
- //******************************************************************************
- // End of the OIC specific code
- //******************************************************************************
-
- private final static String TAG = PresenceServer.class.getSimpleName();
- private TextView mConsoleTextView;
- private ScrollView mScrollView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_presence_server);
-
- mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
- mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
- mScrollView = (ScrollView) findViewById(R.id.scrollView);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
-
- if (null == savedInstanceState) {
- toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- toggleButton.setEnabled(false);
- if (isChecked) {
- new Thread(new Runnable() {
- public void run() {
- startPresenceServer();
- }
- }).start();
- } else {
- new Thread(new Runnable() {
- public void run() {
- stopPresenceServer();
- }
- }).start();
- }
- }
- });
- } else {
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- String consoleOutput = savedInstanceState.getString("consoleOutputString");
- mConsoleTextView.setText(consoleOutput);
-
- final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
- toggleButton.setChecked(buttonCheked);
- }
-
- private void msg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- mConsoleTextView.append("\n");
- mConsoleTextView.append(text);
- mScrollView.fullScroll(View.FOCUS_DOWN);
- }
- });
- Log.i(TAG, text);
- }
-
- private void printLine() {
- msg("------------------------------------------------------------------------");
- }
-
- private void sleep(int seconds) {
- try {
- Thread.sleep(seconds * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- Log.e(TAG, e.toString());
- }
- }
-
- private void enableStartStopButton() {
- runOnUiThread(new Runnable() {
- public void run() {
- ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
- toggleButton.setEnabled(true);
- }
- });
- }
-}
\ No newline at end of file
+++ /dev/null
-apply plugin: 'com.android.application'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "20.0.0"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.provisioningclient"\r
- minSdkVersion 21\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
- lintOptions {\r
- abortOnError false\r
- }\r
-}\r
-repositories {\r
- flatDir {\r
- dirs "../../android_api/base/build/outputs/aar/"\r
- }\r
-}\r
-\r
-try {\r
- dependencies {\r
- compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
- }\r
-} catch (all) {\r
- print "${ERROR_MSG}"\r
- assert all\r
-}\r
-\r
+++ /dev/null
-{
- "acl": [
- {
- "sub": "Kg==",
- "rsrc": [
- "/oic/res",
- "/oic/d",
- "/oic/p",
- "/oic/res/types/d",
- "/oic/ad",
- "/oic/sec/amacl"
- ],
- "perms": 2,
- "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
- },
- {
- "sub": "Kg==",
- "rsrc": [
- "/oic/sec/doxm",
- "/oic/sec/pstat"
- ],
- "perms": 2,
- "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
- }
- ],
- "pstat": {
- "dos": {"s": 3, "p": false},
- "isop": true,
- "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
- "ch": 0,
- "cm": 0,
- "tm": 0,
- "om": 3,
- "sm": [3]
- },
- "doxm": {
- "oxm": [0],
- "oxmsel": 0,
- "sct": 9,
- "owned": true,
- "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
- "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
- }
-}
+++ /dev/null
-package org.iotivity.base.examples.provisioningclient;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.os.Message;
-import android.preference.PreferenceManager;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.Gravity;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-import org.iotivity.base.OcProvisioning;
-import org.iotivity.base.OcSecureResource;
-import org.iotivity.base.ProvisionResult;
-import org.iotivity.base.OxmType;
-import org.iotivity.base.OicSecAcl;
-import org.iotivity.base.CredType;
-import org.iotivity.base.KeySize;
-import org.iotivity.base.DeviceStatus;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-
-public class ProvisioningClient extends Activity implements
- OcSecureResource.DoOwnershipTransferListener,OcSecureResource.ProvisionPairwiseDevicesListener {
-
- private static final String TAG = "Provisioning Client: ";
- private static final int BUFFER_SIZE = 1024;
- int unownedDevCount = StringConstants.NUMBER_ZERO;
- private String filePath = "";
- private OcSecureResource newSecureResource;
- private List<OcSecureResource> deviceList;
- private List<OcSecureResource> ownedDeviceList;
- private TextView mEventsTextView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_secure_provision_client);
- mEventsTextView = new TextView(this);
- mEventsTextView.setGravity(Gravity.BOTTOM);
- mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
- LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
- layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
- );
- filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
- //copy json when application runs first time
- SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
- boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
- if (isFirstRun) {
- copyJsonFromAsset();
- SharedPreferences.Editor editor = wmbPreference.edit();
- editor.putBoolean("FIRSTRUN", false);
- editor.commit();
- }
- initOICStack();
- }
-
- OcProvisioning.PinCallbackListener pinCallbackListener =
- new OcProvisioning.PinCallbackListener() {
- @Override
- public String pinCallbackListener() {
- Log.d(TAG, "Inside Pin Callback ");
- return "";
- }
- };
-
- OcSecureResource.ProvisionAclListener provisionAclListener =
- new OcSecureResource.ProvisionAclListener() {
- @Override
- public void provisionAclListener(List<ProvisionResult> provisionResults,
- int hasError) {
- Log.d(TAG, "Inside ProvisionAclListener ");
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage("Error: ACL Provision failed !!");
- } else {
- logMessage("ACL Provision Done !!");
- new DeviceRevocationAsyncTask().execute();
- }
- }
- };
-
- OcSecureResource.ProvisionCredentialsListener provisionCredentialsListener =
- new OcSecureResource.ProvisionCredentialsListener() {
- @Override
- public void provisionCredentialsListener(List<ProvisionResult> provisionResults,
- int hasError) {
- Log.d(TAG, "Inside ProvisionCredentialsListener ");
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage("Error: Provision Credentials failed !!");
- } else {
- logMessage("Provision Credentials Done !!");
- new ProvisionACLAsyncTask().execute();
- }
- }
- };
-
- OcSecureResource.UnlinkDevicesListener unlinkDevicesListener =
- new OcSecureResource.UnlinkDevicesListener() {
- @Override
- public void unlinkDevicesListener(List<ProvisionResult> provisionResults,
- int hasError) {
- Log.d(TAG, "Inside unlinkDevicesListener ");
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage("Error: UnLinking device !!");
- } else {
- logMessage("Unlink Done !!");
- new ProvisionCredentialAsyncTask().execute();
- }
- }
- };
-
- OcSecureResource.RemoveDeviceListener removeDeviceListener =
- new OcSecureResource.RemoveDeviceListener() {
- @Override
- public void removeDeviceListener(List<ProvisionResult> provisionResults,
- int hasError) {
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage("Error: Remove Fail !!");
- } else {
- logMessage("Remove Device done !!");
- }
- }
- };
-
- /**
- * configure OIC platform and call findResource
- */
- private void initOICStack() {
- //create platform config
- PlatformConfig cfg = new PlatformConfig(
- this,
- ServiceType.IN_PROC,
- ModeType.CLIENT_SERVER,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
- OcPlatform.Configure(cfg);
- try {
- /*
- * Initialize DataBase
- */
- String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
- File.separator;
- File file = new File(sqlDbPath);
- //check files directory exists
- if (!(file.isDirectory())) {
- file.mkdirs();
- Log.d(TAG, "Sql db directory created at " + sqlDbPath);
- }
- Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
- OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
- } catch (OcException e) {
- logMessage(TAG + "provisionInit error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- new DiscoveryOTTransferAsyncTask().execute();
- }
-
- @Override
- synchronized public void doOwnershipTransferListener(List<ProvisionResult> ProvisionResultList,
- int hasError) {
- ProvisionResult pResult = ProvisionResultList.get(0);
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage(TAG + "Ownership Transfer Failed for " + pResult.getDevId());
- } else {
- logMessage(TAG + "Ownership Transfer Successful for "
- + pResult.getDevId());
- unownedDevCount--;
- }
- if (unownedDevCount == 0) { //When done with Ownership Transfer
- new OwnedDiscoveryAsyncTask().execute();
- }
- }
-
- private void doPairwiseProvisioning() {
- try {
- logMessage(TAG + "Pairwise Provisioning b/w " + ownedDeviceList.get(0).getDeviceID()
- + " and " + ownedDeviceList.get(1).getDeviceID());
- newSecureResource = ownedDeviceList.get(0);
- OcSecureResource newSecureResource2 = ownedDeviceList.get(1);
- List<String> resources = new ArrayList<String>();
- List<String> owners = new ArrayList<String>();
- List<String> periods = new ArrayList<String>();
- List<String> recurrences = new ArrayList<String>();
- recurrences.add("Daily");
- resources.add("*");
- owners.add("adminDeviceUUID0");
- periods.add("01-01-15");
- OicSecAcl acl1 = new OicSecAcl(newSecureResource.getDeviceID(), recurrences, periods,
- 31, resources, owners);
- OicSecAcl acl2 = new OicSecAcl(newSecureResource2.getDeviceID(), recurrences, periods,
- 31, resources, owners);
- newSecureResource.provisionPairwiseDevices(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
- KeySize.OWNER_PSK_LENGTH_128, acl1, newSecureResource2, acl2, this);
- } catch (Exception e) {
- logMessage(TAG + "Pairwise Provisioning error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- @Override
- public void provisionPairwiseDevicesListener(List<ProvisionResult> ProvisionResultList,
- int hasError) {
- if (hasError == StringConstants.ERROR_CODE) {
- logMessage(TAG + "provisionPairwiseDevices Failed");
- } else {
- for (int i = 0; i < ProvisionResultList.size(); i++) {
- ProvisionResult pResult = ProvisionResultList.get(i);
- logMessage(TAG + "provisionPairwiseDevices Result for "
- + pResult.getDevId() + "is " + pResult.getResult());
- }
- new GetLinkedDevicesAsyncTask().execute();
- }
- }
-
- /**
- * Copy svr db json file from assets folder to app data files dir
- */
- private void copyJsonFromAsset() {
- InputStream inputStream = null;
- OutputStream outputStream = null;
- int length;
- byte[] buffer = new byte[BUFFER_SIZE];
- try {
- inputStream = getAssets().open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
- File file = new File(filePath);
- //check files directory exists
- if (!(file.exists() && file.isDirectory())) {
- file.mkdirs();
- }
- outputStream = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
- while ((length = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, length);
- }
- } catch (NullPointerException e) {
- logMessage(TAG + "Null pointer exception " + e.getMessage());
- Log.e(TAG, e.getMessage());
- } catch (FileNotFoundException e) {
- logMessage(TAG + "Json svr db file not found " + e.getMessage());
- Log.e(TAG, e.getMessage());
- } catch (IOException e) {
- logMessage(TAG + StringConstants.OIC_CLIENT_JSON_DB_FILE + " file copy failed");
- Log.e(TAG, e.getMessage());
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- }
- }
- if (outputStream != null) {
- try {
- outputStream.close();
- } catch (IOException e) {
- Log.e(TAG, e.getMessage());
- }
- }
- }
- }
-
- public void logMessage(String text) {
- logMsg(text);
- }
-
- public void logMsg(final String text) {
- runOnUiThread(new Runnable() {
- public void run() {
- Message msg = new Message();
- msg.obj = text;
- mEventsTextView.append(text);
- mEventsTextView.append("\n\n");
- }
- });
- Log.i(TAG, text);
- Intent intent = new Intent(getPackageName());
- intent.putExtra(StringConstants.MESSAGE, text);
- sendBroadcast(intent);
- }
-
- private class DiscoveryOTTransferAsyncTask extends AsyncTask<Void, String, String> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected String doInBackground(Void... params) {
- try {
- /**
- * Discover Un-owned devices
- */
- publishProgress(TAG + "Discovering Unowned Devices");
- deviceList = new ArrayList<OcSecureResource>(OcProvisioning.discoverUnownedDevices
- (StringConstants.DISCOVERY_TIMEOUT_10));
- if (deviceList.size() > 0) {
- unownedDevCount = deviceList.size();
- for (int i = 0; i < deviceList.size(); i++) {
- publishProgress(TAG + "Un-owned Discovered Device " + (i + 1) + "= " +
- deviceList.get(i).getDeviceID());
- }
- try {
- OcProvisioning.SetownershipTransferCBdata(OxmType.OIC_JUST_WORKS,
- pinCallbackListener);
- for (int i = 0; i < deviceList.size(); i++) {
- publishProgress(TAG + "Doing Ownership Transfer for " +
- deviceList.get(i).getDeviceID());
- deviceList.get(i).doOwnershipTransfer(ProvisioningClient.this);
- }
- } catch (OcException e) {
- publishProgress(TAG + "Ownership Transfer error: " + e.getMessage());
- return "Ownership Transfer error: " + e.getMessage();
-
- }
- } else {
- publishProgress(TAG + "No un-owned devices present");
- new OwnedDiscoveryAsyncTask().execute();
- }
- } catch (OcException e) {
- publishProgress(TAG + "Un-owned discovery error: " + e.getMessage());
- return "Un-owned discovery error: " + e.getMessage();
- }
- return "success";
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
-
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- }
- }
-
- private class ProvisionACLAsyncTask extends AsyncTask<Void, String, Void> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- try {
- if (ownedDeviceList.size() > 1) {
- OcSecureResource ocSecureResource = ownedDeviceList.get(0);
- OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
- publishProgress(TAG + "ACL Provision for " + ocSecureResource.getDeviceID());
- List<String> resources = new ArrayList<String>();
- List<String> owners = new ArrayList<String>();
- List<String> periods = new ArrayList<String>();
- List<String> recurrences = new ArrayList<String>();
- recurrences.add("Daily");
- resources.add("*");
- owners.add("adminDeviceUUID0");
- periods.add("01-01-15");
- OicSecAcl aclObject = new OicSecAcl(ocSecureResourceDest.getDeviceID(),
- recurrences, periods, 31, resources, owners);
- ocSecureResource.provisionACL(aclObject, provisionAclListener);
- } else {
- publishProgress(TAG + "No Owned devices present");
- }
- } catch (Exception e) {
- publishProgress(TAG + "ProvisionACL error: " + e.getMessage());
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
- }
-
- private class ProvisionCredentialAsyncTask extends AsyncTask<Void, String, Void> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- try {
- if (ownedDeviceList.size() > 1) {
- OcSecureResource ocSecureResource = ownedDeviceList.get(0);
- OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
- publishProgress(TAG + "ProvisionCredential for " +
- ocSecureResource.getDeviceID() + " with " +
- ocSecureResourceDest.getDeviceID());
- ocSecureResource.provisionCredentials(EnumSet.of(CredType.SYMMETRIC_PAIR_WISE_KEY),
- KeySize.OWNER_PSK_LENGTH_128,
- ocSecureResourceDest, provisionCredentialsListener);
- } else {
- publishProgress(TAG + "Cannot perform credentials between devices");
- }
- } catch (Exception e) {
- publishProgress(TAG + "Provision credentials error: " + e.getMessage());
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
- }
-
- private class GetLinkedDevicesAsyncTask extends AsyncTask<Void, String, String> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected String doInBackground(Void... params) {
- try {
- if (ownedDeviceList.size() > 1) {
- OcSecureResource ocSecureResource = ownedDeviceList.get(0);
- publishProgress(TAG + "Get linked devices of " + ocSecureResource.getDeviceID());
- List<String> linkedDevices = ocSecureResource.getLinkedDevices();
- if (linkedDevices.size() > 0) {
- for (int i = 0; i < linkedDevices.size(); i++) {
- publishProgress(TAG + "Linked Devices "+
- (i + 1) + "= " + linkedDevices.get(i));
- }
- } else {
- publishProgress(TAG + "No linked Devices found");
- }
- } else {
- publishProgress(TAG + "Cannot perform linked devices");
- }
- } catch (Exception e) {
- publishProgress(TAG + "getLinked device error: " + e.getMessage());
- return "failed";
- }
- return "success";
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
-
- @Override
- protected void onPostExecute(String s) {
- if ("success".equals(s)) {
- new ProvisionUnlinkAsyncTask().execute();
- }
- }
- }
-
- private class ProvisionUnlinkAsyncTask extends AsyncTask<Void, String, Void> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- try {
- if (ownedDeviceList.size() > 1) {
- OcSecureResource ocSecureResource = ownedDeviceList.get(0);
- OcSecureResource ocSecureResourceDest = ownedDeviceList.get(1);
- publishProgress(TAG + "Un linking " + ocSecureResource.getDeviceID() +
- " with " + ocSecureResourceDest.getDeviceID());
- ocSecureResource.unlinkDevices(ocSecureResourceDest, unlinkDevicesListener);
- } else {
- publishProgress(TAG + "Cannot perform unlink devices");
- }
- } catch (Exception e) {
- publishProgress(TAG + "Unlink error: " + e.getMessage());
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
- }
-
- private class DeviceRevocationAsyncTask extends AsyncTask<Void, String, Void> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected Void doInBackground(Void... params) {
- try {
- if (ownedDeviceList.size() > 0) {
- OcSecureResource ocSecureResource = ownedDeviceList.get(0);
- publishProgress(TAG + "Removing " + ocSecureResource.getDeviceID());
- ocSecureResource.removeDevice(StringConstants.DISCOVERY_TIMEOUT_20,
- removeDeviceListener);
- } else {
- publishProgress(TAG + "Cannot remove");
- }
- } catch (Exception e) {
- publishProgress(TAG + "Remove Device error: " + e.getMessage());
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
- }
-
- private class OwnedDiscoveryAsyncTask extends AsyncTask<Void, String, String> {
-
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- }
-
- @Override
- protected String doInBackground(Void... params) {
- try {
- publishProgress(TAG + "Initiate Owned device Discovery");
- ownedDeviceList = OcProvisioning.discoverOwnedDevices
- (StringConstants.DISCOVERY_TIMEOUT_10);
- if (ownedDeviceList.size() > 0) {
- for (int i = 0; i < ownedDeviceList.size(); i++) {
- publishProgress(TAG + "Owned Discovered Device " + (i + 1) + "= " +
- ownedDeviceList.get(i).getDeviceID()
- + "\nIP Address= " + ownedDeviceList.get(i).getIpAddr()
- + "\nOwned Status= " + ownedDeviceList.get(i).getOwnedStatus()
- + "\nDevice Status= " + ((ownedDeviceList.get(i).
- getDeviceStatus() == DeviceStatus.ON) ? "ON" : "OFF")
- );
- }
- } else {
- publishProgress(TAG + "No Owned devices present");
- }
- } catch (OcException e) {
- publishProgress(TAG + "Owned device Discovery error: " + e.getMessage());
- return "Owned device Discovery error: " + e.getMessage();
- }
- return "success";
- }
-
- @Override
- protected void onProgressUpdate(String... values) {
- logMessage(values[0]);
- }
-
- @Override
- protected void onPostExecute(String s) {
- if (ownedDeviceList.size() > 1 && "success".equals(s)) {
- doPairwiseProvisioning();
- }
- }
- }
-
- /**
- * to display on Server Message on Client screen
- */
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(StringConstants.MESSAGE);
- logMessage(message);
- }
- }
-}
+++ /dev/null
-package org.iotivity.base.examples.provisioningclient;
-
-public interface StringConstants {
-
- public static final int NUMBER_ZERO = 0;
- public static final int DISCOVERY_TIMEOUT_10 = 10;
- public static final int DISCOVERY_TIMEOUT_20 = 20;
- public static final int ERROR_CODE = 1;
- public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.json";
- public static final String MESSAGE = "message";
- public static final String OIC_SQL_DB_FILE = "Pdm.db";
- public static final int CREDENTIAL_TYPE=1;
- public static final int OWNER_PSK_LENGTH_128=128/8;
-}