Merge branch 'resource-container'
[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                 context,
69                 ServiceType.IN_PROC,
70                 ModeType.SERVER,
71                 "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
72                 0,         // Uses randomly available port
73                 QualityOfService.LOW
74         );
75
76         msg("Configuring platform.");
77         OcPlatform.Configure(platformConfig);
78
79         createNewLightResource("/a/light", "John's light");
80
81         msg("Waiting for the requests...");
82         printLine();
83
84         enableStartStopButton();
85     }
86
87     public void createNewLightResource(String resourceUri, String resourceName){
88         msg("Creating a light");
89         Light light = new Light(
90                 resourceUri,     //URI
91                 resourceName,    //name
92                 false,           //state
93                 0                //power
94         );
95         msg(light.toString());
96         light.setContext(this);
97
98         msg("Registering light as a resource");
99         try {
100             light.registerResource();
101         } catch (OcException e) {
102             Log.e(TAG, e.toString());
103             msg("Failed to register a light resource");
104         }
105         lights.add(light);
106     }
107
108     private void stopSimpleServer() {
109         for (Light light : lights) {
110             try {
111                 light.unregisterResource();
112             } catch (OcException e) {
113                 Log.e(TAG, e.toString());
114                 msg("Failed to unregister a light resource");
115             }
116         }
117         lights.clear();
118
119         msg("All created resources have been unregistered");
120         printLine();
121         enableStartStopButton();
122     }
123
124     //******************************************************************************
125     // End of the OIC specific code
126     //******************************************************************************
127
128     private final static String TAG = SimpleServer.class.getSimpleName();
129     private MessageReceiver mMessageReceiver = new MessageReceiver();
130     private TextView mConsoleTextView;
131     private ScrollView mScrollView;
132
133     @Override
134     protected void onCreate(Bundle savedInstanceState) {
135         super.onCreate(savedInstanceState);
136         setContentView(R.layout.activity_simple_server);
137
138         registerReceiver(mMessageReceiver,
139                 new IntentFilter("org.iotivity.base.examples.simpleserver"));
140
141         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
142         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
143         mScrollView = (ScrollView) findViewById(R.id.scrollView);
144         mScrollView.fullScroll(View.FOCUS_DOWN);
145         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
146
147         if (null == savedInstanceState) {
148             toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
149                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
150                     toggleButton.setEnabled(false);
151                     if (isChecked) {
152                         new Thread(new Runnable() {
153                             public void run() {
154                                 startSimpleServer();
155                             }
156                         }).start();
157                     } else {
158                         new Thread(new Runnable() {
159                             public void run() {
160                                 stopSimpleServer();
161                             }
162                         }).start();
163                     }
164                 }
165             });
166         } else {
167             String consoleOutput = savedInstanceState.getString("consoleOutputString");
168             mConsoleTextView.setText(consoleOutput);
169             boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
170             toggleButton.setChecked(buttonCheked);
171         }
172     }
173
174     @Override
175     public void onDestroy() {
176         super.onDestroy();
177         onStop();
178     }
179
180     @Override
181     protected void onStop() {
182         //unregisterReceiver(mMessageReceiver);
183         super.onStop();
184     }
185
186     @Override
187     protected void onSaveInstanceState(Bundle outState) {
188         super.onSaveInstanceState(outState);
189         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
190         ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
191         outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
192     }
193
194     @Override
195     protected void onRestoreInstanceState(Bundle savedInstanceState) {
196         super.onRestoreInstanceState(savedInstanceState);
197
198         String consoleOutput = savedInstanceState.getString("consoleOutputString");
199         mConsoleTextView.setText(consoleOutput);
200
201         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
202         boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
203         toggleButton.setChecked(buttonCheked);
204     }
205
206     private void msg(final String text) {
207         runOnUiThread(new Runnable() {
208             public void run() {
209                 mConsoleTextView.append("\n");
210                 mConsoleTextView.append(text);
211                 mScrollView.fullScroll(View.FOCUS_DOWN);
212             }
213         });
214         Log.i(TAG, text);
215     }
216
217     private void printLine() {
218         msg("------------------------------------------------------------------------");
219     }
220
221     private void sleep(int seconds) {
222         try {
223             Thread.sleep(seconds * 1000);
224         } catch (InterruptedException e) {
225             e.printStackTrace();
226             Log.e(TAG, e.toString());
227         }
228     }
229
230     private void enableStartStopButton() {
231         runOnUiThread(new Runnable() {
232             public void run() {
233                 ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
234                 toggleButton.setEnabled(true);
235             }
236         });
237     }
238
239     public class MessageReceiver extends BroadcastReceiver {
240         @Override
241         public void onReceive(Context context, Intent intent) {
242             final String message = intent.getStringExtra("message");
243             msg(message);
244         }
245     }
246
247     @Override
248     public void onNewIntent(Intent intent) {
249         super.onNewIntent(intent);
250         Log.d(TAG, "onNewIntent with changes sending broadcast IN ");
251
252         Intent i = new Intent();
253         i.setAction(intent.getAction());
254         i.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES,
255                 intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES));
256         sendBroadcast(i);
257         Log.d(TAG, "Initialize Context again resetting");
258     }
259 }