Add logs in android sample of resource encapsulation
[platform/upstream/iotivity.git] / service / resource-encapsulation / examples / android / RESampleClientApp / app / src / main / java / org / iotivity / service / sample / client / ResourceClientActivity.java
1 /******************************************************************
2  * Copyright 2015 Samsung Electronics All Rights Reserved.
3  * <p>
4  * <p>
5  * <p>
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
9  * <p>
10  * http://www.apache.org/licenses/LICENSE-2.0
11  * <p>
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;
19
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;
23
24 import java.lang.ref.WeakReference;
25
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;
34
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;
51
52 /*
53  * Activity for handling user's selection on UI for Resource Client APIs.
54  * & for updating UI.
55  */
56 public class ResourceClientActivity extends Activity
57         implements OnItemClickListener {
58
59     private static final String LOG_TAG = ResourceClientActivity.class
60             .getSimpleName();
61
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;
65
66     private static final String ATTR_KEY_TEMPERATURE = "Temperature";
67
68     private TextView mLogView;
69     private ListView mListView;
70     private Button   mDiscoveryBtn;
71
72     private Handler            mHandler;
73     private ArrayAdapter<Item> mItemAdapter;
74
75     private RcsDiscoveryManager.DiscoveryTask mDiscoveryTask;
76     private RcsRemoteResourceObject           mResourceObj;
77
78     private OnResourceDiscoveredListener mOnResourceDiscoveredListener = new OnResourceDiscoveredListener() {
79
80         @Override
81         public void onResourceDiscovered(
82                 RcsRemoteResourceObject foundResource) {
83             Log.i(LOG_TAG, "onResourceDiscovered");
84
85             mHandler.obtainMessage(MSG_ID_RESOURCE_DISCOVERED, foundResource)
86                     .sendToTarget();
87         }
88     };
89
90     private OnStateChangedListener mOnStateChangedListener = new OnStateChangedListener() {
91
92         @Override
93         public void onStateChanged(ResourceState resourceState) {
94             Log.i(LOG_TAG, "onStateChanged");
95
96             mHandler.obtainMessage(MSG_ID_PRINT_LOG,
97                     "Current Resource State : " + resourceState);
98         }
99     };
100
101     private OnRemoteAttributesReceivedListener mOnRemoteAttributesReceivedListener = new OnRemoteAttributesReceivedListener() {
102         @Override
103         public void onAttributesReceived(RcsResourceAttributes attrs,
104                 int eCode) {
105             Log.i(LOG_TAG, "onAttributesReceived");
106
107             mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
108                     .sendToTarget();
109         }
110     };
111
112     private OnCacheUpdatedListener mOnCacheUpdatedListener = new OnCacheUpdatedListener() {
113         @Override
114         public void onCacheUpdated(RcsResourceAttributes attrs) {
115             Log.i(LOG_TAG, "onCacheUpdated");
116
117             mHandler.obtainMessage(MSG_ID_ATTRIBUTE_RECEIVED, attrs)
118                     .sendToTarget();
119         }
120     };
121
122     private Item mStartMonitoring = new Item("1. Start Monitoring") {
123         @Override
124         public void execute() throws RcsException {
125             if (mResourceObj.isMonitoring()) {
126                 printLog("Monitoring already started");
127                 return;
128             }
129
130             mResourceObj.startMonitoring(mOnStateChangedListener);
131
132             if (mResourceObj.isMonitoring()) {
133                 printLog("Monitoring started successfully");
134             }
135         }
136     };
137
138     private Item mStopMonitoring = new Item("2. Stop Monitoring") {
139         @Override
140         public void execute() throws RcsException {
141             if (mResourceObj.isMonitoring()) {
142
143                 mResourceObj.stopMonitoring();
144
145                 if (!mResourceObj.isMonitoring()) {
146                     printLog("Monitoring stopped successfully");
147                 }
148
149             } else {
150                 printLog("Monitoring not started");
151             }
152         }
153     };
154
155     private Item mGetRemoteAttributes = new Item("3. Get Remote Attributes") {
156         @Override
157         public void execute() throws RcsException {
158             mResourceObj
159                     .getRemoteAttributes(mOnRemoteAttributesReceivedListener);
160         }
161     };
162
163     private Item mSetRemoteAttributes = new Item("4. Set Remote Attributes") {
164
165         @Override
166         public void execute() throws RcsException {
167             showInputValueDialog();
168         }
169     };
170
171     private Item mStartCaching = new Item("5. Start Caching") {
172         @Override
173         public void execute() throws RcsException {
174             if (mResourceObj.isCaching()) {
175                 printLog("Caching already started");
176                 return;
177             }
178
179             mResourceObj.startCaching(mOnCacheUpdatedListener);
180
181             if (mResourceObj.isCaching()) {
182                 printLog("Caching started successfully");
183             }
184
185         }
186     };
187
188     private Item mGetCacheState = new Item("6. Get Cache State") {
189         @Override
190         public void execute() throws RcsException {
191             printLog("Cache State : " + mResourceObj.getCacheState());
192         }
193     };
194
195     private Item mGetCachedAttributes = new Item(
196             "7. Get All Cached Attributes") {
197         @Override
198         public void execute() throws RcsException {
199             printAttributes(mResourceObj.getCachedAttributes());
200         }
201     };
202
203     private Item mGetCachedAttribute = new Item("8. Get Cached Attribute") {
204         @Override
205         public void execute() throws RcsException {
206             printLog(ATTR_KEY_TEMPERATURE + " : " + mResourceObj
207                     .getCachedAttribute(ATTR_KEY_TEMPERATURE).asInt());
208         }
209     };
210
211     private Item mStopCaching = new Item("9. Stop Caching") {
212         @Override
213         public void execute() throws RcsException {
214             if (mResourceObj.isCaching()) {
215
216                 mResourceObj.stopCaching();
217
218                 if (!mResourceObj.isCaching()) {
219                     printLog("Caching stopped successfully");
220                 } else {
221                     printLog("Stopping caching unsuccessful");
222                 }
223
224             } else {
225                 printLog("Caching not started");
226             }
227         }
228
229     };
230
231     @Override
232     protected void onCreate(Bundle savedInstanceState) {
233         super.onCreate(savedInstanceState);
234         setContentView(R.layout.activity_resource_client);
235
236         mListView = (ListView) findViewById(R.id.list_menu);
237         mLogView = (TextView) findViewById(R.id.text_log);
238         mDiscoveryBtn = (Button) findViewById(R.id.btn_discovery);
239
240         mHandler = new ClientHandler(this);
241
242         initMenuList();
243     }
244
245     @Override
246     protected void onDestroy() {
247         super.onDestroy();
248
249         if (mDiscoveryTask != null) mDiscoveryTask.cancel();
250         if (mResourceObj != null) mResourceObj.destroy();
251     }
252
253     private void initMenuList() {
254         Item[] items = new Item[] { mStartMonitoring, mStopMonitoring,
255                 mGetRemoteAttributes, mSetRemoteAttributes, mStartCaching,
256                 mGetCacheState, mGetCachedAttributes, mGetCachedAttribute,
257                 mStopCaching };
258
259         mItemAdapter = new ArrayAdapter<>(this,
260                 android.R.layout.simple_list_item_1, items);
261
262         mListView.setAdapter(mItemAdapter);
263
264         mListView.setOnItemClickListener(this);
265     }
266
267     @Override
268     public void onItemClick(AdapterView<?> parent, View view, int position,
269             long id) {
270         if (mResourceObj == null) {
271             showError("no discovered RemoteResourceObject");
272             return;
273         }
274
275         try {
276             mItemAdapter.getItem(position).execute();
277         } catch (RcsException e) {
278             showError(e);
279         }
280     }
281
282     public void onDiscoverResourceClick(View v) {
283         toggleDiscovery();
284     }
285
286     private void toggleDiscovery() {
287         if (mDiscoveryTask == null) {
288             try {
289                 mDiscoveryTask = RcsDiscoveryManager.getInstance()
290                         .discoverResource(RcsAddress.multicast(),
291                                 mOnResourceDiscoveredListener);
292                 mDiscoveryBtn.setText(R.string.cancel_discovery);
293
294                 mListView.setVisibility(View.INVISIBLE);
295
296                 if (mResourceObj != null) {
297                     mResourceObj.destroy();
298                     mResourceObj = null;
299                 }
300             } catch (RcsException e) {
301                 showError(e);
302             }
303         } else {
304             mDiscoveryTask.cancel();
305             mDiscoveryTask = null;
306
307             mDiscoveryBtn.setText(R.string.discover_resource);
308         }
309     }
310
311     private void printAttributes(RcsResourceAttributes attributes) {
312         try {
313             StringBuilder sb = new StringBuilder();
314             for (String key : attributes.keySet()) {
315                 sb.append(key + " : " + attributes.get(key));
316             }
317             printLog(sb.toString());
318         } catch (Exception e) {
319             printLog(e);
320         }
321     }
322
323     private void setRemoteResourceObject(
324             RcsRemoteResourceObject foundResource) {
325         if (mResourceObj != null) {
326             Log.w(LOG_TAG, "Another remote resource found...");
327             return;
328         }
329
330         mResourceObj = foundResource;
331
332         mListView.setVisibility(View.VISIBLE);
333         toggleDiscovery();
334
335         try {
336             printLog(resourceInfo(mResourceObj));
337         } catch (RcsException e) {
338             showError(e);
339         }
340     }
341
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();
347
348         dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
349                 new DialogInterface.OnClickListener() {
350                     @Override
351                     public void onClick(DialogInterface dialogInterface,
352                             int which) {
353
354                         EditText temperatureValue = (EditText) dialog
355                                 .findViewById(R.id.attributeValue);
356
357                         try {
358                             RcsValue value = new RcsValue(Integer.parseInt(
359                                     temperatureValue.getText().toString()));
360
361                             RcsResourceAttributes attrs = new RcsResourceAttributes();
362                             attrs.put(ATTR_KEY_TEMPERATURE, value);
363
364                             mResourceObj.setRemoteAttributes(attrs,
365                                     mOnRemoteAttributesReceivedListener);
366                         } catch (NumberFormatException e) {
367                             showError("Please enter the Integer Value");
368                         } catch (RcsException e) {
369                             showError(e);
370                         }
371                     }
372                 });
373         dialog.show();
374     }
375
376     private void showError(String msg) {
377         Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
378         Log.e(LOG_TAG, msg);
379     }
380
381     private void showError(Exception e) {
382         Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
383         Log.e(LOG_TAG, e.getMessage(), e);
384     }
385
386     private void printLog(String message) {
387         Log.i(LOG_TAG, message);
388         mLogView.setText(message);
389     }
390
391     private void printLog(Exception e) {
392         Log.i(LOG_TAG, e.getMessage(), e);
393         mLogView.setText(e.getMessage());
394     }
395
396     private String resourceInfo(RcsRemoteResourceObject resourceObject)
397             throws RcsException {
398         StringBuilder sb = new StringBuilder();
399
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");
404         }
405
406         for (String itf : resourceObject.getInterfaces()) {
407             sb.append("resourceInterfaces : " + itf + "\n");
408         }
409
410         sb.append("isObservable : " + resourceObject.isObservable() + "\n");
411
412         return sb.toString();
413     }
414
415     private static abstract class Item {
416         private final String mTitle;
417
418         protected Item(String title) {
419             mTitle = title;
420         }
421
422         @Override
423         public String toString() {
424             return mTitle;
425         }
426
427         public abstract void execute() throws RcsException;
428     }
429
430     private static class ClientHandler extends Handler {
431         private WeakReference<ResourceClientActivity> mActivityRef;
432
433         private ClientHandler(ResourceClientActivity activity) {
434             mActivityRef = new WeakReference<>(activity);
435         }
436
437         @Override
438         public void handleMessage(Message msg) {
439             super.handleMessage(msg);
440
441             ResourceClientActivity activity = mActivityRef.get();
442             if (activity == null) return;
443
444             switch (msg.what) {
445                 case MSG_ID_RESOURCE_DISCOVERED:
446                     activity.setRemoteResourceObject(
447                             (RcsRemoteResourceObject) msg.obj);
448                     break;
449
450                 case MSG_ID_ATTRIBUTE_RECEIVED:
451                     activity.printAttributes((RcsResourceAttributes) msg.obj);
452                     break;
453
454                 case MSG_ID_PRINT_LOG:
455                     activity.printLog(msg.obj.toString());
456                     break;
457             }
458         }
459     }
460 }