Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / android / examples / simpleserver / src / main / java / org / iotivity / base / examples / SimpleServer.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2015 Intel Corporation.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.base.examples;
24
25 import android.app.Activity;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.nfc.NfcAdapter;
31 import android.os.Bundle;
32 import android.text.method.ScrollingMovementMethod;
33 import android.util.Log;
34 import android.view.View;
35 import android.widget.CompoundButton;
36 import android.widget.ScrollView;
37 import android.widget.TextView;
38 import android.widget.ToggleButton;
39
40 import org.iotivity.base.ModeType;
41 import org.iotivity.base.OcException;
42 import org.iotivity.base.OcPlatform;
43 import org.iotivity.base.PlatformConfig;
44 import org.iotivity.base.QualityOfService;
45 import org.iotivity.base.ServiceType;
46
47 import java.util.LinkedList;
48 import java.util.List;
49
50 /**
51  * SimpleServer
52  * <p/>
53  * SimpleServer is a sample OIC server application.
54  * It creates a Light and waits for the incoming client calls to handle
55  * various request scenarios.
56  */
57 public class SimpleServer extends Activity {
58
59     List<Light> lights = new LinkedList<>();
60
61     /**
62      * A local method to configure and initialize platform, and then create a light resource.
63      */
64     private void startSimpleServer() {
65         Context context = this;
66
67         PlatformConfig platformConfig = new PlatformConfig(
68                 this,
69                 context,
70                 ServiceType.IN_PROC,
71                 ModeType.SERVER,
72                 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
73                 0,         // Uses randomly available port
74                 QualityOfService.LOW
75         );
76
77         msg("Configuring platform.");
78         OcPlatform.Configure(platformConfig);
79
80         createNewLightResource("/a/light", "John's light");
81
82         msg("Waiting for the requests...");
83         printLine();
84
85         enableStartStopButton();
86     }
87
88     public void createNewLightResource(String resourceUri, String resourceName){
89         msg("Creating a light");
90         Light light = new Light(
91                 resourceUri,     //URI
92                 resourceName,    //name
93                 false,           //state
94                 0                //power
95         );
96         msg(light.toString());
97         light.setContext(this);
98
99         msg("Registering light as a resource");
100         try {
101             light.registerResource();
102         } catch (OcException e) {
103             Log.e(TAG, e.toString());
104             msg("Failed to register a light resource");
105         }
106         lights.add(light);
107     }
108
109     private void stopSimpleServer() {
110         for (Light light : lights) {
111             try {
112                 light.unregisterResource();
113             } catch (OcException e) {
114                 Log.e(TAG, e.toString());
115                 msg("Failed to unregister a light resource");
116             }
117         }
118         lights.clear();
119
120         msg("All created resources have been unregistered");
121         printLine();
122         enableStartStopButton();
123     }
124
125     //******************************************************************************
126     // End of the OIC specific code
127     //******************************************************************************
128
129     private final static String TAG = SimpleServer.class.getSimpleName();
130     private MessageReceiver mMessageReceiver = new MessageReceiver();
131     private TextView mConsoleTextView;
132     private ScrollView mScrollView;
133
134     @Override
135     protected void onCreate(Bundle savedInstanceState) {
136         super.onCreate(savedInstanceState);
137         setContentView(R.layout.activity_simple_server);
138
139         registerReceiver(mMessageReceiver,
140                 new IntentFilter("org.iotivity.base.examples.simpleserver"));
141
142         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
143         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
144         mScrollView = (ScrollView) findViewById(R.id.scrollView);
145         mScrollView.fullScroll(View.FOCUS_DOWN);
146         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
147
148         if (null == savedInstanceState) {
149             toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
150                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
151                     toggleButton.setEnabled(false);
152                     if (isChecked) {
153                         new Thread(new Runnable() {
154                             public void run() {
155                                 startSimpleServer();
156                             }
157                         }).start();
158                     } else {
159                         new Thread(new Runnable() {
160                             public void run() {
161                                 stopSimpleServer();
162                             }
163                         }).start();
164                     }
165                 }
166             });
167         } else {
168             String consoleOutput = savedInstanceState.getString("consoleOutputString");
169             mConsoleTextView.setText(consoleOutput);
170             boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
171             toggleButton.setChecked(buttonCheked);
172         }
173     }
174
175     @Override
176     public void onDestroy() {
177         super.onDestroy();
178         onStop();
179     }
180
181     @Override
182     protected void onStop() {
183         //unregisterReceiver(mMessageReceiver);
184         super.onStop();
185     }
186
187     @Override
188     protected void onSaveInstanceState(Bundle outState) {
189         super.onSaveInstanceState(outState);
190         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
191         ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
192         outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
193     }
194
195     @Override
196     protected void onRestoreInstanceState(Bundle savedInstanceState) {
197         super.onRestoreInstanceState(savedInstanceState);
198
199         String consoleOutput = savedInstanceState.getString("consoleOutputString");
200         mConsoleTextView.setText(consoleOutput);
201
202         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
203         boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
204         toggleButton.setChecked(buttonCheked);
205     }
206
207     private void msg(final String text) {
208         runOnUiThread(new Runnable() {
209             public void run() {
210                 mConsoleTextView.append("\n");
211                 mConsoleTextView.append(text);
212                 mScrollView.fullScroll(View.FOCUS_DOWN);
213             }
214         });
215         Log.i(TAG, text);
216     }
217
218     private void printLine() {
219         msg("------------------------------------------------------------------------");
220     }
221
222     private void sleep(int seconds) {
223         try {
224             Thread.sleep(seconds * 1000);
225         } catch (InterruptedException e) {
226             e.printStackTrace();
227             Log.e(TAG, e.toString());
228         }
229     }
230
231     private void enableStartStopButton() {
232         runOnUiThread(new Runnable() {
233             public void run() {
234                 ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
235                 toggleButton.setEnabled(true);
236             }
237         });
238     }
239
240     public class MessageReceiver extends BroadcastReceiver {
241         @Override
242         public void onReceive(Context context, Intent intent) {
243             final String message = intent.getStringExtra("message");
244             msg(message);
245         }
246     }
247
248     @Override
249     public void onNewIntent(Intent intent) {
250         super.onNewIntent(intent);
251         Log.d(TAG, "onNewIntent with changes sending broadcast IN ");
252
253         Intent i = new Intent();
254         i.setAction(intent.getAction());
255         i.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES,
256                 intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
257         sendBroadcast(i);
258         Log.d(TAG, "Initialize Context again resetting");
259     }
260 }