Merge remote-tracking branch 'origin/extended-easysetup'
[platform/upstream/iotivity.git] / service / easy-setup / sampleapp / mediator / android / EasySetup / app / src / main / java / org / iotivity / service / easysetup / EasysetupActivity.java
1 /**
2  * ***************************************************************
3  * <p/>
4  * Copyright 2016 Samsung Electronics All Rights Reserved.
5  * <p/>
6  * <p/>
7  * <p/>
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  * <p/>
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * <p/>
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  * <p/>
20  * ****************************************************************
21  */
22
23 package org.iotivity.service.easysetup;
24
25 import android.app.Activity;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.os.Bundle;
30 import android.preference.PreferenceManager;
31 import android.util.Log;
32 import android.view.View;
33 import android.widget.ArrayAdapter;
34 import android.widget.Button;
35 import android.widget.EditText;
36 import android.widget.LinearLayout;
37 import android.widget.RadioButton;
38 import android.widget.RadioGroup;
39 import android.widget.Spinner;
40 import android.widget.TextView;
41 import android.widget.Toast;
42 import android.widget.ToggleButton;
43
44 import org.iotivity.base.ErrorCode;
45 import org.iotivity.base.ModeType;
46 import org.iotivity.base.OcConnectivityType;
47 import org.iotivity.base.OcException;
48 import org.iotivity.base.OcHeaderOption;
49 import org.iotivity.base.OcPlatform;
50 import org.iotivity.base.OcPresenceStatus;
51 import org.iotivity.base.OcProvisioning;
52 import org.iotivity.base.OcRepresentation;
53 import org.iotivity.base.OcResource;
54 import org.iotivity.base.PlatformConfig;
55 import org.iotivity.base.QualityOfService;
56 import org.iotivity.base.ServiceType;
57 import org.iotivity.service.easysetup.mediator.CloudProp;
58 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
59 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
60 import org.iotivity.service.easysetup.mediator.DeviceProp;
61 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
62 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
63 import org.iotivity.service.easysetup.mediator.ESException;
64 import org.iotivity.service.easysetup.mediator.EasySetup;
65 import org.iotivity.service.easysetup.mediator.EnrolleeConf;
66 import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
67 import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
68 import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
69 import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
70 import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
71 import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
72 import org.iotivity.service.easysetup.mediator.enums.ESResult;
73 import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
74 import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
75 import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
76 import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
77
78 import java.io.File;
79 import java.io.FileNotFoundException;
80 import java.io.FileOutputStream;
81 import java.io.IOException;
82 import java.io.InputStream;
83 import java.io.OutputStream;
84 import java.util.ArrayList;
85 import java.util.Arrays;
86 import java.util.EnumSet;
87 import java.util.HashMap;
88 import java.util.List;
89
90
91 public class EasysetupActivity extends Activity implements OcPlatform.OnPresenceListener {
92     private static final String TAG = "Easysetup Mediator: ";
93     PlatformConfig cfg;
94     final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
95     final String samsungCIServer = "coap+tcp://52.69.149.85:5683";
96
97     private static final int BUFFER_SIZE = 1024;
98
99     private String filePath = "";
100     public static final String OIC_CLIENT_JSON_DB_FILE =  "oic_svr_db_client.dat";
101     public static final String OIC_SQL_DB_FILE =  "PDM.db";
102
103     private boolean isFirstTime = true;
104     String mEnrolleeDeviceID;
105     String mAuthCode;
106     String mAuthProvider;
107     String mRefreshtoken;
108     String mUserID;
109     String mAccessToken;
110     String mEnrolleeAuthCode;
111
112
113     ToggleButton mSecurityMode;
114
115     RadioGroup mEasysetupProcess;
116     RadioButton mConfigureSecProcess;
117     RadioButton mGetConfigurationProcess;
118     RadioButton mProvisionDevPropProcess;
119     RadioButton mProvisionCloudPropProcess;
120
121     Button mDiscoverResource;
122     Button mStartGetConfiguration;
123     Button mStartConfigureSec;
124     Button mStartProvisionDevProp;
125     Button mStartProvisionCloudProp;
126
127     TextView mGetconfigurationStateText;
128     TextView mDevNameText;
129     TextView mLanguageText;
130     TextView mCountryText;
131     TextView mWifiModeText;
132     TextView mWifiFreqText;
133     TextView mCloudAccessableText;
134     TextView mSecStateText;
135     TextView mSecDevIDText;
136     TextView mProvisionDevPropState;
137     TextView mProvisionCloudPropState;
138
139     EditText mEnrollerSsidText;
140     EditText mEnrollerPWText;
141     EditText mInputLanguageText;
142     EditText mInputCountryText;
143     EditText mAuthCodeText;
144     EditText mAuthProviderText;
145     EditText mCIServerText;
146
147     LinearLayout mGetConfigurationInfo;
148     LinearLayout mConfigureSecInfo;
149     LinearLayout mProvisionDevPropInfo;
150     LinearLayout mProvisionCloudPropInfo;
151
152     Spinner mAuthType;
153     Spinner mEncType;
154
155     EasySetup mEasySetup;
156     RemoteEnrollee mRemoteEnrollee;
157
158     Activity mActivity;
159     Context mContext;
160
161     @Override
162     protected void onCreate(Bundle savedInstanceState) {
163         super.onCreate(savedInstanceState);
164         setContentView(R.layout.easysetup_main);
165
166         mActivity = EasysetupActivity.this;
167         mContext = mActivity.getBaseContext();
168
169         mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
170
171         mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
172
173         mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
174         mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
175         mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
176         mProvisionCloudPropProcess =
177                 (RadioButton) findViewById(R.id.btn_provisionCloudConf);
178
179         mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
180         mStartGetConfiguration =
181                 (Button) findViewById(R.id.btn_startGetConfiguration);
182         mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
183         mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
184         mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
185
186         mGetconfigurationStateText =
187                 (TextView) findViewById(R.id.txt_getConfigurationState);
188         mDevNameText = (TextView) findViewById(R.id.txt_devName);
189         mLanguageText = (TextView) findViewById(R.id.txt_language);
190         mCountryText = (TextView) findViewById(R.id.txt_country);
191         mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
192         mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
193         mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
194         mSecStateText = (TextView) findViewById(R.id.txt_secState);
195         mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
196         mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
197         mProvisionCloudPropState =
198                 (TextView) findViewById(R.id.txt_provisionCloudConfState);
199
200         mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
201         mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
202         mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
203         mInputCountryText = (EditText) findViewById(R.id.editText_Country);
204         mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
205         mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
206         mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
207
208         mGetConfigurationInfo =
209                 (LinearLayout) findViewById(R.id.layout_GetConfiguration);
210         mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
211         mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
212         mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
213
214         mAuthType = (Spinner) findViewById(R.id.spinner_authType);
215         mEncType = (Spinner) findViewById(R.id.spinner_encType);
216
217         mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
218             @Override
219             public void onCheckedChanged(RadioGroup group, int checkedId) {
220                 mGetConfigurationInfo.setVisibility(View.GONE);
221                 mConfigureSecInfo.setVisibility(View.GONE);
222                 mProvisionDevPropInfo.setVisibility(View.GONE);
223                 mProvisionCloudPropInfo.setVisibility(View.GONE);
224
225                 switch (checkedId) {
226                     case R.id.btn_configurSec:
227                         mConfigureSecInfo.setVisibility(View.VISIBLE);
228                         break;
229
230                     case R.id.btn_getConfiguration:
231                         mGetConfigurationInfo.setVisibility(View.VISIBLE);
232                         break;
233
234                     case R.id.btn_provisionDevConf:
235                         mProvisionDevPropInfo.setVisibility(View.VISIBLE);
236                         break;
237
238                     case R.id.btn_provisionCloudConf:
239                         Log.d(TAG, "Starting login activity");
240                         Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
241                         startActivityForResult(intent, 2);
242                         mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
243                         break;
244                 }
245             }
246         });
247
248         ArrayAdapter<CharSequence> adAuthType, adEnctype;
249
250         adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
251                 android.R.layout.simple_spinner_item);
252         adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
253
254         adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
255                 android.R.layout.simple_spinner_item);
256         adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
257
258         mAuthType.setAdapter(adAuthType);
259         mAuthType.setSelection(0);
260
261         mEncType.setAdapter(adEnctype);
262         mEncType.setSelection(0);
263
264         addListenerForDiscoverEnrollee();
265         addListenerForStartConfigureSec();
266         addListenerForStartGetConfiguration();
267         addListenerForStartProvisionDevProp();
268         addListenerForStartProvisionCloudProp();
269
270         mSecurityMode.setClickable(false);
271         mConfigureSecProcess.setEnabled(false);
272         mGetConfigurationProcess.setEnabled(false);
273         mProvisionDevPropProcess.setEnabled(false);
274         mProvisionCloudPropProcess.setEnabled(false);
275
276         mEasySetup = EasySetup.getInstance(getApplicationContext());
277
278         initOICStack();
279
280         SharedPreferences settings =
281                                 getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
282         mAccessToken = settings.getString("accesstoken", null);
283         mRefreshtoken = settings.getString("refreshtoken", null);
284         mUserID = settings.getString("uid", null);
285
286         if(mRefreshtoken == null)
287         {
288             Log.d(TAG, "Can not find refresh token");
289         }
290
291         if(mAccessToken == null && mRefreshtoken == null)
292         {
293             Log.d(TAG, "Starting login activity");
294             Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
295             startActivityForResult(intent, 1);
296         }
297         else if(mAccessToken != null)
298         {
299             SignInDevice();
300         }
301     }
302
303     private void initOICStack() {
304         filePath = getFilesDir().getPath() + "/";
305
306         SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
307                 (getApplicationContext());
308         boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
309         if (isFirstRun) {
310             if(!copyJsonFromAsset())
311             {
312                 Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
313                 Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
314                     Toast.LENGTH_LONG).show();
315                 return;
316             }
317             SharedPreferences.Editor editor = wmbPreference.edit();
318             editor.putBoolean("FIRSTRUN", false);
319             editor.commit();
320         }
321
322         cfg = new PlatformConfig(
323                 this,
324                 ServiceType.IN_PROC,
325                 ModeType.CLIENT_SERVER,
326                 "0.0.0.0", // bind to all available interfaces
327                 0,
328                 QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
329         try {
330             /*
331              * Initialize DataBase
332              */
333
334             OcPlatform.Configure(cfg);
335
336             String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
337                     File.separator;
338             File file = new File(sqlDbPath);
339             //check files directory exists
340             if (!(file.isDirectory())) {
341                 file.mkdirs();
342                 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
343             }
344             Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
345
346             //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
347             OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
348             mSecurityMode.setChecked(true);
349         } catch (OcException e) {
350             logMessage(TAG + "provisionInit error: " + e.getMessage());
351             Log.e(TAG, e.getMessage());
352             Toast.makeText(this,"provisionInit error: " + e.getMessage(),
353                     Toast.LENGTH_LONG).show();
354             mSecurityMode.setChecked(false);
355             return;
356         } catch (UnsatisfiedLinkError e) {
357
358             // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
359             // while running the Mediator App it couldn't find "libocprovision.so".
360             // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
361             mSecurityMode.setChecked(false);
362             Log.e(TAG, " Easy setup is built with secured  = 0, but executed with security feature");
363             Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
364                     Toast.LENGTH_LONG).show();
365             return;
366         }
367     }
368
369     OcPlatform.OnResourceFoundListener listener =
370             new OcPlatform.OnResourceFoundListener() {
371                 @Override
372                 public void onFindResourceFailed(Throwable throwable, String s) {
373                     Log.e(TAG, "Failed found resource, ecode: " + s);
374                 }
375                 @Override
376                 public void onResourceFound(OcResource ocResource) {
377                     synchronized (mActivity) {
378                         if(isFirstTime){
379                             if (null == ocResource) {
380                                 Log.e(TAG, "Found resource is invalid");
381                                 return;
382                             }
383
384                             if(ocResource.getHost().contains("coap+tcp")) {
385                                 Log.d(TAG, "Recv Found resource event  from tcp port," +
386                                     "ignoring URI : " + ocResource.getUri());
387                                 runOnUiThread(new Runnable() {
388                                     @Override
389                                     public void run() {
390                                         mDiscoverResource.setEnabled(true);
391                                     }
392                                 });
393                                 return;
394                             }
395
396                             // Get the resource URI
397                             String resourceUri = ocResource.getUri();
398                             // Get the resource host address
399                             String hostAddress = ocResource.getHost();
400                             Log.d(TAG,"URI of the resource: " + resourceUri);
401                             Log.d(TAG,"Host address of the resource: " + hostAddress);
402
403                             runOnUiThread(new Runnable() {
404                                 @Override
405                                 public void run() {
406                                     mDiscoverResource.setText("Found");
407                                     if(mSecurityMode.isChecked()) {
408                                         mConfigureSecProcess.setEnabled(true);
409                                     }
410                                     mGetConfigurationProcess.setEnabled(true);
411                                     mProvisionDevPropProcess.setEnabled(true);
412                                     mProvisionCloudPropProcess.setEnabled(true);
413                                 }
414                             });
415                             isFirstTime = false;
416                             mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
417                             mEnrolleeDeviceID = ocResource.getServerId();
418                         }
419                     }
420                 }
421             };
422
423     private void addListenerForDiscoverEnrollee() {
424         mDiscoverResource.setOnClickListener(new View.OnClickListener() {
425             @Override
426             public void onClick(View v) {
427                 Thread thread = new Thread() {
428                     boolean result = true;
429                     @Override
430                     public void run() {
431                         runOnUiThread(new Runnable() {
432                             @Override
433                             public void run() {
434                                 mDiscoverResource.setEnabled(false);
435                             }
436                         });
437
438                         try {
439                             String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=ocf.wk.prov";
440                             OcPlatform.findResource("",
441                                     requestUri,
442                                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
443                                     listener
444                             );
445                         }
446                         catch (OcException e) {
447                             e.printStackTrace();
448                             result = false;
449                             runOnUiThread(new Runnable() {
450                                 @Override
451                                 public void run() {
452                                     mDiscoverResource.setEnabled(true);
453                                 }
454                             });
455                         }
456                     }
457                 };
458
459                 thread.start();
460             }
461         });
462     }
463
464     private void addListenerForStartConfigureSec() {
465         mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
466             @Override
467             public void onClick(View v) {
468                 Thread thread = new Thread() {
469                     @Override
470                     public void run() {
471                         runOnUiThread(new Runnable() {
472                             @Override
473                             public void run() {
474                                 mStartConfigureSec.setEnabled(false);
475                             }
476                         });
477
478                         try {
479                             mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
480                                 @Override
481                                 public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
482                                     if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
483                                         runOnUiThread(new Runnable() {
484                                             @Override
485                                             public void run() {
486                                                 mSecStateText.setText("Success");
487                                                 mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
488                                             }
489                                         });
490                                     }
491                                     else {
492                                         runOnUiThread(new Runnable() {
493                                             @Override
494                                             public void run() {
495                                                 mSecStateText.setText("Failed");
496                                                 mStartConfigureSec.setEnabled(true);
497                                             }
498                                         });
499                                     }
500                                 }
501                             });
502                         } catch (ESException e) {
503                             e.printStackTrace();
504                             runOnUiThread(new Runnable() {
505                                 @Override
506                                 public void run() {
507                                     mStartConfigureSec.setEnabled(true);
508                                 }
509                             });
510                         }
511                     }
512                 };
513
514                 thread.start();
515             }
516         });
517     }
518
519     private void addListenerForStartGetConfiguration(){
520         mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
521             @Override
522             public void onClick(View v) {
523                 Thread thread = new Thread() {
524                     @Override
525                     public void run() {
526                         runOnUiThread(new Runnable() {
527                             @Override
528                             public void run() {
529                                 mGetconfigurationStateText.setText("Process");
530                                 mStartGetConfiguration.setEnabled(false);
531                             }
532                         });
533
534                         try {
535                             mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
536                                 @Override
537                                 public void onProgress(GetConfigurationStatus getConfigurationStatus) {
538                                     if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
539
540                                         final EnrolleeConf enrolleeConf = getConfigurationStatus.getEnrolleeConf();
541                                         runOnUiThread(new Runnable() {
542                                             @Override
543                                             public void run() {
544                                                 mGetconfigurationStateText.setText("Success");
545                                                 mDevNameText.setText(enrolleeConf.getDeviceName());
546                                                 setWifiModes(enrolleeConf.getWiFiModes());
547                                                 setWifiFreq(enrolleeConf.getWiFiFreq());
548
549                                                 if(enrolleeConf.isCloudAccessible()) {
550                                                     mCloudAccessableText.setText("TRUE");
551                                                 }
552                                                 else {
553                                                     mCloudAccessableText.setText("FALSE");
554                                                 }
555                                             }
556                                         });
557
558                                     }
559                                     else {
560                                         runOnUiThread(new Runnable() {
561                                             @Override
562                                             public void run() {
563                                                 mGetconfigurationStateText.setText("Failed");
564                                                 mStartGetConfiguration.setEnabled(true);
565                                             }
566                                         });
567                                     }
568                                 }
569                             });
570                         } catch (ESException e) {
571                             e.printStackTrace();
572                             runOnUiThread(new Runnable() {
573                                 @Override
574                                 public void run() {
575                                     mGetconfigurationStateText.setText("Failed");
576                                     mStartGetConfiguration.setEnabled(true);
577                                 }
578                             });
579                         }
580                     }
581                 };
582
583                 thread.start();
584             }
585         });
586     }
587
588     private void addListenerForStartProvisionDevProp() {
589         mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
590             @Override
591             public void onClick(View v) {
592                 Thread thread = new Thread() {
593                     @Override
594                     public void run() {
595                         try {
596                             runOnUiThread(new Runnable() {
597                                 @Override
598                                 public void run() {
599                                     mProvisionDevPropState.setText("Progress");
600                                     mStartProvisionDevProp.setEnabled(false);
601                                 }
602                             });
603
604                             String enrollerSSID = mEnrollerSsidText.getText().toString();
605                             String enrollerPW = mEnrollerPWText.getText().toString();
606                             WIFI_AUTHTYPE authType =
607                                     WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
608                             WIFI_ENCTYPE encType =
609                                     WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
610                             String inputLanguage = mInputLanguageText.getText().toString();
611                             String inputCountry = mInputCountryText.getText().toString();
612
613                             DeviceProp deviceProp = new DeviceProp();
614                             deviceProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
615                             deviceProp.setDevConfProp(inputLanguage, inputCountry);
616
617                             mRemoteEnrollee.provisionDeviceProperties(deviceProp, new DevicePropProvisioningCallback() {
618                                 @Override
619                                 public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
620                                     final ESResult result = devPropProvisioningStatus.getESResult();
621                                     runOnUiThread(new Runnable() {
622                                         @Override
623                                         public void run() {
624                                             if(result.equals(ESResult.ES_OK)) {
625                                                 mProvisionDevPropState.setText("Success");
626                                             }
627                                             else if(result.equals(ESResult.ES_ERROR)) {
628                                                 mProvisionDevPropState.setText("Failed");
629                                             }
630                                             else if(result.equals(ESResult.ES_UNAUTHORIZED)) {
631                                                 mProvisionDevPropState.setText("Failed. Need SecProv");
632                                             }
633                                             mStartProvisionDevProp.setEnabled(true);
634                                         }
635                                     });
636                                 }
637                             });
638                         } catch (ESException e) {
639                             e.printStackTrace();
640                             runOnUiThread(new Runnable() {
641                                 @Override
642                                 public void run() {
643                                     mProvisionDevPropState.setText("Failed");
644                                     mStartProvisionDevProp.setEnabled(true);
645                                 }
646                             });
647                         }
648                     }
649                 };
650
651                 thread.start();
652             }
653         });
654     }
655
656     private void addListenerForStartProvisionCloudProp() {
657         mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
658             @Override
659             public void onClick(View v) {
660                 Thread thread = new Thread() {
661                     @Override
662                     public void run() {
663                         runOnUiThread(new Runnable() {
664                             @Override
665                             public void run() {
666                                 mProvisionCloudPropState.setText("Progress");
667                                 mStartProvisionCloudProp.setEnabled(false);
668                             }
669                         });
670
671                         try {
672                             String authCode = mAuthCodeText.getText().toString();
673                             String authProvider = mAuthProviderText.getText().toString();
674                             String ciserver = mCIServerText.getText().toString();
675
676                             CloudProp cloudProp = new CloudProp();
677                             cloudProp.setCloudProp(authCode, authProvider, ciserver);
678                             cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
679
680                             mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
681                                 @Override
682                                 public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
683                                     final ESResult result = cloudProvisioningStatus.getESResult();
684                                     final ESCloudProvState state = cloudProvisioningStatus.getESCloudState();
685                                     runOnUiThread(new Runnable() {
686                                         @Override
687                                         public void run() {
688                                             if(result.equals(ESResult.ES_OK)) {
689                                                 if(state.equals(ESCloudProvState.ES_CLOUD_ENROLLEE_FOUND)) {
690                                                     mProvisionCloudPropState.setText("Found Resource");
691                                                 }
692                                                 else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_SUCCESS)) {
693                                                     mProvisionCloudPropState.setText("Success");
694                                                 }
695                                             }
696                                             else {
697                                                 if(state.equals(ESCloudProvState.ES_CLOUD_ENROLLEE_NOT_FOUND)) {
698                                                     mProvisionCloudPropState.setText("Not Found Resource");
699                                                 }
700                                                 else if(state.equals(ESCloudProvState.ES_CLOUD_PROVISIONING_ERROR)) {
701                                                     mProvisionCloudPropState.setText("Failed");
702                                                 }
703                                                 mStartProvisionCloudProp.setEnabled(true);
704                                             }
705                                         }
706                                     });
707                                 }
708                             });
709                         } catch (ESException e) {
710                             e.printStackTrace();
711                             runOnUiThread(new Runnable() {
712                                 @Override
713                                 public void run() {
714                                     mProvisionCloudPropState.setText("Failed");
715                                     mStartProvisionCloudProp.setEnabled(true);
716                                 }
717                             });
718                         }
719                     }
720                 };
721
722                 thread.start();
723             }
724         });
725     }
726
727     private boolean copyJsonFromAsset() {
728         InputStream inputStream = null;
729         OutputStream outputStream = null;
730         int length;
731         byte[] buffer = new byte[BUFFER_SIZE];
732         try {
733             inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
734             File file = new File(filePath);
735             //check files directory exists
736             if (!(file.exists() && file.isDirectory())) {
737                 file.mkdirs();
738             }
739             outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
740             while ((length = inputStream.read(buffer)) != -1) {
741                 outputStream.write(buffer, 0, length);
742             }
743         } catch (NullPointerException e) {
744             logMessage(TAG + "Null pointer exception " + e.getMessage());
745             Log.e(TAG, e.getMessage());
746             return false;
747         } catch (FileNotFoundException e) {
748             logMessage(TAG + "Json svr db file not found " + e.getMessage());
749             Log.e(TAG, e.getMessage());
750             return false;
751         } catch (IOException e) {
752             logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
753             Log.e(TAG, e.getMessage());
754             return false;
755         } finally {
756             if (inputStream != null) {
757                 try {
758                     inputStream.close();
759                 } catch (IOException e) {
760                     Log.e(TAG, e.getMessage());
761                     return false;
762                 }
763             }
764             if (outputStream != null) {
765                 try {
766                     outputStream.close();
767                 } catch (IOException e) {
768                     Log.e(TAG, e.getMessage());
769                     return false;
770                 }
771             }
772         }
773         return true;
774     }
775
776     public void logMessage(String text) {
777
778     }
779
780     public void setWifiModes(ArrayList<WIFI_MODE> types) {
781         String temp = "WIFI - ";
782
783         for(WIFI_MODE type : types) {
784             if(type.equals(WIFI_MODE.WIFI_11A)) {
785                 temp = temp + "11A ";
786             }
787             else if(type.equals(WIFI_MODE.WIFI_11B)) {
788                 temp = temp + "11B ";
789             }
790             else if(type.equals(WIFI_MODE.WIFI_11G)) {
791                 temp = temp + "11G ";
792             }
793             else if(type.equals(WIFI_MODE.WIFI_11N)) {
794                 temp = temp + "11N ";
795             }
796             else if(type.equals(WIFI_MODE.WIFI_11AC)) {
797                 temp = temp + "11AC ";
798             }
799         }
800         final String modeTypes = temp;
801         runOnUiThread(new Runnable() {
802             @Override
803             public void run() {
804                 mWifiModeText.setText(modeTypes);
805             }
806         });
807     }
808
809     public void setWifiFreq(final WIFI_FREQ freq) {
810         runOnUiThread(new Runnable() {
811             @Override
812             public void run() {
813                 if(freq.equals(WIFI_FREQ.WIFI_24G)) {
814                     mWifiFreqText.setText("2.4G");
815                 }
816                 else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
817                     mWifiFreqText.setText("5G");
818                 }
819                 else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
820                     mWifiFreqText.setText("2.4G & 5G");
821                 }
822             }
823         });
824     }
825
826     @Override
827     public void onPresence(OcPresenceStatus status, int sequence, String host) {
828         final String strStaus = status.getValue();
829         Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
830         runOnUiThread(new Runnable()
831         {
832             public void run() {
833                 Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
834             }
835         });
836     }
837
838     @Override
839     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
840         super.onActivityResult(requestCode, resultCode, data);
841         if(resultCode==RESULT_OK && requestCode==1){
842             mAuthCode = data.getStringExtra("authCode");
843             mAuthProvider = data.getStringExtra("authProvider");
844             String text = "Received authCode= " + mAuthCode;
845             Log.d(TAG, text);
846             SignUpDevice();
847         }
848         else if(resultCode==RESULT_OK && requestCode==2)
849         {
850             mEnrolleeAuthCode = data.getStringExtra("authCode");
851             mAuthProvider = data.getStringExtra("authProvider");
852             mAuthCodeText.setText(mEnrolleeAuthCode);
853             mAuthProviderText.setText(mAuthProvider);
854             mAuthCodeText.setEnabled(false);
855             mAuthProviderText.setEnabled(false);
856
857             try
858             {
859                 OcPlatform.subscribePresence(samsungCIServer, "oic.res&di=" + mEnrolleeDeviceID,
860                         EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4), this);
861             }
862             catch (Exception e)
863             {
864                 e.printStackTrace();
865             }
866         }
867     }
868
869     OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
870         @Override
871         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
872             Log.d(TAG, "onRefreshTokenPost..");
873             try {
874                 mAccessToken = ocRepresentation.getValue("accesstoken");
875                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
876
877                 saveCloudTokenAtSharedPreferences();
878             }
879             catch (OcException e)
880             {
881                 e.printStackTrace();
882             }
883
884             SignInDevice();
885         }
886
887         @Override
888         public void onPostFailed(Throwable throwable) {
889             Log.d(TAG, "onRefreshTokenPost failed..");
890         }
891     };
892
893     public void RefreshToken() {
894         try {
895             OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/tokenrefresh",
896                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
897                     false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
898             OcRepresentation rep = new OcRepresentation();
899
900             runOnUiThread(new Runnable()
901             {
902                 public void run() {
903                     Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
904                 }
905             });
906
907             rep.setValue("di", deviceID);
908             rep.setValue("granttype", "refresh_token");
909             rep.setValue("refreshtoken", mRefreshtoken);
910             rep.setValue("uid", mUserID);
911             authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
912         }
913         catch(OcException e)
914         {
915             e.printStackTrace();
916         }
917
918         Log.d(TAG, "No error while executing login");
919     }
920
921     private void saveCloudTokenAtSharedPreferences() {
922         Log.d(TAG, "accesstoken: " + mAccessToken);
923         SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
924         SharedPreferences.Editor editor = settings.edit();
925         editor.putString("accesstoken", mAccessToken);
926         editor.putString("refreshtoken", mRefreshtoken);
927         editor.putString("uid", mUserID);
928
929         if(editor.commit() == true)
930             Log.d(TAG, "accesstoken saved");
931         else
932             Log.d(TAG, "accesstoken not saved");
933     }
934
935     OcResource.OnPostListener onSignUpPost = new OcResource.OnPostListener() {
936         @Override
937         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
938             Log.d(TAG, "onSignUpPost..");
939             try {
940                 runOnUiThread(new Runnable()
941                 {
942                     public void run() {
943                         Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
944                     }
945                 });
946
947                 mAccessToken = ocRepresentation.getValue("accesstoken");
948                 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
949                 mUserID = ocRepresentation.getValue("uid");
950
951                 if(mAccessToken != null)
952                 {
953                     saveCloudTokenAtSharedPreferences();
954                     SignInDevice();
955                 }
956             }
957             catch (OcException e)
958             {
959                 e.printStackTrace();
960             }
961         }
962
963         @Override
964         public void onPostFailed(Throwable throwable) {
965             Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
966         }
967     };
968
969     private void SignUpDevice() {
970         try {
971             OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account",
972                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
973                     false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
974             OcRepresentation rep = new OcRepresentation();
975
976             runOnUiThread(new Runnable()
977             {
978                 public void run() {
979                     Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
980                 }
981             });
982
983             rep.setValue("di", deviceID);
984             rep.setValue("authprovider", mAuthProvider);
985             rep.setValue("authcode", mAuthCode);
986             authResource.post(rep, new HashMap<String, String>(), onSignUpPost);
987         }
988         catch(OcException e)
989         {
990             e.printStackTrace();
991         }
992
993         Log.d(TAG, "No error while executing SignUp");
994     }
995
996     OcResource.OnPostListener onSignInPost = new OcResource.OnPostListener() {
997         @Override
998         public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
999             Log.d(TAG, "onSignInPost..");
1000
1001             runOnUiThread(new Runnable()
1002             {
1003                 public void run() {
1004                     Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
1005                 }
1006             });
1007         }
1008
1009         @Override
1010         public void onPostFailed(Throwable ex) {
1011             if (ex instanceof OcException) {
1012                 OcException ocEx = (OcException) ex;
1013                 ErrorCode errCode = ocEx.getErrorCode();
1014                 Log.e(TAG, ocEx.getMessage());
1015                 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
1016                     RefreshToken();
1017                 }
1018             }
1019         }
1020     };
1021
1022     private void SignInDevice() {
1023         try {
1024             OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/session",
1025                     EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
1026                     false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
1027             OcRepresentation rep = new OcRepresentation();
1028
1029             runOnUiThread(new Runnable()
1030             {
1031                 public void run() {
1032                     Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
1033                 }
1034             });
1035
1036             rep.setValue("di", deviceID);
1037             rep.setValue("accesstoken", mAccessToken);
1038             rep.setValue("login", true);
1039             rep.setValue("uid", mUserID);
1040             authResource.post(rep, new HashMap<String, String>(), onSignInPost);
1041
1042         }
1043         catch(OcException e)
1044         {
1045             e.printStackTrace();
1046         }
1047
1048         Log.d(TAG, "No error while executing login");
1049     }
1050
1051     @Override
1052     protected void onDestroy() {
1053         super.onDestroy();
1054     }
1055 }