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