From 21b403a07f3f9dfeff40f3a4bf2d350f1ed01228 Mon Sep 17 00:00:00 2001 From: Bonzi Date: Mon, 10 Aug 2026 17:04:45 +0000 Subject: [PATCH] Add background trip tracking and reports --- AndroidManifest.xml | 16 +- README.md | 65 ++- build.sh | 34 ++ emulator.sh | 42 ++ src/cloud/molberg/mgutility/BootReceiver.java | 15 + .../molberg/mgutility/EnergyActivity.java | 154 +++++- src/cloud/molberg/mgutility/MainActivity.java | 503 ++++++++++++++++-- src/cloud/molberg/mgutility/RouteMapView.java | 323 +++++++++++ src/cloud/molberg/mgutility/TripDatabase.java | 297 +++++++++++ .../mgutility/TripTrackingService.java | 359 +++++++++++++ .../molberg/mgutility/TripsActivity.java | 276 ++++++++++ 11 files changed, 2021 insertions(+), 63 deletions(-) create mode 100755 build.sh create mode 100755 emulator.sh create mode 100644 src/cloud/molberg/mgutility/BootReceiver.java create mode 100644 src/cloud/molberg/mgutility/RouteMapView.java create mode 100644 src/cloud/molberg/mgutility/TripDatabase.java create mode 100644 src/cloud/molberg/mgutility/TripTrackingService.java create mode 100644 src/cloud/molberg/mgutility/TripsActivity.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 9ac3875..fc14294 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,5 +1,11 @@ - + + + + + + + @@ -8,6 +14,14 @@ + + + + + + + + &2 + exit 1 +fi + +rm -rf "$OUT" +mkdir -p "$OUT/classes" "$OUT/dex" "$OUT/generated" +"$TOOLS/aapt2" compile --dir "$ROOT/res" -o "$OUT/res.zip" +"$TOOLS/aapt2" link -I "$ANDROID_JAR" --manifest "$ROOT/AndroidManifest.xml" \ + --java "$OUT/generated" -o "$OUT/resources.apk" "$OUT/res.zip" +javac -source 8 -target 8 -bootclasspath "$ANDROID_JAR" -d "$OUT/classes" \ + $(find "$ROOT/src" "$OUT/generated" -name '*.java') +"$TOOLS/d8" --lib "$ANDROID_JAR" --output "$OUT/dex" $(find "$OUT/classes" -name '*.class') +cp "$OUT/resources.apk" "$OUT/MG-Utility-unsigned.apk" +(cd "$OUT/dex" && jar uf "$OUT/MG-Utility-unsigned.apk" classes.dex) +"$TOOLS/zipalign" -f 4 "$OUT/MG-Utility-unsigned.apk" "$APK" +rm -f "$APK.idsig" +"$TOOLS/apksigner" sign \ + --ks "$KEYSTORE" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android \ + --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \ + --v4-signing-enabled false --min-sdk-version 23 "$APK" +"$TOOLS/apksigner" verify -v --min-sdk-version 23 "$APK" +echo "Built $APK" diff --git a/emulator.sh b/emulator.sh new file mode 100755 index 0000000..e295eec --- /dev/null +++ b/emulator.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Compatibility wrapper. The shared emulator lives in the sibling +# mg-infotainment-emulator repository. +# Existing MG Utility commands continue to work with this script. + +set -eu + +APP_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +EMULATOR_REPO=${MG_EMULATOR_REPO:-$APP_ROOT/../mg-infotainment-emulator} +if [ ! -x "$EMULATOR_REPO/emulator.sh" ]; then + echo "emulator: shared helper not found at $EMULATOR_REPO/emulator.sh; set MG_EMULATOR_REPO" >&2 + exit 1 +fi +GENERIC=$EMULATOR_REPO/emulator.sh + +case "${1:-}" in + install) + # Preserve the old convenience behavior: build MG Utility on demand + # when no APK has been supplied and the default artifact is absent. + if [ "$#" -eq 1 ] && [ -z "${MG_APP_APK:-}" ] && [ ! -f "$APP_ROOT/build/MG-Utility.apk" ]; then + (cd "$APP_ROOT" && ./build.sh) + fi + MG_APP_APK=${MG_APP_APK:-$APP_ROOT/build/MG-Utility.apk} + export MG_APP_APK + exec "$GENERIC" "$@" + ;; + launch) + MG_APP_PACKAGE=${MG_APP_PACKAGE:-cloud.molberg.mgutility} + MG_APP_ACTIVITY=${MG_APP_ACTIVITY:-.MainActivity} + export MG_APP_PACKAGE MG_APP_ACTIVITY + exec "$GENERIC" "$@" + ;; + screenshot) + if [ "$#" -eq 1 ]; then + exec "$GENERIC" screenshot "$APP_ROOT/build/emulator/screenshot.png" + fi + exec "$GENERIC" "$@" + ;; + *) + exec "$GENERIC" "$@" + ;; +esac diff --git a/src/cloud/molberg/mgutility/BootReceiver.java b/src/cloud/molberg/mgutility/BootReceiver.java new file mode 100644 index 0000000..d6ad41c --- /dev/null +++ b/src/cloud/molberg/mgutility/BootReceiver.java @@ -0,0 +1,15 @@ +package cloud.molberg.mgutility; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** Restarts automatic logging after a head-unit boot or an APK update. */ +public final class BootReceiver extends BroadcastReceiver { + @Override public void onReceive(Context context, Intent intent) { + if (intent == null || Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) || + Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) { + TripTrackingService.start(context); + } + } +} diff --git a/src/cloud/molberg/mgutility/EnergyActivity.java b/src/cloud/molberg/mgutility/EnergyActivity.java index cbe6e3c..0b1c013 100644 --- a/src/cloud/molberg/mgutility/EnergyActivity.java +++ b/src/cloud/molberg/mgutility/EnergyActivity.java @@ -8,7 +8,7 @@ import android.view.*; import android.widget.*; import java.util.*; -/** Read-only energy monitor using SAIC's exported vehicle-service binder. */ +/** Energy monitor using SAIC's exported vehicle-service binder. */ public class EnergyActivity extends Activity { static final int BG=Color.rgb(10,16,20), PANEL=Color.rgb(19,31,38), TEXT=Color.rgb(225,241,238), MUTED=Color.rgb(138,164,160), GREEN=Color.rgb(0,216,165), BLUE=Color.rgb(57,180,255); TextView status, metrics, since; EnergyGraph graph; VehicleGateway car; Handler h=new Handler(); boolean running; @@ -18,7 +18,7 @@ public class EnergyActivity extends Activity { public void onDestroy(){running=false;h.removeCallbacks(tick);try{unbindService(conn);}catch(Exception e){}super.onDestroy();} void immersive(){getWindow().setFlags(128,128);getWindow().getDecorView().setSystemUiVisibility(5894);} View ui(){LinearLayout root=new LinearLayout(this);root.setOrientation(LinearLayout.VERTICAL);root.setPadding(28,16,28,16);root.setBackgroundColor(BG); - LinearLayout bar=new LinearLayout(this);bar.setGravity(Gravity.CENTER_VERTICAL);TextView title=t("ENERGY ANALYSIS",28,TEXT);bar.addView(title,new LinearLayout.LayoutParams(0,54,1));Button back=new Button(this);back.setText("BACK");back.setTextColor(GREEN);back.setOnClickListener(new View.OnClickListener(){public void onClick(View v){finish();}});bar.addView(back,new LinearLayout.LayoutParams(130,54));root.addView(bar); + LinearLayout bar=new LinearLayout(this);bar.setGravity(Gravity.CENTER_VERTICAL);TextView title=t("ENERGY ANALYSIS",28,TEXT);bar.addView(title,new LinearLayout.LayoutParams(0,54,1));Button reports=new Button(this);reports.setText("TRIP REPORTS");reports.setTextColor(GREEN);reports.setTextSize(12);reports.setOnClickListener(new View.OnClickListener(){public void onClick(View v){startActivity(new Intent(EnergyActivity.this,TripsActivity.class));}});bar.addView(reports,new LinearLayout.LayoutParams(180,54));Button back=new Button(this);back.setText("BACK");back.setTextColor(GREEN);back.setOnClickListener(new View.OnClickListener(){public void onClick(View v){finish();}});bar.addView(back,new LinearLayout.LayoutParams(130,54));root.addView(bar); status=t("CONNECTING TO SAIC VEHICLE SERVICE…",14,MUTED);status.setPadding(18,8,18,8);status.setBackgroundColor(PANEL);root.addView(status,new LinearLayout.LayoutParams(-1,42)); LinearLayout top=new LinearLayout(this);top.setPadding(0,12,0,12);metrics=t("WAITING FOR LIVE VALUES",18,TEXT);metrics.setPadding(18,14,18,14);metrics.setBackgroundColor(PANEL);top.addView(metrics,new LinearLayout.LayoutParams(0,-1,1.35f));since=t("SINCE LAST CHARGE\nWaiting for baseline",16,TEXT);since.setPadding(18,14,18,14);since.setBackgroundColor(PANEL);LinearLayout.LayoutParams sp=new LinearLayout.LayoutParams(0,-1,1);sp.setMargins(14,0,0,0);top.addView(since,sp);root.addView(top,new LinearLayout.LayoutParams(-1,142)); graph=new EnergyGraph(this);root.addView(graph,new LinearLayout.LayoutParams(-1,0,1));return root;} @@ -28,8 +28,152 @@ public class EnergyActivity extends Activity { metrics.setText(String.format(java.util.Locale.US,"SOC %.1f %% RANGE %d km SPEED %.0f km/h\nBATTERY %.1f V DRIVE USE %.2f kWh CHARGE STATUS %d",s.soc,s.range,s.speed,s.volts,s.total,s.charging)); since.setText(String.format(java.util.Locale.US,"SINCE LAST CHARGE\n%.1f %% used • %d min\n%.2f kWh reported\n%.1f km/kWh estimate",used,age,s.total,s.total>0?s.range/s.total:0));} static class Sample{float soc,speed,volts,total;int range,charging;Sample(float a,int b,float c,float d,float e,int f){soc=a;range=b;speed=c;volts=d;total=e;charging=f;}} - static class VehicleGateway { final IBinder charging,condition; VehicleGateway(IBinder hub){charging=service(hub,"vehiclecharging");condition=service(hub,"vehiclecondition");} IBinder service(IBinder hub,String name){Parcel d=Parcel.obtain(),r=Parcel.obtain();try{d.writeInterfaceToken("com.saicmotor.sdk.vehiclesettings.IHubService");d.writeString(name);hub.transact(1,d,r,0);r.readException();return r.readStrongBinder();}catch(Exception e){return null;}finally{d.recycle();r.recycle();}} - float f(IBinder b,String token,int code){if(b==null)return Float.NaN;Parcel d=Parcel.obtain(),r=Parcel.obtain();try{d.writeInterfaceToken(token);b.transact(code,d,r,0);r.readException();return r.readFloat();}catch(Exception e){return Float.NaN;}finally{d.recycle();r.recycle();}} int i(IBinder b,String token,int code){if(b==null)return -1;Parcel d=Parcel.obtain(),r=Parcel.obtain();try{d.writeInterfaceToken(token);b.transact(code,d,r,0);r.readException();return r.readInt();}catch(Exception e){return -1;}finally{d.recycle();r.recycle();}} - Sample read(){float soc=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",3),speed=f(condition,"com.saicmotor.sdk.vehiclesettings.IVehicleConditionService",3),volts=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",64),total=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",75);int range=i(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",4),chg=i(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",9);return Float.isNaN(soc)?null:new Sample(soc,range,speed,volts,total,chg);}} + /** + * Small raw-Binder gateway for the exported SAIC hub. The read methods are used by + * the energy dashboard/provider. The two write methods are deliberately limited to + * the startup controls requested by MG Utility; no doors, windows, climate, charging, + * or regenerative-brake switch commands are exposed here. + * + * The transaction numbers and signal values below are from the MG4 Luxury 2022 + * VehicleSettingsService SDK (IVehicleSettingService). Keeping them here avoids a + * compile-time dependency on the OEM APK while still using its exported service. + */ + static class VehicleGateway { + static final String HUB_TOKEN="com.saicmotor.sdk.vehiclesettings.IHubService"; + static final String SETTING_TOKEN="com.saicmotor.sdk.vehiclesettings.IVehicleSettingService"; + static final String SETTING_SERVICE="vehiclesetting"; + static final int GET_DRIVE_MODE_TRANSACTION=0x81; + static final int SET_DRIVE_MODE_TRANSACTION=0x82; + static final int GET_REGENERATIVE_LEVEL_TRANSACTION=0xa0; + static final int SET_REGENERATIVE_LEVEL_TRANSACTION=0xa1; + + // OEM VehicleConstant.DriveModelValid values. + static final int DRIVE_MODE_SNOW=6, DRIVE_MODE_ECO=2, DRIVE_MODE_NORMAL=3, + DRIVE_MODE_SPORT=4, DRIVE_MODE_CUSTOM=7; + static final int REGEN_LEVEL_LOW=0, REGEN_LEVEL_MEDIUM=1, + REGEN_LEVEL_HIGH=2, REGEN_LEVEL_ADAPTIVE=3; + + final IBinder charging,condition,setting; + + VehicleGateway(IBinder hub){ + charging=service(hub,"vehiclecharging"); + condition=service(hub,"vehiclecondition"); + setting=service(hub,SETTING_SERVICE); + } + + IBinder service(IBinder hub,String name){ + if(hub==null)return null; + Parcel d=Parcel.obtain(),r=Parcel.obtain(); + try{ + d.writeInterfaceToken(HUB_TOKEN); + d.writeString(name); + if(!hub.transact(1,d,r,0))return null; + r.readException(); + return r.readStrongBinder(); + }catch(Exception e){return null;}finally{d.recycle();r.recycle();} + } + + float f(IBinder b,String token,int code){ + if(b==null)return Float.NaN; + Parcel d=Parcel.obtain(),r=Parcel.obtain(); + try{ + d.writeInterfaceToken(token); + if(!b.transact(code,d,r,0))return Float.NaN; + r.readException(); + return r.readFloat(); + }catch(Exception e){return Float.NaN;}finally{d.recycle();r.recycle();} + } + + int i(IBinder b,String token,int code){ + if(b==null)return -1; + Parcel d=Parcel.obtain(),r=Parcel.obtain(); + try{ + d.writeInterfaceToken(token); + if(!b.transact(code,d,r,0))return -1; + r.readException(); + return r.readInt(); + }catch(Exception e){return -1;}finally{d.recycle();r.recycle();} + } + + private boolean setInt(IBinder b,String token,int code,int value){ + if(b==null)return false; + Parcel d=Parcel.obtain(); + try{ + d.writeInterfaceToken(token); + d.writeInt(value); + return b.transact(code,d,null,IBinder.FLAG_ONEWAY); + }catch(Exception e){return false;}finally{d.recycle();} + } + + int getDriveMode(){return i(setting,SETTING_TOKEN,GET_DRIVE_MODE_TRANSACTION);} + int getRegenerativeLevel(){return i(setting,SETTING_TOKEN,GET_REGENERATIVE_LEVEL_TRANSACTION);} + + boolean setDriveMode(int value){ + return isDriveMode(value) && setInt(setting,SETTING_TOKEN,SET_DRIVE_MODE_TRANSACTION,value); + } + + boolean setRegenerativeLevel(int value){ + return isRegenerativeLevel(value) && setInt(setting,SETTING_TOKEN,SET_REGENERATIVE_LEVEL_TRANSACTION,value); + } + + /** Apply only values that differ from the car's current setting. */ + ApplyResult applyStartupSettings(int driveMode,int regenerativeLevel){ + int currentDriveMode=getDriveMode(),currentRegenerativeLevel=getRegenerativeLevel(); + // VehicleService exposes its hub before its internal Car managers are ready. In + // that window the OEM setters accept a Binder transaction but silently do nothing; + // treat the -1 read sentinel as not ready so the caller can retry safely. + boolean driveOk=currentDriveMode!=-1 && + (currentDriveMode==driveMode || setDriveMode(driveMode)); + boolean regenOk=currentRegenerativeLevel!=-1 && + (currentRegenerativeLevel==regenerativeLevel || setRegenerativeLevel(regenerativeLevel)); + return new ApplyResult(driveOk,regenOk,driveMode,regenerativeLevel); + } + + static boolean isDriveMode(int value){ + return value==DRIVE_MODE_SNOW || value==DRIVE_MODE_ECO || value==DRIVE_MODE_NORMAL + || value==DRIVE_MODE_SPORT || value==DRIVE_MODE_CUSTOM; + } + + static boolean isRegenerativeLevel(int value){ + return value>=REGEN_LEVEL_LOW && value<=REGEN_LEVEL_ADAPTIVE; + } + + static String driveModeName(int value){ + switch(value){ + case DRIVE_MODE_SNOW:return "Snow"; + case DRIVE_MODE_ECO:return "Eco"; + case DRIVE_MODE_NORMAL:return "Normal"; + case DRIVE_MODE_SPORT:return "Sport"; + case DRIVE_MODE_CUSTOM:return "Custom"; + default:return "Unknown ("+value+")"; + } + } + + static String regenerativeLevelName(int value){ + switch(value){ + case REGEN_LEVEL_LOW:return "Low"; + case REGEN_LEVEL_MEDIUM:return "Medium"; + case REGEN_LEVEL_HIGH:return "High"; + case REGEN_LEVEL_ADAPTIVE:return "Adaptive"; + default:return "Unknown ("+value+")"; + } + } + + Sample read(){ + float soc=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",3), + speed=f(condition,"com.saicmotor.sdk.vehiclesettings.IVehicleConditionService",3), + volts=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",64), + total=f(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",75); + int range=i(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",4), + chg=i(charging,"com.saicmotor.sdk.vehiclesettings.IVehicleChargingService",9); + return Float.isNaN(soc)?null:new Sample(soc,range,speed,volts,total,chg); + } + + static class ApplyResult{ + final boolean driveApplied,regenApplied; final int driveMode,regenerativeLevel; + ApplyResult(boolean d,boolean r,int dm,int rl){driveApplied=d;regenApplied=r;driveMode=dm;regenerativeLevel=rl;} + boolean success(){return driveApplied&®enApplied;} + } + } static class EnergyGraph extends View{ArrayList a=new ArrayList<>();Paint p=new Paint(1);EnergyGraph(Context c){super(c);p.setTypeface(Typeface.MONOSPACE);setBackgroundColor(PANEL);}void add(Sample s){a.add(s);if(a.size()>120)a.remove(0);invalidate();}protected void onDraw(Canvas c){super.onDraw(c);int w=getWidth(),h=getHeight();p.setTextSize(15);p.setColor(MUTED);c.drawText("LIVE TREND • GREEN: state of charge BLUE: speed",18,28,p);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(2);p.setColor(Color.rgb(45,65,72));for(int i=1;i<4;i++)c.drawLine(18,h*i/4,w-18,h*i/4,p);if(a.size()<2){p.setStyle(Paint.Style.FILL);p.setColor(MUTED);c.drawText("Collecting samples…",18,h/2,p);return;}float min=100,max=0;for(Sample s:a){min=Math.min(min,s.soc);max=Math.max(max,s.soc);}if(max-min<1){max=min+1;}line(c,GREEN,min,max,false);line(c,BLUE,0,160,true);p.setStyle(Paint.Style.FILL);p.setColor(GREEN);c.drawText(String.format(java.util.Locale.US,"SOC %.1f%%",a.get(a.size()-1).soc),18,h-16,p);p.setColor(BLUE);c.drawText(String.format(java.util.Locale.US,"%.0f km/h",a.get(a.size()-1).speed),w-105,h-16,p);}void line(Canvas c,int color,float lo,float hi,boolean speed){p.setColor(color);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(3);Path q=new Path();for(int j=0;j adapter = new ArrayAdapter(this, + android.R.layout.simple_spinner_item, labels); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinner.setAdapter(adapter); + spinner.setSelection(selected); + return spinner; + } + + private View settingRow(String label, Spinner spinner) { + LinearLayout row = new LinearLayout(this); + row.setGravity(Gravity.CENTER_VERTICAL); + TextView name = text(label, 13, TEXT, Typeface.BOLD); + row.addView(name, new LinearLayout.LayoutParams(0, 62, 1)); + row.addView(spinner, new LinearLayout.LayoutParams(300, 62)); + return row; + } + + private SharedPreferences vehiclePreferences() { + return getSharedPreferences(VEHICLE_PREFS, MODE_PRIVATE); + } + + private int configuredDriveMode() { + int value = vehiclePreferences().getInt(PREF_DRIVE_MODE, + EnergyActivity.VehicleGateway.DRIVE_MODE_NORMAL); + return EnergyActivity.VehicleGateway.isDriveMode(value) + ? value : EnergyActivity.VehicleGateway.DRIVE_MODE_NORMAL; + } + + private int configuredRegenerativeLevel() { + int value = vehiclePreferences().getInt(PREF_REGEN_LEVEL, + EnergyActivity.VehicleGateway.REGEN_LEVEL_MEDIUM); + return EnergyActivity.VehicleGateway.isRegenerativeLevel(value) + ? value : EnergyActivity.VehicleGateway.REGEN_LEVEL_MEDIUM; + } + + private String startupSummary() { + return "STARTUP\n" + EnergyActivity.VehicleGateway.driveModeName(configuredDriveMode()).toUpperCase(Locale.US) + + " • REGEN " + EnergyActivity.VehicleGateway.regenerativeLevelName(configuredRegenerativeLevel()).toUpperCase(Locale.US); + } + + private void updateStartupSummary() { + if (startupSettingsButton != null) startupSettingsButton.setText(startupSummary()); + } + + private int indexOf(int[] values, int value) { + for (int i = 0; i < values.length; i++) if (values[i] == value) return i; + return 0; + } + + private void applyStartupSettings() { + final EnergyActivity.VehicleGateway gateway = vehicle; + if (gateway == null || !vehicleServiceBound) return; + final int driveMode = configuredDriveMode(); + final int regenLevel = configuredRegenerativeLevel(); + final int request = ++settingsApplyGeneration; + applyStartupSettings(gateway, driveMode, regenLevel, request, 0); + } + + private void applyStartupSettings(final EnergyActivity.VehicleGateway gateway, + final int driveMode, final int regenLevel, final int request, final int attempt) { + connection.setText("SAIC VEHICLE SERVICE • CONNECTED • applying " + + EnergyActivity.VehicleGateway.driveModeName(driveMode) + " / " + + EnergyActivity.VehicleGateway.regenerativeLevelName(regenLevel) + "…"); + connection.setTextColor(ACCENT); + new Thread(new Runnable() { + @Override public void run() { + final EnergyActivity.VehicleGateway.ApplyResult result = + gateway.applyStartupSettings(driveMode, regenLevel); + handler.post(new Runnable() { + @Override public void run() { + if (request != settingsApplyGeneration || gateway != vehicle || !vehicleServiceBound) return; + if (!result.success() && attempt + 1 < SETTINGS_APPLY_ATTEMPTS) { + connection.setText("SAIC VEHICLE SERVICE • CONNECTED • waiting for vehicle settings…"); + connection.setTextColor(MUTED); + handler.postDelayed(new Runnable() { + @Override public void run() { + if (request == settingsApplyGeneration && gateway == vehicle && vehicleServiceBound) { + applyStartupSettings(gateway, driveMode, regenLevel, request, attempt + 1); + } + } + }, SETTINGS_APPLY_RETRY_MS); + return; + } + String prefix = result.success() ? "CONNECTED • startup defaults applied: " : "CONNECTED • startup defaults partially applied: "; + connection.setText("SAIC VEHICLE SERVICE • " + prefix + + EnergyActivity.VehicleGateway.driveModeName(result.driveMode) + " / " + + EnergyActivity.VehicleGateway.regenerativeLevelName(result.regenerativeLevel)); + connection.setTextColor(result.success() ? ACCENT : Color.rgb(255, 179, 71)); + } + }); + } + }, "mg-startup-settings").start(); + } + + private void openIntent(Intent intent) { + try { startActivity(intent); } + catch (Exception e) { Toast.makeText(this, "Page unavailable: " + e.getClass().getSimpleName(), Toast.LENGTH_SHORT).show(); } + } + + private void requestLocationAccess() { + if (Build.VERSION.SDK_INT < 23) return; + if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED || + checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED) return; + requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST); + } + + private void openComponent(String pkg, String cls) { + Intent i = new Intent(); + i.setComponent(new ComponentName(pkg, cls)); + openIntent(i); + } + + private ScrollView scroll(TextView content) { + ScrollView s = new ScrollView(this); + s.setFillViewport(true); + s.setBackgroundColor(PANEL); + s.addView(content); + return s; + } + + private TextView panel(String heading) { + TextView v = text(heading + "\n\n", 15, TEXT, Typeface.NORMAL); + v.setLineSpacing(2, 1f); + v.setPadding(20, 18, 20, 18); + return v; + } + + private TextView text(String s, int size, int color, int style) { + TextView v = new TextView(this); + v.setText(s); + v.setTextSize(size); + v.setTextColor(color); + v.setTypeface(Typeface.create("sans-serif", style)); + return v; + } + private void probeVehicleService() { - try { boolean requested = bindService(new Intent("com.saicmotor.service.vehicle.VehicleService").setPackage("com.saicmotor.service.vehicle"), vehicleConnection, Context.BIND_AUTO_CREATE); if (!requested) connection.setText("SAIC VEHICLE SERVICE • NOT AVAILABLE"); } - catch (Exception e) { connection.setText("SAIC VEHICLE SERVICE • " + e.getClass().getSimpleName()); } + try { + vehicleServiceBindingRequested = bindService( + new Intent("com.saicmotor.service.vehicle.VehicleService") + .setPackage("com.saicmotor.service.vehicle"), + vehicleConnection, Context.BIND_AUTO_CREATE); + if (!vehicleServiceBindingRequested) { + connection.setText("SAIC VEHICLE SERVICE • NOT AVAILABLE"); + connection.setTextColor(Color.rgb(255, 179, 71)); + } + } catch (Exception e) { + vehicleServiceBindingRequested = false; + connection.setText("SAIC VEHICLE SERVICE • " + e.getClass().getSimpleName()); + connection.setTextColor(Color.rgb(255, 179, 71)); + } } + private void refresh() { updated.setText("READING…"); - new Thread(new Runnable() { public void run() { - final String props = readProperties(); final String diag = readDiagnostics(); - handler.post(new Runnable() { public void run() { properties.setText(props); diagnostics.setText(diag); updated.setText("UPDATED " + android.text.format.DateFormat.format("HH:mm:ss", System.currentTimeMillis())); } }); - }}).start(); + new Thread(new Runnable() { + @Override public void run() { + final String props = readProperties(); + final String diag = readDiagnostics(); + handler.post(new Runnable() { + @Override public void run() { + properties.setText(props); + diagnostics.setText(diag); + updated.setText("UPDATED " + android.text.format.DateFormat.format("HH:mm:ss", System.currentTimeMillis())); + } + }); + } + }, "mg-dashboard-refresh").start(); } + private String readProperties() { List kept = new ArrayList<>(); try { - BufferedReader b = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("getprop").getInputStream())); String line; - while ((line = b.readLine()) != null) if (verboseProperties || line.startsWith("[ro.product") || line.startsWith("[ro.build") || line.startsWith("[ro.board") || line.startsWith("[ro.hardware") || line.startsWith("[ro.vehicle") || line.startsWith("[persist.sys") || line.startsWith("[sys.")) kept.add(line.replace("[", "").replace("]: [", " = ").replace("]", "")); + BufferedReader b = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("getprop").getInputStream())); + String line; + while ((line = b.readLine()) != null) { + if (verboseProperties || line.startsWith("[ro.product") || line.startsWith("[ro.build") || + line.startsWith("[ro.board") || line.startsWith("[ro.hardware") || line.startsWith("[ro.vehicle") || + line.startsWith("[persist.sys") || line.startsWith("[sys.")) { + kept.add(line.replace("[", "").replace("]: [", " = ").replace("]", "")); + } + } } catch (Exception e) { kept.add("getprop unavailable: " + e); } - Collections.sort(kept); StringBuilder out = new StringBuilder("LIVE SYSTEM PROPERTIES\n(read-only; sourced from getprop)\n\n"); - for (String x : kept) out.append(x).append('\n'); return out.toString(); + Collections.sort(kept); + StringBuilder out = new StringBuilder("LIVE SYSTEM PROPERTIES\n(read-only; sourced from getprop)\n\n"); + for (String x : kept) out.append(x).append('\n'); + return out.toString(); } + private String readDiagnostics() { return "HEAD UNIT DIAGNOSTICS\n\n" + "MODEL " + Build.MODEL + "\n" + "DEVICE " + Build.DEVICE + "\n" + "HARDWARE " + Build.HARDWARE + "\n" + "BOARD " + Build.BOARD + "\n" + @@ -131,8 +526,8 @@ public class MainActivity extends Activity { "DISPLAY 0 " + getResources().getDisplayMetrics().widthPixels + " × " + getResources().getDisplayMetrics().heightPixels + " px\n" + "DENSITY " + getResources().getDisplayMetrics().densityDpi + " dpi\n" + "ORIENTATION landscape locked\n\n" + - "VEHICLE SDK\nExported SAIC service probe above. This utility intentionally displays diagnostic data only and never sends vehicle-control commands.\n\n" + + "VEHICLE SDK\nExported SAIC service probe above. Startup defaults are the only vehicle-control writes made by this app: drive mode and regenerative level. The energy dashboard and provider remain read-only; the regenerative-brake switch and every other vehicle control are untouched.\n\n" + + "STARTUP DEFAULTS\nDRIVE MODE " + EnergyActivity.VehicleGateway.driveModeName(configuredDriveMode()) + "\nENERGY REGEN " + EnergyActivity.VehicleGateway.regenerativeLevelName(configuredRegenerativeLevel()) + "\n\n" + "KNOWN PLATFORM\nSAIC AUTUS / MT2712\nEH32 EUUK • MG4 Luxury 2022\n1920 × 720 primary display\n"; } - private static class WindowManagerLayout { static final int FLAG_KEEP_SCREEN_ON = 128; } } diff --git a/src/cloud/molberg/mgutility/RouteMapView.java b/src/cloud/molberg/mgutility/RouteMapView.java new file mode 100644 index 0000000..66b6f3d --- /dev/null +++ b/src/cloud/molberg/mgutility/RouteMapView.java @@ -0,0 +1,323 @@ +package cloud.molberg.mgutility; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RectF; +import android.util.LruCache; +import android.view.MotionEvent; +import android.view.View; + +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Lightweight, dependency-free interactive map. It renders an OSM tile layer when the + * head unit has internet access and always renders the recorded route itself, so a GPS + * log remains useful even when tiles cannot be downloaded. Drag to pan and pinch to + * zoom; no Google Play Services or map SDK is required. + */ +final class RouteMapView extends View { + private static final int TILE_SIZE = 256; + private static final int MIN_ZOOM = 3; + private static final int MAX_ZOOM = 19; + private static final int ROUTE = Color.rgb(0, 196, 153); + private static final int START = Color.rgb(0, 216, 165); + private static final int END = Color.rgb(255, 166, 82); + + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint routePaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final LruCache tileCache = new LruCache(24); + private final Set pendingTiles = Collections.synchronizedSet(new HashSet()); + private final ExecutorService tileExecutor = Executors.newFixedThreadPool(2); + private List points = Collections.emptyList(); + private double centerWorldX, centerWorldY; + private int zoom = 14; + private boolean viewportReady; + private float lastX, lastY; + private float pinchStartDistance; + private int pinchStartZoom; + + RouteMapView(android.content.Context context) { + super(context); + setBackgroundColor(Color.rgb(225, 232, 230)); + routePaint.setColor(ROUTE); + routePaint.setStyle(Paint.Style.STROKE); + routePaint.setStrokeWidth(6f); + routePaint.setStrokeCap(Paint.Cap.ROUND); + routePaint.setStrokeJoin(Paint.Join.ROUND); + setFocusable(true); + } + + void setRoute(List route) { + points = route == null ? Collections.emptyList() : + new ArrayList(route); + viewportReady = false; + fitRoute(); + invalidate(); + } + + void fitRoute() { + if (points.isEmpty() || getWidth() <= 0 || getHeight() <= 0) { + viewportReady = false; + return; + } + double minLat = 90, maxLat = -90, minLon = 180, maxLon = -180; + for (TripDatabase.TripPoint point : points) { + minLat = Math.min(minLat, point.latitude); + maxLat = Math.max(maxLat, point.latitude); + minLon = Math.min(minLon, point.longitude); + maxLon = Math.max(maxLon, point.longitude); + } + double latSpan = Math.max(0.002, maxLat - minLat); + double lonSpan = Math.max(0.002, maxLon - minLon); + double usableWidth = Math.max(1, getWidth() - 80); + double usableHeight = Math.max(1, getHeight() - 80); + int chosen = MIN_ZOOM; + for (int candidate = MIN_ZOOM; candidate <= MAX_ZOOM; candidate++) { + double world = worldSize(candidate); + double xSpan = (lonSpan / 360d) * world; + double ySpan = (mercatorY(minLat, candidate) - mercatorY(maxLat, candidate)); + if (xSpan <= usableWidth && ySpan <= usableHeight) chosen = candidate; + else break; + } + zoom = chosen; + centerWorldX = worldX((minLon + maxLon) / 2d, zoom); + centerWorldY = (mercatorY(minLat, zoom) + mercatorY(maxLat, zoom)) / 2d; + viewportReady = true; + } + + @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { + super.onSizeChanged(width, height, oldWidth, oldHeight); + if (!points.isEmpty()) fitRoute(); + } + + @Override protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (points.isEmpty()) { + drawMessage(canvas, "No GPS route recorded for this drive"); + return; + } + if (!viewportReady) fitRoute(); + drawTiles(canvas); + drawRoute(canvas); + paint.setStyle(Paint.Style.FILL); + paint.setColor(Color.argb(210, 255, 255, 255)); + canvas.drawRoundRect(new RectF(14, getHeight() - 38, 340, getHeight() - 10), 6, 6, paint); + paint.setTextSize(12); + paint.setColor(Color.rgb(40, 55, 57)); + canvas.drawText("© OpenStreetMap contributors • Z" + zoom, 24, getHeight() - 20, paint); + } + + private void drawTiles(Canvas canvas) { + double left = centerWorldX - getWidth() / 2d; + double top = centerWorldY - getHeight() / 2d; + int firstX = (int) Math.floor(left / TILE_SIZE) - 1; + int lastX = (int) Math.floor((left + getWidth()) / TILE_SIZE) + 1; + int firstY = (int) Math.floor(top / TILE_SIZE) - 1; + int lastY = (int) Math.floor((top + getHeight()) / TILE_SIZE) + 1; + int tiles = 1 << zoom; + boolean loading = false; + for (int tileX = firstX; tileX <= lastX; tileX++) { + int wrappedX = floorMod(tileX, tiles); + for (int tileY = firstY; tileY <= lastY; tileY++) { + if (tileY < 0 || tileY >= tiles) continue; + float screenX = (float) (tileX * TILE_SIZE - left); + float screenY = (float) (tileY * TILE_SIZE - top); + String key = zoom + "/" + wrappedX + "/" + tileY; + Bitmap tile = tileCache.get(key); + if (tile != null) { + canvas.drawBitmap(tile, screenX, screenY, paint); + } else { + paint.setStyle(Paint.Style.FILL); + paint.setColor(Color.rgb(214, 223, 221)); + canvas.drawRect(screenX, screenY, screenX + TILE_SIZE, screenY + TILE_SIZE, paint); + requestTile(key); + loading = true; + } + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(1f); + paint.setColor(Color.argb(60, 60, 80, 80)); + canvas.drawRect(screenX, screenY, screenX + TILE_SIZE, screenY + TILE_SIZE, paint); + } + } + if (loading) drawMessage(canvas, "Loading map tiles…"); + } + + private void drawRoute(Canvas canvas) { + Path path = new Path(); + boolean started = false; + float lastScreenX = 0; + for (TripDatabase.TripPoint point : points) { + float x = (float) (worldX(point.longitude, zoom) - centerWorldX + getWidth() / 2d); + float y = (float) (mercatorY(point.latitude, zoom) - centerWorldY + getHeight() / 2d); + if (!started || Math.abs(x - lastScreenX) > getWidth()) { + path.moveTo(x, y); + started = true; + } else { + path.lineTo(x, y); + } + lastScreenX = x; + } + canvas.drawPath(path, routePaint); + if (started) { + TripDatabase.TripPoint first = points.get(0); + TripDatabase.TripPoint last = points.get(points.size() - 1); + drawMarker(canvas, first, START); + drawMarker(canvas, last, END); + } + } + + private void drawMarker(Canvas canvas, TripDatabase.TripPoint point, int color) { + float x = (float) (worldX(point.longitude, zoom) - centerWorldX + getWidth() / 2d); + float y = (float) (mercatorY(point.latitude, zoom) - centerWorldY + getHeight() / 2d); + paint.setStyle(Paint.Style.FILL); + paint.setColor(Color.WHITE); + canvas.drawCircle(x, y, 9, paint); + paint.setColor(color); + canvas.drawCircle(x, y, 6, paint); + } + + private void drawMessage(Canvas canvas, String message) { + paint.setStyle(Paint.Style.FILL); + paint.setColor(Color.argb(220, 255, 255, 255)); + canvas.drawRoundRect(new RectF(20, 20, Math.min(getWidth() - 20, 430), 70), 8, 8, paint); + paint.setTextSize(15); + paint.setColor(Color.rgb(42, 62, 64)); + canvas.drawText(message, 34, 51, paint); + } + + private void requestTile(final String key) { + if (!pendingTiles.add(key)) return; + tileExecutor.execute(new Runnable() { + @Override public void run() { + Bitmap bitmap = null; + HttpURLConnection connection = null; + InputStream stream = null; + try { + URL url = new URL("https://tile.openstreetmap.org/" + key + ".png"); + connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(8000); + connection.setReadTimeout(8000); + connection.setRequestProperty("User-Agent", "MG-Utility-trip-log/0.2 (personal use)"); + connection.connect(); + if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { + stream = connection.getInputStream(); + bitmap = BitmapFactory.decodeStream(stream); + } + } catch (Exception ignored) { } + finally { + if (stream != null) try { stream.close(); } catch (Exception ignored) { } + if (connection != null) connection.disconnect(); + pendingTiles.remove(key); + } + if (bitmap != null) { + tileCache.put(key, bitmap); + postInvalidate(); + } + } + }); + } + + @Override public boolean onTouchEvent(MotionEvent event) { + switch (event.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + lastX = event.getX(); + lastY = event.getY(); + return true; + case MotionEvent.ACTION_POINTER_DOWN: + if (event.getPointerCount() >= 2) { + pinchStartDistance = distance(event); + pinchStartZoom = zoom; + } + return true; + case MotionEvent.ACTION_MOVE: + if (event.getPointerCount() >= 2 && pinchStartDistance > 0) { + float scale = distance(event) / pinchStartDistance; + int target = pinchStartZoom; + if (scale > 1.35f) target++; + else if (scale < 0.75f) target--; + setZoom(target); + } else if (event.getPointerCount() == 1) { + float dx = event.getX() - lastX; + float dy = event.getY() - lastY; + centerWorldX -= dx; + centerWorldY -= dy; + lastX = event.getX(); + lastY = event.getY(); + viewportReady = true; + invalidate(); + } + return true; + case MotionEvent.ACTION_POINTER_UP: + pinchStartDistance = 0; + return true; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + pinchStartDistance = 0; + return true; + default: + return true; + } + } + + private void setZoom(int target) { + target = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, target)); + if (target == zoom || !viewportReady) return; + double latitude = latitudeFromWorldY(centerWorldY, zoom); + double longitude = longitudeFromWorldX(centerWorldX, zoom); + zoom = target; + centerWorldX = worldX(longitude, zoom); + centerWorldY = mercatorY(latitude, zoom); + invalidate(); + } + + private float distance(MotionEvent event) { + if (event.getPointerCount() < 2) return 0; + float dx = event.getX(0) - event.getX(1); + float dy = event.getY(0) - event.getY(1); + return (float) Math.sqrt(dx * dx + dy * dy); + } + + private static int floorMod(int value, int modulus) { + int result = value % modulus; + return result < 0 ? result + modulus : result; + } + + private static double worldSize(int zoom) { return TILE_SIZE * Math.pow(2, zoom); } + + private static double worldX(double longitude, int zoom) { + return (longitude + 180d) / 360d * worldSize(zoom); + } + + private static double longitudeFromWorldX(double x, int zoom) { + return x / worldSize(zoom) * 360d - 180d; + } + + private static double mercatorY(double latitude, int zoom) { + double clamped = Math.max(-85.05112878, Math.min(85.05112878, latitude)); + double sin = Math.sin(Math.toRadians(clamped)); + return (0.5d - Math.log((1d + sin) / (1d - sin)) / (4d * Math.PI)) * worldSize(zoom); + } + + private static double latitudeFromWorldY(double y, int zoom) { + double n = Math.PI - 2d * Math.PI * y / worldSize(zoom); + return Math.toDegrees(Math.atan(Math.sinh(n))); + } + + @Override protected void onDetachedFromWindow() { + tileExecutor.shutdownNow(); + super.onDetachedFromWindow(); + } +} diff --git a/src/cloud/molberg/mgutility/TripDatabase.java b/src/cloud/molberg/mgutility/TripDatabase.java new file mode 100644 index 0000000..993fbff --- /dev/null +++ b/src/cloud/molberg/mgutility/TripDatabase.java @@ -0,0 +1,297 @@ +package cloud.molberg.mgutility; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import java.util.ArrayList; +import java.util.List; + +/** + * Small local store for automatically collected drives. It deliberately uses the + * platform SQLite API so MG Utility remains buildable without a Gradle dependency. + */ +final class TripDatabase extends SQLiteOpenHelper { + private static final String NAME = "mg_trips.db"; + private static final int VERSION = 1; + + static final long NO_TRIP = -1L; + + TripDatabase(Context context) { + super(context.getApplicationContext(), NAME, null, VERSION); + setWriteAheadLoggingEnabled(true); + } + + @Override public void onCreate(SQLiteDatabase db) { + db.execSQL("CREATE TABLE trips (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "start_time INTEGER NOT NULL," + + "end_time INTEGER," + + "start_soc REAL," + + "end_soc REAL," + + "start_range_km INTEGER," + + "end_range_km INTEGER," + + "top_speed_kph REAL NOT NULL DEFAULT 0," + + "distance_m REAL NOT NULL DEFAULT 0," + + "energy_start_kwh REAL," + + "energy_end_kwh REAL," + + "sample_count INTEGER NOT NULL DEFAULT 0," + + "moving_ms INTEGER NOT NULL DEFAULT 0," + + "max_voltage REAL NOT NULL DEFAULT 0," + + "gps_points INTEGER NOT NULL DEFAULT 0)"); + db.execSQL("CREATE TABLE trip_points (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "trip_id INTEGER NOT NULL," + + "timestamp INTEGER NOT NULL," + + "latitude REAL NOT NULL," + + "longitude REAL NOT NULL," + + "speed_kph REAL," + + "soc REAL," + + "range_km INTEGER," + + "FOREIGN KEY(trip_id) REFERENCES trips(id) ON DELETE CASCADE)"); + db.execSQL("CREATE INDEX trip_points_trip_time ON trip_points(trip_id, timestamp)"); + db.execSQL("CREATE INDEX trips_start_time ON trips(start_time DESC)"); + } + + @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + // There is no released schema to preserve yet. Keep this explicit so a future + // migration has a safe home instead of silently losing a user's drive history. + if (oldVersion < 1) onCreate(db); + } + + synchronized long startTrip(long startedAt, EnergyActivity.Sample sample) { + SQLiteDatabase db = getWritableDatabase(); + ContentValues values = new ContentValues(); + values.put("start_time", startedAt); + putFloat(values, "start_soc", sample.soc); + putInt(values, "start_range_km", sample.range); + putFloat(values, "energy_start_kwh", sample.total); + putFloat(values, "end_soc", sample.soc); + putInt(values, "end_range_km", sample.range); + putFloat(values, "energy_end_kwh", sample.total); + putFloat(values, "top_speed_kph", safe(sample.speed)); + putFloat(values, "max_voltage", safe(sample.volts)); + values.put("sample_count", 1); + return db.insert("trips", null, values); + } + + synchronized void addSample(long tripId, long timestamp, EnergyActivity.Sample sample, + float distanceMeters, long movingMillis, TripPoint point) { + SQLiteDatabase db = getWritableDatabase(); + db.beginTransaction(); + try { + db.execSQL("UPDATE trips SET " + + "end_soc = ?, end_range_km = ?, energy_end_kwh = ?, " + + "top_speed_kph = MAX(top_speed_kph, ?), " + + "max_voltage = MAX(max_voltage, ?), " + + "distance_m = distance_m + ?, moving_ms = moving_ms + ?, " + + "sample_count = sample_count + ?, gps_points = gps_points + ? " + + "WHERE id = ?", + new Object[]{nullableFloat(sample.soc), nullableInt(sample.range), + nullableFloat(sample.total), safe(sample.speed), safe(sample.volts), + Math.max(0f, distanceMeters), Math.max(0L, movingMillis), 1, + point == null ? 0 : 1, tripId}); + if (point != null) { + ContentValues p = new ContentValues(); + p.put("trip_id", tripId); + p.put("timestamp", timestamp); + p.put("latitude", point.latitude); + p.put("longitude", point.longitude); + putFloat(p, "speed_kph", sample.speed); + putFloat(p, "soc", sample.soc); + putInt(p, "range_km", sample.range); + db.insert("trip_points", null, p); + } + db.setTransactionSuccessful(); + } finally { + db.endTransaction(); + } + } + + synchronized void finishTrip(long tripId, long endedAt, EnergyActivity.Sample sample) { + SQLiteDatabase db = getWritableDatabase(); + ContentValues values = new ContentValues(); + values.put("end_time", endedAt); + putFloat(values, "end_soc", sample.soc); + putInt(values, "end_range_km", sample.range); + putFloat(values, "energy_end_kwh", sample.total); + db.update("trips", values, "id = ? AND end_time IS NULL", + new String[]{String.valueOf(tripId)}); + } + + synchronized long openTripId() { + Cursor c = getReadableDatabase().query("trips", new String[]{"id"}, + "end_time IS NULL", null, null, null, "start_time DESC", "1"); + try { return c.moveToFirst() ? c.getLong(0) : NO_TRIP; } + finally { c.close(); } + } + + synchronized List listTrips() { + ArrayList trips = new ArrayList<>(); + Cursor c = getReadableDatabase().query("trips", null, "end_time IS NOT NULL", + null, null, null, "start_time DESC", "100"); + try { + while (c.moveToNext()) trips.add(TripSummary.from(c)); + } finally { c.close(); } + return trips; + } + + synchronized TripSummary getTrip(long id) { + Cursor c = getReadableDatabase().query("trips", null, "id = ?", + new String[]{String.valueOf(id)}, null, null, null, "1"); + try { return c.moveToFirst() ? TripSummary.from(c) : null; } + finally { c.close(); } + } + + synchronized List getRoute(long tripId) { + ArrayList points = new ArrayList<>(); + Cursor c = getReadableDatabase().query("trip_points", + new String[]{"timestamp", "latitude", "longitude", "speed_kph", "soc"}, + "trip_id = ?", new String[]{String.valueOf(tripId)}, null, null, + "timestamp ASC"); + try { + while (c.moveToNext()) { + points.add(new TripPoint(c.getLong(0), c.getDouble(1), c.getDouble(2), + nullableFloat(c, 3), nullableFloat(c, 4))); + } + } finally { c.close(); } + return points; + } + + synchronized Summary summary() { + Cursor c = getReadableDatabase().rawQuery( + "SELECT COUNT(*), COALESCE(SUM(distance_m),0), COALESCE(SUM(moving_ms),0), " + + "COALESCE(SUM(CASE WHEN energy_end_kwh >= energy_start_kwh " + + "THEN energy_end_kwh - energy_start_kwh ELSE 0 END),0) FROM trips " + + "WHERE end_time IS NOT NULL", null); + try { + if (!c.moveToFirst()) return new Summary(0, 0, 0, 0); + return new Summary(c.getInt(0), c.getDouble(1), c.getLong(2), c.getDouble(3)); + } finally { c.close(); } + } + + private static void putFloat(ContentValues values, String key, float value) { + if (!Float.isNaN(value) && !Float.isInfinite(value)) values.put(key, value); + } + + private static void putInt(ContentValues values, String key, int value) { + if (value >= 0) values.put(key, value); + } + + private static Object nullableFloat(float value) { + return Float.isNaN(value) || Float.isInfinite(value) ? null : value; + } + + private static Object nullableInt(int value) { return value < 0 ? null : value; } + + private static float nullableFloat(Cursor c, int index) { + return c.isNull(index) ? Float.NaN : c.getFloat(index); + } + + private static float safe(float value) { + return Float.isNaN(value) || Float.isInfinite(value) || value < 0 ? 0f : value; + } + + static final class TripPoint { + final long timestamp; + final double latitude, longitude; + final float speedKph, soc; + + TripPoint(long timestamp, double latitude, double longitude, float speedKph, float soc) { + this.timestamp = timestamp; + this.latitude = latitude; + this.longitude = longitude; + this.speedKph = speedKph; + this.soc = soc; + } + } + + static final class TripSummary { + final long id, startTime, endTime; + final float startSoc, endSoc, topSpeedKph, maxVoltage; + final int startRangeKm, endRangeKm, sampleCount, gpsPoints; + final double distanceMeters, energyStartKwh, energyEndKwh; + final long movingMillis; + + private TripSummary(long id, long startTime, long endTime, float startSoc, float endSoc, + int startRangeKm, int endRangeKm, float topSpeedKph, double distanceMeters, + double energyStartKwh, double energyEndKwh, int sampleCount, long movingMillis, + float maxVoltage, int gpsPoints) { + this.id = id; + this.startTime = startTime; + this.endTime = endTime; + this.startSoc = startSoc; + this.endSoc = endSoc; + this.startRangeKm = startRangeKm; + this.endRangeKm = endRangeKm; + this.topSpeedKph = topSpeedKph; + this.distanceMeters = distanceMeters; + this.energyStartKwh = energyStartKwh; + this.energyEndKwh = energyEndKwh; + this.sampleCount = sampleCount; + this.movingMillis = movingMillis; + this.maxVoltage = maxVoltage; + this.gpsPoints = gpsPoints; + } + + static TripSummary from(Cursor c) { + return new TripSummary(c.getLong(c.getColumnIndexOrThrow("id")), + c.getLong(c.getColumnIndexOrThrow("start_time")), + c.isNull(c.getColumnIndexOrThrow("end_time")) ? 0 : + c.getLong(c.getColumnIndexOrThrow("end_time")), + nullableFloat(c, "start_soc"), nullableFloat(c, "end_soc"), + nullableInt(c, "start_range_km"), nullableInt(c, "end_range_km"), + nullableFloat(c, "top_speed_kph"), c.getDouble(c.getColumnIndexOrThrow("distance_m")), + nullableDouble(c, "energy_start_kwh"), nullableDouble(c, "energy_end_kwh"), + c.getInt(c.getColumnIndexOrThrow("sample_count")), + c.getLong(c.getColumnIndexOrThrow("moving_ms")), + nullableFloat(c, "max_voltage"), c.getInt(c.getColumnIndexOrThrow("gps_points"))); + } + + float socUsed() { + return valid(startSoc) && valid(endSoc) ? Math.max(0f, startSoc - endSoc) : Float.NaN; + } + + double reportedEnergyUsed() { + return valid(energyStartKwh) && valid(energyEndKwh) + ? Math.max(0d, energyEndKwh - energyStartKwh) : Double.NaN; + } + + double distanceKm() { return distanceMeters / 1000d; } + + long durationMillis() { return endTime > 0 ? Math.max(0, endTime - startTime) : 0; } + + private static boolean valid(float value) { return !Float.isNaN(value) && !Float.isInfinite(value); } + private static boolean valid(double value) { return !Double.isNaN(value) && !Double.isInfinite(value); } + + private static float nullableFloat(Cursor c, String name) { + int index = c.getColumnIndexOrThrow(name); + return c.isNull(index) ? Float.NaN : c.getFloat(index); + } + + private static int nullableInt(Cursor c, String name) { + int index = c.getColumnIndexOrThrow(name); + return c.isNull(index) ? -1 : c.getInt(index); + } + + private static double nullableDouble(Cursor c, String name) { + int index = c.getColumnIndexOrThrow(name); + return c.isNull(index) ? Double.NaN : c.getDouble(index); + } + } + + static final class Summary { + final int tripCount; + final double distanceMeters, energyKwh; + final long movingMillis; + + Summary(int tripCount, double distanceMeters, long movingMillis, double energyKwh) { + this.tripCount = tripCount; + this.distanceMeters = distanceMeters; + this.movingMillis = movingMillis; + this.energyKwh = energyKwh; + } + } +} diff --git a/src/cloud/molberg/mgutility/TripTrackingService.java b/src/cloud/molberg/mgutility/TripTrackingService.java new file mode 100644 index 0000000..2d574c4 --- /dev/null +++ b/src/cloud/molberg/mgutility/TripTrackingService.java @@ -0,0 +1,359 @@ +package cloud.molberg.mgutility; + +import android.Manifest; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.app.Service; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.pm.PackageManager; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Build; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; + +import java.util.Locale; + +/** + * Always-on, read-only drive logger. It is deliberately a foreground service because + * Android 9 will otherwise reclaim a background process while the launcher is visible. + * Vehicle samples continue even when location permission is denied; route points are + * simply omitted until a GPS fix is available. + */ +public final class TripTrackingService extends Service { + static final String ACTION_START = "cloud.molberg.mgutility.START_TRACKING"; + static final String CHANNEL_ID = "mg_trip_tracking"; + static final int NOTIFICATION_ID = 1404; + + private static final long SAMPLE_INTERVAL_MS = 5000L; + private static final long STOP_GRACE_MS = 5 * 60 * 1000L; + private static final float MOVING_SPEED_KPH = 3f; + private static final float DISTANCE_SPEED_KPH = 1f; + private static final long MAX_DISTANCE_INTERVAL_MS = 15000L; + + private HandlerThread workerThread; + private Handler worker; + private LocationManager locationManager; + private TripDatabase database; + private volatile EnergyActivity.VehicleGateway vehicle; + private volatile boolean bindingRequested; + private volatile Location latestLocation; + private long activeTripId = TripDatabase.NO_TRIP; + private long lastSampleAt; + private Location lastDistanceLocation; + private Location lastStoredLocation; + private long stoppedSince; + private String lastNotificationText = ""; + + private final Runnable poll = new Runnable() { + @Override public void run() { + collect(); + if (worker != null) worker.postDelayed(this, SAMPLE_INTERVAL_MS); + } + }; + + private final ServiceConnection vehicleConnection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder binder) { + vehicle = new EnergyActivity.VehicleGateway(binder); + bindingRequested = true; + updateStatus("Vehicle link ready"); + } + + @Override public void onServiceDisconnected(ComponentName name) { + vehicle = null; + bindingRequested = false; + updateStatus("Waiting for vehicle service"); + if (worker != null) worker.postDelayed(new Runnable() { + @Override public void run() { bindVehicleService(); } + }, 2000L); + } + }; + + private final LocationListener locationListener = new LocationListener() { + @Override public void onLocationChanged(Location location) { + if (location == null) return; + latestLocation = new Location(location); + getSharedPreferences("trip_tracker", MODE_PRIVATE).edit() + .putBoolean("gps_ready", true) + .putLong("last_fix", System.currentTimeMillis()) + .putString("gps_provider", location.getProvider() == null ? "unknown" : location.getProvider()) + .apply(); + updateStatus("GPS route ready"); + } + + @Override public void onStatusChanged(String provider, int status, android.os.Bundle extras) { } + @Override public void onProviderEnabled(String provider) { updateStatus("GPS route ready"); } + @Override public void onProviderDisabled(String provider) { } + }; + + /** Start the logger in the form required by Android O and later. */ + static void start(Context context) { + Intent intent = new Intent(context, TripTrackingService.class).setAction(ACTION_START); + try { + if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent); + else context.startService(intent); + } catch (Exception ignored) { + // A user can still start the service normally after opening MG Utility. + } + } + + @Override public void onCreate() { + super.onCreate(); + database = new TripDatabase(this); + activeTripId = database.openTripId(); + createNotificationChannel(); + startForeground(NOTIFICATION_ID, notification("Starting automatic trip tracking")); + + workerThread = new HandlerThread("mg-trip-tracker"); + workerThread.start(); + worker = new Handler(workerThread.getLooper()); + worker.post(new Runnable() { + @Override public void run() { + bindVehicleService(); + configureLocation(); + collect(); + worker.postDelayed(poll, SAMPLE_INTERVAL_MS); + } + }); + } + + @Override public int onStartCommand(Intent intent, int flags, int startId) { + // The first start can happen before the Activity's runtime location prompt is + // accepted. Re-run provider setup on every explicit start so granting the + // permission immediately enables route logging without a reboot. + if (worker != null) worker.post(new Runnable() { + @Override public void run() { configureLocation(); } + }); + return START_STICKY; + } + + @Override public void onDestroy() { + if (worker != null) worker.removeCallbacksAndMessages(null); + if (locationManager != null && hasLocationPermission()) { + try { locationManager.removeUpdates(locationListener); } catch (Exception ignored) { } + } + if (bindingRequested) { + try { unbindService(vehicleConnection); } catch (Exception ignored) { } + bindingRequested = false; + } + vehicle = null; + if (workerThread != null) workerThread.quitSafely(); + if (database != null) database.close(); + super.onDestroy(); + } + + @Override public IBinder onBind(Intent intent) { return null; } + + private void bindVehicleService() { + if (bindingRequested || vehicle != null) return; + try { + bindingRequested = bindService( + new Intent("com.saicmotor.service.vehicle.VehicleService") + .setPackage("com.saicmotor.service.vehicle"), + vehicleConnection, Context.BIND_AUTO_CREATE); + if (!bindingRequested) updateStatus("Vehicle service unavailable"); + } catch (Exception e) { + bindingRequested = false; + updateStatus("Vehicle service unavailable"); + } + } + + private void configureLocation() { + if (!hasLocationPermission()) { + getSharedPreferences("trip_tracker", MODE_PRIVATE).edit() + .putBoolean("gps_ready", false).putString("gps_status", "Location permission required").apply(); + updateStatus("Vehicle logging on • allow location for maps"); + return; + } + locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); + if (locationManager == null) { + updateStatus("Vehicle logging on • GPS unavailable"); + return; + } + boolean providerFound = false; + String[] providers = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER}; + for (String provider : providers) { + try { + if (!locationManager.isProviderEnabled(provider)) continue; + locationManager.requestLocationUpdates(provider, 2000L, 3f, locationListener, + worker.getLooper()); + Location last = locationManager.getLastKnownLocation(provider); + if (last != null && (latestLocation == null || last.getTime() > latestLocation.getTime())) { + latestLocation = new Location(last); + } + providerFound = true; + } catch (SecurityException ignored) { + // Permission can be revoked while the service is alive. + } catch (Exception ignored) { } + } + if (!providerFound) updateStatus("Vehicle logging on • GPS provider unavailable"); + else if (latestLocation != null) updateStatus("GPS route ready"); + else updateStatus("GPS searching for a fix"); + } + + private boolean hasLocationPermission() { + return Build.VERSION.SDK_INT < 23 || + checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || + checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; + } + + private void collect() { + EnergyActivity.VehicleGateway gateway = vehicle; + if (gateway == null) { + updateStatus("Waiting for vehicle service"); + if (!bindingRequested) bindVehicleService(); + return; + } + EnergyActivity.Sample sample; + try { sample = gateway.read(); } + catch (Exception ignored) { sample = null; } + if (sample == null) { + updateStatus("Vehicle data unavailable"); + return; + } + processSample(sample, System.currentTimeMillis()); + } + + private void processSample(EnergyActivity.Sample sample, long now) { + final float speed = validSpeed(sample.speed); + final boolean moving = speed >= MOVING_SPEED_KPH; + final long elapsed = lastSampleAt == 0 ? 0 : Math.min(MAX_DISTANCE_INTERVAL_MS, + Math.max(0, now - lastSampleAt)); + float distance = distanceDelta(speed, elapsed); + long movingMillis = moving ? elapsed : 0; + TripDatabase.TripPoint routePoint = routePoint(now, speed, sample); + + if (activeTripId == TripDatabase.NO_TRIP && moving) { + activeTripId = database.startTrip(now, sample); + stoppedSince = 0; + lastDistanceLocation = copy(latestLocation); + lastStoredLocation = null; + routePoint = routePoint(now, speed, sample); + updateStatus("Drive recording"); + } + + if (activeTripId != TripDatabase.NO_TRIP) { + // If the process was restarted while the car was already parked, close the + // recovered open trip on its first stationary observation. + if (lastSampleAt == 0 && !moving) stoppedSince = now - STOP_GRACE_MS; + database.addSample(activeTripId, now, sample, distance, movingMillis, routePoint); + + if (moving) { + stoppedSince = 0; + updateStatus("Drive recording"); + } else { + if (stoppedSince == 0) stoppedSince = now; + if (now - stoppedSince >= STOP_GRACE_MS) { + database.finishTrip(activeTripId, lastSampleAt == 0 ? now : stoppedSince, sample); + activeTripId = TripDatabase.NO_TRIP; + lastDistanceLocation = null; + lastStoredLocation = null; + stoppedSince = 0; + updateStatus("Parked • trip saved"); + } else { + updateStatus("Parked • finishing trip timer"); + } + } + } else { + updateStatus(moving ? "Drive starting" : gpsStatus()); + } + lastSampleAt = now; + notifyState(sample, moving); + } + + private float distanceDelta(float speedKph, long elapsedMillis) { + if (elapsedMillis <= 0) return 0f; + Location current = usableLocation(); + if (current != null && lastDistanceLocation != null) { + float direct = lastDistanceLocation.distanceTo(current); + if (direct >= 0 && direct < 5000f) { + lastDistanceLocation = new Location(current); + return direct; + } + } + if (current != null) lastDistanceLocation = new Location(current); + return speedKph >= DISTANCE_SPEED_KPH + ? speedKph / 3.6f * (elapsedMillis / 1000f) : 0f; + } + + private TripDatabase.TripPoint routePoint(long now, float speed, EnergyActivity.Sample sample) { + Location location = usableLocation(); + if (location == null) return null; + if (lastStoredLocation != null && lastStoredLocation.distanceTo(location) < 5f) return null; + lastStoredLocation = new Location(location); + return new TripDatabase.TripPoint(now, location.getLatitude(), location.getLongitude(), + speed, sample == null ? Float.NaN : sample.soc); + } + + private Location usableLocation() { + Location location = latestLocation; + if (location == null) return null; + long age = Math.abs(System.currentTimeMillis() - location.getTime()); + return age <= 30000L ? location : null; + } + + private Location copy(Location location) { return location == null ? null : new Location(location); } + + private float validSpeed(float speed) { + return Float.isNaN(speed) || Float.isInfinite(speed) || speed < 0 ? 0f : Math.min(speed, 300f); + } + + private String gpsStatus() { + if (!hasLocationPermission()) return "Vehicle logging on • allow location for maps"; + return latestLocation == null ? "GPS searching for a fix" : "Ready for next drive"; + } + + private void updateStatus(String status) { + getSharedPreferences("trip_tracker", MODE_PRIVATE).edit() + .putString("status", status).putLong("status_time", System.currentTimeMillis()).apply(); + } + + private void notifyState(EnergyActivity.Sample sample, boolean moving) { + String text; + if (moving) { + text = String.format(Locale.US, "Recording drive • %.0f km/h • %.1f%% battery", + validSpeed(sample.speed), sample.soc); + } else if (activeTripId != TripDatabase.NO_TRIP) { + text = "Parked • closing the current trip"; + } else if (!hasLocationPermission()) { + text = "Vehicle logging on • allow location for route maps"; + } else { + text = latestLocation == null ? "Waiting for GPS fix" : "Ready • waiting for next drive"; + } + if (text.equals(lastNotificationText)) return; + lastNotificationText = text; + NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + if (manager != null) manager.notify(NOTIFICATION_ID, notification(text)); + } + + private Notification notification(String text) { + Intent open = new Intent(this, MainActivity.class); + PendingIntent pending = PendingIntent.getActivity(this, 0, open, + Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : + PendingIntent.FLAG_UPDATE_CURRENT); + Notification.Builder builder = Build.VERSION.SDK_INT >= 26 + ? new Notification.Builder(this, CHANNEL_ID) : new Notification.Builder(this); + return builder.setSmallIcon(R.drawable.ic_mg_utility) + .setContentTitle("MG Utility trip tracking") + .setContentText(text) + .setContentIntent(pending) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setCategory(Notification.CATEGORY_SERVICE) + .build(); + } + + private void createNotificationChannel() { + if (Build.VERSION.SDK_INT < 26) return; + NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + if (manager != null) manager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, + "Trip tracking", NotificationManager.IMPORTANCE_LOW)); + } +} diff --git a/src/cloud/molberg/mgutility/TripsActivity.java b/src/cloud/molberg/mgutility/TripsActivity.java new file mode 100644 index 0000000..6d95117 --- /dev/null +++ b/src/cloud/molberg/mgutility/TripsActivity.java @@ -0,0 +1,276 @@ +package cloud.molberg.mgutility; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Color; +import android.graphics.Typeface; +import android.os.Bundle; +import android.os.Handler; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** Full-screen trip history and route report for the MG4's 1920×720 display. */ +public final class TripsActivity extends Activity { + private static final int BG = Color.rgb(8, 15, 19); + private static final int PANEL = Color.rgb(18, 30, 37); + private static final int PANEL_ALT = Color.rgb(24, 40, 48); + private static final int TEXT = Color.rgb(230, 243, 240); + private static final int MUTED = Color.rgb(141, 167, 163); + private static final int ACCENT = Color.rgb(0, 216, 165); + private static final int ORANGE = Color.rgb(255, 166, 82); + + private final Handler handler = new Handler(); + private TripDatabase database; + private LinearLayout tripList; + private TextView overview; + private TextView trackerStatus; + private TextView reportTitle; + private TextView reportStats; + private TextView mapStatus; + private RouteMapView map; + private long selectedTripId = TripDatabase.NO_TRIP; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + immersive(); + database = new TripDatabase(this); + setContentView(buildUi()); + loadTrips(); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + @Override public void onDestroy() { + if (database != null) database.close(); + super.onDestroy(); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(24, 14, 24, 18); + root.setBackgroundColor(BG); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + TextView title = text("DRIVE LOG", 29, TEXT, Typeface.BOLD); + header.addView(title, new LinearLayout.LayoutParams(0, 56, 1)); + trackerStatus = text(trackerStatusText(), 12, MUTED, Typeface.NORMAL); + trackerStatus.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); + header.addView(trackerStatus, new LinearLayout.LayoutParams(430, 56)); + Button refresh = actionButton("REFRESH", new View.OnClickListener() { + @Override public void onClick(View v) { loadTrips(); } + }); + header.addView(refresh, new LinearLayout.LayoutParams(130, 56)); + Button back = actionButton("BACK", new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }); + LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(130, 56); + bp.setMargins(10, 0, 0, 0); + header.addView(back, bp); + root.addView(header); + + LinearLayout body = new LinearLayout(this); + body.setPadding(0, 12, 0, 0); + + LinearLayout sidebar = new LinearLayout(this); + sidebar.setOrientation(LinearLayout.VERTICAL); + sidebar.setPadding(18, 16, 18, 12); + sidebar.setBackgroundColor(PANEL); + overview = text("LOADING DRIVE HISTORY…", 15, TEXT, Typeface.BOLD); + overview.setLineSpacing(2, 1f); + sidebar.addView(overview, new LinearLayout.LayoutParams(-1, 76)); + TextView history = text("RECENT DRIVES", 11, MUTED, Typeface.BOLD); + history.setPadding(0, 8, 0, 8); + sidebar.addView(history, new LinearLayout.LayoutParams(-1, 36)); + tripList = new LinearLayout(this); + tripList.setOrientation(LinearLayout.VERTICAL); + ScrollView listScroll = new ScrollView(this); + listScroll.setFillViewport(true); + listScroll.addView(tripList); + sidebar.addView(listScroll, new LinearLayout.LayoutParams(-1, 0, 1)); + body.addView(sidebar, new LinearLayout.LayoutParams(420, -1)); + + LinearLayout report = new LinearLayout(this); + report.setOrientation(LinearLayout.VERTICAL); + report.setPadding(18, 16, 0, 0); + reportTitle = text("SELECT A DRIVE", 23, TEXT, Typeface.BOLD); + report.addView(reportTitle, new LinearLayout.LayoutParams(-1, 42)); + reportStats = text("Choose a drive on the left to see its route and statistics.", 15, MUTED, Typeface.NORMAL); + reportStats.setLineSpacing(2, 1f); + report.addView(reportStats, new LinearLayout.LayoutParams(-1, 104)); + map = new RouteMapView(this); + report.addView(map, new LinearLayout.LayoutParams(-1, 0, 1)); + LinearLayout mapBar = new LinearLayout(this); + mapBar.setGravity(Gravity.CENTER_VERTICAL); + mapStatus = text("Route points are collected automatically in the background.", 12, MUTED, Typeface.NORMAL); + mapBar.addView(mapStatus, new LinearLayout.LayoutParams(0, 42, 1)); + Button fit = actionButton("FIT ROUTE", new View.OnClickListener() { + @Override public void onClick(View v) { map.fitRoute(); } + }); + mapBar.addView(fit, new LinearLayout.LayoutParams(140, 42)); + report.addView(mapBar, new LinearLayout.LayoutParams(-1, 48)); + body.addView(report, new LinearLayout.LayoutParams(0, -1, 1)); + root.addView(body, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private void loadTrips() { + if (trackerStatus != null) trackerStatus.setText(trackerStatusText()); + new Thread(new Runnable() { + @Override public void run() { + final List trips = database.listTrips(); + final TripDatabase.Summary summary = database.summary(); + handler.post(new Runnable() { + @Override public void run() { renderTrips(trips, summary); } + }); + } + }, "mg-trip-history").start(); + } + + private void renderTrips(List trips, TripDatabase.Summary summary) { + overview.setText(String.format(Locale.US, "%d DRIVES\n%.1f km • %.2f kWh logged", + summary.tripCount, summary.distanceMeters / 1000d, summary.energyKwh)); + tripList.removeAllViews(); + if (trips.isEmpty()) { + TextView empty = text("No completed drives yet.\n\nLeave the logger running; trips start automatically above 3 km/h and are saved five minutes after parking.", + 14, MUTED, Typeface.NORMAL); + empty.setLineSpacing(2, 1f); + tripList.addView(empty, new LinearLayout.LayoutParams(-1, -2)); + reportTitle.setText("NO DRIVE REPORTS YET"); + reportStats.setText("The tracker is running in the background. GPS routes appear here when a fix is available."); + map.setRoute(null); + mapStatus.setText(trackerStatusText()); + return; + } + for (final TripDatabase.TripSummary trip : trips) { + TextView row = tripRow(trip); + row.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { showTrip(trip); } + }); + tripList.addView(row, new LinearLayout.LayoutParams(-1, 82)); + } + showTrip(trips.get(0)); + } + + private TextView tripRow(TripDatabase.TripSummary trip) { + String date = new SimpleDateFormat("EEE d MMM HH:mm", Locale.US).format(new Date(trip.startTime)); + String distance = trip.distanceKm() >= 0.1 ? String.format(Locale.US, "%.1f km", trip.distanceKm()) : "<0.1 km"; + String top = String.format(Locale.US, "%.0f km/h", trip.topSpeedKph); + TextView row = text(date + "\n" + distance + " • TOP " + top + " • " + + formatDuration(trip.movingMillis > 0 ? trip.movingMillis : trip.durationMillis()), + 13, TEXT, Typeface.NORMAL); + row.setGravity(Gravity.CENTER_VERTICAL); + row.setPadding(14, 0, 10, 0); + row.setBackgroundColor(trip.id == selectedTripId ? Color.rgb(26, 67, 66) : PANEL_ALT); + return row; + } + + private void showTrip(final TripDatabase.TripSummary trip) { + selectedTripId = trip.id; + reportTitle.setText(new SimpleDateFormat("EEE d MMM • HH:mm", Locale.US).format(new Date(trip.startTime))); + String energy = Double.isNaN(trip.reportedEnergyUsed()) ? "—" : + String.format(Locale.US, "%.2f kWh", trip.reportedEnergyUsed()); + String soc = Float.isNaN(trip.socUsed()) ? "—" : String.format(Locale.US, "%.1f%%", trip.socUsed()); + String range = trip.startRangeKm >= 0 && trip.endRangeKm >= 0 + ? String.format(Locale.US, "%d km", Math.max(0, trip.startRangeKm - trip.endRangeKm)) : "—"; + reportStats.setText(String.format(Locale.US, + "DISTANCE %.1f km DURATION %s TOP SPEED %.0f km/h\n" + + "BATTERY USED %s SOC DROP %s EST. RANGE DROP %s\n" + + "GPS POINTS %d SAMPLES %d", + trip.distanceKm(), formatDuration(trip.movingMillis > 0 ? trip.movingMillis : trip.durationMillis()), + trip.topSpeedKph, energy, soc, range, trip.gpsPoints, trip.sampleCount)); + mapStatus.setText(trip.gpsPoints > 0 ? "Drag to pan • pinch to zoom • map tiles require internet" : + "No GPS fix recorded; vehicle speed and battery statistics are still available"); + new Thread(new Runnable() { + @Override public void run() { + final List route = database.getRoute(trip.id); + handler.post(new Runnable() { + @Override public void run() { + if (selectedTripId == trip.id) map.setRoute(route); + } + }); + } + }, "mg-trip-route").start(); + if (tripList != null) loadTripsRowsOnly(); + } + + private void loadTripsRowsOnly() { + new Thread(new Runnable() { + @Override public void run() { + final List trips = database.listTrips(); + handler.post(new Runnable() { + @Override public void run() { + if (tripList == null) return; + tripList.removeAllViews(); + for (final TripDatabase.TripSummary trip : trips) { + TextView row = tripRow(trip); + row.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { showTrip(trip); } + }); + tripList.addView(row, new LinearLayout.LayoutParams(-1, 82)); + } + } + }); + } + }, "mg-trip-list-refresh").start(); + } + + private String trackerStatusText() { + android.content.SharedPreferences prefs = getSharedPreferences("trip_tracker", MODE_PRIVATE); + String status = prefs.getString("status", "Tracker starts automatically after boot"); + boolean gps = prefs.getBoolean("gps_ready", false); + return (gps ? "GPS READY" : "GPS WAITING") + " • " + status; + } + + private Button actionButton(String label, View.OnClickListener listener) { + Button button = new Button(this); + button.setText(label); + button.setTextSize(12); + button.setAllCaps(false); + button.setTextColor(ACCENT); + button.setMinHeight(0); + button.setMinimumHeight(0); + button.setPadding(4, 0, 4, 0); + button.setBackgroundColor(PANEL_ALT); + button.setOnClickListener(listener); + return button; + } + + private TextView text(String value, int size, int color, int style) { + TextView view = new TextView(this); + view.setText(value); + view.setTextSize(size); + view.setTextColor(color); + view.setTypeface(Typeface.create("sans-serif", style)); + return view; + } + + private static String formatDuration(long millis) { + long minutes = Math.max(0, millis / 60000L); + if (minutes < 60) return String.format(Locale.US, "%dm", minutes); + return String.format(Locale.US, "%dh %02dm", minutes / 60, minutes % 60); + } +}