Recorded vehicle data export
"); + JSONObject all = new JSONObject(exportJson(tripId)); + JSONObject tables = all.optJSONObject("tables"); + if (tables != null) { + java.util.IteratorNo rows
"); return; } + JSONObject first = rows.optJSONObject(0); + if (first == null) return; + java.util.List| ").append(escapeHtml(column)).append(" | "); + html.append("
|---|
| ").append(escapeHtml(String.valueOf(row.opt(column)))).append(" | "); + html.append("
No GPS route recorded.
"); return; } + double minLat = Double.MAX_VALUE, maxLat = -Double.MAX_VALUE, minLon = Double.MAX_VALUE, maxLon = -Double.MAX_VALUE; + for (int i = 0; i < points.length(); i++) { + JSONObject p = points.optJSONObject(i); if (p == null) continue; + double lat = p.optDouble("latitude", 0), lon = p.optDouble("longitude", 0); + minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLon = Math.min(minLon, lon); maxLon = Math.max(maxLon, lon); + } + double latSpan = Math.max(0.000001, maxLat - minLat), lonSpan = Math.max(0.000001, maxLon - minLon); + StringBuilder path = new StringBuilder(); + for (int i = 0; i < points.length(); i++) { + JSONObject p = points.optJSONObject(i); if (p == null) continue; + double x = 10 + 780 * (p.optDouble("longitude", 0) - minLon) / lonSpan; + double y = 170 - 150 * (p.optDouble("latitude", 0) - minLat) / latSpan; + path.append(i == 0 ? "M" : " L").append(String.format(java.util.Locale.US, "%.1f %.1f", x, y)); + } + html.append(""); + } + + private static void appendSpeedSvg(StringBuilder html, JSONArray samples) throws JSONException { + if (samples == null || samples.length() < 2) { html.append("No speed samples recorded.
"); return; } + double max = 1d; + for (int i = 0; i < samples.length(); i++) { + JSONObject sample = samples.optJSONObject(i); + if (sample != null) max = Math.max(max, sample.optDouble("speed_kph", 0)); + } + StringBuilder path = new StringBuilder(); + for (int i = 0; i < samples.length(); i++) { + JSONObject sample = samples.optJSONObject(i); if (sample == null) continue; + double x = 10 + 780d * i / Math.max(1, samples.length() - 1); + double y = 170 - 150d * sample.optDouble("speed_kph", 0) / max; + path.append(i == 0 ? "M" : " L").append(String.format(java.util.Locale.US, "%.1f %.1f", x, y)); + } + html.append(""); + } + + private static String escapeHtml(String value) { + if (value == null) return ""; + return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + + private static void exportTable(SQLiteDatabase db, String table, JSONObject target) + throws JSONException { + exportTable(db, table, target, null); + } + + private static void exportTable(SQLiteDatabase db, String table, JSONObject target, String where) + throws JSONException { + JSONArray rows = new JSONArray(); + Cursor cursor = db.query(table, null, where, null, null, null, "id ASC"); + try { + String[] columns = cursor.getColumnNames(); + while (cursor.moveToNext()) { + JSONObject row = new JSONObject(); + for (int i = 0; i < columns.length; i++) { + if (cursor.isNull(i)) { + row.put(columns[i], JSONObject.NULL); + } else { + switch (cursor.getType(i)) { + case Cursor.FIELD_TYPE_INTEGER: row.put(columns[i], cursor.getLong(i)); break; + case Cursor.FIELD_TYPE_FLOAT: + double value = cursor.getDouble(i); + row.put(columns[i], Double.isNaN(value) || Double.isInfinite(value) + ? JSONObject.NULL : value); + break; + case Cursor.FIELD_TYPE_BLOB: row.put(columns[i], "[blob]"); break; + default: row.put(columns[i], cursor.getString(i)); break; + } + } + } + rows.put(row); + } + } finally { + cursor.close(); + } + target.put(table, rows); + } + @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE trips (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + @@ -118,6 +342,27 @@ final class TripDatabase extends SQLiteOpenHelper { "FOREIGN KEY(trip_id) REFERENCES trips(id) ON DELETE CASCADE)"); db.execSQL("CREATE INDEX IF NOT EXISTS trip_samples_trip_time ON trip_samples(trip_id, timestamp)"); } + if (oldVersion < 4) { + // Existing installations recorded the raw condition-service speed + // before the dashboard compensation was introduced. Bring those + // rows into the same units as newly recorded drives. + db.execSQL("UPDATE trips SET top_speed_kph = top_speed_kph * 1.03"); + db.execSQL("UPDATE trip_points SET speed_kph = speed_kph * 1.03 WHERE speed_kph IS NOT NULL"); + db.execSQL("UPDATE trip_samples SET speed_kph = speed_kph * 1.03 WHERE speed_kph IS NOT NULL"); + db.execSQL("UPDATE regen_events SET peak_speed_kph = peak_speed_kph * 1.03"); + db.execSQL("UPDATE trip_samples SET energy_kwh = (" + + "SELECT MAX(previous.energy_kwh) FROM trip_samples previous " + + "WHERE previous.trip_id = trip_samples.trip_id " + + "AND previous.id <= trip_samples.id) " + + "WHERE energy_kwh IS NOT NULL"); + // Reconstruct summaries from the raw cumulative counter when the + // old final sample was a transient zero/reset. + db.execSQL("UPDATE trips SET energy_end_kwh = (" + + "SELECT MAX(energy_kwh) FROM trip_samples " + + "WHERE trip_samples.trip_id = trips.id) " + + "WHERE EXISTS (SELECT 1 FROM trip_samples " + + "WHERE trip_samples.trip_id = trips.id AND energy_kwh IS NOT NULL)"); + } } synchronized long startTrip(long startedAt, EnergyActivity.Sample sample) { @@ -144,13 +389,20 @@ final class TripDatabase extends SQLiteOpenHelper { db.beginTransaction(); try { db.execSQL("UPDATE trips SET " + - "end_soc = ?, end_range_km = ?, energy_end_kwh = ?, " + + "end_soc = ?, end_range_km = ?, " + + // The OEM counter can briefly reset to zero while the vehicle + // transitions to Park. Preserve the highest valid cumulative + // value so the final parked sample cannot erase drive energy. + "energy_end_kwh = CASE WHEN ? IS NULL THEN energy_end_kwh " + + "WHEN energy_end_kwh IS NULL OR ? > energy_end_kwh THEN ? " + + "ELSE energy_end_kwh END, " + "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), nullableFloat(sample.total), nullableFloat(sample.total), safe(sample.speed), safe(sample.volts), Math.max(0f, distanceMeters), Math.max(0L, movingMillis), 1, point == null ? 0 : 1, tripId}); @@ -174,13 +426,15 @@ final class TripDatabase extends SQLiteOpenHelper { 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)}); + // A final parked read is sometimes a transient zero/reset from the OEM + // service. Keep the largest cumulative counter recorded for this trip. + db.execSQL("UPDATE trips SET end_time = ?, end_soc = ?, end_range_km = ?, " + + "energy_end_kwh = CASE WHEN ? IS NULL THEN energy_end_kwh " + + "WHEN energy_end_kwh IS NULL OR ? > energy_end_kwh THEN ? " + + "ELSE energy_end_kwh END WHERE id = ? AND end_time IS NULL", + new Object[]{endedAt, nullableFloat(sample.soc), nullableInt(sample.range), + nullableFloat(sample.total), nullableFloat(sample.total), + nullableFloat(sample.total), tripId}); } synchronized boolean addRegenEvent(long tripId, long startedAt, long endedAt, @@ -192,24 +446,24 @@ final class TripDatabase extends SQLiteOpenHelper { double efficiency = energy > 0.000001d && range > 0d ? range / energy : 0d; db.beginTransaction(); try { - // Personal Best is global across completed and current drives. The - // per-trip best below is retained for the trip report, but it must - // not make a large event on a later trip look like a new record when - // an earlier drive already recovered more energy. + // Personal Best is global across completed and current drives, ranked + // by the recovered range the car reports (the metric that most + // reflects a single strong brake). When range is unavailable, the + // energy counter remains the fallback metric. double oldGlobalEnergy = 0d; double oldGlobalRange = 0d; Cursor global = db.rawQuery( "SELECT energy_kwh, range_km FROM regen_events " + - "ORDER BY energy_kwh DESC, range_km DESC LIMIT 1", null); + "ORDER BY range_km DESC, energy_kwh DESC LIMIT 1", null); try { if (global.moveToFirst()) { oldGlobalEnergy = global.getDouble(0); oldGlobalRange = global.getDouble(1); } } finally { global.close(); } - boolean personalBest = energy > 0.000001d - ? energy > oldGlobalEnergy + 0.000001d - : oldGlobalEnergy <= 0.000001d && range > oldGlobalRange + 0.000001d; + boolean personalBest = range > 0.000001d + ? range > oldGlobalRange + 0.000001d + : energy > oldGlobalEnergy + 0.000001d; double oldBestEnergy = 0d; double oldBestRange = 0d; @@ -222,12 +476,11 @@ final class TripDatabase extends SQLiteOpenHelper { oldBestRange = best.getDouble(1); } } finally { best.close(); } - // A Personal Best is one complete braking event. Prefer the event with - // the most recovered kWh; if the OEM energy counter is unavailable, - // fall back to the event with the greatest recovered range. - boolean better = energy > oldBestEnergy + 0.000001d || - (energy <= 0.000001d && oldBestEnergy <= 0.000001d && - range > oldBestRange + 0.000001d); + // Per-trip Best uses the same range-first ranking as the global + // record so the displayed metric stays consistent across pages. + boolean better = range > 0.000001d + ? range > oldBestRange + 0.000001d + : energy > oldBestEnergy + 0.000001d; ContentValues event = new ContentValues(); event.put("trip_id", tripId); @@ -350,9 +603,28 @@ final class TripDatabase extends SQLiteOpenHelper { putFloat(values, "speed_kph", sample.speed); putFloat(values, "soc", sample.soc); putFloat(values, "volts", sample.volts); - putFloat(values, "energy_kwh", sample.total); - putFloat(values, "regen_energy_kwh", sample.regenEnergyKwh); - putFloat(values, "regen_range_km", sample.regenRangeKm); + // Consumption is a cumulative OEM counter. Store the running maximum + // so a stale/reset read at the end of a trip cannot make the graph dip + // to zero or make the summary report zero energy. + float energy = sample.total; + float regenEnergy = sample.regenEnergyKwh; + float regenRange = sample.regenRangeKm; + Cursor previous = db.rawQuery("SELECT MAX(energy_kwh), MAX(regen_energy_kwh), " + + "MAX(regen_range_km) FROM trip_samples WHERE trip_id = ?", + new String[]{String.valueOf(tripId)}); + try { + if (previous.moveToFirst()) { + if (!previous.isNull(0) && !Float.isNaN(energy) && !Float.isInfinite(energy)) + energy = Math.max(energy, previous.getFloat(0)); + if (!previous.isNull(1) && !Float.isNaN(regenEnergy) && !Float.isInfinite(regenEnergy)) + regenEnergy = Math.max(regenEnergy, previous.getFloat(1)); + if (!previous.isNull(2) && !Float.isNaN(regenRange) && !Float.isInfinite(regenRange)) + regenRange = Math.max(regenRange, previous.getFloat(2)); + } + } finally { previous.close(); } + putFloat(values, "energy_kwh", energy); + putFloat(values, "regen_energy_kwh", regenEnergy); + putFloat(values, "regen_range_km", regenRange); db.insert("trip_samples", null, values); } @@ -372,7 +644,7 @@ final class TripDatabase extends SQLiteOpenHelper { Cursor best = getReadableDatabase().query("trips", new String[]{"best_regen_energy_kwh", "best_regen_range_km", "best_regen_km_per_kwh"}, "end_time IS NOT NULL AND regen_event_count > 0", null, null, null, - "best_regen_energy_kwh DESC, best_regen_range_km DESC", "1"); + "best_regen_range_km DESC, best_regen_energy_kwh DESC", "1"); try { if (best.moveToFirst()) { bestEnergy = best.getDouble(0); @@ -537,7 +809,11 @@ final class TripDatabase extends SQLiteOpenHelper { } double reportedEnergyUsed() { - return valid(energyStartKwh) && valid(energyEndKwh) + // Trust the trip header first. A stale "zero" parked read cannot + // make the headline statistic read 0.00 kWh while the chart still + // shows the correct consumption, because addSample/finishTrip now + // store the running maximum of the OEM counter. + return valid(energyStartKwh) && valid(energyEndKwh) && energyEndKwh >= energyStartKwh ? Math.max(0d, energyEndKwh - energyStartKwh) : Double.NaN; } @@ -586,4 +862,20 @@ final class TripDatabase extends SQLiteOpenHelper { this.bestRegenKmPerKwh = bestRegenKmPerKwh; } } + synchronized Summary summaryForTrip(long tripId) { + SQLiteDatabase db = getReadableDatabase(); + Cursor c = db.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), " + + "COALESCE(SUM(regen_energy_kwh),0), COALESCE(SUM(regen_range_km),0), " + + "COALESCE(SUM(regen_event_count),0) " + + "FROM trips WHERE id = ?", + new String[] { String.valueOf(tripId) }); + try { + if (c.moveToFirst()) return new Summary(c.getInt(0), c.getDouble(1), c.getLong(2), + c.getDouble(3), c.getDouble(4), c.getDouble(5), c.getInt(6), 0d, 0d, 0d); + return new Summary(0, 0d, 0L, 0d, 0d, 0d, 0, 0d, 0d, 0d); + } finally { c.close(); } + } } diff --git a/src/cloud/molberg/mgutility/TripMapActivity.java b/src/cloud/molberg/mgutility/TripMapActivity.java new file mode 100644 index 0000000..327e8c1 --- /dev/null +++ b/src/cloud/molberg/mgutility/TripMapActivity.java @@ -0,0 +1,68 @@ +package cloud.molberg.mgutility; + +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.util.List; + +/** Full-page interactive map for a selected drive. */ +public final class TripMapActivity extends AnimatedActivity { + static final String EXTRA_TRIP_ID = "trip_id"; + private TripDatabase database; + private RouteMapView map; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + immersive(); + database = new TripDatabase(this); + setContentView(buildUi()); + loadRoute(); + } + + @Override public void onDestroy() { + if (database != null) database.close(); + super.onDestroy(); + } + + private void immersive() { + getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + android.view.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.setBackgroundColor(UiTheme.BACKGROUND); + map = new RouteMapView(this); + root.addView(map, new LinearLayout.LayoutParams(-1, 0, 1)); + LinearLayout bar = new LinearLayout(this); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.setPadding(20, 0, 20, 0); + TextView hint = UiTheme.text(this, "Drag to pan • pinch to zoom", 11, UiTheme.MUTED, android.graphics.Typeface.NORMAL); + bar.addView(hint, new LinearLayout.LayoutParams(0, 58, 1)); + Button close = UiTheme.button(this, "BACK TO DRIVE", new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }, false); + bar.addView(close, new LinearLayout.LayoutParams(170, 44)); + root.addView(bar, new LinearLayout.LayoutParams(-1, 58)); + return root; + } + + private void loadRoute() { + final long tripId = getIntent().getLongExtra(EXTRA_TRIP_ID, TripDatabase.NO_TRIP); + if (tripId == TripDatabase.NO_TRIP) return; + new Thread(new Runnable() { @Override public void run() { + final List