Panagiotis Triantafyllou

telematics fixes

......@@ -44,6 +44,8 @@ import java.util.Arrays;
import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import ly.warp.sdk.R;
import ly.warp.sdk.io.callbacks.CallbackReceiver;
import ly.warp.sdk.utils.managers.WarplyManager;
/**
* Created by Panagiotis Triantafyllou on 26/June/2023.
......@@ -245,7 +247,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveAccelerationDataToExternalStorage(jsonArray);
// saveAccelerationDataToExternalStorage(jsonArray);
sendAccelerationDataToServer(jsonArray);
} else {
Snackbar.make(mLlTelematicsMain, "Storage Permission Denied", Snackbar.LENGTH_SHORT).show();
}
......@@ -451,6 +454,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
jobjData.putOpt("latitude", mLatitude);
jobjData.putOpt("longitude", mLongitude);
jobjData.putOpt("limit", getCutOffLimit());
jobjData.putOpt("samples", TextUtils.isEmpty(mEtSampleTime.getText()) ? RECORDS_INTERVAL : Integer.valueOf(mEtSampleTime.getText().toString()));
jobj.putOpt(timestamp, jobjData);
mAccelerationTimestamps.add(jobj);
recordsCount[0]++;
......@@ -484,6 +488,17 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
jsonArray = new JSONArray();
for (JSONObject jsonObject : mAccelerationTimestamps) {
if (jsonObject.keys().hasNext()) {
String parent = jsonObject.keys().next();
JSONObject jobj = jsonObject.optJSONObject(parent);
if (jobj != null) {
try {
jobj.put("stop_time", mStopTimestamp);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
jsonArray.put(jsonObject);
}
......@@ -494,7 +509,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
saveAccelerationDataToExternalStorage(jsonArray);
// saveAccelerationDataToExternalStorage(jsonArray);
sendAccelerationDataToServer(jsonArray);
}
}
......@@ -521,6 +537,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
}
}
private void sendAccelerationDataToServer(JSONArray jsonArray) {
WarplyManager.sendAccelerationDataToServer(jsonArray, mTelematicsCallback);
}
private final View.OnTouchListener mTripTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
......@@ -554,6 +574,18 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
}
};
private final CallbackReceiver<Integer> mTelematicsCallback = new CallbackReceiver<Integer>() {
@Override
public void onSuccess(Integer result) {
Snackbar.make(mLlTelematicsMain, "Success sending data to server", Snackbar.LENGTH_SHORT).show();
}
@Override
public void onFailure(int errorCode) {
Snackbar.make(mLlTelematicsMain, "Error sending data to server", Snackbar.LENGTH_SHORT).show();
}
};
// // Low-pass filter function using Exponential Moving Average (EMA)
// private float lowPassFilter(float currentValue) {
// float filteredValue = alpha * currentValue + (1 - alpha) * previousFilteredValue;
......
......@@ -88,6 +88,18 @@ public interface ApiService {
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature);
@Headers("Content-Type: application/json")
@POST("/oauth/{appUuid}/context")
Call<ResponseBody> sendTelematicsData(@Path("appUuid") String appUuid,
@Body RequestBody request,
@Header(WarpConstants.HEADER_DATE) String timeStamp,
@Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
@Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
@Header(WarpConstants.HEADER_CHANNEL) String channel,
@Header(WarpConstants.HEADER_WEB_ID) String webId,
@Header(WarpConstants.HEADER_SIGNATURE) String signature,
@Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
// ===========================================================
// Getter & Setter
// ===========================================================
......
......@@ -2022,6 +2022,44 @@ public class WarplyManager {
});
}
public static void sendAccelerationDataToServer(JSONArray telematicsData, final CallbackReceiver<Integer> receiver) {
WarpUtils.log("************* WARPLY User Telematics Request ********************");
WarpUtils.log("[WARP Trace] WARPLY User Telematics Request is active");
WarpUtils.log("**************************************************");
ApiService service = ApiClient.getRetrofitInstance().create(ApiService.class);
sendTelematicsData(service, telematicsData, new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseTelematics) {
if (responseTelematics.code() == 200 && responseTelematics.body() != null) {
JSONObject jobjTelematicsResponse = null;
try {
jobjTelematicsResponse = new JSONObject(responseTelematics.body().string());
} catch (Exception e) {
e.printStackTrace();
}
if (jobjTelematicsResponse != null && jobjTelematicsResponse.has("status") && jobjTelematicsResponse.optString("status", "2").equals("1")) {
Integer status = new Integer(jobjTelematicsResponse.optString("status", "2"));
receiver.onSuccess(status);
} else {
receiver.onFailure(2);
}
} else {
receiver.onFailure(responseTelematics.code());
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
dynatraceEvent.setEventName("custom_error_couponsets_sm_loyalty");
EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
receiver.onFailure(2);
}
});
}
public static void getUserCouponsWithCouponsets(WarplyUserCouponsRequest request, final CallbackReceiver<CouponList> receiver) {
WarpUtils.log("************* WARPLY User Coupons Request ********************");
WarpUtils.log("[WARP Trace] WARPLY User Coupons Request is active");
......@@ -2577,6 +2615,76 @@ public class WarplyManager {
});
}
private static void sendTelematicsData(ApiService service, JSONArray accelerationTimestamps, Callback<ResponseBody> callback) {
String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
String webId = WarpUtils.getWebId(Warply.getWarplyContext());
if (accelerationTimestamps == null || (accelerationTimestamps != null && accelerationTimestamps.length() == 0)) {
return;
}
String startTime = "";
String stopTime = "";
int samples = 0;
if (accelerationTimestamps.optJSONObject(0).keys().hasNext()) {
String parent = accelerationTimestamps.optJSONObject(0).keys().next();
JSONObject jobj = accelerationTimestamps.optJSONObject(0).optJSONObject(parent);
if (jobj != null) {
startTime = jobj.optString("start_time");
stopTime = jobj.optString("stop_time");
samples = jobj.optInt("samples");
}
}
Map<String, Object> jsonParamsTelematics = new ArrayMap<>();
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("action", "submit_telematics");
JSONObject rawDataObj = new JSONObject();
try {
rawDataObj.putOpt("total_km", 0.0f);
rawDataObj.putOpt("average_speed", 0.0f);
rawDataObj.putOpt("smoothness", 0.0f);
rawDataObj.putOpt("focus", 0.0f);
rawDataObj.putOpt("trip_start", DateFormat.format("yyyy-MM-dd HH:mm:ss", Long.valueOf(startTime)).toString());
rawDataObj.putOpt("trip_stop", DateFormat.format("yyyy-MM-dd HH:mm:ss", Long.valueOf(stopTime)).toString());
rawDataObj.putOpt("samples", samples);
rawDataObj.putOpt("sample_rate", (samples / 1000));
rawDataObj.putOpt("metadata", accelerationTimestamps);
} catch (JSONException e) {
throw new RuntimeException(e);
}
jsonParams.put("raw_data", rawDataObj);
jsonParamsTelematics.put("telematics", jsonParams);
RequestBody couponsetsRequest = RequestBody.create(MediaType.get("application/json; charset=utf-8"), (new JSONObject(jsonParamsTelematics)).toString());
Call<ResponseBody> telematicsCall = service.getCouponsets(
WarplyProperty.getAppUuid(Warply.getWarplyContext()),
couponsetsRequest,
timeStamp,
"android:" + Warply.getWarplyContext().getPackageName(),
new WarplyDeviceInfoCollector(Warply.getWarplyContext()).getUniqueDeviceId(),
"mobile",
webId,
WarpUtils.produceSignature(apiKey + timeStamp),
"Bearer " + WarplyDBHelper.getInstance(Warply.getWarplyContext()).getAuthValue("access_token")
);
telematicsCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
callback.onResponse(call, response);
}
@Override
public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
callback.onFailure(call, t);
}
});
}
private static void getUnifiedCouponsRetro(ApiService service, Callback<ResponseBody> callback) {
String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
......