Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / service / soft-sensor-manager / SampleApp / android / SSMTesterApp / src / org / iotivity / service / ssm / sample / MainActivity.java
1 package org.iotivity.service.ssm.sample;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.util.ArrayList;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.UUID;
11
12 import org.iotivity.base.ModeType;
13 import org.iotivity.base.OcPlatform;
14 import org.iotivity.base.PlatformConfig;
15 import org.iotivity.base.QualityOfService;
16 import org.iotivity.base.ServiceType;
17 import org.iotivity.service.ssm.DataReader;
18 import org.iotivity.service.ssm.IQueryEngineEvent;
19 import org.iotivity.service.ssm.ModelData;
20 import org.iotivity.service.ssm.R;
21 import org.iotivity.service.ssm.SSMInterface;
22
23 import android.app.Activity;
24 import android.app.AlertDialog;
25 import android.content.Context;
26 import android.content.DialogInterface;
27 import android.content.DialogInterface.OnClickListener;
28 import android.content.SharedPreferences;
29 import android.content.SharedPreferences.Editor;
30 import android.content.res.AssetManager;
31 import android.net.ConnectivityManager;
32 import android.net.NetworkInfo;
33 import android.os.Bundle;
34 import android.os.Handler;
35 import android.os.Message;
36 import android.util.Log;
37 import android.view.View;
38 import android.widget.EditText;
39 import android.widget.ScrollView;
40 import android.widget.TextView;
41
42 public class MainActivity extends Activity {
43
44     private SSMInterface       SoftSensorManager         = null;
45     private ArrayList<Integer> mRunningQueries           = new ArrayList<Integer>();
46
47     private IQueryEngineEvent  mQueryEngineEventListener = null;
48     private final String         LOG_TAG = "SSMSampleApp : " + this.getClass().getSimpleName();
49     private static MainActivity  activityObj;
50
51     void PrintLog(String log) {
52         Message msg = new Message();
53         Bundle data = new Bundle();
54         data.putString("Log", log);
55         msg.setData(data);
56         logHandler.sendMessage(msg);
57         Log.i(LOG_TAG, log);
58     }
59
60     private Handler      logHandler         = new Handler() {
61                                                 @Override
62                                                 public void handleMessage(
63                                                         Message msg) {
64                                                     tvLog.append(msg.getData()
65                                                             .getString("Log")
66                                                             + "\n");
67                                                     svLog.fullScroll(ScrollView.FOCUS_DOWN);
68                                                 }
69                                             };
70
71     private TextView     tvLog              = null;
72     private ScrollView   svLog              = null;
73     private EditText     edtQuery           = null;
74     private EditText     edtUnregisterQuery = null;
75
76     View.OnClickListener clickHandler       = null;
77
78     View.OnClickListener textAddHandler     = null;
79
80     @Override
81     public void onCreate(Bundle savedInstanceState) {
82         super.onCreate(savedInstanceState);
83         setContentView(R.layout.activity_main);
84
85         tvLog = (TextView) findViewById(R.id.txtLog);
86         svLog = (ScrollView) findViewById(R.id.sclLog);
87         edtQuery = (EditText) findViewById(R.id.editQuery);
88         edtUnregisterQuery = (EditText) findViewById(R.id.editUnregisterQuery);
89         
90         // calling the method to check the Wi-fi connectivity and configuring
91         // the OcPlatform
92         configurePlatform();
93
94         mQueryEngineEventListener = new IQueryEngineEvent() {
95             @Override
96             public void onQueryEngineEvent(int cqid, DataReader result) {
97                 Log.i("[SSM]", "event received! cqid=" + cqid);
98                 PrintLog("Event from cqid " + cqid + " has received");
99
100                 List<String> models = result.getAffectedModels();
101
102                 for (String modelName : models) {
103                     PrintLog("Model: " + modelName);
104
105                     try {
106                         int dataCount = result.getModelDataCount(modelName);
107
108                         for (int i = 0; i < dataCount; i++) {
109                             ModelData modelData = result.getModelData(
110                                     modelName, i);
111
112                             for (int j = 0; j < modelData.getPropertyCount(); j++) {
113                                 PrintLog("Name: "
114                                         + modelData.getPropertyName(j)
115                                         + " Value: "
116                                         + modelData.getPropertyValue(j));
117
118                             }
119
120                         }
121                     } catch (Exception e) {
122                         e.printStackTrace();
123                         PrintLog("Receiving Event from cqid " + cqid
124                                 + " failed");
125                     }
126                 }
127             }
128         };
129
130         clickHandler = new View.OnClickListener() {
131
132             public void onClick(View v) {
133                 switch (v.getId()) {
134                     case R.id.btnRegisterQuery:
135                         int cqid = 0;
136                         try {
137                             cqid = SoftSensorManager.registerQuery(edtQuery
138                                     .getText().toString(),
139                                     mQueryEngineEventListener);
140                             mRunningQueries.add(cqid);
141                             PrintLog(edtQuery.getText().toString()
142                                     + " has executed, cqid=" + cqid);
143                         } catch (Exception e) {
144                             PrintLog("Register Query failed");
145                         }
146
147                         break;
148
149                     case R.id.btnUnregisterQuery:
150                         Iterator<Integer> it = mRunningQueries.iterator();
151
152                         while (it.hasNext()) {
153                             if (it.next() == Integer
154                                     .parseInt(edtUnregisterQuery.getText()
155                                             .toString())) {
156                                 try {
157                                     SoftSensorManager.unregisterQuery(Integer
158                                             .parseInt(edtUnregisterQuery
159                                                     .getText().toString()));
160                                     PrintLog("Unregister Query has executed, cqid="
161                                             + Integer
162                                                     .parseInt(edtUnregisterQuery
163                                                             .getText()
164                                                             .toString()));
165                                     it.remove();
166                                 } catch (NumberFormatException e) {
167                                     PrintLog("Invalid Query Id");
168                                 } catch (Exception e) {
169                                     PrintLog("UnRegister Query failed");
170                                 }
171                                 break;
172                             }
173                         }
174                         break;
175
176                     case R.id.btPlus:
177                         int queryNum = 0;
178
179                         try {
180                             queryNum = Integer.parseInt(edtUnregisterQuery
181                                     .getText().toString()) + 1;
182                             edtUnregisterQuery.setText(queryNum + "");
183                         } catch (NumberFormatException e) {
184                             PrintLog("Invalid Query Id");
185                         }
186                         break;
187
188                     case R.id.btMinus:
189                         try {
190                             queryNum = Integer.parseInt(edtUnregisterQuery
191                                     .getText().toString()) - 1;
192                             edtUnregisterQuery.setText(queryNum + "");
193                         } catch (NumberFormatException e) {
194                             PrintLog("Invalid Query Id");
195                         }
196                         break;
197                 }
198             }
199         };
200
201         textAddHandler = new View.OnClickListener() {
202
203             public void onClick(View v) {
204                 switch (v.getId()) {
205                     case R.id.btClear:
206                         edtQuery.setText("");
207                         Log.i(LOG_TAG, "Query textbox is cleared");
208                         break;
209
210                     case R.id.btLogClear:
211                         tvLog.setText("");
212                         Log.i(LOG_TAG, "Log textbox is cleared");
213                         break;
214
215                     case R.id.btFullDevice:
216                         edtQuery.setText("subscribe Device if Device.dataId != 0");
217                         Log.i(LOG_TAG, "subscribe Device if Device.dataId != 0");
218                         break;
219
220                     case R.id.btDiscomfortIndex:
221                         edtQuery.setText("subscribe Device.DiscomfortIndexSensor if Device.DiscomfortIndexSensor.discomfortIndex > 0");
222                         Log.i(LOG_TAG, "subscribe Device.DiscomfortIndexSensor if Device.DiscomfortIndexSensor.discomfortIndex > 0");
223                         break;
224                 }
225             }
226         };
227
228         copyFiles("lib");
229
230         SoftSensorManager = new SSMInterface();
231
232         String initConfig = "<SSMCore>" + "<Device>" + "<UDN>" + getUUID()
233                 + "</UDN>" + "<Name>MyMobile</Name>" + "<Type>Mobile</Type>"
234                 + "</Device>" + "<Config>"
235                 + "<SoftSensorRepository>/data/data/" + getPackageName()
236                 + "/files/</SoftSensorRepository>"
237                 + "<SoftSensorDescription>/data/data/" + getPackageName()
238                 + "/files/SoftSensorDescription.xml</SoftSensorDescription>"
239                 + "</Config>" + "</SSMCore>";
240
241         try {
242             SoftSensorManager.startSSMCore(initConfig);
243         } catch (Exception e) {
244             e.printStackTrace();
245         }
246
247         findViewById(R.id.btnRegisterQuery).setOnClickListener(clickHandler);
248         findViewById(R.id.btnUnregisterQuery).setOnClickListener(clickHandler);
249         findViewById(R.id.btFullDevice).setOnClickListener(textAddHandler);
250         findViewById(R.id.btDiscomfortIndex).setOnClickListener(textAddHandler);
251         findViewById(R.id.btPlus).setOnClickListener(clickHandler);
252         findViewById(R.id.btMinus).setOnClickListener(clickHandler);
253         findViewById(R.id.btClear).setOnClickListener(textAddHandler);
254         findViewById(R.id.btLogClear).setOnClickListener(textAddHandler);
255     }
256
257     @Override
258     protected void onDestroy() {
259         try {
260             SoftSensorManager.stopSSMCore();
261         } catch (Exception e) {
262             e.printStackTrace();
263         }
264
265         super.onDestroy();
266     }
267
268     private String getUUID() {
269         String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
270         SharedPreferences sharedPrefs = getSharedPreferences(PREF_UNIQUE_ID,
271                 Context.MODE_PRIVATE);
272         String uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
273
274         if (uniqueID == null) {
275             uniqueID = UUID.randomUUID().toString();
276             Editor editor = sharedPrefs.edit();
277             editor.putString(PREF_UNIQUE_ID, uniqueID);
278             editor.commit();
279         }
280
281         return uniqueID;
282     }
283
284     private void copyFiles(String path) {
285         AssetManager assetManager = getAssets();
286         String assets[] = null;
287
288         try {
289             assets = assetManager.list(path);
290
291             if (assets.length == 0) {
292                 copyFile(path);
293             } else {
294                 String fullPath = "/data/data/"
295                         + this.getClass().getPackage().toString() + "/" + path;
296                 File dir = new File(fullPath);
297
298                 if (!dir.exists())
299                     dir.mkdir();
300                 for (int i = 0; i < assets.length; ++i) {
301                     copyFiles(path + "/" + assets[i]);
302                 }
303             }
304         } catch (IOException ex) {
305             Log.e("tag", "I/O Exception", ex);
306         }
307     }
308
309     private void copyFile(String filename) {
310         AssetManager assetManager = getAssets();
311         InputStream in = null;
312         OutputStream out = null;
313
314         try {
315             in = assetManager.open(filename);
316             out = openFileOutput(filename.split("/")[1], Context.MODE_PRIVATE);
317
318             byte[] buffer = new byte[1024];
319             int read;
320
321             while ((read = in.read(buffer)) != -1) {
322                 out.write(buffer, 0, read);
323             }
324
325             in.close();
326             in = null;
327             out.flush();
328             out.close();
329             out = null;
330         } catch (Exception e) {
331             Log.e("tag", e.getMessage());
332         }
333     }
334     
335     private void configurePlatform() {
336         // local Variables
337         ConnectivityManager connManager;
338         NetworkInfo wifi;
339         AlertDialog dialog;
340         PlatformConfig platformConfigObj;
341
342         // Check the wifi connectivity
343         connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
344         wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
345         if (false == wifi.isConnected()) {
346             // WiFi is not connected close the application
347             AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
348             dialogBuilder.setTitle("Error");
349             dialogBuilder
350                     .setMessage("WiFi is not enabled/connected! Please connect the WiFi and start application again...");
351             dialogBuilder.setCancelable(false);
352             dialogBuilder.setPositiveButton("OK", new OnClickListener() {
353                 @Override
354                 public void onClick(DialogInterface dialog, int which) {
355                     // Closing the application
356                     activityObj.finish();
357                 }
358             });
359
360             dialog = dialogBuilder.create();
361             dialog.show();
362             return;
363         }
364         // If wifi is connected calling the configure method for configuring the
365         // OcPlatform
366         platformConfigObj = new PlatformConfig(this,ServiceType.IN_PROC,
367                 ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW);
368
369         Log.i(LOG_TAG, "Before Calling Configure of ocPlatform");
370         OcPlatform.Configure(platformConfigObj);
371         Log.i(LOG_TAG, "Configuration done Successfully");
372     }
373 }