1 /******************************************************************
2 * Copyright 2015 Samsung Electronics All Rights Reserved.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 ******************************************************************/
18 package org.iotivity.service.sample.client;
20 import static org.iotivity.service.client.RcsRemoteResourceObject.OnCacheUpdatedListener;
21 import static org.iotivity.service.client.RcsRemoteResourceObject.OnStateChangedListener;
22 import static org.iotivity.service.client.RcsRemoteResourceObject.ResourceState;
24 import java.lang.ref.WeakReference;
26 import org.iotivity.service.RcsException;
27 import org.iotivity.service.RcsResourceAttributes;
28 import org.iotivity.service.RcsValue;
29 import org.iotivity.service.client.RcsAddress;
30 import org.iotivity.service.client.RcsDiscoveryManager;
31 import org.iotivity.service.client.RcsDiscoveryManager.OnResourceDiscoveredListener;
32 import org.iotivity.service.client.RcsRemoteResourceObject;
33 import org.iotivity.service.client.RcsRemoteResourceObject.OnRemoteAttributesReceivedListener;
35 import android.app.Activity;
36 import android.app.AlertDialog;
37 import android.content.DialogInterface;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.Message;
41 import android.util.Log;
42 import android.view.View;
43 import android.widget.AdapterView;
44 import android.widget.AdapterView.OnItemClickListener;
45 import android.widget.ArrayAdapter;
46 import android.widget.Button;
47 import android.widget.EditText;
48 import android.widget.ListView;
49 import android.widget.TextView;
50 import android.widget.Toast;
53 * Activity for handling user's selection on UI for Resource Client APIs.
56 public class ResourceClientActivity extends Activity
57 implements OnItemClickListener {
59 private static final String LOG_TAG = ResourceClientActivity.class
62 private static final int MSG_ID_RESOURCE_DISCOVERED = 0;
63 private static final int MSG_ID_ATTRIBUTE_RECEIVED = 1;
64 private static final int MSG_ID_PRINT_LOG = 2;
66 private static final String ATTR_KEY_TEMPERATURE = "Temperature";
68 private TextView mLogView;
69 private ListView mListView;
70 private Button mDiscoveryBtn;
72 private Handler mHandler;
73 private ArrayAdapter<Item> mItemAdapter;
75 private RcsDiscoveryManager.DiscoveryTask mDiscoveryTask;
76 private RcsRemoteResourceObject mResourceObj;
78 private OnResourceDiscoveredListener mOnResourceDiscoveredListener = new OnResourceDiscoveredListener() {
81 public void onResourceDiscovered(
82 RcsRemoteResourceObject foundResource) {
83 Log.i(LOG_TAG, "onResourceDiscovered");
85 mHandler.obtainMessage(MSG_ID_RESOURCE_DISCOVERED, foundResource)
90 private OnStateChangedListener mOnStateChangedListener = new OnStateChangedListener() {
93 public void onStateChanged(ResourceState resourceState) {
94 Log.i(LOG_TAG, "onStateChanged");
96 mHandler.obtainMessage(MSG_ID_PRINT_LOG,
97 "Current Resource State : " + resourceState);
101 private OnRemoteAttributesReceivedListener mOnRemoteAttributesReceivedListener = new OnRemoteAttributesReceivedListener() {
103 public void onAttributesReceived(RcsResourceAttributes attrs,
105 Log.i(LOG_TAG, "onAttributesReceived");
107 mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
112 private OnCacheUpdatedListener mOnCacheUpdatedListener = new OnCacheUpdatedListener() {
114 public void onCacheUpdated(RcsResourceAttributes attrs) {
115 Log.i(LOG_TAG, "onCacheUpdated");
117 mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
122 private Item mStartMonitoring = new Item("1. Start Monitoring") {
124 public void execute() throws RcsException {
125 if (mResourceObj.isMonitoring()) {
126 printLog("Monitoring already started");
130 mResourceObj.startMonitoring(mOnStateChangedListener);
132 if (mResourceObj.isMonitoring()) {
133 printLog("Monitoring started successfully");
138 private Item mStopMonitoring = new Item("2. Stop Monitoring") {
140 public void execute() throws RcsException {
141 if (mResourceObj.isMonitoring()) {
143 mResourceObj.stopMonitoring();
145 if (!mResourceObj.isMonitoring()) {
146 printLog("Monitoring stopped successfully");
150 printLog("Monitoring not started");
155 private Item mGetRemoteAttributes = new Item("3. Get Remote Attributes") {
157 public void execute() throws RcsException {
159 .getRemoteAttributes(mOnRemoteAttributesReceivedListener);
163 private Item mSetRemoteAttributes = new Item("4. Set Remote Attributes") {
166 public void execute() throws RcsException {
167 showInputValueDialog();
171 private Item mStartCaching = new Item("5. Start Caching") {
173 public void execute() throws RcsException {
174 if (mResourceObj.isCaching()) {
175 printLog("Caching already started");
179 mResourceObj.startCaching(mOnCacheUpdatedListener);
181 if (mResourceObj.isCaching()) {
182 printLog("Caching started successfully");
188 private Item mGetCacheState = new Item("6. Get Cache State") {
190 public void execute() throws RcsException {
191 printLog("Cache State : " + mResourceObj.getCacheState());
195 private Item mGetCachedAttributes = new Item(
196 "7. Get All Cached Attributes") {
198 public void execute() throws RcsException {
199 printAttributes(mResourceObj.getCachedAttributes());
203 private Item mGetCachedAttribute = new Item("8. Get Cached Attribute") {
205 public void execute() throws RcsException {
206 printLog(ATTR_KEY_TEMPERATURE + " : " + mResourceObj
207 .getCachedAttribute(ATTR_KEY_TEMPERATURE).asInt());
211 private Item mStopCaching = new Item("9. Stop Caching") {
213 public void execute() throws RcsException {
214 if (mResourceObj.isCaching()) {
216 mResourceObj.stopCaching();
218 if (!mResourceObj.isCaching()) {
219 printLog("Caching stopped successfully");
221 printLog("Stopping caching unsuccessful");
225 printLog("Caching not started");
232 protected void onCreate(Bundle savedInstanceState) {
233 super.onCreate(savedInstanceState);
234 setContentView(R.layout.activity_resource_client);
236 mListView = (ListView) findViewById(R.id.list_menu);
237 mLogView = (TextView) findViewById(R.id.text_log);
238 mDiscoveryBtn = (Button) findViewById(R.id.btn_discovery);
240 mHandler = new ClientHandler(this);
246 protected void onDestroy() {
249 if (mDiscoveryTask != null) mDiscoveryTask.cancel();
250 if (mResourceObj != null) mResourceObj.destroy();
253 private void initMenuList() {
254 Item[] items = new Item[] { mStartMonitoring, mStopMonitoring,
255 mGetRemoteAttributes, mSetRemoteAttributes, mStartCaching,
256 mGetCacheState, mGetCachedAttributes, mGetCachedAttribute,
259 mItemAdapter = new ArrayAdapter<>(this,
260 android.R.layout.simple_list_item_1, items);
262 mListView.setAdapter(mItemAdapter);
264 mListView.setOnItemClickListener(this);
268 public void onItemClick(AdapterView<?> parent, View view, int position,
270 if (mResourceObj == null) {
271 showError("no discovered RemoteResourceObject");
276 mItemAdapter.getItem(position).execute();
277 } catch (RcsException e) {
282 public void onDiscoverResourceClick(View v) {
286 private void toggleDiscovery() {
287 if (mDiscoveryTask == null) {
289 mDiscoveryTask = RcsDiscoveryManager.getInstance()
290 .discoverResource(RcsAddress.multicast(),
291 mOnResourceDiscoveredListener);
292 mDiscoveryBtn.setText(R.string.cancel_discovery);
294 mListView.setVisibility(View.INVISIBLE);
296 if (mResourceObj != null) {
297 mResourceObj.destroy();
300 } catch (RcsException e) {
304 mDiscoveryTask.cancel();
305 mDiscoveryTask = null;
307 mDiscoveryBtn.setText(R.string.discover_resource);
311 private void printAttributes(RcsResourceAttributes attributes) {
313 StringBuilder sb = new StringBuilder();
314 for (String key : attributes.keySet()) {
315 sb.append(key + " : " + attributes.get(key));
317 printLog(sb.toString());
318 } catch (Exception e) {
323 private void setRemoteResourceObject(
324 RcsRemoteResourceObject foundResource) {
325 if (mResourceObj != null) {
326 Log.w(LOG_TAG, "Another remote resource found...");
330 mResourceObj = foundResource;
332 mListView.setVisibility(View.VISIBLE);
336 printLog(resourceInfo(mResourceObj));
337 } catch (RcsException e) {
342 private void showInputValueDialog() {
343 final AlertDialog dialog = new AlertDialog.Builder(this)
344 .setTitle("Enter the Temperature Value")
345 .setView(R.layout.dialog_content_edit_text)
346 .setNegativeButton("Cancel", null).create();
348 dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
349 new DialogInterface.OnClickListener() {
351 public void onClick(DialogInterface dialogInterface,
354 EditText temperatureValue = (EditText) dialog
355 .findViewById(R.id.attributeValue);
358 RcsValue value = new RcsValue(Integer.parseInt(
359 temperatureValue.getText().toString()));
361 RcsResourceAttributes attrs = new RcsResourceAttributes();
362 attrs.put(ATTR_KEY_TEMPERATURE, value);
364 mResourceObj.setRemoteAttributes(attrs,
365 mOnRemoteAttributesReceivedListener);
366 } catch (NumberFormatException e) {
367 showError("Please enter the Integer Value");
368 } catch (RcsException e) {
376 private void showError(String msg) {
377 Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
381 private void showError(Exception e) {
382 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
383 Log.e(LOG_TAG, e.getMessage(), e);
386 private void printLog(String message) {
387 Log.i(LOG_TAG, message);
388 mLogView.setText(message);
391 private void printLog(Exception e) {
392 Log.i(LOG_TAG, e.getMessage(), e);
393 mLogView.setText(e.getMessage());
396 private String resourceInfo(RcsRemoteResourceObject resourceObject)
397 throws RcsException {
398 StringBuilder sb = new StringBuilder();
400 sb.append("URI : " + resourceObject.getUri() + "\n");
401 sb.append("Host : " + resourceObject.getAddress() + "\n");
402 for (String type : resourceObject.getTypes()) {
403 sb.append("resourceType : " + type + "\n");
406 for (String itf : resourceObject.getInterfaces()) {
407 sb.append("resourceInterfaces : " + itf + "\n");
410 sb.append("isObservable : " + resourceObject.isObservable() + "\n");
412 return sb.toString();
415 private static abstract class Item {
416 private final String mTitle;
418 protected Item(String title) {
423 public String toString() {
427 public abstract void execute() throws RcsException;
430 private static class ClientHandler extends Handler {
431 private WeakReference<ResourceClientActivity> mActivityRef;
433 private ClientHandler(ResourceClientActivity activity) {
434 mActivityRef = new WeakReference<>(activity);
438 public void handleMessage(Message msg) {
439 super.handleMessage(msg);
441 ResourceClientActivity activity = mActivityRef.get();
442 if (activity == null) return;
445 case MSG_ID_RESOURCE_DISCOVERED:
446 activity.setRemoteResourceObject(
447 (RcsRemoteResourceObject) msg.obj);
450 case MSG_ID_ATTRIBUTE_RECEIVED:
451 activity.printAttributes((RcsResourceAttributes) msg.obj);
454 case MSG_ID_PRINT_LOG:
455 activity.printLog(msg.obj.toString());