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