2 * //******************************************************************
4 * // Copyright 2016 Samsung Electronics All Rights Reserved.
6 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
12 * // http://www.apache.org/licenses/LICENSE-2.0
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.
20 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 package org.iotivity.base.examples.DirectPairing;
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;
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;
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;
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;
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() {
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() {
105 onGetResponseList.add(ledResource);
106 exlistAdapter.notifyDataSetChanged();
110 Log.d(TAG, "Got a response from " + ocRepresentation.getUri() +
111 " " + ocRepresentation.getValueBool("state") + " "
112 + ocRepresentation.getValueInt("power") + " " +
113 ocRepresentation.getValueString("name"));
117 public synchronized void onGetFailed(Throwable throwable) {
118 Log.d(TAG, "GET request has failed");
119 Log.e(TAG, throwable.toString());
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() {
128 public void onDirectPairingListener(String devId, int result) {
129 Log.d(TAG, "Inside getDPListener");
130 if (result == StringConstants.SUCCES_CODE) {
132 pairedList.add(devId);
133 onGetResponseList.add(new Led());
134 runOnUiThread(new Runnable() {
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();
144 Log.d(TAG, "direct pair successfull for " + devId);
146 Log.d(TAG, "direct pairing failed");
147 runOnUiThread(new Runnable() {
149 Toast.makeText(getApplicationContext(),
150 "Direct Pairing Failed", Toast.LENGTH_SHORT).show();
157 private List<OcDirectPairDevice> discoveredPairableDevices;
158 OcPlatform.FindDirectPairingListener finddirectPairing =
159 new OcPlatform.FindDirectPairingListener() {
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);
172 runOnUiThread(new Runnable() {
174 mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
175 mListView.setAdapter(adapter);
176 discoverButton.setChecked(false);
183 protected void onCreate(Bundle savedInstanceState) {
184 super.onCreate(savedInstanceState);
185 setContentView(R.layout.activity_main);
187 onGetResponseList = new ArrayList<Object>();
188 discoveredListObj = new ArrayList<OcDirectPairDevice>();
189 pairedList = new ArrayList<String>();
191 ledResource = new Led();
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);
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);
204 SharedPreferences.Editor editor = wmbPreference.edit();
205 editor.putBoolean("FIRSTRUN", false);
211 adapter = new ArrayAdapter<OcDirectPairDevice>(this,
212 android.R.layout.simple_list_item_single_choice,
215 arrayAdapter = new ArrayAdapter<String>(
217 android.R.layout.select_dialog_singlechoice);
219 save = (Button) findViewById(R.id.saveDiscovered);
221 save.setEnabled(false);
222 save.setBackgroundColor(Color.GRAY);
224 resourceInterfaces = new LinkedList<>();
225 resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
227 exlistAdapter = new ExpandableListAdapter(pairedList, onGetResponseList,
229 mPairedListDisplay.setAdapter(exlistAdapter);
231 // to expand only a single group item.
232 mPairedListDisplay.setOnGroupExpandListener(new OnGroupExpandListener() {
233 int previousGroup = -1;
236 public void onGroupExpand(int groupPosition) {
237 Log.d(TAG, "Calling GET api on mResource");
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());
245 if (groupPosition != previousGroup)
246 mPairedListDisplay.collapseGroup(previousGroup);
248 previousGroup = groupPosition;
252 save.setOnClickListener(new View.OnClickListener() {
255 public void onClick(View v) {
257 AlertDialog.Builder alertPinDialog =
258 new AlertDialog.Builder(MainActivity.this);
259 alertPinDialog.setTitle("PIN");
260 alertPinDialog.setMessage("Enter Pin");
262 pinText = new EditText(MainActivity.this);
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) {
276 final AlertDialog alertPrmTypeDialog = new AlertDialog.Builder
278 .setSingleChoiceItems(arrayAdapter, -1,
279 new DialogInterface.OnClickListener() {
281 public void onClick(DialogInterface dialog, int which) {
283 prmType = pList[which];
284 Log.d(TAG, " prmType " + prmType);
287 .setTitle("Select Direct Pair Method")
288 .setPositiveButton("OK", null)
289 .setNegativeButton("CANCEL", null)
292 alertPrmTypeDialog.setOnShowListener(
293 new DialogInterface.OnShowListener() {
295 public void onShow(DialogInterface dialog) {
298 .getButton(AlertDialog.BUTTON_POSITIVE);
302 .getButton(AlertDialog.BUTTON_NEGATIVE);
304 ok.setOnClickListener(new View.OnClickListener() {
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()) {
315 OcDirectPairDevice peer =
319 OcPlatform.doDirectPairing(peer,
320 OcPrmType.convertOcPrmType(prmType),
321 pinText.getText().toString(),
323 } catch (OcException e) {
324 Log.d(TAG, "do Direct Pairing error: "
326 Log.e(TAG, e.getMessage());
329 alertPrmTypeDialog.dismiss();
331 alertPrmTypeDialog.dismiss();
337 cancel.setOnClickListener(new View.OnClickListener() {
339 public void onClick(View view) {
340 alertPrmTypeDialog.dismiss();
346 alertPrmTypeDialog.show();
349 alertPinDialog.show();
353 mListView.setOnItemClickListener(new OnItemClickListener() {
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();
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());
376 discoverButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
377 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
379 save.setEnabled(false);
380 save.setBackgroundColor(Color.GRAY);
381 new GetDiscoveredItems().execute();
389 * Copy svr db CBOR dat file from assets folder to app data files dir
391 private void copyCborFromAsset() {
392 InputStream inputStream = null;
393 OutputStream outputStream = null;
395 byte[] buffer = new byte[BUFFER_SIZE];
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())) {
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);
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());
418 if (inputStream != null) {
421 } catch (IOException e) {
422 Log.e(TAG, e.getMessage());
425 if (outputStream != null) {
427 outputStream.close();
428 } catch (IOException e) {
429 Log.e(TAG, e.getMessage());
437 File sd = Environment.getExternalStorageDirectory();
438 File data = Environment.getDataDirectory();
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());
452 } catch (Exception e) {
453 Log.e(TAG, e.getMessage());
458 * configure OIC platform and call findResource
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
465 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_CBOR_DB_FILE);
466 OcPlatform.Configure(cfg);
469 * Initialize DataBase
471 String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
473 File file = new File(sqlDbPath);
474 //check files directory exists
475 if (!(file.isDirectory())) {
477 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
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());
487 class GetDiscoveredItems extends AsyncTask<Void, Void, List<String>> {
489 ProgressDialog pDialog;
492 protected void onPreExecute() {
493 pDialog = new ProgressDialog(MainActivity.this);
494 pDialog.setMessage("Getting Discovered Items");
495 pDialog.setCancelable(false);
496 pDialog.setCanceledOnTouchOutside(false);
503 protected List<String> doInBackground(Void... params) {
505 OcPlatform.findDirectPairingDevices(5, finddirectPairing);
506 } catch (OcException e) {
507 Log.e(TAG, e.getMessage());
513 protected void onPostExecute(List<String> discoveredItems) {
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");
520 Log.d(TAG, "Constructing Led Resource");
521 led = OcPlatform.constructResourceObject(ledResource.getHost(),
522 "/a/led", ledResource.getConnectivityTypeSet(),
523 false, //isObservable
526 Log.d(TAG, "Constructed Led Resource");
527 } catch (OcException e) {
528 Log.e(TAG, e.getMessage());