2 * //******************************************************************
4 * // Copyright 2015 Intel Corporation.
6 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
12 * // http://www.apache.org/licenses/LICENSE-2.0
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.
20 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 package org.iotivity.base.examples.fridgeclient;
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.os.Message;
32 import android.support.v4.content.LocalBroadcastManager;
33 import android.text.method.ScrollingMovementMethod;
34 import android.util.Log;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.widget.LinearLayout;
38 import android.widget.TextView;
40 import org.iotivity.base.ErrorCode;
41 import org.iotivity.base.ModeType;
42 import org.iotivity.base.OcConnectivityType;
43 import org.iotivity.base.OcException;
44 import org.iotivity.base.OcHeaderOption;
45 import org.iotivity.base.OcPlatform;
46 import org.iotivity.base.OcRepresentation;
47 import org.iotivity.base.OcResource;
48 import org.iotivity.base.PlatformConfig;
49 import org.iotivity.base.QualityOfService;
50 import org.iotivity.base.ServiceType;
52 import java.util.EnumSet;
53 import java.util.HashMap;
54 import java.util.LinkedList;
55 import java.util.List;
57 import base.iotivity.org.examples.message.IMessageLogger;
62 * FridgeClient is a sample client app which should be started after the fridgeServer is started.
63 * It creates DeviceResource, DoorResource, LightResource and performs a get operation on them.
64 * This implements IMessageLogger to display messages on the screen
66 public class FridgeClient extends Activity implements
67 OcPlatform.OnResourceFoundListener, IMessageLogger {
68 private static String TAG = "FridgeClient: ";
70 private MessageReceiver mMessageReceiver = new MessageReceiver();
71 private TextView mEventsTextView;
72 private String mDeviceName;
73 private int mDeviceCode;
74 private List<String> ifaces;
75 private final List<OcResource> resourceList = new LinkedList<OcResource>();
78 * configure OIC platform and call findResource
80 private void initOICStack() {
81 PlatformConfig cfg = new PlatformConfig(
85 "0.0.0.0", // bind to all available interfaces
87 QualityOfService.LOW);
89 OcPlatform.Configure(cfg);
91 OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
92 EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
93 } catch (OcException e) {
94 logMessage(TAG + " init Error. " + e.getMessage());
95 Log.e(TAG, e.getMessage());
100 * prints out the appropriate messages depending on the device code
102 * @param representation representation of the OcResource
103 * @param value clientDeviceCode
105 private void getResponse(OcRepresentation representation, int value) {
110 logMessage(TAG + "Name of device: " +
111 representation.getValue(StringConstants.DEVICE_NAME));
112 } catch (OcException e) {
113 Log.e(TAG, e.getMessage());
117 // get on fridge light
119 boolean lightOn = representation.getValue(StringConstants.ON);
120 logMessage(TAG + "The fridge light is " +
121 (lightOn ? "" : "not " + "on"));
122 } catch (OcException e) {
123 Log.e(TAG, e.getMessage());
128 // get on fridge door(s)
130 boolean doorOpen = representation.getValue(StringConstants.OPEN);
131 logMessage(TAG + "Door is " + (doorOpen ?
132 "open" : "not open") + " and is on the " +
133 representation.getValue(StringConstants.SIDE) + " side");
134 } catch (OcException e) {
135 Log.e(TAG, e.getMessage());
139 // get on fridge random door
141 logMessage("Name of fridge: " +
142 representation.getValue(StringConstants.DEVICE_NAME));
143 } catch (OcException e) {
144 Log.e(TAG, e.getMessage());
148 logMessage("Unexpected State");
154 * this method is used to wait for 1 second between calls to different resources.
155 * It is added for better readability
157 private void doWait() {
159 Thread.sleep(StringConstants.WAIT_TIME);
160 } catch (InterruptedException e) {
161 logMessage(TAG + "doWait exception: " + e.getMessage());
162 Log.e(TAG, e.getMessage());
168 * callback when a resource is found. This method calls getResponse with the correct code
170 synchronized public void onResourceFound(OcResource ocResource) {
171 // eventHandler for onGetListener
172 resourceList.add(ocResource);
173 OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
175 public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation rep) {
176 logMessage(TAG + " Got a response from " + getClientDeviceName());
177 getResponse(rep, getClientDeviceCode());
181 public void onGetFailed(Throwable throwable) {
182 if (throwable instanceof OcException) {
183 OcException ocEx = (OcException) throwable;
184 ErrorCode errCode = ocEx.getErrorCode();
185 //do something based on errorCode
187 Log.e(TAG, throwable.toString());
191 if (ocResource.getUri().equals(StringConstants.RESOURCE_URI)) {
192 logMessage(TAG + "Discovered a device with \nHost: " + ocResource.getHost() +
193 ", Uri: " + ocResource.getUri());
195 List<String> lightTypes = new LinkedList<>();
196 lightTypes.add("intel.fridge.light");
198 OcResource light = OcPlatform.constructResourceObject(ocResource.getHost(),
199 StringConstants.LIGHT, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, lightTypes, ifaces);
201 List<String> doorTypes = new LinkedList<>();
202 doorTypes.add("intel.fridge.door");
203 OcResource leftDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
204 StringConstants.LEFT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
206 OcResource rightDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
207 StringConstants.RIGHT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
209 OcResource randomDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
210 StringConstants.RANDOM_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
212 List<OcHeaderOption> headerOptions = new LinkedList<>();
213 OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,
214 StringConstants.API_VERSION);
215 OcHeaderOption clientToken = new OcHeaderOption(StringConstants.CLIENT_TOKEN_KEY,
216 StringConstants.CLIENT_TOKEN);
217 headerOptions.add(apiVersion);
218 headerOptions.add(clientToken);
219 ocResource.setHeaderOptions(headerOptions);
221 * wait for 1 second before calling get on different resources.
222 * It is done for better readability.
223 * doWait() is called before each call to get
227 setupClientOptions("Device", 0);
228 ocResource.get(new HashMap<String, String>(), onGetListener);
231 setupClientOptions("Fridge Light", 1);
232 light.get(new HashMap<String, String>(), onGetListener);
235 setupClientOptions("Left Door", 2);
236 leftDoor.get(new HashMap<String, String>(), onGetListener);
239 setupClientOptions("Right Door", 3);
240 rightDoor.get(new HashMap<String, String>(), onGetListener);
243 setupClientOptions("Random Door", 4);
244 randomDoor.get(new HashMap<String, String>(), onGetListener);
247 resourceList.add(leftDoor);
248 leftDoor.deleteResource(new OcResource.OnDeleteListener() {
250 public void onDeleteCompleted(List<OcHeaderOption> ocHeaderOptions) {
251 logMessage(TAG + "Delete resource successful");
255 public void onDeleteFailed(Throwable throwable) {
256 if (throwable instanceof OcException) {
257 OcException ocEx = (OcException) throwable;
258 ErrorCode errCode = ocEx.getErrorCode();
259 //do something based on errorCode
261 Log.e(TAG, throwable.toString());
264 } catch (OcException e) {
265 logMessage(TAG + "onResourceFound Error. " + e.getMessage());
266 Log.e(TAG, e.getMessage());
271 protected void onCreate(Bundle savedInstanceState) {
272 super.onCreate(savedInstanceState);
273 setContentView(R.layout.activity_fridge_client);
274 registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));
276 mEventsTextView = new TextView(this);
277 mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
278 LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
279 layout.addView(mEventsTextView, new LinearLayout.LayoutParams
280 (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
281 ifaces = new LinkedList<>();
282 ifaces.add(StringConstants.RESOURCE_INTERFACE);
289 public class MessageReceiver extends BroadcastReceiver {
291 public void onReceive(Context context, Intent intent) {
292 final String message = intent.getStringExtra(StringConstants.MESSAGE);
298 public void logMessage(final String text) {
299 if (StringConstants.ENABLE_PRINTING) {
300 runOnUiThread(new Runnable() {
302 final Message msg = new Message();
304 mEventsTextView.append("\n");
305 mEventsTextView.append(text);
313 private void setupClientOptions(String name, int value) {
318 private String getClientDeviceName() {
322 private int getClientDeviceCode() {
327 //method to print the headerOptions received from the server
328 void printHeaderOptions(List<OcHeaderOption> headerOptions) {
329 for (OcHeaderOption headerOption : headerOptions) {
330 if (StringConstants.API_VERSION_KEY == headerOption.getOptionId()) {
331 logMessage(TAG + "Server API version in GET response: " +
332 headerOption.getOptionData());
338 public boolean onCreateOptionsMenu(Menu menu) {
339 getMenuInflater().inflate(R.menu.menu_fridge_client, menu);
344 public boolean onOptionsItemSelected(MenuItem item) {
345 int id = item.getItemId();
346 if (id == R.id.action_settings) {
349 return super.onOptionsItemSelected(item);
353 public void onDestroy() {
359 protected void onStop() {
360 LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);