Panagiotis Triantafyllou

telemtics now save the data in sdk's db

...@@ -39,6 +39,7 @@ import java.util.Arrays; ...@@ -39,6 +39,7 @@ import java.util.Arrays;
39 39
40 import io.github.inflationx.viewpump.ViewPumpContextWrapper; 40 import io.github.inflationx.viewpump.ViewPumpContextWrapper;
41 import ly.warp.sdk.R; 41 import ly.warp.sdk.R;
42 +import ly.warp.sdk.db.WarplyDBHelper;
42 43
43 /** 44 /**
44 * Created by Panagiotis Triantafyllou on 26/June/2023. 45 * Created by Panagiotis Triantafyllou on 26/June/2023.
...@@ -79,6 +80,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -79,6 +80,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
79 double mLongitude = 0; 80 double mLongitude = 0;
80 // Radius of the Earth in meters 81 // Radius of the Earth in meters
81 private static final double EARTH_RADIUS = 6371000.0; 82 private static final double EARTH_RADIUS = 6371000.0;
83 + private Location previousLocation;
84 + double mSpeed = 0;
82 85
83 // =========================================================== 86 // ===========================================================
84 // Methods for/from SuperClass/Interfaces 87 // Methods for/from SuperClass/Interfaces
...@@ -102,6 +105,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -102,6 +105,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
102 mIvBack.setOnClickListener(this); 105 mIvBack.setOnClickListener(this);
103 106
104 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 107 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
108 + previousLocation = null;
105 109
106 initViews(); 110 initViews();
107 } 111 }
...@@ -115,9 +119,15 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -115,9 +119,15 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
115 @Override 119 @Override
116 protected void onPause() { 120 protected void onPause() {
117 super.onPause(); 121 super.onPause();
118 - if (mIsTripStarted) 122 + }
119 - unregisterStepSensor(); 123 +
120 - stopLocationUpdates(); 124 + @Override
125 + public void onBackPressed() {
126 + super.onBackPressed();
127 + if (mIsTripStarted) {
128 + unregisterSensor();
129 + stopLocationUpdates();
130 + }
121 } 131 }
122 132
123 @Override 133 @Override
...@@ -176,14 +186,14 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -176,14 +186,14 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
176 } 186 }
177 if (view.getId() == R.id.ll_activate_button) { 187 if (view.getId() == R.id.ll_activate_button) {
178 if (mIsTripStarted) { 188 if (mIsTripStarted) {
179 - unregisterStepSensor(); 189 + unregisterSensor();
180 stopLocationUpdates(); 190 stopLocationUpdates();
181 initViews(); 191 initViews();
182 mIsTripStarted = false; 192 mIsTripStarted = false;
183 mTvTripButton.setText(R.string.cos_dlg_start_trip); 193 mTvTripButton.setText(R.string.cos_dlg_start_trip);
184 } else { 194 } else {
185 requestLocationUpdates(); 195 requestLocationUpdates();
186 - registerStepSensor(); 196 + registerSensor();
187 mIsTripStarted = true; 197 mIsTripStarted = true;
188 mTvTripButton.setText(R.string.cos_dlg_stop_trip); 198 mTvTripButton.setText(R.string.cos_dlg_stop_trip);
189 } 199 }
...@@ -218,13 +228,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -218,13 +228,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
218 228
219 @Override 229 @Override
220 public void onLocationChanged(Location location) { 230 public void onLocationChanged(Location location) {
221 - //TODO: uncomment and remove setText if needs revert to handler implementation 231 + //TODO: comment the first block and uncomment the second block if needs revert to handler implementation
222 - //TODO: LOCATION_UPDATE_INTERVAL = 300 when using location.getSpeed()
223 -// float speedKmph = location.getSpeed() * 3.6f;
224 -// mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speedKmph)) + " km/h");
225 if (mLatitude != 0 && mLongitude != 0) { 232 if (mLatitude != 0 && mLongitude != 0) {
226 - double speed = calculateSpeed(mLatitude, mLongitude, location.getLatitude(), location.getLongitude(), (LOCATION_UPDATE_INTERVAL / 1000)); 233 + mSpeed = calculateSpeed(mLatitude, mLongitude, location.getLatitude(), location.getLongitude(), (LOCATION_UPDATE_INTERVAL / 1000));
227 - mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speed)) + " km/h"); 234 + mTvAvgVelocity.setText(String.format("%.1f", Math.floor(mSpeed)) + " km/h");
228 } 235 }
229 236
230 237
...@@ -232,6 +239,22 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -232,6 +239,22 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
232 // requestLocationUpdatePeriodically(location); 239 // requestLocationUpdatePeriodically(location);
233 mLatitude = location.getLatitude(); 240 mLatitude = location.getLatitude();
234 mLongitude = location.getLongitude(); 241 mLongitude = location.getLongitude();
242 +
243 + //TODO: similar implementation, comment all of the above blocks
244 +// if (previousLocation != null) {
245 +// // Calculate the distance traveled between the previous and current location
246 +// float distance = previousLocation.distanceTo(location); // Distance in meters
247 +//
248 +// // Calculate the speed based on the distance traveled over a timeframe of x seconds
249 +// float speed = distance / (LOCATION_UPDATE_INTERVAL / 1000); // Speed in meters/second
250 +//
251 +// // Convert speed to km/h
252 +// float speedKmH = speed * 3.6f;
253 +//
254 +// mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speedKmH)) + " km/h");
255 +// }
256 +//
257 +// previousLocation = location;
235 } 258 }
236 259
237 @Override 260 @Override
...@@ -320,7 +343,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -320,7 +343,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
320 mLoctionHandler.removeCallbacks(mLocationRunnable); 343 mLoctionHandler.removeCallbacks(mLocationRunnable);
321 } 344 }
322 345
323 - private void registerStepSensor() { 346 + private void registerSensor() {
324 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 347 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
325 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 348 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
326 mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); 349 mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
...@@ -334,7 +357,12 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -334,7 +357,12 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
334 @Override 357 @Override
335 public void run() { 358 public void run() {
336 try { 359 try {
337 - mAccelerationTimestamps.add(new JSONObject().putOpt(String.valueOf(System.currentTimeMillis()), mAcceleration)); 360 + JSONObject jobj = new JSONObject();
361 + JSONObject jobjData = new JSONObject();
362 + jobjData.putOpt("acceleration", mAcceleration);
363 + jobjData.putOpt("speed", mSpeed);
364 + jobj.putOpt(String.valueOf(System.currentTimeMillis()), jobjData);
365 + mAccelerationTimestamps.add(jobj);
338 recordsCount[0]++; 366 recordsCount[0]++;
339 mTvRecordsSaved.setText(String.valueOf(recordsCount[0])); 367 mTvRecordsSaved.setText(String.valueOf(recordsCount[0]));
340 } catch (JSONException e) { 368 } catch (JSONException e) {
...@@ -347,50 +375,55 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -347,50 +375,55 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
347 mHandler.postDelayed(mRunnable, delay); 375 mHandler.postDelayed(mRunnable, delay);
348 } 376 }
349 377
350 - private void unregisterStepSensor() { 378 + private void unregisterSensor() {
351 mSensorManager.unregisterListener(this); 379 mSensorManager.unregisterListener(this);
352 mTvVelocity.setText("0.0 km/h"); 380 mTvVelocity.setText("0.0 km/h");
353 mTvAvgVelocity.setText("0.0 km/h"); 381 mTvAvgVelocity.setText("0.0 km/h");
354 Snackbar.make(mLlTelematicsMain, "Sensor Unregistered", Snackbar.LENGTH_SHORT).show(); 382 Snackbar.make(mLlTelematicsMain, "Sensor Unregistered", Snackbar.LENGTH_SHORT).show();
355 - mHandler.removeCallbacks(mRunnable); 383 + if (mHandler != null)
384 + mHandler.removeCallbacks(mRunnable);
356 saveAccelerationDataToFile(); 385 saveAccelerationDataToFile();
357 } 386 }
358 387
359 private void saveAccelerationDataToFile() { 388 private void saveAccelerationDataToFile() {
360 jsonArray = new JSONArray(); 389 jsonArray = new JSONArray();
361 390
362 - // Convert each JSONObject in the array to JSON and add it to the JSONArray
363 for (JSONObject jsonObject : mAccelerationTimestamps) { 391 for (JSONObject jsonObject : mAccelerationTimestamps) {
364 jsonArray.put(jsonObject); 392 jsonArray.put(jsonObject);
365 } 393 }
366 394
367 - if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) 395 + //TODO: uncomment if needed to write to file
368 - != PackageManager.PERMISSION_GRANTED) { 396 +// if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
369 - ActivityCompat.requestPermissions(this, 397 +// != PackageManager.PERMISSION_GRANTED) {
370 - new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 398 +// ActivityCompat.requestPermissions(this,
371 - PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); 399 +// new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
372 - } else { 400 +// PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
401 +// } else {
373 saveAccelerationDataToExternalStorage(jsonArray); 402 saveAccelerationDataToExternalStorage(jsonArray);
374 - } 403 +// }
375 } 404 }
376 405
377 private void saveAccelerationDataToExternalStorage(JSONArray jsonArray) { 406 private void saveAccelerationDataToExternalStorage(JSONArray jsonArray) {
378 - String state = Environment.getExternalStorageState(); 407 + //TODO: comment if needed to write to file
379 - if (Environment.MEDIA_MOUNTED.equals(state)) { 408 + WarplyDBHelper.getInstance(this).saveTelematics(jsonArray);
380 - File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); 409 +
381 - File file = new File(documentsDir, "telematics_data.json"); 410 + //TODO: uncomment if needed to write to file
382 - try { 411 +// String state = Environment.getExternalStorageState();
383 - FileOutputStream fileOutputStream = new FileOutputStream(file); 412 +// if (Environment.MEDIA_MOUNTED.equals(state)) {
384 - fileOutputStream.write(jsonArray.toString().getBytes()); 413 +// File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
385 - fileOutputStream.close(); 414 +// File file = new File(documentsDir, "telematics_data.json");
386 - Snackbar.make(mLlTelematicsMain, "Success saving data to file", Snackbar.LENGTH_SHORT).show(); 415 +// try {
387 - } catch (IOException e) { 416 +// FileOutputStream fileOutputStream = new FileOutputStream(file);
388 - e.printStackTrace(); 417 +// fileOutputStream.write(jsonArray.toString().getBytes());
389 - Snackbar.make(mLlTelematicsMain, "Error saving acceleration data to file", Snackbar.LENGTH_SHORT).show(); 418 +// fileOutputStream.close();
390 - } 419 +// Snackbar.make(mLlTelematicsMain, "Success saving data to file", Snackbar.LENGTH_SHORT).show();
391 - } else { 420 +// } catch (IOException e) {
392 - Snackbar.make(mLlTelematicsMain, "External storage is not accessible", Snackbar.LENGTH_SHORT).show(); 421 +// e.printStackTrace();
393 - } 422 +// Snackbar.make(mLlTelematicsMain, "Error saving acceleration data to file", Snackbar.LENGTH_SHORT).show();
423 +// }
424 +// } else {
425 +// Snackbar.make(mLlTelematicsMain, "External storage is not accessible", Snackbar.LENGTH_SHORT).show();
426 +// }
394 } 427 }
395 428
396 // // Low-pass filter function using Exponential Moving Average (EMA) 429 // // Low-pass filter function using Exponential Moving Average (EMA)
......
...@@ -18,6 +18,9 @@ import net.sqlcipher.database.SQLiteDatabase; ...@@ -18,6 +18,9 @@ import net.sqlcipher.database.SQLiteDatabase;
18 import net.sqlcipher.database.SQLiteOpenHelper; 18 import net.sqlcipher.database.SQLiteOpenHelper;
19 import net.sqlcipher.database.SQLiteStatement; 19 import net.sqlcipher.database.SQLiteStatement;
20 20
21 +import org.json.JSONArray;
22 +import org.json.JSONObject;
23 +
21 import java.io.File; 24 import java.io.File;
22 import java.io.FileNotFoundException; 25 import java.io.FileNotFoundException;
23 import java.io.IOException; 26 import java.io.IOException;
...@@ -37,7 +40,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -37,7 +40,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
37 } 40 }
38 41
39 private static final String DB_NAME = "warply.db"; 42 private static final String DB_NAME = "warply.db";
40 - private static final int DB_VERSION = 8; 43 + private static final int DB_VERSION = 10;
41 private static final String KEY_CIPHER = "tn#mpOl3v3Dy1pr@W"; 44 private static final String KEY_CIPHER = "tn#mpOl3v3Dy1pr@W";
42 45
43 //------------------------------ Fields -----------------------------// 46 //------------------------------ Fields -----------------------------//
...@@ -52,12 +55,16 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -52,12 +55,16 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
52 private static String TABLE_CLIENT = "client"; 55 private static String TABLE_CLIENT = "client";
53 private static String TABLE_AUTH = "auth"; 56 private static String TABLE_AUTH = "auth";
54 private static String TABLE_TAGS = "tags"; 57 private static String TABLE_TAGS = "tags";
58 + private static String TABLE_TELEMATICS = "telematics";
55 public static final String KEY_TAG = "tag"; 59 public static final String KEY_TAG = "tag";
56 public static final String KEY_TAG_LAST_ADD_DATE = "last_add_date"; 60 public static final String KEY_TAG_LAST_ADD_DATE = "last_add_date";
57 public static final String KEY_CLIENT_ID = "client_id"; 61 public static final String KEY_CLIENT_ID = "client_id";
58 public static final String KEY_CLIENT_SECRET = "client_secret"; 62 public static final String KEY_CLIENT_SECRET = "client_secret";
59 public static final String KEY_ACCESS_TOKEN = "access_token"; 63 public static final String KEY_ACCESS_TOKEN = "access_token";
60 public static final String KEY_REFRESH_TOKEN = "refresh_token"; 64 public static final String KEY_REFRESH_TOKEN = "refresh_token";
65 + public static final String KEY_TIMESTAMP = "timestamp";
66 + public static final String KEY_ACCELERATION = "acceleration";
67 + public static final String KEY_SPEED = "speed";
61 68
62 //------------------------------ Tables -----------------------------// 69 //------------------------------ Tables -----------------------------//
63 public static final String CREATE_TABLE_REQUESTS = "create table if not exists " 70 public static final String CREATE_TABLE_REQUESTS = "create table if not exists "
...@@ -99,6 +106,12 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -99,6 +106,12 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
99 + KEY_ACCESS_TOKEN + " text, " 106 + KEY_ACCESS_TOKEN + " text, "
100 + KEY_REFRESH_TOKEN + " text)"; 107 + KEY_REFRESH_TOKEN + " text)";
101 108
109 + public static final String CREATE_TABLE_TELEMATICS = "create table if not exists "
110 + + TABLE_TELEMATICS + " ("
111 + + KEY_TIMESTAMP + " text, "
112 + + KEY_ACCELERATION + " real, "
113 + + KEY_SPEED + " real)";
114 +
102 // =========================================================== 115 // ===========================================================
103 // Fields 116 // Fields
104 // =========================================================== 117 // ===========================================================
...@@ -149,6 +162,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -149,6 +162,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
149 db.execSQL(CREATE_TABLE_PUSH_ACK_REQUESTS); 162 db.execSQL(CREATE_TABLE_PUSH_ACK_REQUESTS);
150 db.execSQL(CREATE_TABLE_CLIENT); 163 db.execSQL(CREATE_TABLE_CLIENT);
151 db.execSQL(CREATE_TABLE_AUTH); 164 db.execSQL(CREATE_TABLE_AUTH);
165 + db.execSQL(CREATE_TABLE_TELEMATICS);
152 } 166 }
153 167
154 @Override 168 @Override
...@@ -161,6 +175,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -161,6 +175,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
161 db.execSQL("drop table if exists " + TABLE_TAGS); 175 db.execSQL("drop table if exists " + TABLE_TAGS);
162 db.execSQL("drop table if exists " + TABLE_CLIENT); 176 db.execSQL("drop table if exists " + TABLE_CLIENT);
163 db.execSQL("drop table if exists " + TABLE_AUTH); 177 db.execSQL("drop table if exists " + TABLE_AUTH);
178 + db.execSQL("drop table if exists " + TABLE_TELEMATICS);
164 onCreate(db); 179 onCreate(db);
165 } 180 }
166 } 181 }
...@@ -173,6 +188,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -173,6 +188,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
173 db.execSQL("drop table if exists " + TABLE_TAGS); 188 db.execSQL("drop table if exists " + TABLE_TAGS);
174 db.execSQL("drop table if exists " + TABLE_CLIENT); 189 db.execSQL("drop table if exists " + TABLE_CLIENT);
175 db.execSQL("drop table if exists " + TABLE_AUTH); 190 db.execSQL("drop table if exists " + TABLE_AUTH);
191 + db.execSQL("drop table if exists " + TABLE_TELEMATICS);
176 onCreate(db); 192 onCreate(db);
177 } 193 }
178 194
...@@ -457,6 +473,25 @@ public class WarplyDBHelper extends SQLiteOpenHelper { ...@@ -457,6 +473,25 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
457 } 473 }
458 } 474 }
459 475
476 + public synchronized void saveTelematics(JSONArray jsonArray) {
477 + if (jsonArray != null && jsonArray.length() > 0) {
478 + ContentValues values = new ContentValues();
479 + for (int i = 0; i < jsonArray.length(); i++) {
480 + JSONObject jsonobject = jsonArray.optJSONObject(i);
481 + if (jsonobject != null) {
482 + String timestamp = jsonobject.keys().next();
483 + values.put(KEY_TIMESTAMP, timestamp);
484 + JSONObject jobjData = jsonobject.optJSONObject(timestamp);
485 + if (jobjData != null) {
486 + values.put(KEY_ACCELERATION, jobjData.optDouble(KEY_ACCELERATION));
487 + values.put(KEY_SPEED, jobjData.optDouble(KEY_SPEED));
488 + }
489 + insert(TABLE_TELEMATICS, values);
490 + }
491 + }
492 + }
493 + }
494 +
460 public synchronized void removeTags(String[] tags) { 495 public synchronized void removeTags(String[] tags) {
461 StringBuilder strFilter = new StringBuilder(); 496 StringBuilder strFilter = new StringBuilder();
462 for (int i = 0; i < tags.length; i++) { 497 for (int i = 0; i < tags.length; i++) {
......