1 /******************************************************************
2 * Copyright 2016 Samsung Electronics All Rights Reserved.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 ******************************************************************/
19 package org.iotivity.service.ns.sample.consumer;
21 import android.app.Dialog;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.os.Message;
27 import android.app.Activity;
28 import android.util.Log;
29 import android.view.View;
30 import android.widget.Button;
31 import android.widget.EditText;
32 import android.widget.TextView;
33 import android.widget.Toast;
35 import org.iotivity.base.ErrorCode;
36 import org.iotivity.base.OcAccountManager;
37 import org.iotivity.base.OcConnectivityType;
38 import org.iotivity.base.OcException;
39 import org.iotivity.base.OcHeaderOption;
40 import org.iotivity.base.OcPlatform;
41 import org.iotivity.base.OcRepresentation;
42 import org.iotivity.base.OcResource;
43 import org.iotivity.service.ns.common.TopicsList;
44 import org.iotivity.service.ns.common.Topic;
46 import java.util.Arrays;
47 import java.util.EnumSet;
48 import java.util.HashMap;
49 import java.util.List;
52 public class MainActivity extends Activity
53 implements OcAccountManager.OnPostListener {
54 private final String TAG = "NS_MAIN_ACTIVITY";
55 private final int REQUEST_LOGIN = 1;
56 private static final String CI_SERVER_PREFIX = "coap+tcp://";
57 private final Context context = this;
59 public static String deviceID = null;
60 public static String CIServer = null;
61 public static String RemoteAddress = null;
62 public static String MQCloudAddress = null;
63 public static String MQCloudTopic = null;
65 private Button btnStart;
66 private Button btnStop;
67 private Button btnRescan;
68 private Button btnSubscribe;
69 private Button btnUnsubscribe;
70 private Button btnEnableRemoteService;
71 private Button btnGetTopicList;
72 private Button btnUpdateTopicList;
73 private Button btnClearLog;
74 private static TextView TvLog;
75 private Button signUp, signIn, signOut;
76 private Button subscribeMQ;
78 private boolean isStarted = false;
80 private ConsumerSample mConsumerSample = null;
81 private OcAccountManager mAccountManager;
88 private static final int PROVIDER_DISCOVERED = 1;
89 private static final int STATE_CHANGED = 2;
90 private static final int MESSAGE_RECEIVED = 3;
91 private static final int SYNCINFO_RECEIVED = 4;
92 private static final int TOPICS_RECEIVED = 5;
94 public static Handler mHandler = new Handler() {
96 public void handleMessage(Message msg) {
98 case PROVIDER_DISCOVERED: {
99 String providerId = (String) msg.obj;
100 if (providerId != null) {
101 TvLog.append(providerId + "\n");
105 case STATE_CHANGED: {
106 String state = (String) msg.obj;
108 TvLog.append(state + "\n");
112 case MESSAGE_RECEIVED: {
113 String message = (String) msg.obj;
114 if (message != null) {
115 TvLog.append(message + "\n");
119 case SYNCINFO_RECEIVED: {
120 String sync = (String) msg.obj;
122 TvLog.append(sync + "\n");
126 case TOPICS_RECEIVED: {
127 String topicList = (String) msg.obj;
128 if (topicList != null) {
129 TvLog.append(topicList + "\n");
139 public void showToast(final String toast) {
140 runOnUiThread(new Runnable() {
143 Toast.makeText(getApplicationContext(), toast,
144 Toast.LENGTH_SHORT).show();
150 protected void onCreate(Bundle savedInstanceState) {
151 super.onCreate(savedInstanceState);
152 setContentView(R.layout.activity_main);
154 btnStart = (Button) findViewById(R.id.BtnStart);
155 btnStop = (Button) findViewById(R.id.BtnStop);
156 btnRescan = (Button) findViewById(R.id.BtnRescan);
157 btnSubscribe = (Button) findViewById(R.id.BtnSubscribe);
158 btnUnsubscribe = (Button) findViewById(R.id.BtnUnsubscribe);
159 btnEnableRemoteService = (Button) findViewById(
160 R.id.BtnEnableRemoteService);
161 btnGetTopicList = (Button) findViewById(R.id.BtnGetTopicList);
162 btnUpdateTopicList = (Button) findViewById(R.id.BtnUpdateTopicList);
163 btnClearLog = (Button) findViewById(R.id.BtnClearLog);
165 signUp = (Button) findViewById(R.id.signup);
166 signIn = (Button) findViewById(R.id.signin);
167 signOut = (Button) findViewById(R.id.signout);
168 subscribeMQ = (Button) findViewById(R.id.subscribeMQService);
169 TvLog = (TextView) findViewById(R.id.TvLog);
171 btnStart.setOnClickListener(mClickListener);
172 btnStop.setOnClickListener(mClickListener);
173 btnRescan.setOnClickListener(mClickListener);
174 btnEnableRemoteService.setOnClickListener(mClickListener);
175 btnGetTopicList.setOnClickListener(mClickListener);
176 btnUpdateTopicList.setOnClickListener(mClickListener);
177 btnClearLog.setOnClickListener(mClickListener);
179 signIn.setEnabled(false);
180 signOut.setEnabled(false);
181 btnEnableRemoteService.setEnabled(false);
183 btnSubscribe.setOnClickListener(mClickListener);
184 btnUnsubscribe.setOnClickListener(mClickListener);
185 signUp.setOnClickListener(mClickListener);
186 signIn.setOnClickListener(mClickListener);
187 signOut.setOnClickListener(mClickListener);
188 subscribeMQ.setOnClickListener(mClickListener);
190 mConsumerSample = new ConsumerSample(getApplicationContext());
191 mConsumerSample.setHandler(mHandler);
195 protected void onDestroy() {
197 mConsumerSample.stopNotificationConsumer();
201 Button.OnClickListener mClickListener = new View.OnClickListener() {
202 public void onClick(View v) {
204 case R.id.BtnStart: {
206 Log.i(TAG, "Start NS Consumer Service");
208 TvLog.setText("Start NS-Consumer\n");
209 mConsumerSample.startNotificationConsumer();
212 Log.e(TAG, "NS Consumer Service has already started");
213 showToast("Error : Service has already started");
221 "Fail to stop service. Service has not been started");
222 showToast("Error : Service has not been started");
225 TvLog.append("Stop NS-Consumer\n");
226 mConsumerSample.stopNotificationConsumer();
230 case R.id.BtnRescan: {
233 "Fail to rescan. Service has not been started");
234 showToast("Error : Service has not been started");
237 TvLog.append("Rescan NS-Consumer\n");
238 mConsumerSample.rescanProvider();
241 case R.id.BtnSubscribe: {
244 "Fail to Subscribe. Service has not been started");
245 showToast("Error : Service has not been started");
248 TvLog.append("Subscribe NS-Consumer\n");
249 mConsumerSample.subscribe();
252 case R.id.BtnUnsubscribe: {
255 "Fail to Unsubscribe. Service has not been started");
256 showToast("Error : Service has not been started");
259 TvLog.append("Unsubscribe NS-Consumer\n");
260 mConsumerSample.unsubscribe();
263 case R.id.BtnEnableRemoteService: {
266 "Fail to Enable RemoteService. Service has not been started");
267 showToast("Error : Service has not been started");
270 TvLog.append("EnableRemoteService NS-Consumer\n");
271 mConsumerSample.enableRemoteService(RemoteAddress);
274 case R.id.BtnGetTopicList: {
277 "Fail to GetTopicList. Service has not been started");
278 showToast("Error : Service has not been started");
281 TvLog.append("GetTopicList NS-Consumer\n");
282 mConsumerSample.getTopicsList();
285 case R.id.BtnUpdateTopicList: {
288 "Fail to UpdateTopicList. Service has not been started");
289 showToast("Error : Service has not been started");
292 if (mConsumerSample.getAcceptor()) {
294 "Operation Not Allowed. ProviderService Acceptor is not Consumer");
296 "Operation Not Allowed. ProviderService Acceptor is not Consumer");
299 TvLog.append("UpdateTopicList NS-Consumer\n");
301 TopicsList topicList = new TopicsList();
302 topicList.addTopic("OCF_TOPIC1",
303 Topic.TopicState.SUBSCRIBED);
304 topicList.addTopic("OCF_TOPIC2",
305 Topic.TopicState.SUBSCRIBED);
306 topicList.addTopic("OCF_TOPIC3",
307 Topic.TopicState.UNSUBSCRIBED);
309 mConsumerSample.updateTopicList(topicList);
312 case R.id.BtnClearLog: {
317 if (isStarted == false) {
318 Log.e(TAG, "Fail to Sign Up");
319 showToast("Start ConsumerService First");
322 TvLog.append("Initiating SignUp\n");
327 if (isStarted == false) {
328 Log.e(TAG, "Fail to Sign In");
329 showToast("Start ConsumerService First");
332 TvLog.append("Initiating SignIn\n");
337 if (isStarted == false) {
338 Log.e(TAG, "Fail to Sign out");
339 showToast("Start ConsumerService First");
342 TvLog.append("Initiating SignOut\n");
346 case R.id.subscribeMQService: {
347 if (isStarted == false) {
348 Log.e(TAG, "Fail to SubscribeMQService");
349 showToast("Start ProviderService First");
352 final Dialog dialog = new Dialog(context);
353 dialog.setContentView(R.layout.dialog_mq);
354 dialog.setTitle("MQ Cloud Service Details");
356 final EditText ip = (EditText) dialog
357 .findViewById(R.id.EditTextIp);
358 final EditText mqTopic = (EditText) dialog
359 .findViewById(R.id.EditTextMqTopic);
360 if (MQCloudAddress != null && MQCloudTopic != null) {
361 ip.setText(MQCloudAddress);
362 mqTopic.setText(MQCloudTopic);
365 Button dialogButton = (Button) dialog
366 .findViewById(R.id.mqButtonOK);
368 dialogButton.setOnClickListener(new View.OnClickListener() {
370 public void onClick(View v) {
372 MQCloudAddress = ip.getText().toString();
373 MQCloudTopic = mqTopic.getText().toString();
374 mConsumerSample.subscribeMQService(
375 MQCloudAddress, MQCloudTopic);
376 TvLog.append("SubscribeMQService success\n");
386 public void logMessage(final String text) {
387 runOnUiThread(new Runnable() {
389 Message msg = new Message();
391 TvLog.append(text + "\n");
397 OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
399 public synchronized void onPostCompleted(List<OcHeaderOption> list,
400 OcRepresentation ocRepresentation) {
401 logMessage("signUp was successful");
402 runOnUiThread(new Runnable() {
404 signIn.setEnabled(true);
405 signUp.setEnabled(false);
409 mUserID = ocRepresentation.getValue("uid");
410 mAccessToken = ocRepresentation.getValue("accesstoken");
411 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
413 logMessage("\tuserID: " + mUserID);
414 logMessage("\taccessToken: " + mAccessToken);
415 logMessage("\trefreshToken: " + mRefreshtoken);
417 if (ocRepresentation.hasAttribute("expiresin")) {
418 int expiresIn = ocRepresentation.getValue("expiresin");
419 logMessage("\texpiresIn: " + expiresIn);
421 } catch (OcException e) {
422 Log.e(TAG, e.toString());
427 public synchronized void onPostFailed(Throwable throwable) {
428 logMessage("Failed to signUp");
429 if (throwable instanceof OcException) {
430 OcException ocEx = (OcException) throwable;
431 Log.e(TAG, ocEx.toString());
432 ErrorCode errCode = ocEx.getErrorCode();
433 logMessage("Error code: " + errCode);
438 OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
440 public synchronized void onPostCompleted(List<OcHeaderOption> list,
441 OcRepresentation ocRepresentation) {
442 logMessage("signIn was successful");
443 runOnUiThread(new Runnable() {
445 signIn.setEnabled(false);
446 signOut.setEnabled(true);
447 btnEnableRemoteService.setEnabled(true);
454 public synchronized void onPostFailed(Throwable throwable) {
455 logMessage("Failed to signIn");
456 if (throwable instanceof OcException) {
457 OcException ocEx = (OcException) throwable;
458 Log.e(TAG, ocEx.toString());
459 ErrorCode errCode = ocEx.getErrorCode();
460 logMessage("Error code: " + errCode);
461 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
468 OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
470 public synchronized void onPostCompleted(List<OcHeaderOption> list,
471 OcRepresentation ocRepresentation) {
472 logMessage("signOut was successful");
473 runOnUiThread(new Runnable() {
475 signIn.setEnabled(true);
476 signOut.setEnabled(false);
477 btnEnableRemoteService.setEnabled(false);
484 public synchronized void onPostFailed(Throwable throwable) {
485 logMessage("Failed to signOut");
486 if (throwable instanceof OcException) {
487 OcException ocEx = (OcException) throwable;
488 Log.e(TAG, ocEx.toString());
489 ErrorCode errCode = ocEx.getErrorCode();
490 logMessage("Error code: " + errCode);
491 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
500 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
501 OcRepresentation ocRepresentation) {
506 public void onPostFailed(Throwable throwable) {
510 private void signIn() {
512 if (mAccountManager == null) {
513 mAccountManager = OcPlatform.constructAccountManagerObject(
515 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
518 mAccountManager.signIn(mUserID, mAccessToken, onSignIn);
519 } catch (OcException e) {
524 private void signOut() {
526 logMessage("signOut");
527 if (mAccountManager == null) {
529 mAccountManager = OcPlatform.constructAccountManagerObject(
531 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
532 } catch (OcException e) {
536 mAccountManager.signOut(mAccessToken, onSignOut);
537 signIn.setEnabled(false);
538 signUp.setEnabled(true);
539 btnEnableRemoteService.setEnabled(false);
540 logMessage("signOut Successful");
541 } catch (OcException e) {
546 private void signUp() {
547 Intent intentLogin = new Intent(this, LoginActivity.class);
548 startActivityForResult(intentLogin, REQUEST_LOGIN);
552 public void onActivityResult(int requestCode, int resultCode, Intent data) {
553 super.onActivityResult(requestCode, resultCode, data);
554 if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
555 mAuthCode = data.getStringExtra("authCode");
556 mAuthProvider = data.getStringExtra("authProvider");
557 logMessage("authCode: " + mAuthCode);
558 logMessage("authProvider: " + mAuthProvider);
560 final Dialog dialog = new Dialog(context);
561 dialog.setContentView(R.layout.dialog_entry);
562 dialog.setTitle("SignUp Acccount IP Address");
563 final EditText ip = (EditText) dialog
564 .findViewById(R.id.EditTextEntry);
565 if (RemoteAddress != null) {
566 ip.setText(RemoteAddress);
568 Button dialogButton = (Button) dialog
569 .findViewById(R.id.entryButtonOK);
570 dialogButton.setOnClickListener(new View.OnClickListener() {
572 public void onClick(View v) {
574 RemoteAddress = ip.getText().toString();
575 CIServer = CI_SERVER_PREFIX + RemoteAddress;
576 logMessage("server address for signup is: \n" + CIServer);
578 mAccountManager = OcPlatform
579 .constructAccountManagerObject(CIServer, EnumSet
580 .of(OcConnectivityType.CT_ADAPTER_TCP));
581 logMessage("Calling signup API");
583 if (mAuthProvider.equals("samsung")
584 || mAuthProvider.equals("samsung-us")) {
585 logMessage("Auth provider is samsung");
586 Map<String, String> options = new HashMap<>();
587 options.put("auth_server_url",
588 "us-auth2.samsungosp.com");
589 options.put("api_server_url",
590 "us-auth2.samsungosp.com");
591 mAccountManager.signUp(mAuthProvider, mAuthCode,
594 mAccountManager.signUp(mAuthProvider, mAuthCode,
597 } catch (OcException e) {
606 OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
608 public void onPostCompleted(List<OcHeaderOption> list,
609 OcRepresentation ocRepresentation) {
610 logMessage("RefreshToken Completed.");
612 mAccessToken = ocRepresentation.getValue("accesstoken");
613 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
614 } catch (OcException e) {
621 public void onPostFailed(Throwable throwable) {
622 logMessage("RefreshToken failed.");
623 Log.d(TAG, "onRefreshTokenPost failed..");
627 public void refreshToken() {
629 if (deviceID == null) {
630 final Dialog dialog = new Dialog(context);
631 dialog.setContentView(R.layout.dialog_entry);
632 dialog.setTitle("Enter Device Id");
633 dialog.setCanceledOnTouchOutside(false);
634 final EditText id = (EditText) dialog
635 .findViewById(R.id.EditTextEntry);
637 Button dialogButton = (Button) dialog
638 .findViewById(R.id.entryButtonOK);
639 dialogButton.setOnClickListener(new View.OnClickListener() {
641 public void onClick(View v) {
643 deviceID = id.getText().toString();
649 OcResource authResource = OcPlatform.constructResourceObject(
650 CIServer, "/.well-known/ocf/account/tokenrefresh",
651 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP,
652 OcConnectivityType.CT_IP_USE_V4),
653 false, Arrays.asList("oic.wk.account"),
654 Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
655 OcRepresentation rep = new OcRepresentation();
657 showToast("RefreshToken in progress..");
658 logMessage("RefreshToken in progress..");
659 rep.setValue("di", deviceID);
660 rep.setValue("granttype", "refresh_token");
661 rep.setValue("refreshtoken", mRefreshtoken);
662 rep.setValue("uid", mUserID);
663 authResource.post(rep, new HashMap<String, String>(),
665 } catch (OcException e) {
669 Log.d(TAG, "No error while executing login");