added code to close the netlink socket.
[contrib/iotivity.git] / android / examples / groupserver / src / main / java / org / iotivity / base / examples / GroupServer.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 package org.iotivity.base.examples;
23
24 import android.app.Activity;
25 import android.content.Context;
26 import android.os.Bundle;
27 import android.text.method.ScrollingMovementMethod;
28 import android.util.Log;
29 import android.view.View;
30 import android.widget.CompoundButton;
31 import android.widget.ScrollView;
32 import android.widget.TextView;
33 import android.widget.ToggleButton;
34
35 import org.iotivity.base.ModeType;
36 import org.iotivity.base.OcConnectivityType;
37 import org.iotivity.base.OcException;
38 import org.iotivity.base.OcPlatform;
39 import org.iotivity.base.OcResource;
40 import org.iotivity.base.OcResourceHandle;
41 import org.iotivity.base.PlatformConfig;
42 import org.iotivity.base.QualityOfService;
43 import org.iotivity.base.ResourceProperty;
44 import org.iotivity.base.ServiceType;
45
46 import java.util.EnumSet;
47 import java.util.LinkedList;
48 import java.util.List;
49
50 /**
51  * GroupServer
52  */
53 public class GroupServer extends Activity implements OcPlatform.OnResourceFoundListener {
54
55     private OcResourceHandle mCollectionResourceHandle;
56     private List<OcResourceHandle> mProxyResourceHandleList = new LinkedList<>();
57
58     /**
59      * A local method to configure and initialize platform, register a collection resource
60      * and then search for the light resources.In addition it creates a local light resource and
61      * adds it to the collection.
62      */
63     private synchronized void startGroupServer() {
64         Context context = this;
65
66         PlatformConfig platformConfig = new PlatformConfig(
67                 context,
68                 ServiceType.IN_PROC,
69                 ModeType.CLIENT_SERVER,
70                 "0.0.0.0", 0,
71                 QualityOfService.LOW
72         );
73
74         msg("Configuring platform.");
75         OcPlatform.Configure(platformConfig);
76
77         String resourceUri = "/core/a/collection";
78         String resourceTypeName = "a.collection";
79         msg("Registering a collection resource.");
80         try {
81             mCollectionResourceHandle = OcPlatform.registerResource(
82                     resourceUri,                //resource URI
83                     resourceTypeName,           //resource type name
84                     OcPlatform.BATCH_INTERFACE, //using batch interface
85                     null,                       //use default entity handler
86                     EnumSet.of(ResourceProperty.DISCOVERABLE)
87             );
88         } catch (OcException e) {
89             Log.e(TAG, e.toString());
90             msg("Failed to register a collection resource");
91         }
92
93         if (null != mCollectionResourceHandle) {
94             try {
95                 OcPlatform.bindInterfaceToResource(
96                         mCollectionResourceHandle,
97                         OcPlatform.GROUP_INTERFACE);
98
99                 OcPlatform.bindInterfaceToResource(
100                         mCollectionResourceHandle,
101                         OcPlatform.DEFAULT_INTERFACE);
102             } catch (OcException e) {
103                 e.printStackTrace();
104             }
105
106         }
107
108         msg("Sending request to find all resources with \"core.light\" type name");
109         try {
110             OcPlatform.findResource(
111                     "",
112                     OcPlatform.WELL_KNOWN_QUERY + "?rt=core.light",
113                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
114                     this);
115
116         } catch (OcException e) {
117             Log.e(TAG, e.toString());
118             msg("Failed to invoke find resource API");
119         }
120
121         OcResourceHandle localLightResourceHandle = null;
122         msg("Registering a local light resource");
123         try {
124             localLightResourceHandle = OcPlatform.registerResource(
125                     "/a/light/local",               //resource URI
126                     "core.light",                   //resource type name
127                     OcPlatform.DEFAULT_INTERFACE,   //using default interface
128                     null,                           //use default entity handler
129                     EnumSet.of(ResourceProperty.DISCOVERABLE)
130             );
131         } catch (OcException e) {
132             Log.e(TAG, e.toString());
133             msg("Failed to register a local ligh resource");
134         }
135
136         if (null != localLightResourceHandle) {
137             msg("Binding a found resource proxy handle to the collection resource");
138             try {
139                 OcPlatform.bindResource(mCollectionResourceHandle, localLightResourceHandle);
140             } catch (OcException e) {
141                 Log.e(TAG, e.toString());
142                 msg("Failed to bind found resource proxy handle to the collection resource");
143             }
144             mProxyResourceHandleList.add(localLightResourceHandle);
145         }
146
147         printLine();
148     }
149
150     /**
151      * An event handler to be executed whenever a "findResource" request completes successfully
152      *
153      * @param foundResource found resource
154      */
155     @Override
156     public synchronized void onResourceFound(OcResource foundResource) {
157         if (null == foundResource) {
158             msg("Found resource is invalid");
159             return;
160         }
161         msg("Found resource with \"core.light\" type name\".");
162         // Get the resource host address
163         String hostAddress = foundResource.getHost();
164         // Get the resource URI
165         String resourceUri = foundResource.getUri();
166         msg("\tHost address of the resource: " + hostAddress);
167         msg("\tURI of the resource: " + resourceUri);
168         // Get the resource types
169         msg("\tList of resource types: ");
170         for (String resourceType : foundResource.getResourceTypes()) {
171             msg("\t\t" + resourceType);
172         }
173         msg("\tList of resource interfaces:");
174         for (String resourceInterface : foundResource.getResourceInterfaces()) {
175             msg("\t\t" + resourceInterface);
176         }
177         msg("\tList of resource connectivity types:");
178         for (OcConnectivityType connectivityType : foundResource.getConnectivityTypeSet()) {
179             msg("\t\t" + connectivityType);
180         }
181
182         //In this example we are only interested in the light resources
183         if (resourceUri.equals("/a/light")) {
184             msg("Registering a found resource as a local proxy resource");
185             OcResourceHandle proxyResourceHandle = null;
186             try {
187                 proxyResourceHandle = OcPlatform.registerResource(foundResource);
188             } catch (OcException e) {
189                 Log.e(TAG, e.toString());
190                 msg("Failed to register a found resource as a local proxy resource");
191             }
192
193             if (null != proxyResourceHandle) {
194                 msg("Binding a found resource proxy handle to the collection resource");
195                 try {
196                     OcPlatform.bindResource(mCollectionResourceHandle, proxyResourceHandle);
197                 } catch (OcException e) {
198                     Log.e(TAG, e.toString());
199                     msg("Failed to bind found resource proxy handle to the collection resource");
200                 }
201                 mProxyResourceHandleList.add(proxyResourceHandle);
202             }
203         }
204
205         printLine();
206         enableStartStopButton();
207     }
208
209     /**
210      * A local method to reset group server
211      */
212     private synchronized void stopGroupServer() {
213         msg("Unregistering resources");
214         for (OcResourceHandle proxyResourceHandle : mProxyResourceHandleList) {
215             try {
216                 OcPlatform.unbindResource(mCollectionResourceHandle, proxyResourceHandle);
217             } catch (OcException e) {
218                 Log.e(TAG, e.toString());
219                 msg("Failed to unbind a proxy resource");
220             }
221             try {
222                 OcPlatform.unregisterResource(proxyResourceHandle);
223             } catch (OcException e) {
224                 Log.e(TAG, e.toString());
225                 msg("Failed to unregister a proxy resource");
226             }
227         }
228         mProxyResourceHandleList.clear();
229
230         if (null != mCollectionResourceHandle) {
231             try {
232                 OcPlatform.unregisterResource(mCollectionResourceHandle);
233             } catch (OcException e) {
234                 Log.e(TAG, e.toString());
235                 msg("Failed to unregister a collection resource");
236             }
237         }
238         msg("Group Server is reset.");
239
240         printLine();
241         enableStartStopButton();
242     }
243
244     //******************************************************************************
245     // End of the OIC specific code
246     //******************************************************************************
247
248     private final static String TAG = GroupServer.class.getSimpleName();
249     private TextView mConsoleTextView;
250     private ScrollView mScrollView;
251
252     @Override
253     protected void onCreate(Bundle savedInstanceState) {
254         super.onCreate(savedInstanceState);
255         setContentView(R.layout.activity_group_server);
256
257         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
258         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
259         mScrollView = (ScrollView) findViewById(R.id.scrollView);
260         mScrollView.fullScroll(View.FOCUS_DOWN);
261         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
262
263         if (null == savedInstanceState) {
264             toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
265                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
266                     toggleButton.setEnabled(false);
267                     if (isChecked) {
268                         new Thread(new Runnable() {
269                             public void run() {
270                                 startGroupServer();
271                             }
272                         }).start();
273                     } else {
274                         new Thread(new Runnable() {
275                             public void run() {
276                                 stopGroupServer();
277                             }
278                         }).start();
279                     }
280                 }
281             });
282         } else {
283             String consoleOutput = savedInstanceState.getString("consoleOutputString");
284             mConsoleTextView.setText(consoleOutput);
285             boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
286             toggleButton.setChecked(buttonCheked);
287         }
288     }
289
290     @Override
291     protected void onSaveInstanceState(Bundle outState) {
292         super.onSaveInstanceState(outState);
293         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
294         ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
295         outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
296     }
297
298     @Override
299     protected void onRestoreInstanceState(Bundle savedInstanceState) {
300         super.onRestoreInstanceState(savedInstanceState);
301
302         String consoleOutput = savedInstanceState.getString("consoleOutputString");
303         mConsoleTextView.setText(consoleOutput);
304
305         final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
306         boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
307         toggleButton.setChecked(buttonCheked);
308     }
309
310     private void msg(final String text) {
311         runOnUiThread(new Runnable() {
312             public void run() {
313                 mConsoleTextView.append("\n");
314                 mConsoleTextView.append(text);
315                 mScrollView.fullScroll(View.FOCUS_DOWN);
316             }
317         });
318         Log.i(TAG, text);
319     }
320
321     private void printLine() {
322         msg("------------------------------------------------------------------------");
323     }
324
325     private void enableStartStopButton() {
326         runOnUiThread(new Runnable() {
327             public void run() {
328                 ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
329                 toggleButton.setEnabled(true);
330             }
331         });
332     }
333 }