Imported Upstream version 1.1.1
[platform/upstream/iotivity.git] / android / examples / DirectPairing / src / main / java / org / iotivity / base / examples / DirectPairing / MainActivity.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
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 package org.iotivity.base.examples.DirectPairing;
23
24 import android.app.Activity;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.content.DialogInterface;
28 import android.content.SharedPreferences;
29 import android.graphics.Color;
30 import android.os.AsyncTask;
31 import android.os.Bundle;
32 import android.os.Environment;
33 import android.preference.PreferenceManager;
34 import android.text.InputFilter;
35 import android.util.Log;
36 import android.view.View;
37 import android.widget.AdapterView;
38 import android.widget.AdapterView.OnItemClickListener;
39 import android.widget.ArrayAdapter;
40 import android.widget.Button;
41 import android.widget.CompoundButton;
42 import android.widget.EditText;
43 import android.widget.ExpandableListView;
44 import android.widget.ExpandableListView.OnGroupExpandListener;
45 import android.widget.LinearLayout;
46 import android.widget.ListView;
47 import android.widget.Switch;
48 import android.widget.Toast;
49
50 import org.iotivity.base.ModeType;
51 import org.iotivity.base.OcDirectPairDevice;
52 import org.iotivity.base.OcException;
53 import org.iotivity.base.OcHeaderOption;
54 import org.iotivity.base.OcPlatform;
55 import org.iotivity.base.OcPrmType;
56 import org.iotivity.base.OcProvisioning;
57 import org.iotivity.base.OcRepresentation;
58 import org.iotivity.base.OcResource;
59 import org.iotivity.base.PlatformConfig;
60 import org.iotivity.base.QualityOfService;
61 import org.iotivity.base.ServiceType;
62 import org.iotivity.base.examples.DirectPairing.Led;
63
64 import java.io.File;
65 import java.io.FileInputStream;
66 import java.io.FileNotFoundException;
67 import java.io.FileOutputStream;
68 import java.io.IOException;
69 import java.io.InputStream;
70 import java.io.OutputStream;
71 import java.nio.channels.FileChannel;
72 import java.util.ArrayList;
73 import java.util.HashMap;
74 import java.util.Iterator;
75 import java.util.LinkedList;
76 import java.util.List;
77
78 public class MainActivity extends Activity {
79     private static final int BUFFER_SIZE = 1024;
80     private static final String TAG = "DirectPairing: ";
81     private static int selected = -1;
82     private int[] pList;
83     private Button save;
84     private int prmType;
85     private EditText pinText;
86     private Led ledResource;
87     private ListView mListView;
88     private String filePath = "";
89     private OcResource led = null;
90     private Switch discoverButton;
91     private List<String> resourceInterfaces;
92     private ArrayAdapter<String> arrayAdapter;
93     private List<Object> onGetResponseList;
94     private ExpandableListAdapter exlistAdapter;
95     OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
96         @Override
97         public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
98                                                 OcRepresentation ocRepresentation) {
99             onGetResponseList = new ArrayList<Object>();
100             ledResource.setState(ocRepresentation.getValueBool("state"));
101             ledResource.setPower(ocRepresentation.getValueInt("power"));
102             ledResource.setUri(ocRepresentation.getUri());
103             runOnUiThread(new Runnable() {
104                 public void run() {
105                     onGetResponseList.add(ledResource);
106                     exlistAdapter.notifyDataSetChanged();
107                 }
108             });
109
110             Log.d(TAG, "Got a response from " + ocRepresentation.getUri() +
111                     " " + ocRepresentation.getValueBool("state") + " "
112                     + ocRepresentation.getValueInt("power") + " " +
113                     ocRepresentation.getValueString("name"));
114         }
115
116         @Override
117         public synchronized void onGetFailed(Throwable throwable) {
118             Log.d(TAG, "GET request has failed");
119             Log.e(TAG, throwable.toString());
120         }
121     };
122     private ExpandableListView mPairedListDisplay;
123     private ArrayAdapter<OcDirectPairDevice> adapter;
124     private List<String> pairedList;
125     private List<OcDirectPairDevice> discoveredListObj;
126     OcPlatform.DirectPairingListener doDPListener = new OcPlatform.DirectPairingListener() {
127         @Override
128         public void onDirectPairingListener(String devId, int result) {
129             Log.d(TAG, "Inside getDPListener");
130             if (result == StringConstants.SUCCES_CODE) {
131                 pairedList.clear();
132                 pairedList.add(devId);
133                 onGetResponseList.add(new Led());
134                 runOnUiThread(new Runnable() {
135                     public void run() {
136                         mPairedListDisplay.setAdapter(exlistAdapter);
137                         int pos = mListView.getCheckedItemPosition();
138                         if (pos != ListView.INVALID_POSITION && discoveredListObj.size() != 0) {
139                             discoveredListObj.remove(pos);
140                             adapter.notifyDataSetChanged();
141                         }
142                     }
143                 });
144                 Log.d(TAG, "direct pair successfull for " + devId);
145             } else {
146                 Log.d(TAG, "direct pairing failed");
147                 runOnUiThread(new Runnable() {
148                     public void run() {
149                         Toast.makeText(getApplicationContext(),
150                                 "Direct Pairing Failed", Toast.LENGTH_SHORT).show();
151                     }
152                 });
153             }
154             exportCBOR();
155         }
156     };
157     private List<OcDirectPairDevice> discoveredPairableDevices;
158     OcPlatform.FindDirectPairingListener finddirectPairing =
159             new OcPlatform.FindDirectPairingListener() {
160                 @Override
161                 public void onFindDirectPairingListener(List<OcDirectPairDevice> direcPairingDevice) {
162                     Log.d(TAG, "find direct pairable successfull ");
163                     discoveredListObj.clear();
164                     discoveredPairableDevices =
165                             new ArrayList<OcDirectPairDevice>(direcPairingDevice);
166                     for (int i = 0; i < direcPairingDevice.size(); i++) {
167                         OcDirectPairDevice dpPairDevice = direcPairingDevice.get(i);
168                         Log.d(TAG, "getHost from Find Direct Pairing " + dpPairDevice.getHost());
169                         discoveredListObj.add(dpPairDevice);
170                     }
171
172                     runOnUiThread(new Runnable() {
173                         public void run() {
174                             mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
175                             mListView.setAdapter(adapter);
176                             discoverButton.setChecked(false);
177                         }
178                     });
179                 }
180             };
181
182     @Override
183     protected void onCreate(Bundle savedInstanceState) {
184         super.onCreate(savedInstanceState);
185         setContentView(R.layout.activity_main);
186
187         onGetResponseList = new ArrayList<Object>();
188         discoveredListObj = new ArrayList<OcDirectPairDevice>();
189         pairedList = new ArrayList<String>();
190
191         ledResource = new Led();
192
193         mListView = (ListView) findViewById(R.id.list_view);
194         discoverButton = (Switch) findViewById(R.id.discover);
195         mPairedListDisplay = (ExpandableListView) findViewById(R.id.list_view_paired_list);
196
197
198         filePath = getFilesDir().getPath() + "/"; //  data/data/<package>/files/
199         //copy CBOR file when application runs first time
200         SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
201         boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
202         if (isFirstRun) {
203             copyCborFromAsset();
204             SharedPreferences.Editor editor = wmbPreference.edit();
205             editor.putBoolean("FIRSTRUN", false);
206             editor.commit();
207         }
208
209         initOICStack();
210
211         adapter = new ArrayAdapter<OcDirectPairDevice>(this,
212                 android.R.layout.simple_list_item_single_choice,
213                 discoveredListObj);
214
215         arrayAdapter = new ArrayAdapter<String>(
216                 MainActivity.this,
217                 android.R.layout.select_dialog_singlechoice);
218
219         save = (Button) findViewById(R.id.saveDiscovered);
220
221         save.setEnabled(false);
222         save.setBackgroundColor(Color.GRAY);
223
224         resourceInterfaces = new LinkedList<>();
225         resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
226
227         exlistAdapter = new ExpandableListAdapter(pairedList, onGetResponseList,
228                 MainActivity.this);
229         mPairedListDisplay.setAdapter(exlistAdapter);
230
231         // to expand only a single group item.
232         mPairedListDisplay.setOnGroupExpandListener(new OnGroupExpandListener() {
233             int previousGroup = -1;
234
235             @Override
236             public void onGroupExpand(int groupPosition) {
237                 Log.d(TAG, "Calling GET api on mResource");
238                 try {
239                     if (null != led) led.get(new HashMap<String, String>(), onGetListener);
240                 } catch (OcException e) {
241                     Log.d(TAG, "Error in GET calls");
242                     Log.e(TAG, e.getMessage());
243                 }
244
245                 if (groupPosition != previousGroup)
246                     mPairedListDisplay.collapseGroup(previousGroup);
247
248                 previousGroup = groupPosition;
249             }
250         });
251
252         save.setOnClickListener(new View.OnClickListener() {
253
254             @Override
255             public void onClick(View v) {
256
257                 AlertDialog.Builder alertPinDialog =
258                         new AlertDialog.Builder(MainActivity.this);
259                 alertPinDialog.setTitle("PIN");
260                 alertPinDialog.setMessage("Enter Pin");
261
262                 pinText = new EditText(MainActivity.this);
263                 int maxLength = 8;
264                 InputFilter[] fArray = new InputFilter[1];
265                 fArray[0] = new InputFilter.LengthFilter(maxLength);
266                 pinText.setFilters(fArray);
267                 pinText.setMaxLines(1);
268                 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
269                         LinearLayout.LayoutParams.MATCH_PARENT,
270                         LinearLayout.LayoutParams.MATCH_PARENT);
271                 pinText.setLayoutParams(lp);
272                 alertPinDialog.setView(pinText);
273                 alertPinDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
274                     public void onClick(DialogInterface dialog, int which) {
275                         selected = -1;
276                         final AlertDialog alertPrmTypeDialog = new AlertDialog.Builder
277                                 (MainActivity.this)
278                                 .setSingleChoiceItems(arrayAdapter, -1,
279                                         new DialogInterface.OnClickListener() {
280                                             @Override
281                                             public void onClick(DialogInterface dialog, int which) {
282                                                 selected = which;
283                                                 prmType = pList[which];
284                                                 Log.d(TAG, " prmType " + prmType);
285                                             }
286                                         })
287                                 .setTitle("Select Direct Pair Method")
288                                 .setPositiveButton("OK", null)
289                                 .setNegativeButton("CANCEL", null)
290                                 .create();
291
292                         alertPrmTypeDialog.setOnShowListener(
293                                 new DialogInterface.OnShowListener() {
294                                     @Override
295                                     public void onShow(DialogInterface dialog) {
296                                         Button ok =
297                                                 alertPrmTypeDialog
298                                                         .getButton(AlertDialog.BUTTON_POSITIVE);
299
300                                         Button cancel =
301                                                 alertPrmTypeDialog
302                                                         .getButton(AlertDialog.BUTTON_NEGATIVE);
303
304                                         ok.setOnClickListener(new View.OnClickListener() {
305                                             @Override
306                                             public void onClick(View view) {
307                                                 int pos = mListView.getCheckedItemPosition();
308                                                 if (selected == -1) {
309                                                     Toast.makeText(getApplicationContext(),
310                                                             "Please Select A Value",
311                                                             Toast.LENGTH_SHORT).show();
312                                                 } else if (pos != ListView.INVALID_POSITION) {
313                                                     if (!discoveredListObj.isEmpty()) {
314                                                         try {
315                                                             OcDirectPairDevice peer =
316                                                                     (OcDirectPairDevice)
317                                                                             discoveredListObj.
318                                                                                     get(pos);
319                                                             OcPlatform.doDirectPairing(peer,
320                                                                     OcPrmType.convertOcPrmType(prmType),
321                                                                     pinText.getText().toString(),
322                                                                     doDPListener);
323                                                         } catch (OcException e) {
324                                                             Log.d(TAG, "do Direct Pairing error: "
325                                                                     + e.getMessage());
326                                                             Log.e(TAG, e.getMessage());
327                                                         }
328
329                                                         alertPrmTypeDialog.dismiss();
330                                                     } else {
331                                                         alertPrmTypeDialog.dismiss();
332                                                     }
333                                                 }
334                                             }
335                                         });
336
337                                         cancel.setOnClickListener(new View.OnClickListener() {
338                                             @Override
339                                             public void onClick(View view) {
340                                                 alertPrmTypeDialog.dismiss();
341                                             }
342                                         });
343                                     }
344                                 });
345
346                         alertPrmTypeDialog.show();
347                     }
348                 });
349                 alertPinDialog.show();
350             }
351         });
352
353         mListView.setOnItemClickListener(new OnItemClickListener() {
354             @Override
355             public void onItemClick(AdapterView adapt, View view, int position, long itemId) {
356                 save.setEnabled(true);
357                 save.setBackgroundColor(Color.parseColor("#13AEF4"));
358                 OcDirectPairDevice dpPairDevice =
359                         (OcDirectPairDevice) adapt.getItemAtPosition(position);
360                 Log.d(TAG, "DevId On List Item Clicked " + dpPairDevice.getDevId());
361                 List<Integer> pTypeList = dpPairDevice.getPairingMethodList();
362                 pList = new int[pTypeList.size()];
363                         Iterator<Integer> iterator = pTypeList.iterator();
364                         for(int k = 0; k < pList.length; k++){
365                             pList[k]=iterator.next().intValue();
366                         }
367                 arrayAdapter.clear();
368                 for (int j = 0; j < pList.length; j++) {
369                     Log.d(TAG, " List Item Value " + pList[j]);
370                     OcPrmType prmTy = OcPrmType.convertOcPrmType(pList[j]);
371                     arrayAdapter.add(prmTy.name());
372                 }
373             }
374         });
375
376         discoverButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
377             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
378                 if (isChecked) {
379                     save.setEnabled(false);
380                     save.setBackgroundColor(Color.GRAY);
381                     new GetDiscoveredItems().execute();
382                 }
383             }
384         });
385
386     }
387
388     /**
389      * Copy svr db CBOR dat file from assets folder to app data files dir
390      */
391     private void copyCborFromAsset() {
392         InputStream inputStream = null;
393         OutputStream outputStream = null;
394         int length;
395         byte[] buffer = new byte[BUFFER_SIZE];
396         try {
397             inputStream = getAssets().open(StringConstants.OIC_CLIENT_CBOR_DB_FILE);
398             File file = new File(filePath);
399             //check files directory exists
400             if (!(file.exists() && file.isDirectory())) {
401                 file.mkdirs();
402             }
403             outputStream = new FileOutputStream(filePath +
404                     StringConstants.OIC_CLIENT_CBOR_DB_FILE);
405             while ((length = inputStream.read(buffer)) != -1) {
406                 outputStream.write(buffer, 0, length);
407             }
408         } catch (NullPointerException e) {
409             Log.d(TAG, "Null pointer exception " + e.getMessage());
410             Log.e(TAG, e.getMessage());
411         } catch (FileNotFoundException e) {
412             Log.d(TAG, "CBOR svr db file not found " + e.getMessage());
413             Log.e(TAG, e.getMessage());
414         } catch (IOException e) {
415             Log.d(TAG, StringConstants.OIC_CLIENT_CBOR_DB_FILE + " file copy failed");
416             Log.e(TAG, e.getMessage());
417         } finally {
418             if (inputStream != null) {
419                 try {
420                     inputStream.close();
421                 } catch (IOException e) {
422                     Log.e(TAG, e.getMessage());
423                 }
424             }
425             if (outputStream != null) {
426                 try {
427                     outputStream.close();
428                 } catch (IOException e) {
429                     Log.e(TAG, e.getMessage());
430                 }
431             }
432         }
433     }
434
435     void exportCBOR() {
436         try {
437             File sd = Environment.getExternalStorageDirectory();
438             File data = Environment.getDataDirectory();
439             if (sd.canWrite()) {
440                 String currentDBPath = "/data/data/" + getPackageName() +
441                         "/files/" + StringConstants.OIC_CLIENT_CBOR_DB_FILE;
442                 File currentDB = new File(currentDBPath);
443                 File backupDB = new File(sd, StringConstants.OIC_CLIENT_CBOR_DB_FILE);
444                 if (currentDB.exists()) {
445                     FileChannel src = new FileInputStream(currentDB).getChannel();
446                     FileChannel dst = new FileOutputStream(backupDB).getChannel();
447                     dst.transferFrom(src, 0, src.size());
448                     src.close();
449                     dst.close();
450                 }
451             }
452         } catch (Exception e) {
453             Log.e(TAG, e.getMessage());
454         }
455     }
456
457     /**
458      * configure OIC platform and call findResource
459      */
460     private void initOICStack() {
461         //create platform config
462         PlatformConfig cfg = new PlatformConfig(this, ServiceType.IN_PROC, ModeType.CLIENT_SERVER,
463                 "0.0.0.0", // bind to all available interfaces
464                 0,
465                 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
466         OcPlatform.Configure(cfg);
467         try {
468             /*
469              * Initialize DataBase
470              */
471             String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
472                     File.separator;
473             File file = new File(sqlDbPath);
474             //check files directory exists
475             if (!(file.isDirectory())) {
476                 file.mkdirs();
477                 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
478             }
479             Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
480             OcProvisioning.provisionInit(sqlDbPath + StringConstants.OIC_SQL_DB_FILE);
481         } catch (OcException e) {
482             Log.d(TAG, "provisionInit error: " + e.getMessage());
483             Log.e(TAG, e.getMessage());
484         }
485     }
486
487     class GetDiscoveredItems extends AsyncTask<Void, Void, List<String>> {
488
489         ProgressDialog pDialog;
490
491         @Override
492         protected void onPreExecute() {
493             pDialog = new ProgressDialog(MainActivity.this);
494             pDialog.setMessage("Getting Discovered Items");
495             pDialog.setCancelable(false);
496             pDialog.setCanceledOnTouchOutside(false);
497             pDialog.show();
498         }
499
500         ;
501
502         @Override
503         protected List<String> doInBackground(Void... params) {
504             try {
505                 OcPlatform.findDirectPairingDevices(5, finddirectPairing);
506             } catch (OcException e) {
507                 Log.e(TAG, e.getMessage());
508             }
509             return null;
510         }
511
512         @Override
513         protected void onPostExecute(List<String> discoveredItems) {
514             pDialog.dismiss();
515             for (Iterator iterator = discoveredListObj.iterator(); iterator.hasNext(); ) {
516                 OcDirectPairDevice ledResource = (OcDirectPairDevice) iterator.next();
517                 List<String> lightTypes = new LinkedList<>();
518                 lightTypes.add("core.led");
519                 try {
520                     Log.d(TAG, "Constructing Led Resource");
521                     led = OcPlatform.constructResourceObject(ledResource.getHost(),
522                             "/a/led", ledResource.getConnectivityTypeSet(),
523                             false, //isObservable
524                             lightTypes,
525                             resourceInterfaces);
526                     Log.d(TAG, "Constructed Led Resource");
527                 } catch (OcException e) {
528                     Log.e(TAG, e.getMessage());
529                 }
530             }
531         }
532
533     }
534 }