added code to close the netlink socket.
[contrib/iotivity.git] / android / examples / fridgegroupclient / src / main / java / org / iotivity / base / examples / FridgeGroupClient.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.os.Bundle;
27 import android.os.Message;
28 import android.text.method.ScrollingMovementMethod;
29 import android.util.Log;
30 import android.view.View;
31 import android.widget.Button;
32 import android.widget.TextView;
33
34 import org.iotivity.base.ModeType;
35 import org.iotivity.base.OcConnectivityType;
36 import org.iotivity.base.OcException;
37 import org.iotivity.base.OcHeaderOption;
38 import org.iotivity.base.OcPlatform;
39 import org.iotivity.base.OcRepresentation;
40 import org.iotivity.base.OcResource;
41 import org.iotivity.base.PlatformConfig;
42 import org.iotivity.base.QualityOfService;
43 import org.iotivity.base.ServiceType;
44
45 import java.util.EnumSet;
46 import java.util.HashMap;
47 import java.util.LinkedList;
48 import java.util.List;
49
50 /**
51  * FridgeGroupClient
52  * <p/>
53  * FridgeGroupClient is a sample client app which should be started after the fridgeGroupServer is
54  * started. It discovers a fridge resource and then creates the proxy resources for each one of its
55  * children (light and door) and performs a GET on them.
56  */
57 public class FridgeGroupClient extends Activity implements
58         OcPlatform.OnResourceFoundListener,
59         OcResource.OnGetListener {
60     private static String TAG = "FridgeGroupClient: ";
61
62     private final List<OcResource> childResourceList = new LinkedList<>();
63     private OcResource fridgeResource;
64
65     private void startFridgeClient() {
66         PlatformConfig cfg = new PlatformConfig(
67                 this, // context
68                 ServiceType.IN_PROC,
69                 ModeType.CLIENT,
70                 "0.0.0.0", // bind to all available interfaces
71                 0,
72                 QualityOfService.LOW);
73
74         logMessage("Configuring platform");
75         OcPlatform.Configure(cfg);
76         String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=intel.fridge.group";
77         logMessage("Initiating fridge discovery");
78         try {
79             OcPlatform.findResource("",
80                     requestUri,
81                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
82                     this);
83         } catch (OcException e) {
84             logMessage("Failed to discover resource");
85             Log.e(TAG, e.getMessage());
86         }
87         logMessage("-----------------------------------------------------");
88     }
89
90     /**
91      * callback when a fridge resource is found.
92      */
93     @Override
94     public synchronized void onResourceFound(OcResource ocResource) {
95         if ((null != fridgeResource) && !fridgeResource.getUri().equals("/fridge/group")) {
96             logMessage("Didn't find the correct fridge resource. Exiting");
97             return;
98         }
99         fridgeResource = ocResource;
100         logMessage("Discovered a fridge with \nHost: " + fridgeResource.getHost());
101         logMessage("Trying to call GET api on fridgeResource");
102         try {
103             fridgeResource.get(new HashMap<String, String>(), this);
104         } catch (OcException e) {
105             logMessage("Failed to call GET api");
106             Log.e(TAG, e.getMessage());
107         }
108         logMessage("-----------------------------------------------------");
109     }
110
111     /**
112      * once the fridge resource is discovered, create proxy child resources of the fridge
113      * and call GET on each of the child resource proxies.
114      *
115      * @param list
116      * @param ocRepresentation parent resource
117      */
118     @Override
119     public synchronized void onGetCompleted(List<OcHeaderOption> list,
120                                             OcRepresentation ocRepresentation) {
121         logMessage("Got a response from " + ocRepresentation.getUri());
122         for (OcRepresentation child : ocRepresentation.getChildren()) {
123             try {
124                 logMessage("Creating child resource proxy from fridgeResource with uri " +
125                         child.getUri());
126                 OcResource childResource = OcPlatform.constructResourceObject(
127                         fridgeResource.getHost(),
128                         child.getUri(),
129                         fridgeResource.getConnectivityTypeSet(),
130                         false, // isObservable set to false
131                         child.getResourceTypes(),
132                         child.getResourceInterfaces());
133                 childResourceList.add(childResource);
134             } catch (OcException e) {
135                 logMessage("Error in creating child resource proxy");
136                 Log.e(TAG, e.getMessage());
137             }
138             logMessage("-----------------------------------------------------");
139         }
140
141         OcResource.OnGetListener childOnGetListener = new OcResource.OnGetListener() {
142             public static final String DOOR_STATE_KEY = "state";
143             public static final String DOOR_SIDE_KEY = "side";
144             public static final String LIGHT_STATUS_KEY = "light";
145
146             @Override
147             public synchronized void onGetCompleted(List<OcHeaderOption> list,
148                                                     OcRepresentation ocRepresentation) {
149                 logMessage("Received a response from a child of the fridge with uri: " +
150                         ocRepresentation.getUri());
151                 for (String resType : ocRepresentation.getResourceTypes()) {
152                     if (resType.equals("intel.fridge.door")) {
153                         try {
154                             logMessage(ocRepresentation.getValue(DOOR_SIDE_KEY) +
155                                     " door is " + ((ocRepresentation.getValue(DOOR_STATE_KEY)
156                                     ) ? "open" : "close"));
157                         } catch (OcException e) {
158                             logMessage("Failed to get the door resource representation");
159                             Log.e(TAG, e.getMessage());
160                         }
161                     } else if (resType.equals("intel.fridge.light")) {
162                         try {
163                             logMessage("Fridge light is " +
164                                     ((ocRepresentation.getValue(LIGHT_STATUS_KEY)) ?
165                                             "on" : "off"));
166                         } catch (OcException e) {
167                             logMessage("Failed to get the light resource representation");
168                             Log.e(TAG, e.getMessage());
169                         }
170                     }
171                 }
172                 logMessage("-----------------------------------------------------");
173             }
174
175             @Override
176             public synchronized void onGetFailed(Throwable throwable) {
177                 logMessage("OnGet failed for child of fridge");
178                 Log.e(TAG, throwable.getMessage());
179             }
180         };
181
182         for (OcResource child : childResourceList) {
183             try {
184                 logMessage("Trying to get a representation of " + child.getUri() +
185                         " resource from server");
186                 child.get(new HashMap<String, String>(), childOnGetListener);
187             } catch (OcException e) {
188                 logMessage(e.getMessage());
189                 Log.e(TAG, e.getMessage());
190             }
191         }
192
193     }
194
195     @Override
196     public synchronized void onGetFailed(Throwable throwable) {
197         logMessage("Failed to get representation of the fridge");
198         Log.e(TAG, throwable.toString());
199     }
200
201     //******************************************************************************
202     // End of the OIC specific code
203     //******************************************************************************
204     private TextView mConsoleTextView;
205
206     @Override
207     protected void onCreate(Bundle savedInstanceState) {
208         super.onCreate(savedInstanceState);
209         setContentView(R.layout.activity_fridge_client);
210
211         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
212         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
213         final Button button = (Button) findViewById(R.id.button);
214
215         if (null == savedInstanceState) {
216             button.setOnClickListener(new View.OnClickListener() {
217                 @Override
218                 public void onClick(View v) {
219                     button.setEnabled(false);
220                     new Thread(new Runnable() {
221                         public void run() {
222                             startFridgeClient();
223                         }
224                     }).start();
225                 }
226             });
227         } else {
228             String consoleOutput = savedInstanceState.getString("consoleOutputString");
229             mConsoleTextView.setText(consoleOutput);
230         }
231     }
232
233     @Override
234     protected void onSaveInstanceState(Bundle outState) {
235         super.onSaveInstanceState(outState);
236         outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
237     }
238
239     @Override
240     protected void onRestoreInstanceState(Bundle savedInstanceState) {
241         super.onRestoreInstanceState(savedInstanceState);
242
243         String consoleOutput = savedInstanceState.getString("consoleOutputString");
244         mConsoleTextView.setText(consoleOutput);
245     }
246
247     private void logMessage(final String text) {
248         runOnUiThread(new Runnable() {
249             public void run() {
250                 final Message msg = new Message();
251                 msg.obj = text;
252                 mConsoleTextView.append("\n");
253                 mConsoleTextView.append(text);
254             }
255         });
256         Log.i(TAG, text);
257     }
258 }