2 //******************************************************************
4 // Copyright 2016 Samsung Electronics All Rights Reserved.
6 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
20 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 package org.iotivity.service.ns.sample.provider;
25 import android.app.Dialog;
26 import android.app.Notification;
27 import android.app.NotificationManager;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.Message;
33 import android.util.Log;
34 import android.view.View;
35 import android.widget.Button;
36 import android.widget.EditText;
37 import android.widget.RadioButton;
38 import android.widget.TextView;
39 import android.widget.Toast;
40 import android.app.Activity;
42 import org.iotivity.base.ErrorCode;
43 import org.iotivity.base.OcAccountManager;
44 import org.iotivity.base.OcConnectivityType;
45 import org.iotivity.base.OcException;
46 import org.iotivity.base.OcHeaderOption;
47 import org.iotivity.base.OcPlatform;
48 import org.iotivity.base.OcRepresentation;
49 import org.iotivity.base.OcResource;
51 import java.util.Arrays;
52 import java.util.EnumSet;
53 import java.util.HashMap;
54 import java.util.List;
57 public class MainActivity extends Activity
58 implements OcAccountManager.OnPostListener {
60 private final String TAG = "NS_MAIN_ACTIVITY";
61 private static final int CONSUMER_SUBSCRIBED = 1;
62 private static final int MESSAGE_SYNC = 2;
63 private final int REQUEST_LOGIN = 1;
64 private static final String CI_SERVER_PREFIX = "coap+tcp://";
65 private final Context context = this;
67 public static String deviceID = null;
68 public static String CIServer = null;
69 public static String RemoteAddress = null;
70 public static String MQCloudAddress = null;
71 public static String MQCloudTopic = null;
73 private Button btnTitle;
74 private Button btnBody;
75 private Button btnTopic;
76 private Button btnSend;
77 private Button btnStart;
78 private Button btnRegister;
79 private Button btnSet;
80 private Button btnStop;
81 private Button btnLog;
82 private Button signUp, signIn, signOut;
83 private Button remoteService, subscribeMQ;
84 private EditText editTextTitle;
85 private EditText editTextBody;
86 private EditText editTextTopic;
87 private RadioButton radioProvider;
88 private RadioButton radioConsumer;
89 private static TextView TvLog;
91 private OcAccountManager mAccountManager;
98 private static int notiId = 100;
99 private boolean isStarted = false;
100 private boolean gAcceptor = true;
101 private boolean gRemoteService = true;
103 private NotiListener mNotiListener = null;
104 private ProviderSample mProviderSample = null;
106 public static Handler mHandler = new Handler() {
108 public void handleMessage(Message msg) {
110 case CONSUMER_SUBSCRIBED:
111 String ConsumerId = (String) msg.obj;
112 if (ConsumerId != null)
113 TvLog.append("Consumer Subscibed: " + ConsumerId + "\n");
117 String sync = (String) msg.obj;
119 TvLog.append("SyncInfo Received :" + sync + "\n");
129 public void showToast(final String toast) {
130 runOnUiThread(new Runnable() {
133 Toast.makeText(getApplicationContext(), toast,
134 Toast.LENGTH_SHORT).show();
140 protected void onCreate(Bundle savedInstanceState) {
141 super.onCreate(savedInstanceState);
142 setContentView(R.layout.activity_main);
144 btnTitle = (Button) findViewById(R.id.BtnTitle);
145 btnBody = (Button) findViewById(R.id.BtnBody);
146 btnTopic = (Button) findViewById(R.id.BtnTopic);
147 btnSend = (Button) findViewById(R.id.BtnCreateNoti);
149 btnStart = (Button) findViewById(R.id.BtnStart);
150 btnRegister = (Button) findViewById(R.id.BtnRegister);
151 btnSet = (Button) findViewById(R.id.BtnSet);
152 btnLog = (Button) findViewById(R.id.BtnLog);
153 btnStop = (Button) findViewById(R.id.BtnStop);
155 signUp = (Button) findViewById(R.id.signup);
156 signIn = (Button) findViewById(R.id.signin);
157 signOut = (Button) findViewById(R.id.signout);
158 remoteService = (Button) findViewById(R.id.remoteService);
159 subscribeMQ = (Button) findViewById(R.id.subscribeMQService);
161 editTextTitle = (EditText) findViewById(R.id.EditTextTitle);
162 editTextBody = (EditText) findViewById(R.id.EditTextBody);
163 editTextTopic = (EditText) findViewById(R.id.EditTextTopic);
165 radioProvider = (RadioButton) findViewById(R.id.RadioProvider);
166 radioConsumer = (RadioButton) findViewById(R.id.RadioConsumer);
168 TvLog = (TextView) findViewById(R.id.TvLog);
170 btnTitle.setEnabled(false);
171 btnBody.setEnabled(false);
172 btnTopic.setEnabled(false);
174 signIn.setEnabled(false);
175 signOut.setEnabled(false);
176 remoteService.setEnabled(false);
178 btnSend.setOnClickListener(mClickListener);
179 btnStart.setOnClickListener(mClickListener);
180 btnRegister.setOnClickListener(mClickListener);
181 btnSet.setOnClickListener(mClickListener);
182 btnLog.setOnClickListener(mClickListener);
183 btnStop.setOnClickListener(mClickListener);
184 radioProvider.setOnClickListener(mClickListener);
185 radioConsumer.setOnClickListener(mClickListener);
187 signUp.setOnClickListener(mClickListener);
188 signIn.setOnClickListener(mClickListener);
189 signOut.setOnClickListener(mClickListener);
191 remoteService.setOnClickListener(mClickListener);
192 subscribeMQ.setOnClickListener(mClickListener);
194 mProviderSample = new ProviderSample(getApplicationContext());
195 mProviderSample.setHandler(mHandler);
197 mNotiListener = new NotiListener(this);
198 Intent intent = new Intent(
199 "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
200 startActivity(intent);
204 protected void onDestroy() {
208 public ProviderSample getProviderSample() {
209 return mProviderSample;
212 Button.OnClickListener mClickListener = new View.OnClickListener() {
213 public void onClick(View v) {
215 case R.id.RadioProvider: {
216 if (isStarted == false) {
218 showToast("Provider as acceptor is " + gAcceptor);
221 "Start ProviderService again to change acceptor as provider");
225 case R.id.RadioConsumer: {
226 if (isStarted == false) {
228 showToast("Provider as acceptor is " + gAcceptor);
231 "Start ProviderService again to change acceptor as consumer");
235 case R.id.BtnStart: {
236 if (isStarted == false) {
237 Log.i(TAG, "Start Provider Service");
238 TvLog.setText("Start Provider Service\n");
239 mProviderSample.start(gAcceptor);
241 radioProvider.setEnabled(false);
242 radioConsumer.setEnabled(false);
246 Log.e(TAG, " Provider Service had already started");
247 showToast(" Provider Service had already started");
252 case R.id.BtnRegister: {
253 if (isStarted == false) {
254 Log.i(TAG, "Start Provider Service");
255 TvLog.append("Register Topic : OCF_TOPIC1\n");
256 TvLog.append("Register Topic : OCF_TOPIC2\n");
257 TvLog.append("Register Topic : OCF_TOPIC3\n");
258 TvLog.append("Register Topic : OCF_TOPIC4\n");
259 showToast("Start Provider Service First");
262 mProviderSample.registerTopic();
268 if (isStarted == false) {
269 Log.i(TAG, "Start Provider Service");
270 TvLog.append("Set Topic : OCF_TOPIC1\n");
271 TvLog.append("Set Topic : OCF_TOPIC2\n");
272 TvLog.append("Set Topic : OCF_TOPIC3\n");
273 TvLog.append("Set Topic : OCF_TOPIC4\n");
274 showToast("Start Provider Service First");
277 if (gAcceptor == false) {
279 "Operation Not Permitted: \nStart Provider Service with provider as acceptor");
282 mProviderSample.setTopic();
287 case R.id.BtnCreateNoti: {
289 String id = Integer.toString(notiId); // generate
291 String title = editTextTitle.getText().toString();
292 String body = editTextBody.getText().toString();
293 String topic = editTextTopic.getText().toString();
295 if (isStarted == false) {
296 Log.e(TAG, "Fail to send NSMessage");
297 showToast("Start ProviderService First");
301 // Build android noti object and send it to Notification
303 Notification.Builder notiBuilder = new Notification.Builder(
304 getApplicationContext());
305 notiBuilder.setContentTitle(title);
306 notiBuilder.setContentText(body);
307 notiBuilder.setSubText(topic);
308 notiBuilder.setPriority(Notification.PRIORITY_MAX);
309 notiBuilder.setDefaults(Notification.DEFAULT_ALL);
310 notiBuilder.setSmallIcon(R.mipmap.ic_launcher);
311 NotificationManager notiMgr = (NotificationManager) getSystemService(
312 NOTIFICATION_SERVICE);
313 notiMgr.notify(notiId, notiBuilder.build());
315 Log.i(TAG, "#" + notiId + " notified ..");
316 TvLog.append("Send Notitication(Msg ID: " + notiId + ")\n");
322 if (isStarted == false) {
323 Log.e(TAG, "Fail to stop service");
324 showToast("Already Stopped");
328 mProviderSample.stop();
330 radioProvider.setEnabled(true);
331 radioConsumer.setEnabled(true);
332 showToast("Stopped ProviderService" + isStarted);
333 TvLog.append("Stop Provider Service\n");
343 if (isStarted == false) {
344 Log.e(TAG, "Fail to Sign Up");
345 showToast("Start ProviderService First");
348 TvLog.append("Initiating SignUp\n");
353 if (isStarted == false) {
354 Log.e(TAG, "Fail to Sign In");
355 showToast("Start ProviderService First");
358 TvLog.append("Initiating SignIn\n");
363 if (isStarted == false) {
364 Log.e(TAG, "Fail to Sign out");
365 showToast("Start ProviderService First");
368 TvLog.append("Initiating SignOut\n");
372 case R.id.remoteService: {
373 remoteService.setEnabled(false);
374 if (isStarted == false) {
375 Log.e(TAG, "Fail to Enable/Disable RemoteService");
376 showToast("Start ProviderService First");
379 if (gRemoteService) {
380 TvLog.append("Enable Remote Service\n");
381 mProviderSample.enableRemoteService(RemoteAddress);
382 remoteService.setText(R.string.disableRemoteService);
383 gRemoteService = false;
384 remoteService.setEnabled(true);
385 TvLog.append("EnableRemoteService success \n");
387 TvLog.append("Disable Remote Service\n");
388 mProviderSample.disableRemoteService(RemoteAddress);
389 remoteService.setText(R.string.enableRemoteService);
390 gRemoteService = true;
391 remoteService.setEnabled(true);
392 TvLog.append("DisableRemoteService success\n");
396 case R.id.subscribeMQService: {
397 if (isStarted == false) {
398 Log.e(TAG, "Fail to SubscribeMQService");
399 showToast("Start ProviderService First");
402 final Dialog dialog = new Dialog(context);
403 dialog.setContentView(R.layout.dialog_mq);
404 dialog.setTitle("MQ Cloud Service Details");
406 final EditText ip = (EditText) dialog
407 .findViewById(R.id.EditTextIp);
408 final EditText mqTopic = (EditText) dialog
409 .findViewById(R.id.EditTextMqTopic);
410 if (MQCloudAddress != null && MQCloudTopic != null) {
411 ip.setText(MQCloudAddress);
412 mqTopic.setText(MQCloudTopic);
415 Button dialogButton = (Button) dialog
416 .findViewById(R.id.mqButtonOK);
418 dialogButton.setOnClickListener(new View.OnClickListener() {
420 public void onClick(View v) {
422 MQCloudAddress = ip.getText().toString();
423 MQCloudTopic = mqTopic.getText().toString();
424 mProviderSample.subscribeMQService(
425 MQCloudAddress, MQCloudTopic);
426 TvLog.append("SubscribeMQService success\n");
436 public void logMessage(final String text) {
437 runOnUiThread(new Runnable() {
439 Message msg = new Message();
441 TvLog.append(text + "\n");
447 OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
449 public synchronized void onPostCompleted(List<OcHeaderOption> list,
450 OcRepresentation ocRepresentation) {
451 logMessage("signUp was successful");
452 runOnUiThread(new Runnable() {
454 signIn.setEnabled(true);
455 signUp.setEnabled(false);
459 mUserID = ocRepresentation.getValue("uid");
460 mAccessToken = ocRepresentation.getValue("accesstoken");
461 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
463 logMessage("\tuserID: " + mUserID);
464 logMessage("\taccessToken: " + mAccessToken);
465 logMessage("\trefreshToken: " + mRefreshtoken);
467 if (ocRepresentation.hasAttribute("expiresin")) {
468 int expiresIn = ocRepresentation.getValue("expiresin");
469 logMessage("\texpiresIn: " + expiresIn);
471 } catch (OcException e) {
472 Log.e(TAG, e.toString());
477 public synchronized void onPostFailed(Throwable throwable) {
478 logMessage("Failed to signUp");
479 if (throwable instanceof OcException) {
480 OcException ocEx = (OcException) throwable;
481 Log.e(TAG, ocEx.toString());
482 ErrorCode errCode = ocEx.getErrorCode();
483 logMessage("Error code: " + errCode);
488 OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
490 public synchronized void onPostCompleted(List<OcHeaderOption> list,
491 OcRepresentation ocRepresentation) {
492 logMessage("signIn was successful");
493 runOnUiThread(new Runnable() {
495 signIn.setEnabled(false);
496 signOut.setEnabled(true);
497 remoteService.setEnabled(true);
503 public synchronized void onPostFailed(Throwable throwable) {
504 logMessage("Failed to signIn");
505 if (throwable instanceof OcException) {
506 OcException ocEx = (OcException) throwable;
507 Log.e(TAG, ocEx.toString());
508 ErrorCode errCode = ocEx.getErrorCode();
509 logMessage("Error code: " + errCode);
510 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
517 OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
519 public synchronized void onPostCompleted(List<OcHeaderOption> list,
520 OcRepresentation ocRepresentation) {
521 logMessage("signOut was successful");
522 runOnUiThread(new Runnable() {
524 signIn.setEnabled(true);
525 signOut.setEnabled(false);
526 remoteService.setEnabled(false);
533 public synchronized void onPostFailed(Throwable throwable) {
534 logMessage("Failed to signOut");
535 if (throwable instanceof OcException) {
536 OcException ocEx = (OcException) throwable;
537 Log.e(TAG, ocEx.toString());
538 ErrorCode errCode = ocEx.getErrorCode();
539 logMessage("Error code: " + errCode);
540 if (ErrorCode.UNAUTHORIZED_REQ != errCode) {
548 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
549 OcRepresentation ocRepresentation) {
554 public void onPostFailed(Throwable throwable) {
558 private void signIn() {
560 if (mAccountManager == null) {
561 mAccountManager = OcPlatform.constructAccountManagerObject(
563 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
566 mAccountManager.signIn(mUserID, mAccessToken, onSignIn);
567 } catch (OcException e) {
572 private void signOut() {
574 logMessage("signOut");
575 if (mAccountManager == null) {
577 mAccountManager = OcPlatform.constructAccountManagerObject(
579 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
580 } catch (OcException e) {
584 mAccountManager.signOut(mAccessToken, onSignOut);
585 signIn.setEnabled(false);
586 signUp.setEnabled(true);
587 remoteService.setEnabled(false);
588 logMessage("signOut Successful");
589 } catch (OcException e) {
594 private void signUp() {
595 Intent intentLogin = new Intent(this, LoginActivity.class);
596 startActivityForResult(intentLogin, REQUEST_LOGIN);
600 public void onActivityResult(int requestCode, int resultCode, Intent data) {
601 super.onActivityResult(requestCode, resultCode, data);
602 if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
603 mAuthCode = data.getStringExtra("authCode");
604 mAuthProvider = data.getStringExtra("authProvider");
605 logMessage("authCode: " + mAuthCode);
606 logMessage("authProvider: " + mAuthProvider);
608 final Dialog dialog = new Dialog(context);
609 dialog.setContentView(R.layout.dialog_entry);
610 dialog.setTitle("SignUp Acccount IP Address");
611 final EditText ip = (EditText) dialog
612 .findViewById(R.id.EditTextEntry);
613 if (RemoteAddress != null) {
614 ip.setText(RemoteAddress);
616 Button dialogButton = (Button) dialog
617 .findViewById(R.id.entryButtonOK);
618 dialogButton.setOnClickListener(new View.OnClickListener() {
620 public void onClick(View v) {
622 RemoteAddress = ip.getText().toString();
623 CIServer = CI_SERVER_PREFIX + RemoteAddress;
624 logMessage("server address for signup is: \n" + CIServer);
626 mAccountManager = OcPlatform
627 .constructAccountManagerObject(CIServer, EnumSet
628 .of(OcConnectivityType.CT_ADAPTER_TCP));
629 logMessage("Calling signup API");
631 if (mAuthProvider.equals("samsung")
632 || mAuthProvider.equals("samsung-us"))
635 logMessage("Auth provider is samsung");
636 Map<String, String> options = new HashMap<>();
637 options.put("auth_server_url",
638 "us-auth2.samsungosp.com");
639 options.put("api_server_url",
640 "us-auth2.samsungosp.com");
641 mAccountManager.signUp(mAuthProvider, mAuthCode,
644 mAccountManager.signUp(mAuthProvider, mAuthCode,
647 } catch (OcException e) {
656 OcResource.OnPostListener onRefreshTokenPost = new OcResource.OnPostListener() {
658 public void onPostCompleted(List<OcHeaderOption> list,
659 OcRepresentation ocRepresentation) {
660 logMessage("RefreshToken Completed.");
662 mAccessToken = ocRepresentation.getValue("accesstoken");
663 mRefreshtoken = ocRepresentation.getValue("refreshtoken");
664 } catch (OcException e) {
671 public void onPostFailed(Throwable throwable) {
672 logMessage("RefreshToken failed.");
673 Log.d(TAG, "onRefreshTokenPost failed.");
677 public void refreshToken() {
679 if (deviceID == null) {
680 final Dialog dialog = new Dialog(context);
681 dialog.setContentView(R.layout.dialog_entry);
682 dialog.setTitle("Enter Device Id");
683 dialog.setCanceledOnTouchOutside(false);
684 final EditText id = (EditText) dialog
685 .findViewById(R.id.EditTextEntry);
687 Button dialogButton = (Button) dialog
688 .findViewById(R.id.entryButtonOK);
689 dialogButton.setOnClickListener(new View.OnClickListener() {
691 public void onClick(View v) {
693 deviceID = id.getText().toString();
699 OcResource authResource = OcPlatform.constructResourceObject(
700 CIServer, "/.well-known/ocf/account/tokenrefresh",
701 EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP,
702 OcConnectivityType.CT_IP_USE_V4),
703 false, Arrays.asList("oic.wk.account"),
704 Arrays.asList(OcPlatform.DEFAULT_INTERFACE));
705 OcRepresentation rep = new OcRepresentation();
707 showToast("RefreshToken in progress..");
708 logMessage("RefreshToken in progress..");
709 rep.setValue("di", deviceID);
710 rep.setValue("granttype", "refresh_token");
711 rep.setValue("refreshtoken", mRefreshtoken);
712 rep.setValue("uid", mUserID);
713 authResource.post(rep, new HashMap<String, String>(),
715 } catch (OcException e) {
719 Log.d(TAG, "No error while executing login");