Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / android / examples / fridgeclient / src / main / java / org / iotivity / base / examples / fridgeclient / FridgeClient.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2015 Intel Corporation.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.base.examples.fridgeclient;
24
25 import android.app.Activity;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.os.Bundle;
31 import android.os.Message;
32 import android.support.v4.content.LocalBroadcastManager;
33 import android.text.method.ScrollingMovementMethod;
34 import android.util.Log;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.widget.LinearLayout;
38 import android.widget.TextView;
39
40 import org.iotivity.base.ErrorCode;
41 import org.iotivity.base.ModeType;
42 import org.iotivity.base.OcConnectivityType;
43 import org.iotivity.base.OcException;
44 import org.iotivity.base.OcHeaderOption;
45 import org.iotivity.base.OcPlatform;
46 import org.iotivity.base.OcRepresentation;
47 import org.iotivity.base.OcResource;
48 import org.iotivity.base.PlatformConfig;
49 import org.iotivity.base.QualityOfService;
50 import org.iotivity.base.ServiceType;
51
52 import java.util.EnumSet;
53 import java.util.HashMap;
54 import java.util.LinkedList;
55 import java.util.List;
56
57 import base.iotivity.org.examples.message.IMessageLogger;
58
59 /**
60  * FridgeClient
61  * <p/>
62  * FridgeClient is a sample client app which should be started after the fridgeServer is started.
63  * It creates DeviceResource, DoorResource, LightResource and performs a get operation on them.
64  * This implements IMessageLogger to display messages on the screen
65  */
66 public class FridgeClient extends Activity implements
67         OcPlatform.OnResourceFoundListener, IMessageLogger {
68     private static String TAG = "FridgeClient: ";
69
70     private MessageReceiver mMessageReceiver = new MessageReceiver();
71     private TextView mEventsTextView;
72     private String mDeviceName;
73     private int mDeviceCode;
74     private List<String> ifaces;
75     private final List<OcResource> resourceList = new LinkedList<OcResource>();
76
77     /**
78      * configure OIC platform and call findResource
79      */
80     private void initOICStack() {
81         PlatformConfig cfg = new PlatformConfig(
82                 this,
83                 ServiceType.IN_PROC,
84                 ModeType.CLIENT,
85                 "0.0.0.0", // bind to all available interfaces
86                 0,
87                 QualityOfService.LOW);
88
89         OcPlatform.Configure(cfg);
90         try {
91             OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
92                     EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
93         } catch (OcException e) {
94             logMessage(TAG + " init Error. " + e.getMessage());
95             Log.e(TAG, e.getMessage());
96         }
97     }
98
99     /**
100      * prints out the appropriate messages depending on the device code
101      *
102      * @param representation representation of the OcResource
103      * @param value          clientDeviceCode
104      */
105     private void getResponse(OcRepresentation representation, int value) {
106         switch (value) {
107             case 0:
108                 // Get on device
109                 try {
110                     logMessage(TAG + "Name of device: " +
111                             representation.getValue(StringConstants.DEVICE_NAME));
112                 } catch (OcException e) {
113                     Log.e(TAG, e.getMessage());
114                 }
115                 break;
116             case 1:
117                 // get on fridge light
118                 try {
119                     boolean lightOn = representation.getValue(StringConstants.ON);
120                     logMessage(TAG + "The fridge light is " +
121                             (lightOn ? "" : "not " + "on"));
122                 } catch (OcException e) {
123                     Log.e(TAG, e.getMessage());
124                 }
125                 break;
126             case 2:
127             case 3:
128                 // get on fridge door(s)
129                 try {
130                     boolean doorOpen = representation.getValue(StringConstants.OPEN);
131                     logMessage(TAG + "Door is " + (doorOpen ?
132                             "open" : "not open") + " and is on the " +
133                             representation.getValue(StringConstants.SIDE) + " side");
134                 } catch (OcException e) {
135                     Log.e(TAG, e.getMessage());
136                 }
137                 break;
138             case 4:
139                 // get on fridge random door
140                 try {
141                     logMessage("Name of fridge: " +
142                             representation.getValue(StringConstants.DEVICE_NAME));
143                 } catch (OcException e) {
144                     Log.e(TAG, e.getMessage());
145                 }
146                 break;
147             default:
148                 logMessage("Unexpected State");
149                 break;
150         }
151     }
152
153     /**
154      * this method is used to wait for 1 second between calls to different resources.
155      * It is added for better readability
156      */
157     private void doWait() {
158         try {
159             Thread.sleep(StringConstants.WAIT_TIME);
160         } catch (InterruptedException e) {
161             logMessage(TAG + "doWait exception: " + e.getMessage());
162             Log.e(TAG, e.getMessage());
163         }
164     }
165
166     @Override
167     /**
168      *  callback when a resource is found. This method calls getResponse with the correct code
169      */
170     synchronized public void onResourceFound(OcResource ocResource) {
171         // eventHandler for onGetListener
172         resourceList.add(ocResource);
173         OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
174             @Override
175             public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation rep) {
176                 logMessage(TAG + " Got a response from " + getClientDeviceName());
177                 getResponse(rep, getClientDeviceCode());
178             }
179
180             @Override
181             public void onGetFailed(Throwable throwable) {
182                 if (throwable instanceof OcException) {
183                     OcException ocEx = (OcException) throwable;
184                     ErrorCode errCode = ocEx.getErrorCode();
185                     //do something based on errorCode
186                 }
187                 Log.e(TAG, throwable.toString());
188             }
189         };
190
191         if (ocResource.getUri().equals(StringConstants.RESOURCE_URI)) {
192             logMessage(TAG + "Discovered a device with \nHost: " + ocResource.getHost() +
193                     ", Uri: " + ocResource.getUri());
194         }
195         List<String> lightTypes = new LinkedList<>();
196         lightTypes.add("intel.fridge.light");
197         try {
198             OcResource light = OcPlatform.constructResourceObject(ocResource.getHost(),
199                     StringConstants.LIGHT, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, lightTypes, ifaces);
200
201             List<String> doorTypes = new LinkedList<>();
202             doorTypes.add("intel.fridge.door");
203             OcResource leftDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
204                     StringConstants.LEFT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
205
206             OcResource rightDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
207                     StringConstants.RIGHT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
208
209             OcResource randomDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
210                     StringConstants.RANDOM_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
211
212             List<OcHeaderOption> headerOptions = new LinkedList<>();
213             OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,
214                     StringConstants.API_VERSION);
215             OcHeaderOption clientToken = new OcHeaderOption(StringConstants.CLIENT_TOKEN_KEY,
216                     StringConstants.CLIENT_TOKEN);
217             headerOptions.add(apiVersion);
218             headerOptions.add(clientToken);
219             ocResource.setHeaderOptions(headerOptions);
220             /**
221              *  wait for 1 second before calling get on different resources.
222              *  It is done for better readability.
223              *  doWait() is called before each call to get
224              */
225             doWait();
226
227             setupClientOptions("Device", 0);
228             ocResource.get(new HashMap<String, String>(), onGetListener);
229             doWait();
230
231             setupClientOptions("Fridge Light", 1);
232             light.get(new HashMap<String, String>(), onGetListener);
233             doWait();
234
235             setupClientOptions("Left Door", 2);
236             leftDoor.get(new HashMap<String, String>(), onGetListener);
237             doWait();
238
239             setupClientOptions("Right Door", 3);
240             rightDoor.get(new HashMap<String, String>(), onGetListener);
241             doWait();
242
243             setupClientOptions("Random Door", 4);
244             randomDoor.get(new HashMap<String, String>(), onGetListener);
245             doWait();
246
247             resourceList.add(leftDoor);
248             leftDoor.deleteResource(new OcResource.OnDeleteListener() {
249                 @Override
250                 public void onDeleteCompleted(List<OcHeaderOption> ocHeaderOptions) {
251                     logMessage(TAG + "Delete resource successful");
252                 }
253
254                 @Override
255                 public void onDeleteFailed(Throwable throwable) {
256                     if (throwable instanceof OcException) {
257                         OcException ocEx = (OcException) throwable;
258                         ErrorCode errCode = ocEx.getErrorCode();
259                         //do something based on errorCode
260                     }
261                     Log.e(TAG, throwable.toString());
262                 }
263             });
264         } catch (OcException e) {
265             logMessage(TAG + "onResourceFound Error. " + e.getMessage());
266             Log.e(TAG, e.getMessage());
267         }
268     }
269
270     @Override
271     protected void onCreate(Bundle savedInstanceState) {
272         super.onCreate(savedInstanceState);
273         setContentView(R.layout.activity_fridge_client);
274         registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));
275
276         mEventsTextView = new TextView(this);
277         mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
278         LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
279         layout.addView(mEventsTextView, new LinearLayout.LayoutParams
280                 (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
281         ifaces = new LinkedList<>();
282         ifaces.add(StringConstants.RESOURCE_INTERFACE);
283         mDeviceCode = -1;
284         mDeviceName = "";
285
286         initOICStack();
287     }
288
289     public class MessageReceiver extends BroadcastReceiver {
290         @Override
291         public void onReceive(Context context, Intent intent) {
292             final String message = intent.getStringExtra(StringConstants.MESSAGE);
293             logMessage(message);
294         }
295     }
296
297     @Override
298     public void logMessage(final String text) {
299         if (StringConstants.ENABLE_PRINTING) {
300             runOnUiThread(new Runnable() {
301                 public void run() {
302                     final Message msg = new Message();
303                     msg.obj = text;
304                     mEventsTextView.append("\n");
305                     mEventsTextView.append(text);
306                 }
307             });
308             Log.i(TAG, text);
309         }
310     }
311
312
313     private void setupClientOptions(String name, int value) {
314         mDeviceName = name;
315         mDeviceCode = value;
316     }
317
318     private String getClientDeviceName() {
319         return mDeviceName;
320     }
321
322     private int getClientDeviceCode() {
323         return mDeviceCode;
324     }
325
326
327     //method to print the headerOptions received from the server
328     void printHeaderOptions(List<OcHeaderOption> headerOptions) {
329         for (OcHeaderOption headerOption : headerOptions) {
330             if (StringConstants.API_VERSION_KEY == headerOption.getOptionId()) {
331                 logMessage(TAG + "Server API version in GET response: " +
332                         headerOption.getOptionData());
333             }
334         }
335     }
336
337     @Override
338     public boolean onCreateOptionsMenu(Menu menu) {
339         getMenuInflater().inflate(R.menu.menu_fridge_client, menu);
340         return true;
341     }
342
343     @Override
344     public boolean onOptionsItemSelected(MenuItem item) {
345         int id = item.getItemId();
346         if (id == R.id.action_settings) {
347             return true;
348         }
349         return super.onOptionsItemSelected(item);
350     }
351
352     @Override
353     public void onDestroy() {
354         super.onDestroy();
355         onStop();
356     }
357
358     @Override
359     protected void onStop() {
360         LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
361         super.onStop();
362     }
363 }