d20794e4882d84a2179078520b32e0003846f2e4
[platform/upstream/iotivity.git] / android / examples / simpleclient / src / main / java / org / iotivity / base / examples / simpleclient / SimpleClient.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.simpleclient;
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.SharedPreferences;
30 import android.content.res.AssetManager;
31 import android.os.Bundle;
32 import android.os.Message;
33 import android.preference.PreferenceManager;
34 import android.text.method.ScrollingMovementMethod;
35 import android.util.Log;
36 import android.widget.LinearLayout;
37 import android.widget.TextView;
38
39 import org.iotivity.base.ErrorCode;
40 import org.iotivity.base.ModeType;
41 import org.iotivity.base.ObserveType;
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.io.File;
53 import java.io.FileNotFoundException;
54 import java.io.FileOutputStream;
55 import java.io.IOException;
56 import java.io.InputStream;
57 import java.io.OutputStream;
58 import java.util.EnumSet;
59 import java.util.HashMap;
60 import java.util.List;
61
62 import base.iotivity.org.examples.message.IMessageLogger;
63
64 /**
65  * SimpleClient
66  * <p/>
67  * SimpleClient is a sample client app which should be started after the simpleServer is started.
68  * It finds resources advertised by the server and calls different operations on it (GET, PUT,
69  * POST and OBSERVE).
70  * This implements IMessageLogger to display messages on the screen
71  */
72 public class SimpleClient extends Activity implements OcPlatform.OnResourceFoundListener,
73         IMessageLogger {
74     private static final String TAG = "SimpleClient: ";
75
76     private static final int BUFFER_SIZE = 1024;
77     private String filePath = "";
78     private Light myLight;
79     private OcResource curResource;
80
81     //for display
82     private TextView mEventsTextView;
83     private static boolean printOnce = true;
84
85     /**
86      * configure OIC platform and call findResource
87      */
88     private void initOICStack() {
89         //create platform config
90         PlatformConfig cfg = new PlatformConfig(
91                 this,
92                 ServiceType.IN_PROC,
93                 ModeType.CLIENT_SERVER,
94                 "0.0.0.0", // bind to all available interfaces
95                 0,
96                 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
97         OcPlatform.Configure(cfg);
98         try {
99             /**
100              * find all resources
101              */
102             OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "core.light",
103                     EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
104         } catch (OcException e) {
105             logMessage(TAG + "findResource error: " + e.getMessage());
106             Log.e(TAG, e.getMessage());
107         }
108     }
109
110     @Override
111     /**
112      *  callback when a resource is found. This method calls doGetLightRepresentation to get the
113      *  current values of myLight
114      */
115     synchronized public void onResourceFound(OcResource ocResource) {
116         /**
117          *  this may potentially be called by multiple threads at the same time
118          */
119         synchronized (this) {
120             String resourceUri;
121             String hostAddress;
122             resourceUri = ocResource.getUri();
123             hostAddress = ocResource.getHost();
124             logMessage(TAG + "Discovered Resource\nUri: " + resourceUri + " \n Host: " + hostAddress);
125             // get the resource types
126             if (resourceUri.contains("light")) {
127                 curResource = ocResource;
128                 doGetLightRepresentation();
129             }
130         }
131     }
132
133     /**
134      * get myLight values after observe
135      */
136     private void doObserveLightRepresentation() {
137         // eventhandler for observe()
138         OcResource.OnObserveListener onObserveListener = new OcResource.OnObserveListener() {
139             @Override
140             public void onObserveCompleted(List<OcHeaderOption> ocHeaderOptions,
141                                            OcRepresentation ocRepresentation, int seqNum) {
142                 if (printOnce) {
143                     logMessage(TAG + "OBSERVE request was successful");
144                     printOnce = false;
145                 }
146                 try {
147                     boolean state = ocRepresentation.getValue(StringConstants.STATE);
148                     int power = ocRepresentation.getValue(StringConstants.POWER);
149                     String name = ocRepresentation.getValue(StringConstants.NAME);
150                     myLight.setState(state);
151                     myLight.setPower(power);
152                     myLight.setName(name);
153                 } catch (OcException e) {
154                     Log.e(TAG, e.getMessage());
155                 }
156                 logMessage(TAG + "onObserve: Power: " + myLight.getPower());
157                 if (seqNum > 20) {
158                     try {
159                         curResource.cancelObserve();
160                         logMessage(TAG + "Successfully cancelled observe");
161                    } catch (OcException e) {
162                         logMessage(TAG + "cancelObserve error. " + e.getMessage());
163                         Log.e(TAG, e.getMessage());
164                     }
165                 }
166
167             }
168
169             @Override
170             public void onObserveFailed(Throwable throwable) {
171                 if (throwable instanceof OcException) {
172                     OcException ocEx = (OcException) throwable;
173                     ErrorCode errCode = ocEx.getErrorCode();
174                     //do something based on errorCode
175                 }
176                 Log.e(TAG, throwable.toString());
177             }
178         };
179         try {
180             curResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), onObserveListener);
181         } catch (OcException e) {
182             logMessage(TAG + e.getMessage());
183             Log.e(TAG, e.getMessage());
184         }
185     }
186
187     /**
188      * get the current value of myLight after POST and call doObserveLightRepresentation
189      *
190      * @param ocRepresentation needed to invoke post()
191      */
192     private void doOnPost2(OcRepresentation ocRepresentation) {
193         // eventhandler for post()
194         OcResource.OnPostListener onPostListener2 = new OcResource.OnPostListener() {
195             @Override
196             public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation rep) {
197                 logMessage(TAG + "POST request was successful");
198                 String createdUri = rep.getUri();
199                 if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
200                     logMessage(TAG + "Uri of the created resource: " + createdUri);
201                 } else {
202                     try {
203                         boolean state = rep.getValue(StringConstants.STATE);
204                         int power = rep.getValue(StringConstants.POWER);
205                         String name = rep.getValue(StringConstants.NAME);
206                         myLight.setState(state);
207                         myLight.setPower(power);
208                         myLight.setName(name);
209                     } catch (OcException e) {
210                         Log.e(TAG, e.getMessage());
211                     }
212                     logMessage(TAG + "onPost\nState: " + myLight.getState() + "\nPower: " +
213                             myLight.getPower() + "\nName: " + myLight.getName());
214                 }
215                 doObserveLightRepresentation();
216             }
217
218             @Override
219             public void onPostFailed(Throwable throwable) {
220                 if (throwable instanceof OcException) {
221                     OcException ocEx = (OcException) throwable;
222                     ErrorCode errCode = ocEx.getErrorCode();
223                     //do something based on errorCode
224                 }
225                 Log.e(TAG, throwable.toString());
226             }
227         };
228         try {
229             curResource.post(ocRepresentation, new HashMap<String, String>(), onPostListener2);
230         } catch (OcException e) {
231             logMessage(TAG + e.getMessage());
232             Log.e(TAG, e.getMessage());
233         }
234     }
235
236     /**
237      * create a new resource and update its value.
238      */
239     private void doPostLightRepresentation() {
240         // eventhandler for post()
241         OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
242             @Override
243             public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
244                                         OcRepresentation ocRepresentation) {
245                 String createdUri = "";
246                 try {
247                     createdUri = ocRepresentation.getValue(StringConstants.CREATED_URI);
248                 } catch (OcException e) {
249                     Log.e(TAG, e.getMessage());
250                 }
251                 if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
252                     logMessage(TAG + "Uri of the created resource: " + createdUri);
253                 } else {
254                     boolean state = false;
255                     try {
256                         state = ocRepresentation.getValue(StringConstants.STATE);
257                         int power = ocRepresentation.getValue(StringConstants.POWER);
258                         String name = ocRepresentation.getValue(StringConstants.NAME);
259                         myLight.setState(state);
260                         myLight.setPower(power);
261                         myLight.setName(name);
262                     } catch (OcException e) {
263                         Log.e(TAG, e.getMessage());
264                     }
265                 }
266                 OcRepresentation rep = new OcRepresentation();
267                 myLight.setState(true);
268                 myLight.setPower(55);
269                 try {
270                     rep.setValue(StringConstants.POWER, myLight.getPower());
271                     rep.setValue(StringConstants.STATE, myLight.getState());
272                 } catch (OcException e) {
273                     Log.e(TAG, e.getMessage());
274                 }
275                 doOnPost2(rep);
276             }
277
278             @Override
279             public void onPostFailed(Throwable throwable) {
280                 if (throwable instanceof OcException) {
281                     OcException ocEx = (OcException) throwable;
282                     ErrorCode errCode = ocEx.getErrorCode();
283                     //do something based on errorCode
284                 }
285                 Log.e(TAG, throwable.toString());
286             }
287         };
288
289         OcRepresentation rep = new OcRepresentation();
290         myLight.setState(false);
291         myLight.setPower(105);
292         try {
293             rep.setValue(StringConstants.STATE, myLight.getState());
294             rep.setValue(StringConstants.POWER, myLight.getPower());
295         } catch (OcException e) {
296             Log.e(TAG, e.getMessage());
297         }
298         try {
299             curResource.post(rep, new HashMap<String, String>(), onPostListener);
300         } catch (OcException e) {
301             logMessage(TAG + e.getMessage());
302             Log.e(TAG, e.getMessage());
303         }
304     }
305
306     /**
307      * modify the current value of myLight and call doPostLightRepresentation
308      */
309     private void doPutLightRepresentation() {
310         // eventhandler for put()
311         OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
312             @Override
313             public void onPutCompleted(List<OcHeaderOption> ocHeaderOptions,
314                                        OcRepresentation ocRepresentation) {
315                 logMessage(TAG + "PUT resource was successful");
316                 try {
317                     boolean state = ocRepresentation.getValue(StringConstants.STATE);
318                     int power = ocRepresentation.getValue(StringConstants.POWER);
319                     String name = ocRepresentation.getValue(StringConstants.NAME);
320                     myLight.setState(state);
321                     myLight.setPower(power);
322                     myLight.setName(name);
323                 } catch (OcException e) {
324                     Log.e(TAG, e.getMessage());
325                 }
326
327                 logMessage(TAG + "onPutCompleted:\nState:" + myLight.getState() + "\nPower: " +
328                         myLight.getPower() + "\nName: " + myLight.getName());
329                 doPostLightRepresentation();
330             }
331
332             @Override
333             public void onPutFailed(Throwable throwable) {
334
335                 if (throwable instanceof OcException) {
336                     OcException ocEx = (OcException) throwable;
337                     ErrorCode errCode = ocEx.getErrorCode();
338                     //do something based on errorCode
339                 }
340                 Log.e(TAG, throwable.toString());
341             }
342         };
343
344         OcRepresentation rep = new OcRepresentation();
345         Log.d(TAG, "myLight settings: power = 15");
346         myLight.setState(true);
347         myLight.setPower(15);
348         try {
349             rep.setValue(StringConstants.STATE, myLight.getState());
350             rep.setValue(StringConstants.POWER, myLight.getPower());
351             rep.setValue(StringConstants.NAME, myLight.getName());
352         } catch (OcException e) {
353             Log.e(TAG, e.getMessage());
354         }
355         try {
356             Log.d(TAG, "before calling put");
357             curResource.put(rep, new HashMap<String, String>(), onPutListener);
358         } catch (OcException e) {
359             logMessage(TAG + e.getMessage());
360             Log.e(TAG, e.getMessage());
361         }
362         Log.d(TAG, "end of put call");
363     }
364
365     /**
366      * get the existing value of myLight and call doPutLightRepresentation() to modify the current values
367      */
368     private void doGetLightRepresentation() {
369         // eventhandler for get()
370         OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
371             @Override
372             public void onGetCompleted(List<OcHeaderOption> headerOptionList,
373                                        OcRepresentation ocRepresentation) {
374                 logMessage(TAG + "GET resource was successful " + StringConstants.STATE);
375                 try {
376                     boolean state = ocRepresentation.getValue(StringConstants.STATE);
377                     int power = ocRepresentation.getValue(StringConstants.POWER);
378                     String name = ocRepresentation.getValue(StringConstants.NAME);
379                     myLight.setState(state);
380                     myLight.setPower(power);
381                     myLight.setName(name);
382                 } catch (OcException e) {
383                     Log.e(TAG, e.getMessage());
384                 }
385                 logMessage(TAG + "onGetCompleted\nState: " + myLight.getState() + "\nPower: " +
386                         myLight.getPower() + "\nName: " + myLight.getName());
387                 doPutLightRepresentation();
388             }
389
390             @Override
391             public void onGetFailed(Throwable throwable) {
392                 if (throwable instanceof OcException) {
393                     OcException ocEx = (OcException) throwable;
394                     ErrorCode errCode = ocEx.getErrorCode();
395                     //do something based on errorCode
396                 }
397                 Log.e(TAG, throwable.toString());
398             }
399         };
400
401         try {
402             curResource.get(new HashMap<String, String>(), onGetListener);
403         } catch (OcException e) {
404             logMessage(TAG + e.getMessage());
405             Log.e(TAG, e.getMessage());
406         }
407     }
408
409     /**
410      * to display on SimpleClient screen
411      */
412     public class MessageReceiver extends BroadcastReceiver {
413         @Override
414         public void onReceive(Context context, Intent intent) {
415             final String message = intent.getStringExtra(StringConstants.MESSAGE);
416             logMessage(message);
417         }
418     }
419
420     @Override
421     protected void onCreate(Bundle savedInstanceState) {
422         super.onCreate(savedInstanceState);
423         setContentView(R.layout.activity_main);
424         mEventsTextView = new TextView(this);
425         mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
426         LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
427         layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
428                 LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
429         );
430         myLight = new Light();
431         filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
432         //copy json when application runs first time
433         SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
434         boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
435         if (isFirstRun) {
436             copyJsonFromAsset();
437             SharedPreferences.Editor editor = wmbPreference.edit();
438             editor.putBoolean("FIRSTRUN", false);
439             editor.commit();
440         }
441
442
443         initOICStack();
444     }
445 /**
446      * Copy svr db json file from assets folder to app data files dir
447      */
448     private void copyJsonFromAsset() {
449         AssetManager assetManager = getAssets();
450         InputStream in = null;
451         OutputStream out = null;
452         try {
453             in = assetManager.open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
454             File file = new File(filePath);
455             //check files directory exists
456             if (!(file.exists() && file.isDirectory())) {
457                 file.mkdirs();
458             }
459             out = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
460             copyFile(in, out);
461         } catch (NullPointerException e) {
462             logMessage(TAG + "Null pointer exception " + e.getMessage());
463             Log.e(TAG, e.getMessage());
464         } catch (FileNotFoundException e) {
465             logMessage(TAG + "Json svr db file not found " + e.getMessage());
466             Log.e(TAG, e.getMessage());
467         } catch (IOException e) {
468             logMessage(TAG + StringConstants.OIC_CLIENT_JSON_DB_FILE+ " file copy failed");
469             Log.e(TAG, e.getMessage());
470         } finally {
471             if (in != null) {
472                 try {
473                     in.close();
474                 } catch (IOException e) {
475                     Log.e(TAG, e.getMessage());
476                 }
477             }
478             if (out != null) {
479                 try {
480                     out.close();
481                 } catch (IOException e) {
482                     Log.e(TAG, e.getMessage());
483                 }
484             }
485         }
486     }
487
488     private void copyFile(InputStream in, OutputStream out) throws IOException {
489         byte[] buffer = new byte[BUFFER_SIZE];
490         int read;
491         while ((read = in.read(buffer)) != -1) {
492             out.write(buffer, 0, read);
493         }
494     }
495     @Override
496     public void logMessage(String text) {
497         logMsg(text);
498     }
499
500     public void logMsg(final String text) {
501         runOnUiThread(new Runnable() {
502             public void run() {
503                 Message msg = new Message();
504                 msg.obj = text;
505                 mEventsTextView.append("\n");
506                 mEventsTextView.append(text);
507             }
508         });
509         Log.i(TAG, text);
510         //to print on SimpleServer screen
511         Intent intent = new Intent("org.iotivity.base.examples.simpleclient");
512         intent.putExtra(StringConstants.MESSAGE, text);
513         sendBroadcast(intent);
514     }
515 }