Panagiotis Triantafyllou

telemtics now save the data in sdk's db

......@@ -39,6 +39,7 @@ import java.util.Arrays;
import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import ly.warp.sdk.R;
import ly.warp.sdk.db.WarplyDBHelper;
/**
* Created by Panagiotis Triantafyllou on 26/June/2023.
......@@ -79,6 +80,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
double mLongitude = 0;
// Radius of the Earth in meters
private static final double EARTH_RADIUS = 6371000.0;
private Location previousLocation;
double mSpeed = 0;
// ===========================================================
// Methods for/from SuperClass/Interfaces
......@@ -102,6 +105,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
mIvBack.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
previousLocation = null;
initViews();
}
......@@ -115,10 +119,16 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
@Override
protected void onPause() {
super.onPause();
if (mIsTripStarted)
unregisterStepSensor();
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (mIsTripStarted) {
unregisterSensor();
stopLocationUpdates();
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
......@@ -176,14 +186,14 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
}
if (view.getId() == R.id.ll_activate_button) {
if (mIsTripStarted) {
unregisterStepSensor();
unregisterSensor();
stopLocationUpdates();
initViews();
mIsTripStarted = false;
mTvTripButton.setText(R.string.cos_dlg_start_trip);
} else {
requestLocationUpdates();
registerStepSensor();
registerSensor();
mIsTripStarted = true;
mTvTripButton.setText(R.string.cos_dlg_stop_trip);
}
......@@ -218,13 +228,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
@Override
public void onLocationChanged(Location location) {
//TODO: uncomment and remove setText if needs revert to handler implementation
//TODO: LOCATION_UPDATE_INTERVAL = 300 when using location.getSpeed()
// float speedKmph = location.getSpeed() * 3.6f;
// mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speedKmph)) + " km/h");
//TODO: comment the first block and uncomment the second block if needs revert to handler implementation
if (mLatitude != 0 && mLongitude != 0) {
double speed = calculateSpeed(mLatitude, mLongitude, location.getLatitude(), location.getLongitude(), (LOCATION_UPDATE_INTERVAL / 1000));
mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speed)) + " km/h");
mSpeed = calculateSpeed(mLatitude, mLongitude, location.getLatitude(), location.getLongitude(), (LOCATION_UPDATE_INTERVAL / 1000));
mTvAvgVelocity.setText(String.format("%.1f", Math.floor(mSpeed)) + " km/h");
}
......@@ -232,6 +239,22 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
// requestLocationUpdatePeriodically(location);
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//TODO: similar implementation, comment all of the above blocks
// if (previousLocation != null) {
// // Calculate the distance traveled between the previous and current location
// float distance = previousLocation.distanceTo(location); // Distance in meters
//
// // Calculate the speed based on the distance traveled over a timeframe of x seconds
// float speed = distance / (LOCATION_UPDATE_INTERVAL / 1000); // Speed in meters/second
//
// // Convert speed to km/h
// float speedKmH = speed * 3.6f;
//
// mTvAvgVelocity.setText(String.format("%.1f", Math.floor(speedKmH)) + " km/h");
// }
//
// previousLocation = location;
}
@Override
......@@ -320,7 +343,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
mLoctionHandler.removeCallbacks(mLocationRunnable);
}
private void registerStepSensor() {
private void registerSensor() {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
......@@ -334,7 +357,12 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
@Override
public void run() {
try {
mAccelerationTimestamps.add(new JSONObject().putOpt(String.valueOf(System.currentTimeMillis()), mAcceleration));
JSONObject jobj = new JSONObject();
JSONObject jobjData = new JSONObject();
jobjData.putOpt("acceleration", mAcceleration);
jobjData.putOpt("speed", mSpeed);
jobj.putOpt(String.valueOf(System.currentTimeMillis()), jobjData);
mAccelerationTimestamps.add(jobj);
recordsCount[0]++;
mTvRecordsSaved.setText(String.valueOf(recordsCount[0]));
} catch (JSONException e) {
......@@ -347,11 +375,12 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
mHandler.postDelayed(mRunnable, delay);
}
private void unregisterStepSensor() {
private void unregisterSensor() {
mSensorManager.unregisterListener(this);
mTvVelocity.setText("0.0 km/h");
mTvAvgVelocity.setText("0.0 km/h");
Snackbar.make(mLlTelematicsMain, "Sensor Unregistered", Snackbar.LENGTH_SHORT).show();
if (mHandler != null)
mHandler.removeCallbacks(mRunnable);
saveAccelerationDataToFile();
}
......@@ -359,38 +388,42 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
private void saveAccelerationDataToFile() {
jsonArray = new JSONArray();
// Convert each JSONObject in the array to JSON and add it to the JSONArray
for (JSONObject jsonObject : mAccelerationTimestamps) {
jsonArray.put(jsonObject);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
//TODO: uncomment if needed to write to file
// if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
// ActivityCompat.requestPermissions(this,
// new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
// PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
// } else {
saveAccelerationDataToExternalStorage(jsonArray);
}
// }
}
private void saveAccelerationDataToExternalStorage(JSONArray jsonArray) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(documentsDir, "telematics_data.json");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(jsonArray.toString().getBytes());
fileOutputStream.close();
Snackbar.make(mLlTelematicsMain, "Success saving data to file", Snackbar.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Snackbar.make(mLlTelematicsMain, "Error saving acceleration data to file", Snackbar.LENGTH_SHORT).show();
}
} else {
Snackbar.make(mLlTelematicsMain, "External storage is not accessible", Snackbar.LENGTH_SHORT).show();
}
//TODO: comment if needed to write to file
WarplyDBHelper.getInstance(this).saveTelematics(jsonArray);
//TODO: uncomment if needed to write to file
// String state = Environment.getExternalStorageState();
// if (Environment.MEDIA_MOUNTED.equals(state)) {
// File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
// File file = new File(documentsDir, "telematics_data.json");
// try {
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(jsonArray.toString().getBytes());
// fileOutputStream.close();
// Snackbar.make(mLlTelematicsMain, "Success saving data to file", Snackbar.LENGTH_SHORT).show();
// } catch (IOException e) {
// e.printStackTrace();
// Snackbar.make(mLlTelematicsMain, "Error saving acceleration data to file", Snackbar.LENGTH_SHORT).show();
// }
// } else {
// Snackbar.make(mLlTelematicsMain, "External storage is not accessible", Snackbar.LENGTH_SHORT).show();
// }
}
// // Low-pass filter function using Exponential Moving Average (EMA)
......
......@@ -18,6 +18,9 @@ import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;
import net.sqlcipher.database.SQLiteStatement;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
......@@ -37,7 +40,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
}
private static final String DB_NAME = "warply.db";
private static final int DB_VERSION = 8;
private static final int DB_VERSION = 10;
private static final String KEY_CIPHER = "tn#mpOl3v3Dy1pr@W";
//------------------------------ Fields -----------------------------//
......@@ -52,12 +55,16 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
private static String TABLE_CLIENT = "client";
private static String TABLE_AUTH = "auth";
private static String TABLE_TAGS = "tags";
private static String TABLE_TELEMATICS = "telematics";
public static final String KEY_TAG = "tag";
public static final String KEY_TAG_LAST_ADD_DATE = "last_add_date";
public static final String KEY_CLIENT_ID = "client_id";
public static final String KEY_CLIENT_SECRET = "client_secret";
public static final String KEY_ACCESS_TOKEN = "access_token";
public static final String KEY_REFRESH_TOKEN = "refresh_token";
public static final String KEY_TIMESTAMP = "timestamp";
public static final String KEY_ACCELERATION = "acceleration";
public static final String KEY_SPEED = "speed";
//------------------------------ Tables -----------------------------//
public static final String CREATE_TABLE_REQUESTS = "create table if not exists "
......@@ -99,6 +106,12 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
+ KEY_ACCESS_TOKEN + " text, "
+ KEY_REFRESH_TOKEN + " text)";
public static final String CREATE_TABLE_TELEMATICS = "create table if not exists "
+ TABLE_TELEMATICS + " ("
+ KEY_TIMESTAMP + " text, "
+ KEY_ACCELERATION + " real, "
+ KEY_SPEED + " real)";
// ===========================================================
// Fields
// ===========================================================
......@@ -149,6 +162,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
db.execSQL(CREATE_TABLE_PUSH_ACK_REQUESTS);
db.execSQL(CREATE_TABLE_CLIENT);
db.execSQL(CREATE_TABLE_AUTH);
db.execSQL(CREATE_TABLE_TELEMATICS);
}
@Override
......@@ -161,6 +175,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
db.execSQL("drop table if exists " + TABLE_TAGS);
db.execSQL("drop table if exists " + TABLE_CLIENT);
db.execSQL("drop table if exists " + TABLE_AUTH);
db.execSQL("drop table if exists " + TABLE_TELEMATICS);
onCreate(db);
}
}
......@@ -173,6 +188,7 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
db.execSQL("drop table if exists " + TABLE_TAGS);
db.execSQL("drop table if exists " + TABLE_CLIENT);
db.execSQL("drop table if exists " + TABLE_AUTH);
db.execSQL("drop table if exists " + TABLE_TELEMATICS);
onCreate(db);
}
......@@ -457,6 +473,25 @@ public class WarplyDBHelper extends SQLiteOpenHelper {
}
}
public synchronized void saveTelematics(JSONArray jsonArray) {
if (jsonArray != null && jsonArray.length() > 0) {
ContentValues values = new ContentValues();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.optJSONObject(i);
if (jsonobject != null) {
String timestamp = jsonobject.keys().next();
values.put(KEY_TIMESTAMP, timestamp);
JSONObject jobjData = jsonobject.optJSONObject(timestamp);
if (jobjData != null) {
values.put(KEY_ACCELERATION, jobjData.optDouble(KEY_ACCELERATION));
values.put(KEY_SPEED, jobjData.optDouble(KEY_SPEED));
}
insert(TABLE_TELEMATICS, values);
}
}
}
}
public synchronized void removeTags(String[] tags) {
StringBuilder strFilter = new StringBuilder();
for (int i = 0; i < tags.length; i++) {
......