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.simpleclient;
25 import android.app.Activity;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.res.AssetManager;
31 import android.os.Bundle;
32 import android.os.Message;
33 import android.preference.PreferenceManager;
34 import android.text.method.ScrollingMovementMethod;
35 import android.util.Log;
36 import android.widget.LinearLayout;
37 import android.widget.TextView;
39 import org.iotivity.base.ErrorCode;
40 import org.iotivity.base.ModeType;
41 import org.iotivity.base.ObserveType;
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;
53 import java.io.FileNotFoundException;
54 import java.io.FileOutputStream;
55 import java.io.IOException;
56 import java.io.InputStream;
57 import java.io.OutputStream;
58 import java.util.EnumSet;
59 import java.util.HashMap;
60 import java.util.List;
62 import base.iotivity.org.examples.message.IMessageLogger;
67 * SimpleClient is a sample client app which should be started after the simpleServer is started.
68 * It finds resources advertised by the server and calls different operations on it (GET, PUT,
70 * This implements IMessageLogger to display messages on the screen
72 public class SimpleClient extends Activity implements OcPlatform.OnResourceFoundListener,
74 private static final String TAG = "SimpleClient: ";
76 private static final int BUFFER_SIZE = 1024;
77 private String filePath = "";
78 private Light myLight;
79 private OcResource curResource;
82 private TextView mEventsTextView;
83 private static boolean printOnce = true;
86 * configure OIC platform and call findResource
88 private void initOICStack() {
89 //create platform config
90 PlatformConfig cfg = new PlatformConfig(
93 ModeType.CLIENT_SERVER,
94 "0.0.0.0", // bind to all available interfaces
96 QualityOfService.LOW, filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
97 OcPlatform.Configure(cfg);
102 OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "core.light",
103 EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
104 } catch (OcException e) {
105 logMessage(TAG + "findResource error: " + e.getMessage());
106 Log.e(TAG, e.getMessage());
112 * callback when a resource is found. This method calls doGetLightRepresentation to get the
113 * current values of myLight
115 synchronized public void onResourceFound(OcResource ocResource) {
117 * this may potentially be called by multiple threads at the same time
119 synchronized (this) {
122 resourceUri = ocResource.getUri();
123 hostAddress = ocResource.getHost();
124 logMessage(TAG + "Discovered Resource\nUri: " + resourceUri + " \n Host: " + hostAddress);
125 // get the resource types
126 if (resourceUri.contains("light")) {
127 curResource = ocResource;
128 doGetLightRepresentation();
134 * get myLight values after observe
136 private void doObserveLightRepresentation() {
137 // eventhandler for observe()
138 OcResource.OnObserveListener onObserveListener = new OcResource.OnObserveListener() {
140 public void onObserveCompleted(List<OcHeaderOption> ocHeaderOptions,
141 OcRepresentation ocRepresentation, int seqNum) {
143 logMessage(TAG + "OBSERVE request was successful");
147 boolean state = ocRepresentation.getValue(StringConstants.STATE);
148 int power = ocRepresentation.getValue(StringConstants.POWER);
149 String name = ocRepresentation.getValue(StringConstants.NAME);
150 myLight.setState(state);
151 myLight.setPower(power);
152 myLight.setName(name);
153 } catch (OcException e) {
154 Log.e(TAG, e.getMessage());
156 logMessage(TAG + "onObserve: Power: " + myLight.getPower());
159 curResource.cancelObserve();
160 logMessage(TAG + "Successfully cancelled observe");
161 } catch (OcException e) {
162 logMessage(TAG + "cancelObserve error. " + e.getMessage());
163 Log.e(TAG, e.getMessage());
170 public void onObserveFailed(Throwable throwable) {
171 if (throwable instanceof OcException) {
172 OcException ocEx = (OcException) throwable;
173 ErrorCode errCode = ocEx.getErrorCode();
174 //do something based on errorCode
176 Log.e(TAG, throwable.toString());
180 curResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), onObserveListener);
181 } catch (OcException e) {
182 logMessage(TAG + e.getMessage());
183 Log.e(TAG, e.getMessage());
188 * get the current value of myLight after POST and call doObserveLightRepresentation
190 * @param ocRepresentation needed to invoke post()
192 private void doOnPost2(OcRepresentation ocRepresentation) {
193 // eventhandler for post()
194 OcResource.OnPostListener onPostListener2 = new OcResource.OnPostListener() {
196 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions, OcRepresentation rep) {
197 logMessage(TAG + "POST request was successful");
198 String createdUri = rep.getUri();
199 if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
200 logMessage(TAG + "Uri of the created resource: " + createdUri);
203 boolean state = rep.getValue(StringConstants.STATE);
204 int power = rep.getValue(StringConstants.POWER);
205 String name = rep.getValue(StringConstants.NAME);
206 myLight.setState(state);
207 myLight.setPower(power);
208 myLight.setName(name);
209 } catch (OcException e) {
210 Log.e(TAG, e.getMessage());
212 logMessage(TAG + "onPost\nState: " + myLight.getState() + "\nPower: " +
213 myLight.getPower() + "\nName: " + myLight.getName());
215 doObserveLightRepresentation();
219 public void onPostFailed(Throwable throwable) {
220 if (throwable instanceof OcException) {
221 OcException ocEx = (OcException) throwable;
222 ErrorCode errCode = ocEx.getErrorCode();
223 //do something based on errorCode
225 Log.e(TAG, throwable.toString());
229 curResource.post(ocRepresentation, new HashMap<String, String>(), onPostListener2);
230 } catch (OcException e) {
231 logMessage(TAG + e.getMessage());
232 Log.e(TAG, e.getMessage());
237 * create a new resource and update its value.
239 private void doPostLightRepresentation() {
240 // eventhandler for post()
241 OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
243 public void onPostCompleted(List<OcHeaderOption> ocHeaderOptions,
244 OcRepresentation ocRepresentation) {
245 String createdUri = "";
247 createdUri = ocRepresentation.getValue(StringConstants.CREATED_URI);
248 } catch (OcException e) {
249 Log.e(TAG, e.getMessage());
251 if (createdUri.equals(StringConstants.RESOURCE_URI1)) {
252 logMessage(TAG + "Uri of the created resource: " + createdUri);
254 boolean state = false;
256 state = ocRepresentation.getValue(StringConstants.STATE);
257 int power = ocRepresentation.getValue(StringConstants.POWER);
258 String name = ocRepresentation.getValue(StringConstants.NAME);
259 myLight.setState(state);
260 myLight.setPower(power);
261 myLight.setName(name);
262 } catch (OcException e) {
263 Log.e(TAG, e.getMessage());
266 OcRepresentation rep = new OcRepresentation();
267 myLight.setState(true);
268 myLight.setPower(55);
270 rep.setValue(StringConstants.POWER, myLight.getPower());
271 rep.setValue(StringConstants.STATE, myLight.getState());
272 } catch (OcException e) {
273 Log.e(TAG, e.getMessage());
279 public void onPostFailed(Throwable throwable) {
280 if (throwable instanceof OcException) {
281 OcException ocEx = (OcException) throwable;
282 ErrorCode errCode = ocEx.getErrorCode();
283 //do something based on errorCode
285 Log.e(TAG, throwable.toString());
289 OcRepresentation rep = new OcRepresentation();
290 myLight.setState(false);
291 myLight.setPower(105);
293 rep.setValue(StringConstants.STATE, myLight.getState());
294 rep.setValue(StringConstants.POWER, myLight.getPower());
295 } catch (OcException e) {
296 Log.e(TAG, e.getMessage());
299 curResource.post(rep, new HashMap<String, String>(), onPostListener);
300 } catch (OcException e) {
301 logMessage(TAG + e.getMessage());
302 Log.e(TAG, e.getMessage());
307 * modify the current value of myLight and call doPostLightRepresentation
309 private void doPutLightRepresentation() {
310 // eventhandler for put()
311 OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
313 public void onPutCompleted(List<OcHeaderOption> ocHeaderOptions,
314 OcRepresentation ocRepresentation) {
315 logMessage(TAG + "PUT resource was successful");
317 boolean state = ocRepresentation.getValue(StringConstants.STATE);
318 int power = ocRepresentation.getValue(StringConstants.POWER);
319 String name = ocRepresentation.getValue(StringConstants.NAME);
320 myLight.setState(state);
321 myLight.setPower(power);
322 myLight.setName(name);
323 } catch (OcException e) {
324 Log.e(TAG, e.getMessage());
327 logMessage(TAG + "onPutCompleted:\nState:" + myLight.getState() + "\nPower: " +
328 myLight.getPower() + "\nName: " + myLight.getName());
329 doPostLightRepresentation();
333 public void onPutFailed(Throwable throwable) {
335 if (throwable instanceof OcException) {
336 OcException ocEx = (OcException) throwable;
337 ErrorCode errCode = ocEx.getErrorCode();
338 //do something based on errorCode
340 Log.e(TAG, throwable.toString());
344 OcRepresentation rep = new OcRepresentation();
345 Log.d(TAG, "myLight settings: power = 15");
346 myLight.setState(true);
347 myLight.setPower(15);
349 rep.setValue(StringConstants.STATE, myLight.getState());
350 rep.setValue(StringConstants.POWER, myLight.getPower());
351 rep.setValue(StringConstants.NAME, myLight.getName());
352 } catch (OcException e) {
353 Log.e(TAG, e.getMessage());
356 Log.d(TAG, "before calling put");
357 curResource.put(rep, new HashMap<String, String>(), onPutListener);
358 } catch (OcException e) {
359 logMessage(TAG + e.getMessage());
360 Log.e(TAG, e.getMessage());
362 Log.d(TAG, "end of put call");
366 * get the existing value of myLight and call doPutLightRepresentation() to modify the current values
368 private void doGetLightRepresentation() {
369 // eventhandler for get()
370 OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
372 public void onGetCompleted(List<OcHeaderOption> headerOptionList,
373 OcRepresentation ocRepresentation) {
374 logMessage(TAG + "GET resource was successful " + StringConstants.STATE);
376 boolean state = ocRepresentation.getValue(StringConstants.STATE);
377 int power = ocRepresentation.getValue(StringConstants.POWER);
378 String name = ocRepresentation.getValue(StringConstants.NAME);
379 myLight.setState(state);
380 myLight.setPower(power);
381 myLight.setName(name);
382 } catch (OcException e) {
383 Log.e(TAG, e.getMessage());
385 logMessage(TAG + "onGetCompleted\nState: " + myLight.getState() + "\nPower: " +
386 myLight.getPower() + "\nName: " + myLight.getName());
387 doPutLightRepresentation();
391 public void onGetFailed(Throwable throwable) {
392 if (throwable instanceof OcException) {
393 OcException ocEx = (OcException) throwable;
394 ErrorCode errCode = ocEx.getErrorCode();
395 //do something based on errorCode
397 Log.e(TAG, throwable.toString());
402 curResource.get(new HashMap<String, String>(), onGetListener);
403 } catch (OcException e) {
404 logMessage(TAG + e.getMessage());
405 Log.e(TAG, e.getMessage());
410 * to display on SimpleClient screen
412 public class MessageReceiver extends BroadcastReceiver {
414 public void onReceive(Context context, Intent intent) {
415 final String message = intent.getStringExtra(StringConstants.MESSAGE);
421 protected void onCreate(Bundle savedInstanceState) {
422 super.onCreate(savedInstanceState);
423 setContentView(R.layout.activity_main);
424 mEventsTextView = new TextView(this);
425 mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
426 LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
427 layout.addView(mEventsTextView, new LinearLayout.LayoutParams(
428 LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
430 myLight = new Light();
431 filePath = getFilesDir().getPath() + "/"; // data/data/<package>/files/
432 //copy json when application runs first time
433 SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
434 boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
437 SharedPreferences.Editor editor = wmbPreference.edit();
438 editor.putBoolean("FIRSTRUN", false);
446 * Copy svr db json file from assets folder to app data files dir
448 private void copyJsonFromAsset() {
449 AssetManager assetManager = getAssets();
450 InputStream in = null;
451 OutputStream out = null;
453 in = assetManager.open(StringConstants.OIC_CLIENT_JSON_DB_FILE);
454 File file = new File(filePath);
455 //check files directory exists
456 if (!(file.exists() && file.isDirectory())) {
459 out = new FileOutputStream(filePath + StringConstants.OIC_CLIENT_JSON_DB_FILE);
461 } catch (NullPointerException e) {
462 logMessage(TAG + "Null pointer exception " + e.getMessage());
463 Log.e(TAG, e.getMessage());
464 } catch (FileNotFoundException e) {
465 logMessage(TAG + "Json svr db file not found " + e.getMessage());
466 Log.e(TAG, e.getMessage());
467 } catch (IOException e) {
468 logMessage(TAG + StringConstants.OIC_CLIENT_JSON_DB_FILE+ " file copy failed");
469 Log.e(TAG, e.getMessage());
474 } catch (IOException e) {
475 Log.e(TAG, e.getMessage());
481 } catch (IOException e) {
482 Log.e(TAG, e.getMessage());
488 private void copyFile(InputStream in, OutputStream out) throws IOException {
489 byte[] buffer = new byte[BUFFER_SIZE];
491 while ((read = in.read(buffer)) != -1) {
492 out.write(buffer, 0, read);
496 public void logMessage(String text) {
500 public void logMsg(final String text) {
501 runOnUiThread(new Runnable() {
503 Message msg = new Message();
505 mEventsTextView.append("\n");
506 mEventsTextView.append(text);
510 //to print on SimpleServer screen
511 Intent intent = new Intent("org.iotivity.base.examples.simpleclient");
512 intent.putExtra(StringConstants.MESSAGE, text);
513 sendBroadcast(intent);