2 * ***************************************************************
4 * Copyright 2016 Samsung Electronics All Rights Reserved.
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 * ****************************************************************
23 package org.iotivity.service.easysetup;
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;
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.ObserveType;
50 import org.iotivity.base.OcPlatform;
51 import org.iotivity.base.OcPresenceStatus;
52 import org.iotivity.base.OcProvisioning;
53 import org.iotivity.base.OcRepresentation;
54 import org.iotivity.base.OcResource;
55 import org.iotivity.base.PlatformConfig;
56 import org.iotivity.base.QualityOfService;
57 import org.iotivity.base.ServiceType;
58 import org.iotivity.base.OcAccountManager;
59 import org.iotivity.service.easysetup.mediator.ESConstants;
60 import org.iotivity.service.easysetup.mediator.CloudProp;
61 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningCallback;
62 import org.iotivity.service.easysetup.mediator.CloudPropProvisioningStatus;
63 import org.iotivity.service.easysetup.mediator.DeviceProp;
64 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningCallback;
65 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
66 import org.iotivity.service.easysetup.mediator.ESException;
67 import org.iotivity.service.easysetup.mediator.EasySetup;
68 import org.iotivity.service.easysetup.mediator.EnrolleeConf;
69 import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
70 import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
71 import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
72 import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
73 import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
74 import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
75 import org.iotivity.service.easysetup.mediator.enums.ESResult;
76 import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
77 import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
78 import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
79 import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
82 import java.io.FileNotFoundException;
83 import java.io.FileOutputStream;
84 import java.io.IOException;
85 import java.io.InputStream;
86 import java.io.OutputStream;
87 import java.util.ArrayList;
88 import java.util.Arrays;
89 import java.util.EnumSet;
90 import java.util.HashMap;
91 import java.util.List;
94 public class EasysetupActivity extends Activity
95 implements OcPlatform.OnPresenceListener,
96 OcResource.OnObserveListener{
97 private static final String TAG = "Easysetup Mediator: ";
99 OcAccountManager m_accountManager = null;
100 final String deviceID = "9E09F4FE-978A-4BC3-B356-1F93BCA37829";
101 final String CIServer = "coap+tcp://52.69.149.85:5683";
103 private static final int BUFFER_SIZE = 1024;
105 private String filePath = "";
106 public static final String OIC_CLIENT_JSON_DB_FILE = "oic_svr_db_client.dat";
107 public static final String OIC_SQL_DB_FILE = "PDM.db";
109 private boolean isFirstTime = true;
111 String mEnrolleeDeviceID;
113 String mAuthProvider;
114 String mRefreshtoken;
117 String mEnrolleeAuthCode;
121 ToggleButton mSecurityMode;
123 RadioGroup mEasysetupProcess;
124 RadioButton mConfigureSecProcess;
125 RadioButton mGetConfigurationProcess;
126 RadioButton mProvisionDevPropProcess;
127 RadioButton mProvisionCloudPropProcess;
129 Button mDiscoverResource;
130 Button mStartGetConfiguration;
131 Button mStartConfigureSec;
132 Button mStartProvisionDevProp;
133 Button mStartProvisionCloudProp;
135 TextView mGetconfigurationStateText;
136 TextView mDevNameText;
137 TextView mModelNumberText;
138 TextView mLanguageText;
139 TextView mCountryText;
140 TextView mWifiModeText;
141 TextView mWifiFreqText;
142 TextView mCloudAccessableText;
143 TextView mSecStateText;
144 TextView mSecDevIDText;
145 TextView mProvisionDevPropState;
146 TextView mProvisionCloudPropState;
148 EditText mEnrollerSsidText;
149 EditText mEnrollerPWText;
150 EditText mInputLanguageText;
151 EditText mInputCountryText;
152 EditText mInputLocationText;
153 EditText mAuthCodeText;
154 EditText mAuthProviderText;
155 EditText mCIServerText;
157 LinearLayout mGetConfigurationInfo;
158 LinearLayout mConfigureSecInfo;
159 LinearLayout mProvisionDevPropInfo;
160 LinearLayout mProvisionCloudPropInfo;
165 EasySetup mEasySetup;
166 RemoteEnrollee mRemoteEnrollee;
172 protected void onCreate(Bundle savedInstanceState) {
173 super.onCreate(savedInstanceState);
174 setContentView(R.layout.easysetup_main);
176 mActivity = EasysetupActivity.this;
177 mContext = mActivity.getBaseContext();
179 mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
181 mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
183 mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
184 mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
185 mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
186 mProvisionCloudPropProcess =
187 (RadioButton) findViewById(R.id.btn_provisionCloudConf);
189 mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
190 mStartGetConfiguration =
191 (Button) findViewById(R.id.btn_startGetConfiguration);
192 mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
193 mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
194 mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
196 mGetconfigurationStateText =
197 (TextView) findViewById(R.id.txt_getConfigurationState);
198 mDevNameText = (TextView) findViewById(R.id.txt_devName);
199 mModelNumberText = (TextView) findViewById(R.id.txt_modelNumber);
200 mLanguageText = (TextView) findViewById(R.id.txt_language);
201 mCountryText = (TextView) findViewById(R.id.txt_country);
202 mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
203 mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
204 mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
205 mSecStateText = (TextView) findViewById(R.id.txt_secState);
206 mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
207 mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
208 mProvisionCloudPropState =
209 (TextView) findViewById(R.id.txt_provisionCloudConfState);
211 mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
212 mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
213 mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
214 mInputCountryText = (EditText) findViewById(R.id.editText_Country);
215 mInputLocationText = (EditText) findViewById(R.id.editText_Location);
216 mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
217 mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
218 mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
220 mGetConfigurationInfo =
221 (LinearLayout) findViewById(R.id.layout_GetConfiguration);
222 mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
223 mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
224 mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
226 mAuthType = (Spinner) findViewById(R.id.spinner_authType);
227 mEncType = (Spinner) findViewById(R.id.spinner_encType);
229 mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
231 public void onCheckedChanged(RadioGroup group, int checkedId) {
232 mGetConfigurationInfo.setVisibility(View.GONE);
233 mConfigureSecInfo.setVisibility(View.GONE);
234 mProvisionDevPropInfo.setVisibility(View.GONE);
235 mProvisionCloudPropInfo.setVisibility(View.GONE);
238 case R.id.btn_configurSec:
239 mConfigureSecInfo.setVisibility(View.VISIBLE);
242 case R.id.btn_getConfiguration:
243 mGetConfigurationInfo.setVisibility(View.VISIBLE);
246 case R.id.btn_provisionDevConf:
247 mProvisionDevPropInfo.setVisibility(View.VISIBLE);
250 case R.id.btn_provisionCloudConf:
251 Log.d(TAG, "Starting login activity");
252 Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
253 startActivityForResult(intent, 2);
254 mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
260 ArrayAdapter<CharSequence> adAuthType, adEnctype;
262 adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
263 android.R.layout.simple_spinner_item);
264 adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
266 adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
267 android.R.layout.simple_spinner_item);
268 adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
270 mAuthType.setAdapter(adAuthType);
271 mAuthType.setSelection(0);
273 mEncType.setAdapter(adEnctype);
274 mEncType.setSelection(0);
276 addListenerForDiscoverEnrollee();
277 addListenerForStartConfigureSec();
278 addListenerForStartGetConfiguration();
279 addListenerForStartProvisionDevProp();
280 addListenerForStartProvisionCloudProp();
282 mSecurityMode.setClickable(false);
283 mConfigureSecProcess.setEnabled(false);
284 mGetConfigurationProcess.setEnabled(false);
285 mProvisionDevPropProcess.setEnabled(false);
286 mProvisionCloudPropProcess.setEnabled(false);
288 mEasySetup = EasySetup.getInstance(getApplicationContext());
293 m_accountManager = OcPlatform.constructAccountManagerObject(
295 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
297 Log.e(TAG, "constructAccountManagerObject is successful");
298 } catch (OcException e) {
299 Log.e(TAG, e.toString());
300 Log.e(TAG,"Failed to constructAccountManagerObject");
302 SharedPreferences settings =
303 getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
304 mAccessToken = settings.getString("accesstoken", null);
305 mRefreshtoken = settings.getString("refreshtoken", null);
306 mUserID = settings.getString("uid", null);
308 if(mRefreshtoken == null)
310 Log.d(TAG, "Can not find refresh token");
313 if(mAccessToken == null && mRefreshtoken == null)
315 Log.d(TAG, "Starting login activity");
316 Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
317 startActivityForResult(intent, 1);
319 else if(mAccessToken != null)
325 private void initOICStack() {
326 filePath = getFilesDir().getPath() + "/";
328 SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
329 (getApplicationContext());
330 boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
332 if(!copyJsonFromAsset())
334 Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
335 Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
336 Toast.LENGTH_LONG).show();
339 SharedPreferences.Editor editor = wmbPreference.edit();
340 editor.putBoolean("FIRSTRUN", false);
344 cfg = new PlatformConfig(
347 ModeType.CLIENT_SERVER,
348 "0.0.0.0", // bind to all available interfaces
350 QualityOfService.HIGH, filePath + OIC_CLIENT_JSON_DB_FILE);
353 * Initialize DataBase
356 OcPlatform.Configure(cfg);
358 String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
360 File file = new File(sqlDbPath);
361 //check files directory exists
362 if (!(file.isDirectory())) {
364 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
366 Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
368 //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
369 OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
370 mSecurityMode.setChecked(true);
371 } catch (OcException e) {
372 logMessage(TAG + "provisionInit error: " + e.getMessage());
373 Log.e(TAG, e.getMessage());
374 Toast.makeText(this,"provisionInit error: " + e.getMessage(),
375 Toast.LENGTH_LONG).show();
376 mSecurityMode.setChecked(false);
378 } catch (UnsatisfiedLinkError e) {
380 // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
381 // while running the Mediator App it couldn't find "libocprovision.so".
382 // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
383 mSecurityMode.setChecked(false);
384 Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");
385 Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
386 Toast.LENGTH_LONG).show();
391 OcPlatform.OnResourceFoundListener listener =
392 new OcPlatform.OnResourceFoundListener() {
394 public void onFindResourceFailed(Throwable throwable, String s) {
395 Log.e(TAG, "Failed found resource, ecode: " + s);
398 public void onResourceFound(OcResource ocResource) {
399 synchronized (mActivity) {
401 if (null == ocResource) {
402 Log.e(TAG, "Found resource is invalid");
406 if(ocResource.getHost().contains("+tcp")) {
407 Log.d(TAG, "Recv Found resource event from tcp port," +
408 "ignoring URI : " + ocResource.getUri());
409 runOnUiThread(new Runnable() {
412 mDiscoverResource.setEnabled(true);
418 // Get the resource URI
419 String resourceUri = ocResource.getUri();
420 // Get the resource host address
421 String hostAddress = ocResource.getHost();
422 Log.d(TAG,"URI of the resource: " + resourceUri);
423 Log.d(TAG,"Host address of the resource: " + hostAddress);
425 mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
427 if(mRemoteEnrollee == null) {
428 Log.d(TAG, "Recv Found resource event," +
429 "ignoring URI : " + ocResource.getUri());
430 runOnUiThread(new Runnable() {
433 mDiscoverResource.setEnabled(true);
440 mEnrolleeDeviceID = ocResource.getServerId();
442 runOnUiThread(new Runnable() {
445 mDiscoverResource.setText("Found");
446 if(mSecurityMode.isChecked()) {
447 mConfigureSecProcess.setEnabled(true);
449 mGetConfigurationProcess.setEnabled(true);
450 mProvisionDevPropProcess.setEnabled(true);
451 mProvisionCloudPropProcess.setEnabled(true);
459 private void addListenerForDiscoverEnrollee() {
460 mDiscoverResource.setOnClickListener(new View.OnClickListener() {
462 public void onClick(View v) {
463 Thread thread = new Thread() {
464 boolean result = true;
467 runOnUiThread(new Runnable() {
470 mDiscoverResource.setEnabled(false);
475 String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=" + ESConstants.OC_RSRVD_ES_RES_TYPE_EASYSETUP;
476 OcPlatform.findResource("",
478 EnumSet.of(OcConnectivityType.CT_DEFAULT),
482 catch (OcException e) {
485 runOnUiThread(new Runnable() {
488 mDiscoverResource.setEnabled(true);
500 private void addListenerForStartConfigureSec() {
501 mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
503 public void onClick(View v) {
504 Thread thread = new Thread() {
507 runOnUiThread(new Runnable() {
510 mStartConfigureSec.setEnabled(false);
515 mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
517 public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
518 if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
519 runOnUiThread(new Runnable() {
522 mSecStateText.setText("Success");
523 mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
527 else if(securityProvisioningStatus.getESResult()
528 == ESResult.ES_SECURE_RESOURCE_DISCOVERY_FAILURE) {
529 runOnUiThread(new Runnable() {
532 mSecStateText.setText("Not found Secure Resource");
533 mStartConfigureSec.setEnabled(true);
537 else if(securityProvisioningStatus.getESResult()
538 == ESResult.ES_OWNERSHIP_TRANSFER_FAILURE) {
539 runOnUiThread(new Runnable() {
542 mSecStateText.setText("Ownership transfer failed");
543 mStartConfigureSec.setEnabled(true);
548 runOnUiThread(new Runnable() {
551 mSecStateText.setText("Failed");
552 mStartConfigureSec.setEnabled(true);
558 } catch (ESException e) {
560 runOnUiThread(new Runnable() {
563 mStartConfigureSec.setEnabled(true);
575 private void addListenerForStartGetConfiguration(){
576 mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
578 public void onClick(View v) {
579 Thread thread = new Thread() {
582 runOnUiThread(new Runnable() {
585 mGetconfigurationStateText.setText("Process");
586 mStartGetConfiguration.setEnabled(false);
591 mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
593 public void onProgress(GetConfigurationStatus getConfigurationStatus) {
594 if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
595 final EnrolleeConf enrolleeConf = getConfigurationStatus.getEnrolleeConf();
596 runOnUiThread(new Runnable() {
599 mGetconfigurationStateText.setText("Success");
600 mDevNameText.setText(enrolleeConf.getDeviceName());
601 mModelNumberText.setText(enrolleeConf.getModelNumber());
602 setWifiModes(enrolleeConf.getWiFiModes());
603 setWifiFreq(enrolleeConf.getWiFiFreq());
605 if(enrolleeConf.isCloudAccessible()) {
606 mCloudAccessableText.setText("TRUE");
609 mCloudAccessableText.setText("FALSE");
614 else if(getConfigurationStatus.getESResult() == ESResult.ES_COMMUNICATION_ERROR)
616 runOnUiThread(new Runnable() {
619 mGetconfigurationStateText.setText("Communication Error");
620 mStartGetConfiguration.setEnabled(true);
625 runOnUiThread(new Runnable() {
628 mGetconfigurationStateText.setText("Failed");
629 mStartGetConfiguration.setEnabled(true);
635 } catch (ESException e) {
637 runOnUiThread(new Runnable() {
640 mGetconfigurationStateText.setText("Failed");
641 mStartGetConfiguration.setEnabled(true);
653 private void addListenerForStartProvisionDevProp() {
654 mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
656 public void onClick(View v) {
657 Thread thread = new Thread() {
661 runOnUiThread(new Runnable() {
664 mProvisionDevPropState.setText("Progress");
665 mStartProvisionDevProp.setEnabled(false);
669 String enrollerSSID = mEnrollerSsidText.getText().toString();
670 String enrollerPW = mEnrollerPWText.getText().toString();
671 WIFI_AUTHTYPE authType =
672 WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
673 WIFI_ENCTYPE encType =
674 WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
675 String inputLanguage = mInputLanguageText.getText().toString();
676 String inputCountry = mInputCountryText.getText().toString();
677 String inputLocation = mInputLocationText.getText().toString();
679 DeviceProp deviceProp = new DeviceProp();
680 deviceProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
681 deviceProp.setDevConfProp(inputLanguage, inputCountry, inputLocation);
683 mRemoteEnrollee.provisionDeviceProperties(deviceProp, new DevicePropProvisioningCallback() {
685 public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
686 final ESResult result = devPropProvisioningStatus.getESResult();
687 runOnUiThread(new Runnable() {
690 if(result.equals(ESResult.ES_OK)) {
691 mProvisionDevPropState.setText("Success");
693 else if(result.equals(ESResult.ES_ERROR)) {
694 mProvisionDevPropState.setText("Failed");
696 else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)) {
697 mProvisionDevPropState.setText("Communication Error");
699 mStartProvisionDevProp.setEnabled(true);
704 } catch (ESException e) {
706 runOnUiThread(new Runnable() {
709 mProvisionDevPropState.setText("Failed");
710 mStartProvisionDevProp.setEnabled(true);
722 private void addListenerForStartProvisionCloudProp() {
723 mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
725 public void onClick(View v) {
726 Thread thread = new Thread() {
729 runOnUiThread(new Runnable() {
732 mProvisionCloudPropState.setText("Progress");
733 mStartProvisionCloudProp.setEnabled(false);
738 String authCode = mAuthCodeText.getText().toString();
739 String authProvider = mAuthProviderText.getText().toString();
740 String ciserver = mCIServerText.getText().toString();
742 CloudProp cloudProp = new CloudProp();
743 cloudProp.setCloudProp(authCode, authProvider, ciserver);
744 cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
745 cloudProp.setCredID(1);
747 mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
749 public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
750 final ESResult result = cloudProvisioningStatus.getESResult();
751 runOnUiThread(new Runnable() {
754 if(result.equals(ESResult.ES_ENROLLEE_DISCOVERY_FAILURE)) {
755 mProvisionCloudPropState.setText("Not Found Resource");
757 else if(result.equals(ESResult.ES_OK)) {
758 mProvisionCloudPropState.setText("Cloud Provisioning succeeds");
760 else if(result.equals(ESResult.ES_ACL_PROVISIONING_FAILURE)){
761 mProvisionCloudPropState.setText("ACL-provisioning fails");
763 else if(result.equals(ESResult.ES_CERT_PROVISIONING_FAILURE)){
764 mProvisionCloudPropState.setText("CERT-provisioning fails");
766 else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)){
767 mProvisionCloudPropState.setText("Communication Error");
770 mProvisionCloudPropState.setText("Cloud Provisioning fails");
776 } catch (ESException e) {
778 runOnUiThread(new Runnable() {
781 mProvisionCloudPropState.setText("Failed");
782 mStartProvisionCloudProp.setEnabled(true);
794 private boolean copyJsonFromAsset() {
795 InputStream inputStream = null;
796 OutputStream outputStream = null;
798 byte[] buffer = new byte[BUFFER_SIZE];
800 inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
801 File file = new File(filePath);
802 //check files directory exists
803 if (!(file.exists() && file.isDirectory())) {
806 outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
807 while ((length = inputStream.read(buffer)) != -1) {
808 outputStream.write(buffer, 0, length);
810 } catch (NullPointerException e) {
811 logMessage(TAG + "Null pointer exception " + e.getMessage());
812 Log.e(TAG, e.getMessage());
814 } catch (FileNotFoundException e) {
815 logMessage(TAG + "Json svr db file not found " + e.getMessage());
816 Log.e(TAG, e.getMessage());
818 } catch (IOException e) {
819 logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
820 Log.e(TAG, e.getMessage());
823 if (inputStream != null) {
826 } catch (IOException e) {
827 Log.e(TAG, e.getMessage());
831 if (outputStream != null) {
833 outputStream.close();
834 } catch (IOException e) {
835 Log.e(TAG, e.getMessage());
843 public void logMessage(String text) {
847 public void setWifiModes(ArrayList<WIFI_MODE> types) {
848 String temp = "WIFI - ";
850 for(WIFI_MODE type : types) {
851 if(type.equals(WIFI_MODE.WIFI_11A)) {
852 temp = temp + "11A ";
854 else if(type.equals(WIFI_MODE.WIFI_11B)) {
855 temp = temp + "11B ";
857 else if(type.equals(WIFI_MODE.WIFI_11G)) {
858 temp = temp + "11G ";
860 else if(type.equals(WIFI_MODE.WIFI_11N)) {
861 temp = temp + "11N ";
863 else if(type.equals(WIFI_MODE.WIFI_11AC)) {
864 temp = temp + "11AC ";
867 final String modeTypes = temp;
868 runOnUiThread(new Runnable() {
871 mWifiModeText.setText(modeTypes);
876 public void setWifiFreq(final WIFI_FREQ freq) {
877 runOnUiThread(new Runnable() {
880 if(freq.equals(WIFI_FREQ.WIFI_24G)) {
881 mWifiFreqText.setText("2.4G");
883 else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
884 mWifiFreqText.setText("5G");
886 else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
887 mWifiFreqText.setText("2.4G & 5G");
894 public void onPresence(OcPresenceStatus status, int sequence, String host) {
895 final String strStaus = status.getValue();
896 Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
897 runOnUiThread(new Runnable()
900 Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
906 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
907 super.onActivityResult(requestCode, resultCode, data);
908 if(resultCode==RESULT_OK && requestCode==1){
909 mAuthCode = data.getStringExtra("authCode");
910 mAuthProvider = data.getStringExtra("authProvider");
911 String text = "Received authCode= " + mAuthCode;
915 else if(resultCode==RESULT_OK && requestCode==2)
917 mEnrolleeAuthCode = data.getStringExtra("authCode");
918 mAuthProvider = data.getStringExtra("authProvider");
919 mAuthCodeText.setText(mEnrolleeAuthCode);
920 mAuthProviderText.setText(mAuthProvider);
921 mAuthCodeText.setEnabled(false);
922 mAuthProviderText.setEnabled(false);
924 subscribeDevicePresence();
928 OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
930 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
931 Log.d(TAG, "onRefreshTokenPost..");
933 mAccessToken = ocRepresentation.getValue("accesstoken");
934 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
936 saveCloudTokenAtSharedPreferences();
938 catch (OcException e)
947 public void onPostFailed(Throwable throwable) {
948 Log.d(TAG, "onRefreshTokenPost failed..");
952 public void RefreshToken() {
954 OcResource authResource = OcPlatform.constructResourceObject(CIServer, "/.well-known/ocf/account/tokenrefresh",
955 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
956 false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
957 OcRepresentation rep = new OcRepresentation();
959 runOnUiThread(new Runnable()
962 Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
966 rep.setValue("di", deviceID);
967 rep.setValue("granttype", "refresh_token");
968 rep.setValue("refreshtoken", mRefreshtoken);
969 rep.setValue("uid", mUserID);
970 authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
977 Log.d(TAG, "No error while executing login");
980 private void saveCloudTokenAtSharedPreferences() {
981 Log.d(TAG, "accesstoken: " + mAccessToken);
982 SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
983 SharedPreferences.Editor editor = settings.edit();
984 editor.putString("accesstoken", mAccessToken);
985 editor.putString("refreshtoken", mRefreshtoken);
986 editor.putString("uid", mUserID);
988 if(editor.commit() == true)
989 Log.d(TAG, "accesstoken saved");
991 Log.d(TAG, "accesstoken not saved");
994 OcAccountManager.OnPostListener onSignUpPost = new OcAccountManager.OnPostListener() {
996 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
997 Log.d(TAG, "onSignUpPost..");
999 runOnUiThread(new Runnable()
1002 Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
1006 mAccessToken = ocRepresentation.getValue("accesstoken");
1007 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
1008 mUserID = ocRepresentation.getValue("uid");
1010 if(mAccessToken != null)
1012 saveCloudTokenAtSharedPreferences();
1015 //TODO : save certificate
1017 catch (OcException e)
1019 e.printStackTrace();
1024 public void onPostFailed(Throwable throwable) {
1025 Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
1029 private void SignUpDevice() {
1031 Log.d(TAG, "SignUpDevice..");
1033 runOnUiThread(new Runnable()
1036 Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
1040 if(m_accountManager != null) {
1041 m_accountManager.signUp(mAuthProvider, mAuthCode, onSignUpPost);
1044 catch(OcException e)
1046 e.printStackTrace();
1049 Log.d(TAG, "No error while executing SignUp");
1052 OcAccountManager.OnPostListener onSignInPost = new OcAccountManager.OnPostListener() {
1054 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
1055 Log.d(TAG, "onSignInPost..");
1057 runOnUiThread(new Runnable()
1060 Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
1066 public void onPostFailed(Throwable ex) {
1067 if (ex instanceof OcException) {
1068 OcException ocEx = (OcException) ex;
1069 ErrorCode errCode = ocEx.getErrorCode();
1070 Log.e(TAG, ocEx.getMessage());
1071 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
1078 private void SignInDevice() {
1080 Log.d(TAG, "SignInDevice..");
1082 runOnUiThread(new Runnable()
1085 Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
1088 if(m_accountManager != null) {
1089 m_accountManager.signIn(mUserID, mAccessToken, onSignInPost);
1092 catch(OcException e)
1094 e.printStackTrace();
1097 Log.d(TAG, "No error while executing login");
1101 public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
1102 Log.d(TAG,"onObserveCompleted");
1106 public void onObserveFailed(Throwable throwable) {
1107 Log.d(TAG,"onObserveFailed");
1110 public void subscribeDevicePresence()
1112 List<String> deviceIDs = new ArrayList<String>();
1113 deviceIDs.add(mEnrolleeDeviceID);
1117 OcPlatform.subscribeDevicePresence(CIServer, deviceIDs, EnumSet.of(OcConnectivityType.
1118 CT_ADAPTER_TCP), this);
1119 } catch(OcException e)
1121 e.printStackTrace();
1127 protected void onDestroy() {