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.DevicePropProvisioningCallback;
64 import org.iotivity.service.easysetup.mediator.DevicePropProvisioningStatus;
65 import org.iotivity.service.easysetup.mediator.ESException;
66 import org.iotivity.service.easysetup.mediator.EasySetup;
67 import org.iotivity.service.easysetup.mediator.GetConfigurationCallback;
68 import org.iotivity.service.easysetup.mediator.GetConfigurationStatus;
69 import org.iotivity.service.easysetup.mediator.RemoteEnrollee;
70 import org.iotivity.service.easysetup.mediator.SecurityProvisioningCallback;
71 import org.iotivity.service.easysetup.mediator.SecurityProvisioningStatus;
72 import org.iotivity.service.easysetup.mediator.enums.ESCloudProvState;
73 import org.iotivity.service.easysetup.mediator.enums.ESResult;
74 import org.iotivity.service.easysetup.mediator.enums.WIFI_AUTHTYPE;
75 import org.iotivity.service.easysetup.mediator.enums.WIFI_ENCTYPE;
76 import org.iotivity.service.easysetup.mediator.enums.WIFI_FREQ;
77 import org.iotivity.service.easysetup.mediator.enums.WIFI_MODE;
78 import org.iotivity.service.easysetup.mediator.samsung.SCDeviceProp;
79 import org.iotivity.service.easysetup.mediator.samsung.SCEnrolleeConf;
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 samsungCIServer = "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;
110 String mEnrolleeDeviceID;
112 String mAuthProvider;
113 String mRefreshtoken;
116 String mEnrolleeAuthCode;
118 ToggleButton mSecurityMode;
120 RadioGroup mEasysetupProcess;
121 RadioButton mConfigureSecProcess;
122 RadioButton mGetConfigurationProcess;
123 RadioButton mProvisionDevPropProcess;
124 RadioButton mProvisionCloudPropProcess;
126 Button mDiscoverResource;
127 Button mStartGetConfiguration;
128 Button mStartConfigureSec;
129 Button mStartProvisionDevProp;
130 Button mStartProvisionCloudProp;
132 TextView mGetconfigurationStateText;
133 TextView mDevNameText;
134 TextView mModelNumberText;
135 TextView mDevTypeText;
136 TextView mDevSubTypeText;
137 TextView mWifiModeText;
138 TextView mWifiFreqText;
139 TextView mCloudAccessableText;
140 TextView mSecStateText;
141 TextView mSecDevIDText;
142 TextView mProvisionDevPropState;
143 TextView mProvisionCloudPropState;
145 EditText mEnrollerSsidText;
146 EditText mEnrollerPWText;
147 EditText mInputLanguageText;
148 EditText mInputCountryText;
149 EditText mInputLocationText;
150 EditText mDiscoveryChannelText;
152 EditText mZipCodeText;
153 EditText mBuildingText;
154 EditText mAuthCodeText;
155 EditText mAuthProviderText;
156 EditText mCIServerText;
158 LinearLayout mGetConfigurationInfo;
159 LinearLayout mConfigureSecInfo;
160 LinearLayout mProvisionDevPropInfo;
161 LinearLayout mProvisionCloudPropInfo;
166 EasySetup mEasySetup;
167 RemoteEnrollee mRemoteEnrollee;
173 protected void onCreate(Bundle savedInstanceState) {
174 super.onCreate(savedInstanceState);
175 setContentView(R.layout.easysetup_main);
177 mActivity = EasysetupActivity.this;
178 mContext = mActivity.getBaseContext();
180 mSecurityMode = (ToggleButton) findViewById(R.id.btn_Security);
182 mEasysetupProcess = (RadioGroup) findViewById(R.id.rg_EasysetupProcess);
184 mConfigureSecProcess = (RadioButton) findViewById(R.id.btn_configurSec);
185 mGetConfigurationProcess = (RadioButton) findViewById(R.id.btn_getConfiguration);
186 mProvisionDevPropProcess = (RadioButton) findViewById(R.id.btn_provisionDevConf);
187 mProvisionCloudPropProcess =
188 (RadioButton) findViewById(R.id.btn_provisionCloudConf);
190 mDiscoverResource = (Button) findViewById(R.id.btn_discoverResource);
191 mStartGetConfiguration =
192 (Button) findViewById(R.id.btn_startGetConfiguration);
193 mStartConfigureSec = (Button) findViewById(R.id.btn_startConfigureSec);
194 mStartProvisionDevProp = (Button) findViewById(R.id.btn_startProvisionDevConf);
195 mStartProvisionCloudProp = (Button) findViewById(R.id.btn_startProvisionCloudConf);
197 mGetconfigurationStateText =
198 (TextView) findViewById(R.id.txt_getConfigurationState);
199 mDevNameText = (TextView) findViewById(R.id.txt_devName);
200 mModelNumberText = (TextView) findViewById(R.id.txt_modelNumber);
201 mDevTypeText = (TextView) findViewById(R.id.txt_devType);
202 mDevSubTypeText = (TextView) findViewById(R.id.txt_devSubType);
203 mWifiModeText = (TextView) findViewById(R.id.txt_wifiMode);
204 mWifiFreqText = (TextView) findViewById(R.id.txt_wifiFreq);
205 mCloudAccessableText = (TextView) findViewById(R.id.txt_cloudAccessable);
206 mSecStateText = (TextView) findViewById(R.id.txt_secState);
207 mSecDevIDText = (TextView) findViewById(R.id.txt_secDevID);
208 mProvisionDevPropState = (TextView) findViewById(R.id.txt_provisionDevConfState);
209 mProvisionCloudPropState =
210 (TextView) findViewById(R.id.txt_provisionCloudConfState);
212 mEnrollerSsidText = (EditText) findViewById(R.id.editText_EnrollerSSID);
213 mEnrollerPWText = (EditText) findViewById(R.id.editText_EnrollerPW);
214 mInputLanguageText = (EditText) findViewById(R.id.editText_Language);
215 mInputCountryText = (EditText) findViewById(R.id.editText_Country);
216 mInputLocationText = (EditText) findViewById(R.id.editText_Location);
217 mDiscoveryChannelText = (EditText) findViewById(R.id.editText_DiscoveryChannel);
218 mAddrText = (EditText) findViewById(R.id.editText_LocationAddr);
219 mZipCodeText = (EditText) findViewById(R.id.editText_LocationZip);
220 mBuildingText = (EditText) findViewById(R.id.editText_LocationBuilding);
221 mAuthCodeText = (EditText) findViewById(R.id.editText_authcode);
222 mAuthProviderText = (EditText) findViewById(R.id.editText_authprovider);
223 mCIServerText = (EditText) findViewById(R.id.editText_ciserver);
225 mGetConfigurationInfo =
226 (LinearLayout) findViewById(R.id.layout_GetConfiguration);
227 mConfigureSecInfo = (LinearLayout) findViewById(R.id.layout_ConfigurSec);
228 mProvisionDevPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionDevConf);
229 mProvisionCloudPropInfo = (LinearLayout) findViewById(R.id.layout_ProvisionCloudConf);
231 mAuthType = (Spinner) findViewById(R.id.spinner_authType);
232 mEncType = (Spinner) findViewById(R.id.spinner_encType);
234 mEasysetupProcess.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
236 public void onCheckedChanged(RadioGroup group, int checkedId) {
237 mGetConfigurationInfo.setVisibility(View.GONE);
238 mConfigureSecInfo.setVisibility(View.GONE);
239 mProvisionDevPropInfo.setVisibility(View.GONE);
240 mProvisionCloudPropInfo.setVisibility(View.GONE);
243 case R.id.btn_configurSec:
244 mConfigureSecInfo.setVisibility(View.VISIBLE);
247 case R.id.btn_getConfiguration:
248 mGetConfigurationInfo.setVisibility(View.VISIBLE);
251 case R.id.btn_provisionDevConf:
252 mProvisionDevPropInfo.setVisibility(View.VISIBLE);
255 case R.id.btn_provisionCloudConf:
256 Log.d(TAG, "Starting login activity");
257 Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
258 startActivityForResult(intent, 2);
259 mProvisionCloudPropInfo.setVisibility(View.VISIBLE);
265 ArrayAdapter<CharSequence> adAuthType, adEnctype;
267 adAuthType = ArrayAdapter.createFromResource(this, R.array.auth_type,
268 android.R.layout.simple_spinner_item);
269 adAuthType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
271 adEnctype = ArrayAdapter.createFromResource(this, R.array.enc_type,
272 android.R.layout.simple_spinner_item);
273 adEnctype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
275 mAuthType.setAdapter(adAuthType);
276 mAuthType.setSelection(0);
278 mEncType.setAdapter(adEnctype);
279 mEncType.setSelection(0);
281 addListenerForDiscoverEnrollee();
282 addListenerForStartConfigureSec();
283 addListenerForStartGetConfiguration();
284 addListenerForStartProvisionDevProp();
285 addListenerForStartProvisionCloudProp();
287 mSecurityMode.setClickable(false);
288 mConfigureSecProcess.setEnabled(false);
289 mGetConfigurationProcess.setEnabled(false);
290 mProvisionDevPropProcess.setEnabled(false);
291 mProvisionCloudPropProcess.setEnabled(false);
293 mEasySetup = EasySetup.getInstance(getApplicationContext());
298 m_accountManager = OcPlatform.constructAccountManagerObject(
300 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
302 Log.e(TAG, "constructAccountManagerObject is successful");
303 } catch (OcException e) {
304 Log.e(TAG, e.toString());
305 Log.e(TAG,"Failed to constructAccountManagerObject");
307 SharedPreferences settings =
308 getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
309 mAccessToken = settings.getString("accesstoken", null);
310 mRefreshtoken = settings.getString("refreshtoken", null);
311 mUserID = settings.getString("uid", null);
313 if(mRefreshtoken == null)
315 Log.d(TAG, "Can not find refresh token");
318 if(mAccessToken == null && mRefreshtoken == null)
320 /* Samsung account */
321 Log.d(TAG, "Starting login activity");
323 Intent intent = new Intent(EasysetupActivity.this, LoginActivity.class);
324 startActivityForResult(intent, 1);
326 else if(mAccessToken != null)
332 private void initOICStack() {
333 filePath = getFilesDir().getPath() + "/";
335 SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences
336 (getApplicationContext());
337 boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
339 if(!copyJsonFromAsset())
341 Log.e(TAG, "initOICStack error: " + "copyJsonFromAsset()");
342 Toast.makeText(this,"Can't Copy DB file from asset, please retry start SampleApp.",
343 Toast.LENGTH_LONG).show();
346 SharedPreferences.Editor editor = wmbPreference.edit();
347 editor.putBoolean("FIRSTRUN", false);
351 cfg = new PlatformConfig(
354 ModeType.CLIENT_SERVER,
355 "0.0.0.0", // bind to all available interfaces
357 QualityOfService.LOW, filePath + OIC_CLIENT_JSON_DB_FILE);
360 * Initialize DataBase
363 OcPlatform.Configure(cfg);
365 String sqlDbPath = getFilesDir().getAbsolutePath().replace("files", "databases") +
367 File file = new File(sqlDbPath);
368 //check files directory exists
369 if (!(file.isDirectory())) {
371 Log.d(TAG, "Sql db directory created at " + sqlDbPath);
373 Log.d(TAG, "Sql db directory exists at " + sqlDbPath);
375 //SQLiteDatabase.openOrCreateDatabase(sqlDbPath+ OIC_SQL_DB_FILE, null);
376 OcProvisioning.provisionInit(sqlDbPath + OIC_SQL_DB_FILE);
377 mSecurityMode.setChecked(true);
378 } catch (OcException e) {
379 logMessage(TAG + "provisionInit error: " + e.getMessage());
380 Log.e(TAG, e.getMessage());
381 Toast.makeText(this,"provisionInit error: " + e.getMessage(),
382 Toast.LENGTH_LONG).show();
383 mSecurityMode.setChecked(false);
385 } catch (UnsatisfiedLinkError e) {
387 // Note : Easy setup is built with SECURED = 0, but user still selects Security feature
388 // while running the Mediator App it couldn't find "libocprovision.so".
389 // As per the programmer guide, security feature should be invoked only if build is done with SECURED = 1.
390 mSecurityMode.setChecked(false);
391 Log.e(TAG, " Easy setup is built with secured = 0, but executed with security feature");
392 Toast.makeText(this,"Security is not enabled [Easy setup is built with SECURED = 0]",
393 Toast.LENGTH_LONG).show();
398 OcPlatform.OnResourceFoundListener listener =
399 new OcPlatform.OnResourceFoundListener() {
401 public void onFindResourceFailed(Throwable throwable, String s) {
402 Log.e(TAG, "Failed found resource, ecode: " + s);
405 public void onResourceFound(OcResource ocResource) {
406 synchronized (mActivity) {
408 if (null == ocResource) {
409 Log.e(TAG, "Found resource is invalid");
413 if(ocResource.getHost().contains("coap+tcp")) {
414 Log.d(TAG, "Recv Found resource event from tcp port," +
415 "ignoring URI : " + ocResource.getUri());
416 runOnUiThread(new Runnable() {
419 mDiscoverResource.setEnabled(true);
425 // Get the resource URI
426 String resourceUri = ocResource.getUri();
427 // Get the resource host address
428 String hostAddress = ocResource.getHost();
429 Log.d(TAG,"URI of the resource: " + resourceUri);
430 Log.d(TAG,"Host address of the resource: " + hostAddress);
432 runOnUiThread(new Runnable() {
435 mDiscoverResource.setText("Found");
436 if(mSecurityMode.isChecked()) {
437 mConfigureSecProcess.setEnabled(true);
439 mGetConfigurationProcess.setEnabled(true);
440 mProvisionDevPropProcess.setEnabled(true);
441 mProvisionCloudPropProcess.setEnabled(true);
445 mRemoteEnrollee = mEasySetup.createRemoteEnrollee(ocResource);
446 mEnrolleeDeviceID = ocResource.getServerId();
452 private void addListenerForDiscoverEnrollee() {
453 mDiscoverResource.setOnClickListener(new View.OnClickListener() {
455 public void onClick(View v) {
456 Thread thread = new Thread() {
457 boolean result = true;
460 runOnUiThread(new Runnable() {
463 mDiscoverResource.setEnabled(false);
468 String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=" + ESConstants.OC_RSRVD_ES_RES_TYPE_EASYSETUP;
469 OcPlatform.findResource("",
471 EnumSet.of(OcConnectivityType.CT_DEFAULT),
475 catch (OcException e) {
478 runOnUiThread(new Runnable() {
481 mDiscoverResource.setEnabled(true);
493 private void addListenerForStartConfigureSec() {
494 mStartConfigureSec.setOnClickListener(new View.OnClickListener() {
496 public void onClick(View v) {
497 Thread thread = new Thread() {
500 runOnUiThread(new Runnable() {
503 mStartConfigureSec.setEnabled(false);
508 mRemoteEnrollee.provisionSecurity(new SecurityProvisioningCallback() {
510 public void onProgress(final SecurityProvisioningStatus securityProvisioningStatus) {
511 if(securityProvisioningStatus.getESResult() == ESResult.ES_OK) {
512 runOnUiThread(new Runnable() {
515 mSecStateText.setText("Success");
516 mSecDevIDText.setText(securityProvisioningStatus.getDevUUID());
520 else if(securityProvisioningStatus.getESResult()
521 == ESResult.ES_SECURE_RESOURCE_DISCOVERY_FAILURE) {
522 runOnUiThread(new Runnable() {
525 mSecStateText.setText("Not found Secure Resource");
526 mStartConfigureSec.setEnabled(true);
530 else if(securityProvisioningStatus.getESResult()
531 == ESResult.ES_OWNERSHIP_TRANSFER_FAILURE) {
532 runOnUiThread(new Runnable() {
535 mSecStateText.setText("Ownership transfer failed");
536 mStartConfigureSec.setEnabled(true);
541 runOnUiThread(new Runnable() {
544 mSecStateText.setText("Failed");
545 mStartConfigureSec.setEnabled(true);
551 } catch (ESException e) {
553 runOnUiThread(new Runnable() {
556 mStartConfigureSec.setEnabled(true);
568 private void addListenerForStartGetConfiguration(){
569 mStartGetConfiguration.setOnClickListener(new View.OnClickListener() {
571 public void onClick(View v) {
572 Thread thread = new Thread() {
575 runOnUiThread(new Runnable() {
578 mGetconfigurationStateText.setText("Process");
579 mStartGetConfiguration.setEnabled(false);
584 mRemoteEnrollee.getConfiguration(new GetConfigurationCallback() {
586 public void onProgress(GetConfigurationStatus getConfigurationStatus) {
587 if(getConfigurationStatus.getESResult() == ESResult.ES_OK) {
589 final SCEnrolleeConf scEnrolleeConf =
590 new SCEnrolleeConf(getConfigurationStatus.getEnrolleeConf());
592 runOnUiThread(new Runnable() {
595 mGetconfigurationStateText.setText("Success");
596 mDevNameText.setText(scEnrolleeConf.getDeviceName());
597 mModelNumberText.setText(scEnrolleeConf.getModelNumber());
598 mDevTypeText.setText(scEnrolleeConf.getDeviceType());
599 mDevSubTypeText.setText(scEnrolleeConf.getDeviceSubType());
600 setWifiModes(scEnrolleeConf.getWiFiModes());
601 setWifiFreq(scEnrolleeConf.getWiFiFreq());
603 if(scEnrolleeConf.isCloudAccessible()) {
604 mCloudAccessableText.setText("TRUE");
607 mCloudAccessableText.setText("FALSE");
612 else if(getConfigurationStatus.getESResult() == ESResult.ES_COMMUNICATION_ERROR)
614 runOnUiThread(new Runnable() {
617 mGetconfigurationStateText.setText("Communication Error");
618 mStartGetConfiguration.setEnabled(true);
623 runOnUiThread(new Runnable() {
626 mGetconfigurationStateText.setText("Failed");
627 mStartGetConfiguration.setEnabled(true);
633 } catch (ESException e) {
635 runOnUiThread(new Runnable() {
638 mGetconfigurationStateText.setText("Failed");
639 mStartGetConfiguration.setEnabled(true);
651 private void addListenerForStartProvisionDevProp() {
652 mStartProvisionDevProp.setOnClickListener(new View.OnClickListener() {
654 public void onClick(View v) {
655 Thread thread = new Thread() {
659 runOnUiThread(new Runnable() {
662 mProvisionDevPropState.setText("Progress");
663 mStartProvisionDevProp.setEnabled(false);
667 String enrollerSSID = mEnrollerSsidText.getText().toString();
668 String enrollerPW = mEnrollerPWText.getText().toString();
669 String discoveryChannel = mDiscoveryChannelText.getText().toString();
670 String addr = mAddrText.getText().toString();
671 String zipcode = mZipCodeText.getText().toString();
672 String building = mBuildingText.getText().toString();
673 WIFI_AUTHTYPE authType =
674 WIFI_AUTHTYPE.fromInt(mAuthType.getSelectedItemPosition());
675 WIFI_ENCTYPE encType =
676 WIFI_ENCTYPE.fromInt(mEncType.getSelectedItemPosition());
677 String inputLanguage = mInputLanguageText.getText().toString();
678 String inputCountry = mInputCountryText.getText().toString();
679 String inputLocation = mInputLocationText.getText().toString();
681 ArrayList<String> locations = new ArrayList<String>();
683 locations.add(zipcode);
684 locations.add(building);
686 SCDeviceProp scDevProp = new SCDeviceProp();
687 scDevProp.setWiFiProp(enrollerSSID, enrollerPW, authType, encType);
688 scDevProp.setDevConfProp(inputLanguage, inputCountry, inputLocation);
689 scDevProp.setDiscoveryChannel(Integer.parseInt(discoveryChannel));
690 scDevProp.setSCLocation(locations);
692 mRemoteEnrollee.provisionDeviceProperties(scDevProp, new DevicePropProvisioningCallback() {
694 public void onProgress(DevicePropProvisioningStatus devPropProvisioningStatus) {
695 final ESResult result = devPropProvisioningStatus.getESResult();
696 runOnUiThread(new Runnable() {
699 if(result.equals(ESResult.ES_OK)) {
700 mProvisionDevPropState.setText("Success");
702 else if(result.equals(ESResult.ES_ERROR)) {
703 mProvisionDevPropState.setText("Failed");
705 else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)) {
706 mProvisionDevPropState.setText("Communication Error");
708 mStartProvisionDevProp.setEnabled(true);
713 } catch (ESException e) {
715 runOnUiThread(new Runnable() {
718 mProvisionDevPropState.setText("Failed");
719 mStartProvisionDevProp.setEnabled(true);
731 private void addListenerForStartProvisionCloudProp() {
732 mStartProvisionCloudProp.setOnClickListener(new View.OnClickListener() {
734 public void onClick(View v) {
735 Thread thread = new Thread() {
738 runOnUiThread(new Runnable() {
741 mProvisionCloudPropState.setText("Progress");
742 mStartProvisionCloudProp.setEnabled(false);
747 String authCode = mAuthCodeText.getText().toString();
748 String authProvider = mAuthProviderText.getText().toString();
749 String ciserver = samsungCIServer;
751 CloudProp cloudProp = new CloudProp();
752 cloudProp.setCloudProp(authCode, authProvider, ciserver);
753 cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3");
754 cloudProp.setCredID(1);
756 mRemoteEnrollee.provisionCloudProperties(cloudProp, new CloudPropProvisioningCallback() {
758 public void onProgress(CloudPropProvisioningStatus cloudProvisioningStatus) {
759 final ESResult result = cloudProvisioningStatus.getESResult();
760 runOnUiThread(new Runnable() {
763 if(result.equals(ESResult.ES_ENROLLEE_DISCOVERY_FAILURE)) {
764 mProvisionCloudPropState.setText("Not Found Resource");
766 else if(result.equals(ESResult.ES_OK)) {
767 mProvisionCloudPropState.setText("Cloud Provisioning succeeds");
769 else if(result.equals(ESResult.ES_ACL_PROVISIONING_FAILURE)){
770 mProvisionCloudPropState.setText("ACL-provisioning fails");
772 else if(result.equals(ESResult.ES_CERT_PROVISIONING_FAILURE)){
773 mProvisionCloudPropState.setText("CERT-provisioning fails");
775 else if(result.equals(ESResult.ES_COMMUNICATION_ERROR)){
776 mProvisionCloudPropState.setText("Communication Error");
779 mProvisionCloudPropState.setText("Cloud Provisioning fails");
785 } catch (ESException e) {
787 runOnUiThread(new Runnable() {
790 mProvisionCloudPropState.setText("Failed");
791 mStartProvisionCloudProp.setEnabled(true);
803 private boolean copyJsonFromAsset() {
804 InputStream inputStream = null;
805 OutputStream outputStream = null;
807 byte[] buffer = new byte[BUFFER_SIZE];
809 inputStream = getAssets().open(OIC_CLIENT_JSON_DB_FILE);
810 File file = new File(filePath);
811 //check files directory exists
812 if (!(file.exists() && file.isDirectory())) {
815 outputStream = new FileOutputStream(filePath + OIC_CLIENT_JSON_DB_FILE);
816 while ((length = inputStream.read(buffer)) != -1) {
817 outputStream.write(buffer, 0, length);
819 } catch (NullPointerException e) {
820 logMessage(TAG + "Null pointer exception " + e.getMessage());
821 Log.e(TAG, e.getMessage());
823 } catch (FileNotFoundException e) {
824 logMessage(TAG + "Json svr db file not found " + e.getMessage());
825 Log.e(TAG, e.getMessage());
827 } catch (IOException e) {
828 logMessage(TAG + OIC_CLIENT_JSON_DB_FILE + " file copy failed");
829 Log.e(TAG, e.getMessage());
832 if (inputStream != null) {
835 } catch (IOException e) {
836 Log.e(TAG, e.getMessage());
840 if (outputStream != null) {
842 outputStream.close();
843 } catch (IOException e) {
844 Log.e(TAG, e.getMessage());
852 public void logMessage(String text) {
856 public void setWifiModes(ArrayList<WIFI_MODE> types) {
857 String temp = "WIFI - ";
859 for(WIFI_MODE type : types) {
860 if(type.equals(WIFI_MODE.WIFI_11A)) {
861 temp = temp + "11A ";
863 else if(type.equals(WIFI_MODE.WIFI_11B)) {
864 temp = temp + "11B ";
866 else if(type.equals(WIFI_MODE.WIFI_11G)) {
867 temp = temp + "11G ";
869 else if(type.equals(WIFI_MODE.WIFI_11N)) {
870 temp = temp + "11N ";
872 else if(type.equals(WIFI_MODE.WIFI_11AC)) {
873 temp = temp + "11AC ";
876 final String modeTypes = temp;
877 runOnUiThread(new Runnable() {
880 mWifiModeText.setText(modeTypes);
885 public void setWifiFreq(final WIFI_FREQ freq) {
886 runOnUiThread(new Runnable() {
889 if(freq.equals(WIFI_FREQ.WIFI_24G)) {
890 mWifiFreqText.setText("2.4G");
892 else if(freq.equals(WIFI_FREQ.WIFI_5G)) {
893 mWifiFreqText.setText("5G");
895 else if(freq.equals(WIFI_FREQ.WIFI_BOTH)) {
896 mWifiFreqText.setText("2.4G & 5G");
903 public void onPresence(OcPresenceStatus status, int sequence, String host) {
904 final String strStaus = status.getValue();
905 Log.d(TAG, "Presence response: " + strStaus + " sequence: " + sequence + " host: " + host);
906 runOnUiThread(new Runnable()
909 Toast.makeText(EasysetupActivity.this, "Easy-Setup completed", Toast.LENGTH_SHORT).show();
915 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
916 super.onActivityResult(requestCode, resultCode, data);
917 if(resultCode==RESULT_OK && requestCode==1){
918 mAuthCode = data.getStringExtra("authCode");
919 mAuthProvider = data.getStringExtra("authProvider");
920 String text = "Received authCode= " + mAuthCode;
924 else if(resultCode==RESULT_OK && requestCode==2)
926 mEnrolleeAuthCode = data.getStringExtra("authCode");
927 mAuthCodeText.setText(mEnrolleeAuthCode);
928 mAuthProviderText.setText("samsung");
929 mAuthCodeText.setEnabled(false);
930 mAuthProviderText.setEnabled(false);
931 subscribeDevicePresence();
935 OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
937 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
938 Log.d(TAG, "onRefreshTokenPost..");
940 mAccessToken = ocRepresentation.getValue("accesstoken");
941 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
943 saveCloudTokenAtSharedPreferences();
945 catch (OcException e)
954 public void onPostFailed(Throwable throwable) {
955 Log.d(TAG, "onRefreshTokenPost failed..");
959 public void RefreshToken() {
961 OcResource authResource = OcPlatform.constructResourceObject(samsungCIServer, "/.well-known/ocf/account/tokenrefresh",
962 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
963 false, Arrays.asList("oic.wk.account"), Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
964 OcRepresentation rep = new OcRepresentation();
966 runOnUiThread(new Runnable()
969 Toast.makeText(EasysetupActivity.this, "RefreshToken in progress..", Toast.LENGTH_SHORT).show();
973 rep.setValue("di", deviceID);
974 rep.setValue("granttype", "refresh_token");
975 rep.setValue("refreshtoken", mRefreshtoken);
976 rep.setValue("uid", mUserID);
977 authResource.post(rep, new HashMap<String, String>(), onRefreshTokenPost);
984 Log.d(TAG, "No error while executing login");
987 private void saveCloudTokenAtSharedPreferences() {
988 Log.d(TAG, "accesstoken: " + mAccessToken);
989 SharedPreferences settings = getApplicationContext().getSharedPreferences("IoTivityCloud", 0);
990 SharedPreferences.Editor editor = settings.edit();
991 editor.putString("accesstoken", mAccessToken);
992 editor.putString("refreshtoken", mRefreshtoken);
993 editor.putString("uid", mUserID);
995 if(editor.commit() == true)
996 Log.d(TAG, "accesstoken saved");
998 Log.d(TAG, "accesstoken not saved");
1001 OcAccountManager.OnPostListener onSignUpPost = new OcAccountManager.OnPostListener() {
1003 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
1004 Log.d(TAG, "onSignUpPost..");
1006 runOnUiThread(new Runnable()
1009 Toast.makeText(EasysetupActivity.this, "Sign-up completed", Toast.LENGTH_SHORT).show();
1013 mAccessToken = ocRepresentation.getValue("accesstoken");
1014 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
1015 mUserID = ocRepresentation.getValue("uid");
1017 if(mAccessToken != null)
1019 saveCloudTokenAtSharedPreferences();
1023 catch (OcException e)
1025 e.printStackTrace();
1030 public void onPostFailed(Throwable throwable) {
1031 Log.d(TAG, "onSignUpPost failed.. : " + throwable.getMessage());
1035 private void SignUpDevice() {
1037 Log.d(TAG, "SignUpDevice..");
1039 runOnUiThread(new Runnable()
1042 Toast.makeText(EasysetupActivity.this, "SignUpDevice in progress..", Toast.LENGTH_SHORT).show();
1046 if(m_accountManager != null) {
1047 m_accountManager.signUp(mAuthProvider, mAuthCode, onSignUpPost);
1050 catch(OcException e)
1052 e.printStackTrace();
1055 Log.d(TAG, "No error while executing SignUp");
1058 OcAccountManager.OnPostListener onSignInPost = new OcAccountManager.OnPostListener() {
1060 public void onPostCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
1061 Log.d(TAG, "onSignInPost..");
1063 runOnUiThread(new Runnable()
1066 Toast.makeText(EasysetupActivity.this, "Sign-in completed", Toast.LENGTH_SHORT).show();
1072 public void onPostFailed(Throwable ex) {
1073 if (ex instanceof OcException) {
1074 OcException ocEx = (OcException) ex;
1075 ErrorCode errCode = ocEx.getErrorCode();
1076 Log.e(TAG, ocEx.getMessage());
1077 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
1084 private void SignInDevice() {
1086 Log.d(TAG, "SignInDevice..");
1088 runOnUiThread(new Runnable()
1091 Toast.makeText(EasysetupActivity.this, "SignInDevice in progress..", Toast.LENGTH_SHORT).show();
1094 if(m_accountManager != null) {
1095 m_accountManager.signIn(mUserID, mAccessToken, onSignInPost);
1098 catch(OcException e)
1100 e.printStackTrace();
1103 Log.d(TAG, "No error while executing login");
1107 public void onObserveCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation, int i) {
1108 Log.d(TAG,"onObserveCompleted");
1112 public void onObserveFailed(Throwable throwable) {
1113 Log.d(TAG,"onObserveFailed");
1116 public void subscribeDevicePresence()
1118 List<String> deviceIDs = new ArrayList<String>();
1119 deviceIDs.add(mEnrolleeDeviceID);
1123 OcPlatform.subscribeDevicePresence(samsungCIServer, deviceIDs, EnumSet.of(OcConnectivityType.
1124 CT_ADAPTER_TCP), this);
1125 } catch(OcException e)
1127 e.printStackTrace();
1133 protected void onDestroy() {