Panagiotis Triantafyllou

telematics fixes

...@@ -44,6 +44,8 @@ import java.util.Arrays; ...@@ -44,6 +44,8 @@ import java.util.Arrays;
44 44
45 import io.github.inflationx.viewpump.ViewPumpContextWrapper; 45 import io.github.inflationx.viewpump.ViewPumpContextWrapper;
46 import ly.warp.sdk.R; 46 import ly.warp.sdk.R;
47 +import ly.warp.sdk.io.callbacks.CallbackReceiver;
48 +import ly.warp.sdk.utils.managers.WarplyManager;
47 49
48 /** 50 /**
49 * Created by Panagiotis Triantafyllou on 26/June/2023. 51 * Created by Panagiotis Triantafyllou on 26/June/2023.
...@@ -245,7 +247,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -245,7 +247,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
245 247
246 if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) { 248 if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
247 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 249 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
248 - saveAccelerationDataToExternalStorage(jsonArray); 250 +// saveAccelerationDataToExternalStorage(jsonArray);
251 + sendAccelerationDataToServer(jsonArray);
249 } else { 252 } else {
250 Snackbar.make(mLlTelematicsMain, "Storage Permission Denied", Snackbar.LENGTH_SHORT).show(); 253 Snackbar.make(mLlTelematicsMain, "Storage Permission Denied", Snackbar.LENGTH_SHORT).show();
251 } 254 }
...@@ -451,6 +454,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -451,6 +454,7 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
451 jobjData.putOpt("latitude", mLatitude); 454 jobjData.putOpt("latitude", mLatitude);
452 jobjData.putOpt("longitude", mLongitude); 455 jobjData.putOpt("longitude", mLongitude);
453 jobjData.putOpt("limit", getCutOffLimit()); 456 jobjData.putOpt("limit", getCutOffLimit());
457 + jobjData.putOpt("samples", TextUtils.isEmpty(mEtSampleTime.getText()) ? RECORDS_INTERVAL : Integer.valueOf(mEtSampleTime.getText().toString()));
454 jobj.putOpt(timestamp, jobjData); 458 jobj.putOpt(timestamp, jobjData);
455 mAccelerationTimestamps.add(jobj); 459 mAccelerationTimestamps.add(jobj);
456 recordsCount[0]++; 460 recordsCount[0]++;
...@@ -484,6 +488,17 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -484,6 +488,17 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
484 jsonArray = new JSONArray(); 488 jsonArray = new JSONArray();
485 489
486 for (JSONObject jsonObject : mAccelerationTimestamps) { 490 for (JSONObject jsonObject : mAccelerationTimestamps) {
491 + if (jsonObject.keys().hasNext()) {
492 + String parent = jsonObject.keys().next();
493 + JSONObject jobj = jsonObject.optJSONObject(parent);
494 + if (jobj != null) {
495 + try {
496 + jobj.put("stop_time", mStopTimestamp);
497 + } catch (JSONException e) {
498 + throw new RuntimeException(e);
499 + }
500 + }
501 + }
487 jsonArray.put(jsonObject); 502 jsonArray.put(jsonObject);
488 } 503 }
489 504
...@@ -494,7 +509,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -494,7 +509,8 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
494 new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 509 new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
495 PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); 510 PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
496 } else { 511 } else {
497 - saveAccelerationDataToExternalStorage(jsonArray); 512 +// saveAccelerationDataToExternalStorage(jsonArray);
513 + sendAccelerationDataToServer(jsonArray);
498 } 514 }
499 } 515 }
500 516
...@@ -521,6 +537,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -521,6 +537,10 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
521 } 537 }
522 } 538 }
523 539
540 + private void sendAccelerationDataToServer(JSONArray jsonArray) {
541 + WarplyManager.sendAccelerationDataToServer(jsonArray, mTelematicsCallback);
542 + }
543 +
524 private final View.OnTouchListener mTripTouchListener = new View.OnTouchListener() { 544 private final View.OnTouchListener mTripTouchListener = new View.OnTouchListener() {
525 @Override 545 @Override
526 public boolean onTouch(View view, MotionEvent motionEvent) { 546 public boolean onTouch(View view, MotionEvent motionEvent) {
...@@ -554,6 +574,18 @@ public class TelematicsActivity extends Activity implements View.OnClickListener ...@@ -554,6 +574,18 @@ public class TelematicsActivity extends Activity implements View.OnClickListener
554 } 574 }
555 }; 575 };
556 576
577 + private final CallbackReceiver<Integer> mTelematicsCallback = new CallbackReceiver<Integer>() {
578 + @Override
579 + public void onSuccess(Integer result) {
580 + Snackbar.make(mLlTelematicsMain, "Success sending data to server", Snackbar.LENGTH_SHORT).show();
581 + }
582 +
583 + @Override
584 + public void onFailure(int errorCode) {
585 + Snackbar.make(mLlTelematicsMain, "Error sending data to server", Snackbar.LENGTH_SHORT).show();
586 + }
587 + };
588 +
557 // // Low-pass filter function using Exponential Moving Average (EMA) 589 // // Low-pass filter function using Exponential Moving Average (EMA)
558 // private float lowPassFilter(float currentValue) { 590 // private float lowPassFilter(float currentValue) {
559 // float filteredValue = alpha * currentValue + (1 - alpha) * previousFilteredValue; 591 // float filteredValue = alpha * currentValue + (1 - alpha) * previousFilteredValue;
......
...@@ -88,6 +88,18 @@ public interface ApiService { ...@@ -88,6 +88,18 @@ public interface ApiService {
88 @Header(WarpConstants.HEADER_WEB_ID) String webId, 88 @Header(WarpConstants.HEADER_WEB_ID) String webId,
89 @Header(WarpConstants.HEADER_SIGNATURE) String signature); 89 @Header(WarpConstants.HEADER_SIGNATURE) String signature);
90 90
91 + @Headers("Content-Type: application/json")
92 + @POST("/oauth/{appUuid}/context")
93 + Call<ResponseBody> sendTelematicsData(@Path("appUuid") String appUuid,
94 + @Body RequestBody request,
95 + @Header(WarpConstants.HEADER_DATE) String timeStamp,
96 + @Header(WarpConstants.HEADER_LOYALTY_BUNDLE_ID) String bundleId,
97 + @Header(WarpConstants.HEADER_UNIQUE_DEVICE_ID) String deviceId,
98 + @Header(WarpConstants.HEADER_CHANNEL) String channel,
99 + @Header(WarpConstants.HEADER_WEB_ID) String webId,
100 + @Header(WarpConstants.HEADER_SIGNATURE) String signature,
101 + @Header(WarpConstants.HEADER_AUTHORIZATION) String bearer);
102 +
91 // =========================================================== 103 // ===========================================================
92 // Getter & Setter 104 // Getter & Setter
93 // =========================================================== 105 // ===========================================================
......
...@@ -2022,6 +2022,44 @@ public class WarplyManager { ...@@ -2022,6 +2022,44 @@ public class WarplyManager {
2022 }); 2022 });
2023 } 2023 }
2024 2024
2025 + public static void sendAccelerationDataToServer(JSONArray telematicsData, final CallbackReceiver<Integer> receiver) {
2026 + WarpUtils.log("************* WARPLY User Telematics Request ********************");
2027 + WarpUtils.log("[WARP Trace] WARPLY User Telematics Request is active");
2028 + WarpUtils.log("**************************************************");
2029 + ApiService service = ApiClient.getRetrofitInstance().create(ApiService.class);
2030 + sendTelematicsData(service, telematicsData, new Callback<ResponseBody>() {
2031 + @Override
2032 + public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseTelematics) {
2033 + if (responseTelematics.code() == 200 && responseTelematics.body() != null) {
2034 + JSONObject jobjTelematicsResponse = null;
2035 + try {
2036 + jobjTelematicsResponse = new JSONObject(responseTelematics.body().string());
2037 + } catch (Exception e) {
2038 + e.printStackTrace();
2039 + }
2040 +
2041 + if (jobjTelematicsResponse != null && jobjTelematicsResponse.has("status") && jobjTelematicsResponse.optString("status", "2").equals("1")) {
2042 + Integer status = new Integer(jobjTelematicsResponse.optString("status", "2"));
2043 + receiver.onSuccess(status);
2044 + } else {
2045 + receiver.onFailure(2);
2046 + }
2047 +
2048 + } else {
2049 + receiver.onFailure(responseTelematics.code());
2050 + }
2051 + }
2052 +
2053 + @Override
2054 + public void onFailure(Call<ResponseBody> call, Throwable t) {
2055 + LoyaltySDKDynatraceEventModel dynatraceEvent = new LoyaltySDKDynatraceEventModel();
2056 + dynatraceEvent.setEventName("custom_error_couponsets_sm_loyalty");
2057 + EventBus.getDefault().post(new WarplyEventBusManager(dynatraceEvent));
2058 + receiver.onFailure(2);
2059 + }
2060 + });
2061 + }
2062 +
2025 public static void getUserCouponsWithCouponsets(WarplyUserCouponsRequest request, final CallbackReceiver<CouponList> receiver) { 2063 public static void getUserCouponsWithCouponsets(WarplyUserCouponsRequest request, final CallbackReceiver<CouponList> receiver) {
2026 WarpUtils.log("************* WARPLY User Coupons Request ********************"); 2064 WarpUtils.log("************* WARPLY User Coupons Request ********************");
2027 WarpUtils.log("[WARP Trace] WARPLY User Coupons Request is active"); 2065 WarpUtils.log("[WARP Trace] WARPLY User Coupons Request is active");
...@@ -2577,6 +2615,76 @@ public class WarplyManager { ...@@ -2577,6 +2615,76 @@ public class WarplyManager {
2577 }); 2615 });
2578 } 2616 }
2579 2617
2618 + private static void sendTelematicsData(ApiService service, JSONArray accelerationTimestamps, Callback<ResponseBody> callback) {
2619 + String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
2620 + String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
2621 + String webId = WarpUtils.getWebId(Warply.getWarplyContext());
2622 +
2623 + if (accelerationTimestamps == null || (accelerationTimestamps != null && accelerationTimestamps.length() == 0)) {
2624 + return;
2625 + }
2626 +
2627 + String startTime = "";
2628 + String stopTime = "";
2629 + int samples = 0;
2630 +
2631 + if (accelerationTimestamps.optJSONObject(0).keys().hasNext()) {
2632 + String parent = accelerationTimestamps.optJSONObject(0).keys().next();
2633 + JSONObject jobj = accelerationTimestamps.optJSONObject(0).optJSONObject(parent);
2634 + if (jobj != null) {
2635 + startTime = jobj.optString("start_time");
2636 + stopTime = jobj.optString("stop_time");
2637 + samples = jobj.optInt("samples");
2638 + }
2639 + }
2640 +
2641 + Map<String, Object> jsonParamsTelematics = new ArrayMap<>();
2642 + Map<String, Object> jsonParams = new ArrayMap<>();
2643 + jsonParams.put("action", "submit_telematics");
2644 + JSONObject rawDataObj = new JSONObject();
2645 + try {
2646 + rawDataObj.putOpt("total_km", 0.0f);
2647 + rawDataObj.putOpt("average_speed", 0.0f);
2648 + rawDataObj.putOpt("smoothness", 0.0f);
2649 + rawDataObj.putOpt("focus", 0.0f);
2650 + rawDataObj.putOpt("trip_start", DateFormat.format("yyyy-MM-dd HH:mm:ss", Long.valueOf(startTime)).toString());
2651 + rawDataObj.putOpt("trip_stop", DateFormat.format("yyyy-MM-dd HH:mm:ss", Long.valueOf(stopTime)).toString());
2652 + rawDataObj.putOpt("samples", samples);
2653 + rawDataObj.putOpt("sample_rate", (samples / 1000));
2654 + rawDataObj.putOpt("metadata", accelerationTimestamps);
2655 + } catch (JSONException e) {
2656 + throw new RuntimeException(e);
2657 + }
2658 + jsonParams.put("raw_data", rawDataObj);
2659 +
2660 + jsonParamsTelematics.put("telematics", jsonParams);
2661 + RequestBody couponsetsRequest = RequestBody.create(MediaType.get("application/json; charset=utf-8"), (new JSONObject(jsonParamsTelematics)).toString());
2662 +
2663 + Call<ResponseBody> telematicsCall = service.getCouponsets(
2664 + WarplyProperty.getAppUuid(Warply.getWarplyContext()),
2665 + couponsetsRequest,
2666 + timeStamp,
2667 + "android:" + Warply.getWarplyContext().getPackageName(),
2668 + new WarplyDeviceInfoCollector(Warply.getWarplyContext()).getUniqueDeviceId(),
2669 + "mobile",
2670 + webId,
2671 + WarpUtils.produceSignature(apiKey + timeStamp),
2672 + "Bearer " + WarplyDBHelper.getInstance(Warply.getWarplyContext()).getAuthValue("access_token")
2673 + );
2674 +
2675 + telematicsCall.enqueue(new Callback<ResponseBody>() {
2676 + @Override
2677 + public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
2678 + callback.onResponse(call, response);
2679 + }
2680 +
2681 + @Override
2682 + public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
2683 + callback.onFailure(call, t);
2684 + }
2685 + });
2686 + }
2687 +
2580 private static void getUnifiedCouponsRetro(ApiService service, Callback<ResponseBody> callback) { 2688 private static void getUnifiedCouponsRetro(ApiService service, Callback<ResponseBody> callback) {
2581 String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString(); 2689 String timeStamp = DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString();
2582 String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext()); 2690 String apiKey = WarpUtils.getApiKey(Warply.getWarplyContext());
......