Imported Upstream version 1.0.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.os.Bundle;
31 import android.text.method.ScrollingMovementMethod;
32 import android.util.Log;
33 import android.view.View;
34 import android.widget.CompoundButton;
35 import android.widget.ScrollView;
36 import android.widget.TextView;
37 import android.widget.ToggleButton;
38
39 import org.iotivity.base.ModeType;
40 import org.iotivity.base.OcException;
41 import org.iotivity.base.OcPlatform;
42 import org.iotivity.base.PlatformConfig;
43 import org.iotivity.base.QualityOfService;
44 import org.iotivity.base.ServiceType;
45
46 import java.util.LinkedList;
47 import java.util.List;
48
49 /**
50  * SimpleServer
51  * <p/>
52  * SimpleServer is a sample OIC server application.
53  * It creates a Light and waits for the incoming client calls to handle
54  * various request scenarios.
55  */
56 public class SimpleServer extends Activity {
57
58     List<Light> lights = new LinkedList<>();
59
60     /**
61      * A local method to configure and initialize platform, and then create a light resource.
62      */
63     private void startSimpleServer() {
64         Context context = this;
65
66         PlatformConfig platformConfig = new PlatformConfig(
67                 context,
68                 ServiceType.IN_PROC,
69                 ModeType.SERVER,
70                 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
71                 0,         // Uses randomly available port
72                 QualityOfService.LOW
73         );
74
75         msg("Configuring platform.");
76         OcPlatform.Configure(platformConfig);
77
78         createNewLightResource("/a/light", "John's light");
79
80         msg("Waiting for the requests...");
81         printLine();
82
83         enableStartStopButton();
84     }
85
86     public void createNewLightResource(String resourceUri, String resourceName){
87         msg("Creating a light");
88         Light light = new Light(
89                 resourceUri,     //URI
90                 resourceName,    //name
91                 false,           //state
92                 0                //power
93         );
94         msg(light.toString());
95         light.setContext(this);
96
97         msg("Registering light as a resource");
98         try {
99             light.registerResource();
100         } catch (OcException e) {
101             Log.e(TAG, e.toString());
102             msg("Failed to register a light resource");
103         }
104         lights.add(light);
105     }
106
107     private void stopSimpleServer() {
108         for (Light light : lights) {
109             try {
110                 light.unregisterResource();
111             } catch (OcException e) {
112                 Log.e(TAG, e.toString());
113                 msg("Failed to unregister a light resource");
114             }
115         }
116         lights.clear();
117
118         msg("All created resources have been unregistered");
119         printLine();
120         enableStartStopButton();
121     }
122
123     //******************************************************************************
124     // End of the OIC specific code
125     //******************************************************************************
126
127     private final static String TAG = SimpleServer.class.getSimpleName();
128     private MessageReceiver mMessageReceiver = new MessageReceiver();
129     private TextView mConsoleTextView;
130     private ScrollView mScrollView;
131
132     @Override
133     protected void onCreate(Bundle savedInstanceState) {
134         super.onCreate(savedInstanceState);
135         setContentView(R.layout.activity_simple_server);
136
137         registerReceiver(mMessageReceiver,
138                 new IntentFilter("org.iotivity.base.examples.simpleserver"));
139
140         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
141         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
142         mScrollView = (ScrollView) findViewById(R.id.scrollView);
143         mScrollView.fullScroll(View.FOCUS_DOWN);
144         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
145
146         if (null == savedInstanceState) {
147             toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
148                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
149                     toggleButton.setEnabled(false);
150                     if (isChecked) {
151                         new Thread(new Runnable() {
152                             public void run() {
153                                 startSimpleServer();
154                             }
155                         }).start();
156                     } else {
157                         new Thread(new Runnable() {
158                             public void run() {
159                                 stopSimpleServer();
160                             }
161                         }).start();
162                     }
163                 }
164             });
165         } else {
166             String consoleOutput = savedInstanceState.getString("consoleOutputString");
167             mConsoleTextView.setText(consoleOutput);
168             boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
169             toggleButton.setChecked(buttonCheked);
170         }
171     }
172
173     @Override
174     public void onDestroy() {
175         super.onDestroy();
176         onStop();
177     }
178
179     @Override
180     protected void onStop() {
181         //unregisterReceiver(mMessageReceiver);
182         super.onStop();
183     }
184
185     @Override
186     protected void onSaveInstanceState(Bundle outState) {
187         super.onSaveInstanceState(outState);
188         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
189         ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
190         outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
191     }
192
193     @Override
194     protected void onRestoreInstanceState(Bundle savedInstanceState) {
195         super.onRestoreInstanceState(savedInstanceState);
196
197         String consoleOutput = savedInstanceState.getString("consoleOutputString");
198         mConsoleTextView.setText(consoleOutput);
199
200         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
201         boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
202         toggleButton.setChecked(buttonCheked);
203     }
204
205     private void msg(final String text) {
206         runOnUiThread(new Runnable() {
207             public void run() {
208                 mConsoleTextView.append("\n");
209                 mConsoleTextView.append(text);
210                 mScrollView.fullScroll(View.FOCUS_DOWN);
211             }
212         });
213         Log.i(TAG, text);
214     }
215
216     private void printLine() {
217         msg("------------------------------------------------------------------------");
218     }
219
220     private void sleep(int seconds) {
221         try {
222             Thread.sleep(seconds * 1000);
223         } catch (InterruptedException e) {
224             e.printStackTrace();
225             Log.e(TAG, e.toString());
226         }
227     }
228
229     private void enableStartStopButton() {
230         runOnUiThread(new Runnable() {
231             public void run() {
232                 ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
233                 toggleButton.setEnabled(true);
234             }
235         });
236     }
237
238     public class MessageReceiver extends BroadcastReceiver {
239         @Override
240         public void onReceive(Context context, Intent intent) {
241             final String message = intent.getStringExtra("message");
242             msg(message);
243         }
244     }
245 }