[IOT-1089] Change Android build system to accomodate both Android and Generic Java...
[contrib/iotivity.git] / java / examples-java / fridgeclient / src / main / java / org / iotivity / base / examples / FridgeClient.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  * FridgeClient
52  * <p/>
53  * FridgeClient is a sample client app which should be started after the fridgeServer is started.
54  * It creates DeviceResource, DoorResources, LightResource and performs a GET operation on them.
55  */
56 public class FridgeClient extends Activity implements
57         OcPlatform.OnResourceFoundListener,
58         OcResource.OnGetListener {
59     public static final String DEVICE_URI = "/device";
60     public static final String LIGHT = "/light";
61     public static final String LEFT_DOOR = "/door/left";
62     public static final String RIGHT_DOOR = "/door/right";
63     public static final String RANDOM_DOOR = "/door/random";
64     public static final String API_VERSION = "v.1.0";
65     public static final String CLIENT_TOKEN = "21ae43gf";
66     public static final int API_VERSION_KEY = 2048;
67     public static final int CLIENT_TOKEN_KEY = 3000;
68
69     private final List<OcResource> mResourceList = new LinkedList<OcResource>();
70     private OcResource mFridgeResource;
71
72     /**
73      * configure OIC platform and call findResource
74      */
75     private void startFridgeClient() {
76         PlatformConfig cfg = new PlatformConfig(
77                 this, // context
78                 ServiceType.IN_PROC,
79                 ModeType.CLIENT,
80                 "0.0.0.0", // bind to all available interfaces
81                 0,
82                 QualityOfService.LOW);
83
84         logMessage("Configuring platform");
85         OcPlatform.Configure(cfg);
86         logMessage("Initiating fridge discovery");
87         try {
88             OcPlatform.findResource("",
89                     OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
90                     EnumSet.of(OcConnectivityType.CT_DEFAULT),
91                     this);
92         } catch (OcException e) {
93             logMessage(" Failed to discover resource");
94             Log.e(TAG, e.getMessage());
95         }
96         logMessage("-----------------------------------------------------");
97     }
98
99     /**
100      * An event handler to be executed whenever a "findResource" request completes successfully
101      *
102      * @param ocResource found resource
103      */
104     @Override
105     public synchronized void onResourceFound(OcResource ocResource) {
106         if (null != mFridgeResource || !ocResource.getUri().equals(DEVICE_URI)) {
107             logMessage("Didn't find the correct fridge resource. Exiting");
108             return;
109         }
110         mFridgeResource = ocResource;
111         logMessage("Discovered a fridge with \nHost: " + mFridgeResource.getHost());
112
113         List<String> lightTypes = new LinkedList<>();
114         lightTypes.add("intel.fridge.light");
115         List<String> doorTypes = new LinkedList<>();
116         doorTypes.add("intel.fridge.door");
117         List<String> resourceInterfaces = new LinkedList<>();
118         resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
119         logMessage("Creating child resource proxies for the previously known fridge components");
120         OcResource light = null;
121         OcResource leftDoor = null;
122         OcResource rightDoor = null;
123         OcResource randomDoor = null;
124         try {
125             light = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
126                     LIGHT,
127                     mFridgeResource.getConnectivityTypeSet(),
128                     false, //isObservable
129                     lightTypes,
130                     resourceInterfaces);
131             mResourceList.add(light);
132
133             leftDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
134                     LEFT_DOOR,
135                     mFridgeResource.getConnectivityTypeSet(),
136                     false, //isObservable
137                     doorTypes,
138                     resourceInterfaces);
139             mResourceList.add(leftDoor);
140
141             rightDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
142                     RIGHT_DOOR,
143                     mFridgeResource.getConnectivityTypeSet(),
144                     false, //isObservable
145                     doorTypes,
146                     resourceInterfaces);
147             mResourceList.add(rightDoor);
148
149             randomDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
150                     RANDOM_DOOR,
151                     mFridgeResource.getConnectivityTypeSet(),
152                     false, //isObservable
153                     doorTypes,
154                     resourceInterfaces);
155             mResourceList.add(randomDoor);
156         } catch (OcException e) {
157             logMessage("Error in constructResourceObject");
158             Log.e(TAG, e.getMessage());
159         }
160
161         List<OcHeaderOption> headerOptions = new LinkedList<>();
162         OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY, API_VERSION);
163         OcHeaderOption clientToken = new OcHeaderOption(CLIENT_TOKEN_KEY, CLIENT_TOKEN);
164         headerOptions.add(apiVersion);
165         headerOptions.add(clientToken);
166         mFridgeResource.setHeaderOptions(headerOptions);
167
168         logMessage("Calling GET api on mFridgeResource and other component resources");
169         try {
170             mFridgeResource.get(new HashMap<String, String>(), this);
171             if (null != light) light.get(new HashMap<String, String>(), this);
172             if (null != leftDoor) leftDoor.get(new HashMap<String, String>(), this);
173             if (null != rightDoor) rightDoor.get(new HashMap<String, String>(), this);
174             if (null != randomDoor) randomDoor.get(new HashMap<String, String>(), this);
175         } catch (OcException e) {
176             logMessage("Error in GET calls");
177             Log.e(TAG, e.getMessage());
178         }
179     }
180
181     /**
182      * An event handler to be executed whenever a "get" request completes successfully
183      *
184      * @param headerOptionList list of the header options
185      * @param ocRepresentation representation of a resource
186      */
187     @Override
188     public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
189                                             OcRepresentation ocRepresentation) {
190         logMessage("Got a response from " + ocRepresentation.getUri());
191     }
192
193     /**
194      * An event handler to be executed whenever a "get" request fails
195      *
196      * @param throwable exception
197      */
198     @Override
199     public synchronized void onGetFailed(Throwable throwable) {
200         logMessage("GET request has failed");
201         Log.e(TAG, throwable.toString());
202     }
203
204     //******************************************************************************
205     // End of the OIC specific code
206     //******************************************************************************
207     @Override
208     protected void onCreate(Bundle savedInstanceState) {
209         super.onCreate(savedInstanceState);
210         setContentView(R.layout.activity_fridge_client);
211
212         mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
213         mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
214         final Button button = (Button) findViewById(R.id.button);
215
216         if (null == savedInstanceState) {
217             button.setOnClickListener(new View.OnClickListener() {
218                 @Override
219                 public void onClick(View v) {
220                     button.setEnabled(false);
221                     new Thread(new Runnable() {
222                         public void run() {
223                             startFridgeClient();
224                         }
225                     }).start();
226                 }
227             });
228         } else {
229             String consoleOutput = savedInstanceState.getString("consoleOutputString");
230             mConsoleTextView.setText(consoleOutput);
231         }
232     }
233
234     private void logMessage(final String text) {
235         runOnUiThread(new Runnable() {
236             public void run() {
237                 final Message msg = new Message();
238                 msg.obj = text;
239                 mConsoleTextView.append("\n");
240                 mConsoleTextView.append(text);
241             }
242         });
243         Log.i(TAG, text);
244     }
245
246     private static String TAG = "FridgeClient: ";
247     private TextView mConsoleTextView;
248 }