feat: full mg-utility v0.3.0 update
- Charging: arrival briefing + geofence + automation rules - Audio: adaptive leveling manager + raw samples activity + speed audio curve - Display: brightness schedule + scheduler + widgets panel overlay - Trips: charts, database, tracking service, map activity - Theming: config store, theme editor, UI theme expansion - UX: control panel overlay + soundboard + settings overhaul - Tests: AdaptiveAudioCurveTest, BrightnessScheduleTest - Manifest: new permissions and queries for added features - README + THIRD_PARTY_NOTICES refreshed
This commit is contained in:
1 parent
891831f08f
commit
bb6255c45b
34 files changed
+4168
-216
No files matched your search
@@ -44,16 +44,20 @@
|
||||
<activity android:name=".SpeedTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".ChargingActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".TripsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".RawSamplesActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".TripMapActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SoundboardActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".DebugActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".VehicleSettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".KeyRemappingActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SpeedAudioActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".AdaptiveAudioLevelingActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".CustomThemeEditorActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".CustomThemeEditActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".ControlPanelSettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SetupWizardActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".ArrivalGeofenceActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<service android:name=".TripTrackingService" android:enabled="true" android:exported="false" android:stopWithTask="false" android:foregroundServiceType="location" />
|
||||
<service android:name=".MediaNotificationListener" android:label="MG Utility media information" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" android:exported="true">
|
||||
<intent-filter><action android:name="android.service.notification.NotificationListenerService" /></intent-filter>
|
||||
@@ -79,6 +83,7 @@
|
||||
<data android:scheme="package" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver android:name=".BrightnessScheduler" android:enabled="true" android:exported="false" />
|
||||
<provider
|
||||
android:name=".VehicleDataProvider"
|
||||
android:authorities="cloud.molberg.mgutility.vehicle"
|
||||
|
||||
@@ -63,6 +63,7 @@ The app does not require an internet connection for its core dashboard or local
|
||||
- Android `HOME` intent support: choose MG Utility as the default Home app when the head unit offers that option.
|
||||
- Full-width music panel with notification-based media title, artist, album art, progress, and playback controls.
|
||||
- Configurable themes, palettes, fonts, home-screen options, and visualizer settings.
|
||||
- Automatic daily screen-brightness schedule with smooth fade-in/fade-out (see Settings → Appearance → Screen brightness).
|
||||
- Swipe-up app drawer populated from the user's pinned applications.
|
||||
- Swipe-down control panel with configurable quick controls, sliders, toggles, and shortcuts.
|
||||
- Physical key remapping for supported foreground actions, with short, long, double, and repeat gestures.
|
||||
@@ -101,8 +102,12 @@ The app does not require an internet connection for its core dashboard or local
|
||||
- Local top-five acceleration leaderboard; records remain on the device.
|
||||
- Soundboard for locked, booted, regeneration-best, and battery-threshold events.
|
||||
- Speed-reactive audio with configurable clip, speed range, pitch, playback rate, volume, and playback mode.
|
||||
- Adaptive audio leveling with three configurable speed/multiplier points; manual media-volume changes remain the reference level.
|
||||
- Optional live music visualizer using the Android audio FFT callback.
|
||||
- Spectrum Bars, Oscilloscope, and Speed Gauge Ring visualizer effects.
|
||||
- Spectrum Bars, Oscilloscope, Speed Gauge Ring, and Ferrofluid visualizer effects.
|
||||
- Ferrofluid uses the Robert Leitl WebGL2 simulation as a transparent background layer;
|
||||
Android playback FFT bass energy drives its audio response. Devices without WebGL2
|
||||
automatically use the bundled GLES shader fallback.
|
||||
- Configurable visualizer framerate, subject to the head unit's supported capture rate.
|
||||
|
||||
### Settings and backup
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Third-party notices
|
||||
|
||||
## Ferrofluid
|
||||
|
||||
The Ferrofluid music visualizer includes adapted shader techniques and code from
|
||||
[robert-leitl/ferrofluid](https://github.com/robert-leitl/ferrofluid).
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Robert Leitl
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,73 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
/** Pure three-point speed-to-volume curve for adaptive audio leveling. */
|
||||
public final class AdaptiveAudioCurve {
|
||||
private AdaptiveAudioCurve() { }
|
||||
|
||||
/**
|
||||
* Returns a volume multiplier percentage for the supplied speed. Values at
|
||||
* and below level 1 use level 1, values at and above level 3 use level 3,
|
||||
* and the two spans between them are blended linearly.
|
||||
*/
|
||||
public static float multiplierPercent(float speedKph,
|
||||
int level1SpeedKph, int level1Percent,
|
||||
int level2SpeedKph, int level2Percent,
|
||||
int level3SpeedKph, int level3Percent) {
|
||||
if (!finite(speedKph)) speedKph = 0f;
|
||||
if (speedKph <= level1SpeedKph) return level1Percent;
|
||||
if (speedKph < level2SpeedKph) {
|
||||
return interpolate(speedKph, level1SpeedKph, level2SpeedKph,
|
||||
level1Percent, level2Percent);
|
||||
}
|
||||
if (speedKph < level3SpeedKph) {
|
||||
return interpolate(speedKph, level2SpeedKph, level3SpeedKph,
|
||||
level2Percent, level3Percent);
|
||||
}
|
||||
return level3Percent;
|
||||
}
|
||||
|
||||
/** Applies a percentage multiplier to a driver's unmodified volume step. */
|
||||
public static int targetVolume(int baseVolume, int minimum, int maximum,
|
||||
float multiplierPercent) {
|
||||
if (maximum <= minimum) return minimum;
|
||||
int safeBase = clamp(baseVolume, minimum, maximum);
|
||||
float multiplier = finite(multiplierPercent) ? multiplierPercent / 100f : 1f;
|
||||
int target = minimum + Math.round((safeBase - minimum) * multiplier);
|
||||
return clamp(target, minimum, maximum);
|
||||
}
|
||||
|
||||
/** Moves no more than one hardware volume notch toward an automatic target. */
|
||||
public static int stepToward(int current, int target, int minimum, int maximum) {
|
||||
int safeCurrent = clamp(current, minimum, maximum);
|
||||
int safeTarget = clamp(target, minimum, maximum);
|
||||
if (safeTarget > safeCurrent) return safeCurrent + 1;
|
||||
if (safeTarget < safeCurrent) return safeCurrent - 1;
|
||||
return safeCurrent;
|
||||
}
|
||||
|
||||
/** Infers the unmodified driver reference from a manual audible-volume change. */
|
||||
public static float referenceFraction(float audibleFraction, float multiplierPercent) {
|
||||
float audible = finite(audibleFraction) ? clamp(audibleFraction, 0f, 1f) : 0f;
|
||||
float multiplier = finite(multiplierPercent) ? multiplierPercent / 100f : 1f;
|
||||
return clamp(audible / Math.max(0.01f, multiplier), 0f, 1f);
|
||||
}
|
||||
|
||||
private static float interpolate(float value, float start, float end,
|
||||
float startValue, float endValue) {
|
||||
if (end <= start) return endValue;
|
||||
float progress = (value - start) / (end - start);
|
||||
return startValue + (endValue - startValue) * progress;
|
||||
}
|
||||
|
||||
private static int clamp(int value, int minimum, int maximum) {
|
||||
return Math.max(minimum, Math.min(maximum, value));
|
||||
}
|
||||
|
||||
private static float clamp(float value, float minimum, float maximum) {
|
||||
return Math.max(minimum, Math.min(maximum, value));
|
||||
}
|
||||
|
||||
private static boolean finite(float value) {
|
||||
return !Float.isNaN(value) && !Float.isInfinite(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Bundle;
|
||||
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.SeekBar;
|
||||
import android.widget.Switch;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
/** Settings for the three-point adaptive media-volume curve. */
|
||||
public final class AdaptiveAudioLevelingActivity extends AnimatedActivity {
|
||||
private Switch enabled;
|
||||
private final SeekBar[] audio = new SeekBar[3];
|
||||
private final SeekBar[] speed = new SeekBar[3];
|
||||
private final TextView[] audioValue = new TextView[3];
|
||||
private final TextView[] speedValue = new TextView[3];
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
UiTheme.applyFontScale(this);
|
||||
setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
|
||||
immersive();
|
||||
setContentView(buildUi());
|
||||
}
|
||||
|
||||
@Override public void onWindowFocusChanged(boolean focused) {
|
||||
super.onWindowFocusChanged(focused);
|
||||
if (focused) immersive();
|
||||
}
|
||||
|
||||
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() {
|
||||
AdaptiveAudioLevelingManager.Config cfg = AdaptiveAudioLevelingManager.config(this);
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(28, 16, 28, 16);
|
||||
root.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
|
||||
LinearLayout bar = new LinearLayout(this);
|
||||
bar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
bar.addView(UiTheme.title(this, "ADAPTIVE AUDIO LEVELING", 26),
|
||||
new LinearLayout.LayoutParams(0, 58, 1));
|
||||
Button save = UiTheme.button(this, "SAVE & APPLY", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { saveAll(); }
|
||||
}, true);
|
||||
bar.addView(save, new LinearLayout.LayoutParams(190, 58));
|
||||
Button back = UiTheme.backButton(this, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { finish(); }
|
||||
});
|
||||
LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(120, 58);
|
||||
backParams.setMargins(12, 0, 0, 0);
|
||||
bar.addView(back, backParams);
|
||||
root.addView(bar);
|
||||
|
||||
TextView intro = text("Keeps your chosen media volume, then gently scales it as road speed changes. The three speed points blend smoothly, so there are no sudden volume jumps.",
|
||||
12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
intro.setPadding(4, 4, 4, 10);
|
||||
root.addView(intro);
|
||||
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.setFillViewport(true);
|
||||
LinearLayout list = new LinearLayout(this);
|
||||
list.setOrientation(LinearLayout.VERTICAL);
|
||||
list.setBackground(UiTheme.surface(UiTheme.SURFACE, 12));
|
||||
|
||||
enabled = new Switch(this);
|
||||
enabled.setText("ADJUST MEDIA VOLUME WHILE DRIVING");
|
||||
enabled.setTextColor(UiTheme.TEXT);
|
||||
enabled.setTextSize(14);
|
||||
enabled.setChecked(cfg.enabled);
|
||||
list.addView(card("FEATURE", enabled));
|
||||
|
||||
addLevel(list, 0, cfg.level1AudioPercent, cfg.level1SpeedKph,
|
||||
"Used at and below this speed");
|
||||
addLevel(list, 1, cfg.level2AudioPercent, cfg.level2SpeedKph,
|
||||
"Blends from Level 1 to this point");
|
||||
addLevel(list, 2, cfg.level3AudioPercent, cfg.level3SpeedKph,
|
||||
"Used at and above this speed");
|
||||
|
||||
TextView footer = text("100% leaves your chosen volume unchanged. For example, 90% makes it slightly quieter and 110% makes it slightly louder. Automatic changes ramp one volume notch at a time; steering-wheel changes remain immediate and become the new reference volume.",
|
||||
11, UiTheme.MUTED, Typeface.NORMAL);
|
||||
footer.setPadding(12, 12, 12, 14);
|
||||
list.addView(footer);
|
||||
|
||||
scroll.addView(list);
|
||||
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
return root;
|
||||
}
|
||||
|
||||
private void addLevel(LinearLayout parent, final int index, int audioPercent,
|
||||
int speedKph, String hint) {
|
||||
LinearLayout group = new LinearLayout(this);
|
||||
group.setOrientation(LinearLayout.VERTICAL);
|
||||
group.setPadding(14, 10, 14, 10);
|
||||
group.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10));
|
||||
|
||||
TextView heading = text("LEVEL " + (index + 1), 13, UiTheme.TEXT, Typeface.BOLD);
|
||||
group.addView(heading);
|
||||
TextView description = text(hint, 10, UiTheme.MUTED, Typeface.NORMAL);
|
||||
description.setPadding(0, 1, 0, 5);
|
||||
group.addView(description);
|
||||
|
||||
audio[index] = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(audio[index]);
|
||||
audio[index].setMax(AdaptiveAudioLevelingManager.MAX_AUDIO_PERCENT -
|
||||
AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT);
|
||||
audio[index].setProgress(AdaptiveAudioLevelingManager.clampAudio(audioPercent) -
|
||||
AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT);
|
||||
audio[index].setContentDescription("Level " + (index + 1) + " audio multiplier");
|
||||
audioValue[index] = valueLabel(formatAudio(audioPercent));
|
||||
audio[index].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
|
||||
audioValue[index].setText(formatAudio(audioPercent(index)));
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar bar) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar bar) { }
|
||||
});
|
||||
group.addView(sliderRow("AUDIO LEVEL", audio[index], audioValue[index]));
|
||||
|
||||
speed[index] = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(speed[index]);
|
||||
speed[index].setMax(AdaptiveAudioLevelingManager.MAX_SPEED_KPH);
|
||||
speed[index].setProgress(AdaptiveAudioLevelingManager.clampSpeed(speedKph));
|
||||
speed[index].setContentDescription("Level " + (index + 1) + " speed");
|
||||
speedValue[index] = valueLabel(formatSpeed(speedKph));
|
||||
speed[index].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
|
||||
speedValue[index].setText(formatSpeed(bar.getProgress()));
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar bar) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar bar) { }
|
||||
});
|
||||
group.addView(sliderRow("SPEED", speed[index], speedValue[index]));
|
||||
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
|
||||
params.setMargins(8, 8, 8, 0);
|
||||
parent.addView(group, params);
|
||||
}
|
||||
|
||||
private View card(String label, View control) {
|
||||
LinearLayout card = new LinearLayout(this);
|
||||
card.setOrientation(LinearLayout.VERTICAL);
|
||||
card.setPadding(14, 10, 14, 10);
|
||||
card.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10));
|
||||
card.addView(text(label, 12, UiTheme.TEXT, Typeface.BOLD));
|
||||
card.addView(control);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
|
||||
params.setMargins(8, 8, 8, 0);
|
||||
card.setLayoutParams(params);
|
||||
return card;
|
||||
}
|
||||
|
||||
private View sliderRow(String label, SeekBar slider, TextView value) {
|
||||
LinearLayout row = new LinearLayout(this);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
TextView name = text(label, 11, UiTheme.MUTED, Typeface.BOLD);
|
||||
row.addView(name, new LinearLayout.LayoutParams(125, 44));
|
||||
row.addView(slider, new LinearLayout.LayoutParams(0, 44, 1));
|
||||
row.addView(value, new LinearLayout.LayoutParams(105, 44));
|
||||
return row;
|
||||
}
|
||||
|
||||
private TextView valueLabel(String value) {
|
||||
TextView label = text(value, 11, UiTheme.RED, Typeface.BOLD);
|
||||
label.setGravity(Gravity.CENTER);
|
||||
return label;
|
||||
}
|
||||
|
||||
private void saveAll() {
|
||||
int speed1 = speed[0].getProgress();
|
||||
int speed2 = speed[1].getProgress();
|
||||
int speed3 = speed[2].getProgress();
|
||||
if (speed1 >= speed2 || speed2 >= speed3) {
|
||||
Toast.makeText(this, "Level speeds must increase from Level 1 to Level 3",
|
||||
Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
AdaptiveAudioLevelingManager.save(this, enabled.isChecked(),
|
||||
audioPercent(0), speed1, audioPercent(1), speed2, audioPercent(2), speed3);
|
||||
Toast.makeText(this, "Adaptive audio leveling saved", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private int audioPercent(int index) {
|
||||
return AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT + audio[index].getProgress();
|
||||
}
|
||||
|
||||
private static String formatAudio(int percent) {
|
||||
return String.format(java.util.Locale.US, "%.2f× (%d%%)", percent / 100f, percent);
|
||||
}
|
||||
|
||||
private static String formatSpeed(int speedKph) { return speedKph + " km/h"; }
|
||||
|
||||
private TextView text(String value, int size, int color, int style) {
|
||||
TextView view = new TextView(this);
|
||||
view.setText(value);
|
||||
view.setTextSize(size * 1.25f);
|
||||
view.setTextColor(color);
|
||||
view.setTypeface(Typeface.create("sans-serif", style));
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.media.AudioManager;
|
||||
import android.os.Build;
|
||||
import android.os.SystemClock;
|
||||
|
||||
/** Applies a speed-sensitive multiplier to the driver's media-volume setting. */
|
||||
public final class AdaptiveAudioLevelingManager {
|
||||
public static final String PREFS = "adaptive_audio_leveling";
|
||||
|
||||
private static final String KEY_ENABLED = "adaptive_enabled";
|
||||
private static final String KEY_LEVEL_1_AUDIO = "adaptive_level_1_audio";
|
||||
private static final String KEY_LEVEL_1_SPEED = "adaptive_level_1_speed";
|
||||
private static final String KEY_LEVEL_2_AUDIO = "adaptive_level_2_audio";
|
||||
private static final String KEY_LEVEL_2_SPEED = "adaptive_level_2_speed";
|
||||
private static final String KEY_LEVEL_3_AUDIO = "adaptive_level_3_audio";
|
||||
private static final String KEY_LEVEL_3_SPEED = "adaptive_level_3_speed";
|
||||
|
||||
public static final int MIN_AUDIO_PERCENT = 50;
|
||||
public static final int MAX_AUDIO_PERCENT = 150;
|
||||
public static final int MAX_SPEED_KPH = 200;
|
||||
public static final int DEFAULT_LEVEL_1_AUDIO = 90;
|
||||
public static final int DEFAULT_LEVEL_1_SPEED = 20;
|
||||
public static final int DEFAULT_LEVEL_2_AUDIO = 100;
|
||||
public static final int DEFAULT_LEVEL_2_SPEED = 70;
|
||||
public static final int DEFAULT_LEVEL_3_AUDIO = 110;
|
||||
public static final int DEFAULT_LEVEL_3_SPEED = 110;
|
||||
private static final long AUTOMATIC_STEP_INTERVAL_MS = 750L;
|
||||
private static final long VOLUME_WRITE_SETTLE_MS = 600L;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static float baseFraction = Float.NaN;
|
||||
private static float lastAppliedFraction = Float.NaN;
|
||||
private static float lastMultiplier = 1f;
|
||||
private static float fractionBeforeLastWrite = Float.NaN;
|
||||
private static long lastAutomaticStepAt;
|
||||
private static long lastVolumeWriteAt;
|
||||
private static int cachedMgMinimum = -1;
|
||||
private static int cachedMgMaximum = -1;
|
||||
|
||||
private AdaptiveAudioLevelingManager() { }
|
||||
|
||||
public static final class Config {
|
||||
public final boolean enabled;
|
||||
public final int level1AudioPercent;
|
||||
public final int level1SpeedKph;
|
||||
public final int level2AudioPercent;
|
||||
public final int level2SpeedKph;
|
||||
public final int level3AudioPercent;
|
||||
public final int level3SpeedKph;
|
||||
|
||||
Config(boolean enabled, int level1AudioPercent, int level1SpeedKph,
|
||||
int level2AudioPercent, int level2SpeedKph,
|
||||
int level3AudioPercent, int level3SpeedKph) {
|
||||
this.enabled = enabled;
|
||||
this.level1AudioPercent = clampAudio(level1AudioPercent);
|
||||
this.level1SpeedKph = Math.min(MAX_SPEED_KPH - 2, clampSpeed(level1SpeedKph));
|
||||
this.level2AudioPercent = clampAudio(level2AudioPercent);
|
||||
this.level2SpeedKph = Math.max(this.level1SpeedKph + 1,
|
||||
Math.min(MAX_SPEED_KPH - 1, clampSpeed(level2SpeedKph)));
|
||||
this.level3AudioPercent = clampAudio(level3AudioPercent);
|
||||
this.level3SpeedKph = Math.max(this.level2SpeedKph + 1,
|
||||
clampSpeed(level3SpeedKph));
|
||||
}
|
||||
|
||||
public float multiplierPercent(float speedKph) {
|
||||
return AdaptiveAudioCurve.multiplierPercent(speedKph,
|
||||
level1SpeedKph, level1AudioPercent,
|
||||
level2SpeedKph, level2AudioPercent,
|
||||
level3SpeedKph, level3AudioPercent);
|
||||
}
|
||||
}
|
||||
|
||||
public static Config config(Context context) {
|
||||
if (context == null) return defaults();
|
||||
SharedPreferences p = preferences(context);
|
||||
return new Config(p.getBoolean(KEY_ENABLED, false),
|
||||
p.getInt(KEY_LEVEL_1_AUDIO, DEFAULT_LEVEL_1_AUDIO),
|
||||
p.getInt(KEY_LEVEL_1_SPEED, DEFAULT_LEVEL_1_SPEED),
|
||||
p.getInt(KEY_LEVEL_2_AUDIO, DEFAULT_LEVEL_2_AUDIO),
|
||||
p.getInt(KEY_LEVEL_2_SPEED, DEFAULT_LEVEL_2_SPEED),
|
||||
p.getInt(KEY_LEVEL_3_AUDIO, DEFAULT_LEVEL_3_AUDIO),
|
||||
p.getInt(KEY_LEVEL_3_SPEED, DEFAULT_LEVEL_3_SPEED));
|
||||
}
|
||||
|
||||
public static void save(Context context, boolean enabled,
|
||||
int level1AudioPercent, int level1SpeedKph,
|
||||
int level2AudioPercent, int level2SpeedKph,
|
||||
int level3AudioPercent, int level3SpeedKph) {
|
||||
if (context == null) return;
|
||||
Config safe = new Config(enabled, level1AudioPercent, level1SpeedKph,
|
||||
level2AudioPercent, level2SpeedKph, level3AudioPercent, level3SpeedKph);
|
||||
preferences(context).edit()
|
||||
.putBoolean(KEY_ENABLED, safe.enabled)
|
||||
.putInt(KEY_LEVEL_1_AUDIO, safe.level1AudioPercent)
|
||||
.putInt(KEY_LEVEL_1_SPEED, safe.level1SpeedKph)
|
||||
.putInt(KEY_LEVEL_2_AUDIO, safe.level2AudioPercent)
|
||||
.putInt(KEY_LEVEL_2_SPEED, safe.level2SpeedKph)
|
||||
.putInt(KEY_LEVEL_3_AUDIO, safe.level3AudioPercent)
|
||||
.putInt(KEY_LEVEL_3_SPEED, safe.level3SpeedKph)
|
||||
.apply();
|
||||
if (!safe.enabled) stopAndRestore(context);
|
||||
}
|
||||
|
||||
public static boolean shouldPoll(Context context) {
|
||||
return config(context).enabled;
|
||||
}
|
||||
|
||||
/** Called by the always-on vehicle worker whenever a fresh speed is available. */
|
||||
public static void updateSpeed(Context context, float speedKph) {
|
||||
if (context == null || Float.isNaN(speedKph) || Float.isInfinite(speedKph)) return;
|
||||
Config cfg = config(context);
|
||||
if (!cfg.enabled) {
|
||||
stopAndRestore(context);
|
||||
return;
|
||||
}
|
||||
synchronized (LOCK) {
|
||||
VolumeState volume = readVolume(context);
|
||||
if (volume == null) return;
|
||||
float multiplier = cfg.multiplierPercent(Math.max(0f, speedKph)) / 100f;
|
||||
float currentFraction = volume.fraction();
|
||||
float tolerance = Math.max(0.01f, 0.55f / volume.range());
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
|
||||
if (Float.isNaN(baseFraction)) {
|
||||
// The volume in place when the feature starts is the driver's base.
|
||||
baseFraction = currentFraction;
|
||||
} else if (Float.isNaN(lastAppliedFraction) ||
|
||||
Math.abs(currentFraction - lastAppliedFraction) > tolerance) {
|
||||
// Some MG mixers briefly return the value from immediately before
|
||||
// our last acknowledged write. Wait for that write to settle rather
|
||||
// than mistaking it for steering-wheel input.
|
||||
boolean staleOwnWrite = lastVolumeWriteAt > 0L &&
|
||||
now - lastVolumeWriteAt < VOLUME_WRITE_SETTLE_MS &&
|
||||
!Float.isNaN(fractionBeforeLastWrite) &&
|
||||
Math.abs(currentFraction - fractionBeforeLastWrite) <= tolerance;
|
||||
if (staleOwnWrite) return;
|
||||
// A volume key/knob changed the stream after our last write. Treat
|
||||
// the newly selected audible value as authoritative and infer the
|
||||
// corresponding unmodified base for subsequent speed changes.
|
||||
baseFraction = AdaptiveAudioCurve.referenceFraction(currentFraction,
|
||||
multiplier * 100f);
|
||||
lastAutomaticStepAt = now;
|
||||
lastVolumeWriteAt = 0L;
|
||||
}
|
||||
|
||||
float targetFraction = clampFraction(baseFraction * multiplier);
|
||||
int target = volume.fromFraction(targetFraction);
|
||||
if (target != volume.current) {
|
||||
// The underlying mixer is integer-stepped, so ramp one notch at a
|
||||
// time. Steering-wheel changes bypass this path and remain immediate.
|
||||
if (lastAutomaticStepAt != 0L &&
|
||||
now - lastAutomaticStepAt < AUTOMATIC_STEP_INTERVAL_MS) {
|
||||
lastAppliedFraction = currentFraction;
|
||||
lastMultiplier = multiplier;
|
||||
return;
|
||||
}
|
||||
int next = AdaptiveAudioCurve.stepToward(volume.current, target,
|
||||
volume.minimum, volume.maximum);
|
||||
if (!volume.write(context, next)) return;
|
||||
fractionBeforeLastWrite = currentFraction;
|
||||
lastAppliedFraction = volume.fraction(next);
|
||||
lastAutomaticStepAt = now;
|
||||
lastVolumeWriteAt = now;
|
||||
} else {
|
||||
lastAppliedFraction = currentFraction;
|
||||
}
|
||||
lastMultiplier = multiplier;
|
||||
}
|
||||
}
|
||||
|
||||
/** Restores the driver's unmodified volume when leveling stops. */
|
||||
public static void stopAndRestore(Context context) {
|
||||
if (context == null) return;
|
||||
synchronized (LOCK) {
|
||||
if (Float.isNaN(baseFraction)) return;
|
||||
VolumeState volume = readVolume(context);
|
||||
if (volume != null) {
|
||||
float currentFraction = volume.fraction();
|
||||
float tolerance = Math.max(0.01f, 0.55f / volume.range());
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
boolean staleOwnWrite = lastVolumeWriteAt > 0L &&
|
||||
now - lastVolumeWriteAt < VOLUME_WRITE_SETTLE_MS &&
|
||||
!Float.isNaN(fractionBeforeLastWrite) &&
|
||||
Math.abs(currentFraction - fractionBeforeLastWrite) <= tolerance;
|
||||
if (!Float.isNaN(lastAppliedFraction) &&
|
||||
Math.abs(currentFraction - lastAppliedFraction) > tolerance &&
|
||||
!staleOwnWrite) {
|
||||
baseFraction = AdaptiveAudioCurve.referenceFraction(currentFraction,
|
||||
lastMultiplier * 100f);
|
||||
}
|
||||
int target = volume.fromFraction(baseFraction);
|
||||
if (target != volume.current) volume.write(context, target);
|
||||
}
|
||||
resetSession();
|
||||
}
|
||||
}
|
||||
|
||||
public static int clampAudio(int value) {
|
||||
return Math.max(MIN_AUDIO_PERCENT, Math.min(MAX_AUDIO_PERCENT, value));
|
||||
}
|
||||
|
||||
public static int clampSpeed(int value) {
|
||||
return Math.max(0, Math.min(MAX_SPEED_KPH, value));
|
||||
}
|
||||
|
||||
private static void resetSession() {
|
||||
baseFraction = Float.NaN;
|
||||
lastAppliedFraction = Float.NaN;
|
||||
lastMultiplier = 1f;
|
||||
fractionBeforeLastWrite = Float.NaN;
|
||||
lastAutomaticStepAt = 0L;
|
||||
lastVolumeWriteAt = 0L;
|
||||
}
|
||||
|
||||
private static float clampFraction(float value) {
|
||||
return Math.max(0f, Math.min(1f, value));
|
||||
}
|
||||
|
||||
private static VolumeState readVolume(Context context) {
|
||||
MgServiceBridge bridge = MgServiceBridge.get();
|
||||
try { bridge.ensureBound(context); } catch (Exception ignored) { }
|
||||
int current = bridge.getVolume(MgServiceBridge.VOL_TYPE_MEDIA);
|
||||
int maximum = cachedMgMaximum;
|
||||
int minimum = cachedMgMinimum;
|
||||
if (current >= 0 && maximum <= minimum) {
|
||||
maximum = bridge.getMaxVolume(MgServiceBridge.VOL_TYPE_MEDIA);
|
||||
minimum = bridge.getMinVolume(MgServiceBridge.VOL_TYPE_MEDIA);
|
||||
if (minimum < 0) minimum = 0;
|
||||
if (maximum > minimum) {
|
||||
cachedMgMinimum = minimum;
|
||||
cachedMgMaximum = maximum;
|
||||
}
|
||||
}
|
||||
if (maximum > minimum && current >= minimum && current <= maximum) {
|
||||
return new VolumeState(current, minimum, maximum, true);
|
||||
}
|
||||
|
||||
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (audio == null) return null;
|
||||
try {
|
||||
maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
|
||||
minimum = Build.VERSION.SDK_INT >= 28
|
||||
? audio.getStreamMinVolume(AudioManager.STREAM_MUSIC) : 0;
|
||||
current = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
|
||||
return maximum > minimum ? new VolumeState(current, minimum, maximum, false) : null;
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class VolumeState {
|
||||
final int current;
|
||||
final int minimum;
|
||||
final int maximum;
|
||||
final boolean mgService;
|
||||
|
||||
VolumeState(int current, int minimum, int maximum, boolean mgService) {
|
||||
this.current = current;
|
||||
this.minimum = minimum;
|
||||
this.maximum = maximum;
|
||||
this.mgService = mgService;
|
||||
}
|
||||
|
||||
int range() { return maximum - minimum; }
|
||||
float fraction() { return fraction(current); }
|
||||
float fraction(int value) { return (value - minimum) / (float) range(); }
|
||||
int fromFraction(float value) {
|
||||
return Math.max(minimum, Math.min(maximum,
|
||||
minimum + Math.round(clampFraction(value) * range())));
|
||||
}
|
||||
|
||||
boolean write(Context context, int value) {
|
||||
if (mgService) {
|
||||
return MgServiceBridge.get().setVolume(MgServiceBridge.VOL_TYPE_MEDIA, value);
|
||||
}
|
||||
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (audio == null) return false;
|
||||
try {
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC, value, 0);
|
||||
return true;
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Config defaults() {
|
||||
return new Config(false,
|
||||
DEFAULT_LEVEL_1_AUDIO, DEFAULT_LEVEL_1_SPEED,
|
||||
DEFAULT_LEVEL_2_AUDIO, DEFAULT_LEVEL_2_SPEED,
|
||||
DEFAULT_LEVEL_3_AUDIO, DEFAULT_LEVEL_3_SPEED);
|
||||
}
|
||||
|
||||
private static SharedPreferences preferences(Context context) {
|
||||
return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** Human-readable post-drive summary. Range depletion is intentionally in km. */
|
||||
final class ArrivalBriefing {
|
||||
private ArrivalBriefing() { }
|
||||
|
||||
static String tripText(TripDatabase.TripSummary trip, String location) {
|
||||
if (trip == null) return "Drive completed";
|
||||
StringBuilder text = new StringBuilder();
|
||||
text.append(location == null || location.length() == 0 ? "Drive completed" : "Arrived at " + location);
|
||||
text.append("\n").append(String.format(Locale.US, "%.1f km driven", trip.distanceKm()));
|
||||
text.append(" • ").append(formatDuration(trip.durationMillis()));
|
||||
if (trip.startRangeKm >= 0 && trip.endRangeKm >= 0) {
|
||||
text.append("\nEstimated range depleted: ")
|
||||
.append(String.format(Locale.US, "%.0f km", Math.max(0, trip.startRangeKm - trip.endRangeKm)));
|
||||
}
|
||||
double energy = trip.reportedEnergyUsed();
|
||||
if (!Double.isNaN(energy)) text.append("\nEnergy used: ").append(String.format(Locale.US, "%.2f kWh", energy));
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private static String formatDuration(long millis) {
|
||||
long minutes = Math.max(0L, millis) / 60000L;
|
||||
long hours = minutes / 60L;
|
||||
minutes %= 60L;
|
||||
return hours > 0 ? String.format(Locale.US, "%dh %02dm", hours, minutes)
|
||||
: String.format(Locale.US, "%dm", minutes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Local, user-defined arrival areas. No network/location service is required. */
|
||||
final class ArrivalGeofence {
|
||||
private static final String KEY_JSON = "arrival_geofences";
|
||||
private static final float MIN_RADIUS_M = 50f;
|
||||
private static final float MAX_RADIUS_M = 2000f;
|
||||
|
||||
final String id;
|
||||
final String name;
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
final float radiusM;
|
||||
final boolean enabled;
|
||||
|
||||
ArrivalGeofence(String id, String name, double latitude, double longitude,
|
||||
float radiusM, boolean enabled) {
|
||||
this.id = id == null || id.length() == 0 ? UUID.randomUUID().toString() : id;
|
||||
this.name = name == null || name.trim().length() == 0 ? "Unnamed area" : name.trim();
|
||||
this.latitude = latitude;
|
||||
this.longitude = longitude;
|
||||
this.radiusM = Math.max(MIN_RADIUS_M, Math.min(MAX_RADIUS_M, radiusM));
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
boolean contains(double lat, double lon) {
|
||||
float[] result = new float[1];
|
||||
android.location.Location.distanceBetween(latitude, longitude, lat, lon, result);
|
||||
return result[0] <= radiusM;
|
||||
}
|
||||
|
||||
static List<ArrivalGeofence> load(Context context) {
|
||||
String raw = ConfigStore.of(context).getString(KEY_JSON, "[]");
|
||||
ArrayList<ArrivalGeofence> result = new ArrayList<ArrivalGeofence>();
|
||||
try {
|
||||
JSONArray values = new JSONArray(raw);
|
||||
for (int i = 0; i < values.length(); i++) {
|
||||
JSONObject value = values.optJSONObject(i);
|
||||
if (value == null) continue;
|
||||
result.add(new ArrivalGeofence(value.optString("id"), value.optString("name"),
|
||||
value.optDouble("latitude", 0d), value.optDouble("longitude", 0d),
|
||||
(float) value.optDouble("radius_m", 150d), value.optBoolean("enabled", true)));
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return result;
|
||||
}
|
||||
|
||||
static void save(Context context, List<ArrivalGeofence> input) {
|
||||
JSONArray values = new JSONArray();
|
||||
if (input != null) for (ArrivalGeofence fence : input) {
|
||||
if (fence == null) continue;
|
||||
JSONObject value = new JSONObject();
|
||||
try {
|
||||
value.put("id", fence.id).put("name", fence.name)
|
||||
.put("latitude", fence.latitude).put("longitude", fence.longitude)
|
||||
.put("radius_m", fence.radiusM).put("enabled", fence.enabled);
|
||||
values.put(value);
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
ConfigStore.of(context).sharedPreferences().edit().putString(KEY_JSON, values.toString()).apply();
|
||||
}
|
||||
|
||||
static List<ArrivalGeofence> matches(Context context, double lat, double lon) {
|
||||
ArrayList<ArrivalGeofence> result = new ArrayList<ArrivalGeofence>();
|
||||
for (ArrivalGeofence fence : load(context)) if (fence.enabled && fence.contains(lat, lon)) result.add(fence);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.Location;
|
||||
import android.location.LocationManager;
|
||||
import android.os.Bundle;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Editor for multiple local arrival areas. */
|
||||
public final class ArrivalGeofenceActivity extends AnimatedActivity {
|
||||
private LinearLayout list;
|
||||
private List<ArrivalGeofence> fences;
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
UiTheme.applyFontScale(this);
|
||||
immersive();
|
||||
fences = new ArrayList<ArrivalGeofence>(ArrivalGeofence.load(this));
|
||||
setContentView(buildUi());
|
||||
render();
|
||||
}
|
||||
|
||||
private View buildUi() {
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL); root.setPadding(24, 14, 24, 18);
|
||||
root.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
LinearLayout header = new LinearLayout(this); header.setGravity(Gravity.CENTER_VERTICAL);
|
||||
header.addView(UiTheme.title(this, "ARRIVAL AREAS", 28), new LinearLayout.LayoutParams(0, 56, 1));
|
||||
Button add = UiTheme.button(this, "ADD CURRENT LOCATION", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { addCurrent(); }
|
||||
}, true); header.addView(add, new LinearLayout.LayoutParams(250, 52));
|
||||
Button manual = UiTheme.button(this, "ADD MANUALLY", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { edit(new ArrivalGeofence(null, "New area", 0d, 0d, 150f, true)); }
|
||||
}, false); header.addView(manual, new LinearLayout.LayoutParams(170, 52));
|
||||
Button back = UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } });
|
||||
header.addView(back, new LinearLayout.LayoutParams(130, 52)); root.addView(header);
|
||||
TextView hint = UiTheme.text(this, "Charging price windows are shown only after arriving inside an enabled area. Areas use a configurable radius and can be enabled independently.", 12, UiTheme.MUTED, android.graphics.Typeface.NORMAL);
|
||||
hint.setPadding(0, 10, 0, 12); root.addView(hint, new LinearLayout.LayoutParams(-1, -2));
|
||||
ScrollView scroll = new ScrollView(this); list = new LinearLayout(this); list.setOrientation(LinearLayout.VERTICAL); scroll.addView(list);
|
||||
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); return root;
|
||||
}
|
||||
|
||||
private void render() {
|
||||
list.removeAllViews();
|
||||
if (fences.isEmpty()) { list.addView(UiTheme.text(this, "No arrival areas configured.", 15, UiTheme.MUTED, android.graphics.Typeface.NORMAL)); return; }
|
||||
for (final ArrivalGeofence fence : fences) {
|
||||
LinearLayout row = new LinearLayout(this); row.setGravity(Gravity.CENTER_VERTICAL); row.setPadding(14, 8, 8, 8);
|
||||
row.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10));
|
||||
TextView label = UiTheme.text(this, fence.name + "\n" + String.format(Locale.US, "%.5f, %.5f • %.0f m", fence.latitude, fence.longitude, fence.radiusM), 13, UiTheme.TEXT, android.graphics.Typeface.NORMAL);
|
||||
row.addView(label, new LinearLayout.LayoutParams(0, 62, 1));
|
||||
Button toggle = UiTheme.button(this, fence.enabled ? "ON" : "OFF", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { replace(new ArrivalGeofence(fence.id, fence.name, fence.latitude, fence.longitude, fence.radiusM, !fence.enabled)); }
|
||||
}, fence.enabled); row.addView(toggle, new LinearLayout.LayoutParams(70, 44));
|
||||
Button edit = UiTheme.button(this, "EDIT", new View.OnClickListener() { @Override public void onClick(View v) { edit(fence); } }, false); row.addView(edit, new LinearLayout.LayoutParams(80, 44));
|
||||
Button remove = UiTheme.button(this, "REMOVE", new View.OnClickListener() { @Override public void onClick(View v) { fences.remove(fence); ArrivalGeofence.save(ArrivalGeofenceActivity.this, fences); render(); } }, false); row.addView(remove, new LinearLayout.LayoutParams(105, 44));
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 80); p.setMargins(0, 0, 0, 6); list.addView(row, p);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCurrent() {
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 7001); return;
|
||||
}
|
||||
LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE); Location location = null;
|
||||
try { location = manager == null ? null : manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null && manager != null) location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } catch (Exception ignored) { }
|
||||
if (location == null) {
|
||||
// The always-on tracker may have a newer fix than the provider cache
|
||||
// exposed to this Activity.
|
||||
android.content.SharedPreferences tracker = getSharedPreferences("trip_tracker", MODE_PRIVATE);
|
||||
try {
|
||||
String lat = tracker.getString("last_latitude", "");
|
||||
String lon = tracker.getString("last_longitude", "");
|
||||
if (lat.length() > 0 && lon.length() > 0) {
|
||||
location = new Location("mg-tracker");
|
||||
location.setLatitude(Double.parseDouble(lat));
|
||||
location.setLongitude(Double.parseDouble(lon));
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
if (location == null) { UiTheme.dialog(this).setTitle("Location unavailable").setMessage("Wait for a GPS fix, then try again.").setPositiveButton("OK", null).show(); return; }
|
||||
edit(new ArrivalGeofence(null, "New area", location.getLatitude(), location.getLongitude(), 150f, true));
|
||||
}
|
||||
|
||||
private void edit(final ArrivalGeofence original) {
|
||||
LinearLayout form = new LinearLayout(this); form.setOrientation(LinearLayout.VERTICAL); form.setPadding(20, 4, 20, 0);
|
||||
final EditText name = new EditText(this); name.setHint("Name (e.g. Home)"); name.setText(original.name); form.addView(name);
|
||||
final EditText radius = new EditText(this); radius.setHint("Radius in metres (50–2000)"); radius.setInputType(2 | 8192); radius.setText(String.format(Locale.US, "%.0f", original.radiusM)); form.addView(radius);
|
||||
final EditText coordinates = new EditText(this); coordinates.setHint("latitude, longitude"); coordinates.setText(String.format(Locale.US, "%.6f, %.6f", original.latitude, original.longitude)); form.addView(coordinates);
|
||||
new AlertDialog.Builder(this).setTitle("Arrival area").setView(form).setNegativeButton("CANCEL", null).setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
try {
|
||||
String[] parts = coordinates.getText().toString().split(",");
|
||||
float r = Float.parseFloat(radius.getText().toString());
|
||||
replace(new ArrivalGeofence(original.id, name.getText().toString(), Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()), r, true));
|
||||
} catch (Exception ignored) { UiTheme.dialog(ArrivalGeofenceActivity.this).setTitle("Invalid area").setMessage("Enter coordinates as latitude, longitude and a numeric radius.").setPositiveButton("OK", null).show(); }
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void replace(ArrivalGeofence value) {
|
||||
for (int i = 0; i < fences.size(); i++) if (fences.get(i).id.equals(value.id)) { fences.set(i, value); ArrivalGeofence.save(this, fences); render(); return; }
|
||||
fences.add(value); ArrivalGeofence.save(this, fences); render();
|
||||
}
|
||||
|
||||
private void immersive() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility(5894); }
|
||||
}
|
||||
@@ -18,6 +18,9 @@ public final class BootReceiver extends BroadcastReceiver {
|
||||
if (context == null) return;
|
||||
String action = intent == null ? null : intent.getAction();
|
||||
if (!isStartAction(context, intent, action)) return;
|
||||
// Restore the daily brightness alarm across boot, unlock, updates and
|
||||
// screen/power broadcasts. The scheduler is a no-op when disabled.
|
||||
BrightnessScheduler.rearm(context);
|
||||
|
||||
// Keep the last trigger visible in preferences so an installation can be
|
||||
// diagnosed without attaching a debugger to the head unit. This write is
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Pure-Java automatic brightness schedule and smooth transition math. */
|
||||
public final class BrightnessSchedule {
|
||||
private BrightnessSchedule() { }
|
||||
static final int DEFAULT_PEAK_MINUTES = 7 * 60;
|
||||
static final int DEFAULT_DARK_MINUTES = 21 * 60;
|
||||
static final int DEFAULT_TRANSITION_MINUTES = 10;
|
||||
static final int DEFAULT_PEAK_PERCENT = 100;
|
||||
static final int DEFAULT_DARK_PERCENT = 0;
|
||||
static final int MIN_TRANSITION_MINUTES = 1;
|
||||
static final int MAX_TRANSITION_MINUTES = 60;
|
||||
static final long USER_OVERRIDE_PAUSE_MS = 30L * 60L * 1000L;
|
||||
|
||||
/** Return the target brightness percentage for an epoch timestamp. */
|
||||
public static int compute(long nowMillis, int peakMinutes, int darkMinutes, int transitionMinutes,
|
||||
int peakPercent, int darkPercent, int lastAppliedPercent) {
|
||||
int peak = clamp(peakPercent, 0, 100), dark = clamp(darkPercent, 0, 100);
|
||||
int transition = clamp(transitionMinutes, MIN_TRANSITION_MINUTES, MAX_TRANSITION_MINUTES);
|
||||
int now = minutesOfDay(nowMillis);
|
||||
int peakTime = clamp(peakMinutes, 0, 1439), darkTime = clamp(darkMinutes, 0, 1439);
|
||||
int brightDuration = (darkTime - peakTime + 1440) % 1440;
|
||||
if (brightDuration == 0) return peak;
|
||||
int darkDuration = 1440 - brightDuration;
|
||||
int fadeDown = Math.min(transition, Math.max(1, brightDuration / 2));
|
||||
int fadeUp = Math.min(transition, Math.max(1, darkDuration / 2));
|
||||
int sincePeak = (now - peakTime + 1440) % 1440;
|
||||
if (sincePeak < brightDuration) {
|
||||
if (sincePeak >= brightDuration - fadeDown) {
|
||||
return lerp(peak, dark, smooth(sincePeak - (brightDuration - fadeDown), fadeDown));
|
||||
}
|
||||
return peak;
|
||||
}
|
||||
if (sincePeak >= 1440 - fadeUp) {
|
||||
return lerp(dark, peak, smooth(sincePeak - (1440 - fadeUp), fadeUp));
|
||||
}
|
||||
return dark;
|
||||
}
|
||||
|
||||
public static int minutesOfDay(long epochMillis) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTimeInMillis(epochMillis);
|
||||
return c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
private static float smooth(int distance, int duration) {
|
||||
float t = Math.max(0f, Math.min(1f, (float) distance / (float) Math.max(1, duration)));
|
||||
return t * t * (3f - 2f * t);
|
||||
}
|
||||
|
||||
private static int lerp(int from, int to, float t) { return clamp(Math.round(from + (to - from) * t), 0, 100); }
|
||||
private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
public static String formatMinutes(int minutes) {
|
||||
int value = clamp(minutes, 0, 1439);
|
||||
return String.format(Locale.US, "%02d:%02d", value / 60, value % 60);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.provider.Settings;
|
||||
|
||||
/** Alarm-driven automatic display brightness controller. */
|
||||
public final class BrightnessScheduler extends BroadcastReceiver {
|
||||
static final String ACTION_TICK = "cloud.molberg.mgutility.AUTO_BRIGHTNESS_TICK";
|
||||
private static final int REQUEST = 9182;
|
||||
private static final long TICK_MS = 60_000L;
|
||||
|
||||
/** Rebuild the minute alarm; safe to call after every settings edit or boot. */
|
||||
public static void rearm(Context context) {
|
||||
if (context == null) return;
|
||||
Context app = context.getApplicationContext();
|
||||
AlarmManager alarms = (AlarmManager) app.getSystemService(Context.ALARM_SERVICE);
|
||||
if (alarms == null) return;
|
||||
PendingIntent pending = pendingIntent(app);
|
||||
alarms.cancel(pending);
|
||||
if (!prefs(app).getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false)) return;
|
||||
applyNow(app, System.currentTimeMillis());
|
||||
long next = ((System.currentTimeMillis() / TICK_MS) + 1L) * TICK_MS;
|
||||
if (Build.VERSION.SDK_INT >= 23) alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, next, pending);
|
||||
else alarms.setExact(AlarmManager.RTC_WAKEUP, next, pending);
|
||||
}
|
||||
|
||||
public static void pauseForManualOverride(Context context) {
|
||||
if (context == null) return;
|
||||
prefs(context).edit().putLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL,
|
||||
System.currentTimeMillis() + BrightnessSchedule.USER_OVERRIDE_PAUSE_MS).apply();
|
||||
}
|
||||
|
||||
@Override public void onReceive(Context context, Intent intent) {
|
||||
if (context == null) return;
|
||||
if (ACTION_TICK.equals(intent == null ? null : intent.getAction())) rearm(context);
|
||||
}
|
||||
|
||||
private static void applyNow(Context context, long now) {
|
||||
SharedPreferences p = prefs(context);
|
||||
long overrideUntil = p.getLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL, 0L);
|
||||
if (overrideUntil > now) return;
|
||||
int last = p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, 50);
|
||||
int target = BrightnessSchedule.compute(now,
|
||||
p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES, BrightnessSchedule.DEFAULT_PEAK_MINUTES),
|
||||
p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, BrightnessSchedule.DEFAULT_DARK_MINUTES),
|
||||
p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES, BrightnessSchedule.DEFAULT_TRANSITION_MINUTES),
|
||||
p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_PERCENT, BrightnessSchedule.DEFAULT_PEAK_PERCENT),
|
||||
p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_DARK_PERCENT, BrightnessSchedule.DEFAULT_DARK_PERCENT), last);
|
||||
int system = Math.max(0, Math.min(255, Math.round(target * 255f / 100f)));
|
||||
MgServiceBridge bridge = MgServiceBridge.get();
|
||||
try { bridge.ensureBound(context); } catch (Exception ignored) { }
|
||||
if (!bridge.setBrightness(system)) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT < 23 || Settings.System.canWrite(context)) {
|
||||
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, system);
|
||||
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE,
|
||||
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
p.edit().putInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, target)
|
||||
.putLong(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_TICK_AT, now).apply();
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static PendingIntent pendingIntent(Context context) {
|
||||
Intent intent = new Intent(context, BrightnessScheduler.class).setAction(ACTION_TICK);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
return PendingIntent.getBroadcast(context, REQUEST, intent, flags);
|
||||
}
|
||||
}
|
||||
@@ -313,17 +313,10 @@ public final class ChargingActivity extends AnimatedActivity {
|
||||
}
|
||||
final List<ChargingAutomation.PricePoint> points = loadedPoints;
|
||||
final String error = fetchError;
|
||||
float liveSoc;
|
||||
try {
|
||||
EnergyActivity.VehicleGateway gateway = vehicle;
|
||||
liveSoc = gateway == null ? Float.NaN : gateway.read().soc;
|
||||
} catch (Exception ignored) {
|
||||
liveSoc = Float.NaN;
|
||||
}
|
||||
final ChargingAutomation.Prediction prediction =
|
||||
points.isEmpty() ? null
|
||||
: ChargingAutomation.predictNext(
|
||||
ChargingActivity.this, points, liveSoc, System.currentTimeMillis());
|
||||
ChargingActivity.this, points, System.currentTimeMillis());
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override public void run() {
|
||||
if (isFinishing() || !dialog.isShowing()) return;
|
||||
|
||||
@@ -609,14 +609,12 @@ final class ChargingAutomation {
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the saved rules forward in time and report the next matching start/stop
|
||||
* transitions against the supplied price series. Time-only rules contribute
|
||||
* their deterministic matches; price and SOC rules are evaluated per interval.
|
||||
* When the caller provides a current SOC, charging is assumed to add about
|
||||
* 6.6 kW into a 64 kWh pack so SOC-bound windows can flip during the projection.
|
||||
* Walk price slots forward and report the next charging transitions. This is
|
||||
* deliberately a price-only forecast: arrival planning must not pretend to
|
||||
* know the future SOC, connector state, or time-window state. Non-price rules
|
||||
* (and non-price AND clauses) are ignored for this look-ahead.
|
||||
*/
|
||||
static Prediction predictNext(Context context, List<PricePoint> prices,
|
||||
float currentSoc, long nowMs) {
|
||||
static Prediction predictNext(Context context, List<PricePoint> prices, long nowMs) {
|
||||
long startAt = Long.MAX_VALUE;
|
||||
long stopAt = Long.MAX_VALUE;
|
||||
String startRule = "";
|
||||
@@ -628,13 +626,9 @@ final class ChargingAutomation {
|
||||
}
|
||||
|
||||
List<Rule> rules = loadRules(context);
|
||||
long lastIndexAt = prices.get(prices.size() - 1).timestamp;
|
||||
boolean hasSoc = !Float.isNaN(currentSoc) && !Float.isInfinite(currentSoc)
|
||||
&& currentSoc >= 0f && currentSoc <= 100f;
|
||||
float soc = hasSoc ? currentSoc : 50f;
|
||||
final float perIntervalFraction = 6.6f * (MINUTES_PER_PRICE_POINT / 60f) / 64f * 100f;
|
||||
|
||||
Integer previousDesired = null;
|
||||
// Treat the state immediately before the first visible slot as idle so a
|
||||
// currently-cheap first slot is reported as an actionable START.
|
||||
Integer previousDesired = ACTION_NONE;
|
||||
for (int i = 0; i < prices.size(); i++) {
|
||||
PricePoint point = prices.get(i);
|
||||
long intervalEnd = point.timestamp + MINUTES_PER_PRICE_POINT * 60L * 1000L;
|
||||
@@ -642,38 +636,49 @@ final class ChargingAutomation {
|
||||
String matched = "";
|
||||
for (Rule rule : rules) {
|
||||
if (!rule.enabled) continue;
|
||||
float probe = hasSoc ? soc : (rule.condition == CONDITION_TIME_WINDOW ? soc : 50f);
|
||||
if (probe < 0f || Float.isNaN(probe)) probe = 50f;
|
||||
if (!matches(rule, probe, point.price, point.timestamp)) continue;
|
||||
if (!matchesPriceOnly(rule, point.price)) continue;
|
||||
resolved = rule.action;
|
||||
matched = describe(rule, point.price);
|
||||
}
|
||||
|
||||
if (previousDesired != null && previousDesired != resolved) {
|
||||
if (previousDesired == ACTION_START && intervalEnd > nowMs && startAt == Long.MAX_VALUE) {
|
||||
startAt = intervalEnd;
|
||||
if (resolved == ACTION_START && intervalEnd > nowMs && startAt == Long.MAX_VALUE) {
|
||||
startAt = Math.max(nowMs, point.timestamp);
|
||||
startRule = matched;
|
||||
startPrice = point.price;
|
||||
} else if (previousDesired == ACTION_STOP && intervalEnd > nowMs && stopAt == Long.MAX_VALUE) {
|
||||
stopAt = intervalEnd;
|
||||
} else if (resolved == ACTION_STOP && intervalEnd > nowMs && stopAt == Long.MAX_VALUE) {
|
||||
stopAt = Math.max(nowMs, point.timestamp);
|
||||
stopRule = matched;
|
||||
stopPrice = point.price;
|
||||
}
|
||||
if (startAt != Long.MAX_VALUE && stopAt != Long.MAX_VALUE) break;
|
||||
}
|
||||
previousDesired = resolved;
|
||||
|
||||
if (hasSoc && resolved == ACTION_START) {
|
||||
soc = Math.min(100f, soc + perIntervalFraction);
|
||||
}
|
||||
}
|
||||
|
||||
long horizonMs = lastIndexAt + MINUTES_PER_PRICE_POINT * 60L * 1000L;
|
||||
if (startAt == Long.MAX_VALUE) startAt = horizonMs <= nowMs ? Long.MAX_VALUE : horizonMs;
|
||||
if (stopAt == Long.MAX_VALUE) stopAt = horizonMs <= nowMs ? Long.MAX_VALUE : horizonMs;
|
||||
return new Prediction(startAt, stopAt, startRule, stopRule, startPrice, stopPrice);
|
||||
}
|
||||
|
||||
private static boolean matchesPriceOnly(Rule rule, double price) {
|
||||
boolean primary = isPriceCondition(rule.condition) &&
|
||||
matchesPriceCondition(rule.condition, rule.value, price);
|
||||
if (!primary) return false;
|
||||
for (Condition extra : rule.andConditions) {
|
||||
if (extra == null || !isPriceCondition(extra.condition)) continue;
|
||||
if (!matchesPriceCondition(extra.condition, extra.value, price)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isPriceCondition(int condition) {
|
||||
return condition == CONDITION_PRICE_BELOW || condition == CONDITION_PRICE_ABOVE;
|
||||
}
|
||||
|
||||
private static boolean matchesPriceCondition(int condition, float value, double price) {
|
||||
if (Double.isNaN(price) || Double.isInfinite(price)) return false;
|
||||
return condition == CONDITION_PRICE_BELOW ? price < value : price > value;
|
||||
}
|
||||
|
||||
private static double currentPrice(Context context, long now) {
|
||||
SharedPreferences p = prefs(context);
|
||||
String area = getPriceArea(context);
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Centralized preference store and JSON export/import helper. */
|
||||
public final class ConfigStore {
|
||||
public static final String STORE_NAME = "mg_config";
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
|
||||
/** Pure-JSON variant of {@link #exportJson()} for tests. */
|
||||
public static String exportJson(Map<String, ?> values) throws JSONException {
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", SCHEMA_VERSION);
|
||||
root.put("store", STORE_NAME);
|
||||
JSONObject settings = new JSONObject();
|
||||
for (Map.Entry<String, ?> e : values.entrySet()) {
|
||||
if (!isExportableKey(e.getKey())) continue;
|
||||
settings.put(e.getKey(), e.getValue());
|
||||
}
|
||||
root.put("settings", settings);
|
||||
return root.toString(2);
|
||||
}
|
||||
|
||||
/** Pure-JSON variant of {@link #importJson()} for tests. */
|
||||
public static ImportResult importJsonToMap(String json, java.util.Map<String, Object> sink)
|
||||
throws JSONException {
|
||||
JSONObject root = new JSONObject(json);
|
||||
int schema = root.optInt("schema", -1);
|
||||
if (schema != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported config schema " + schema);
|
||||
JSONObject settings = root.optJSONObject("settings");
|
||||
int count = 0;
|
||||
if (settings != null) {
|
||||
java.util.Iterator<String> keys = settings.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = settings.get(key);
|
||||
if (value instanceof Boolean) sink.put(key, value);
|
||||
else if (value instanceof Integer) sink.put(key, value);
|
||||
else if (value instanceof Long) sink.put(key, value);
|
||||
else if (value instanceof Number) sink.put(key, ((Number) value).floatValue());
|
||||
else if (value instanceof JSONArray || value instanceof JSONObject) sink.put(key, value.toString());
|
||||
else if (value != JSONObject.NULL) sink.put(key, String.valueOf(value));
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return new ImportResult(count);
|
||||
}
|
||||
|
||||
private static final String KEY_MIGRATED = "__migrated__";
|
||||
private static final String KEY_SCHEMA = "__schema__";
|
||||
private static final String[] LEGACY_FILES = {
|
||||
UiTheme.UI_PREFS, "trip_tracker", "vehicle_defaults", "soundboard",
|
||||
"charging_automation", "key_remapping", "speed_reactive_audio", "adaptive_audio_leveling",
|
||||
"map_tile_cache", "speed_test_records", "energy"
|
||||
};
|
||||
private static ConfigStore singleton;
|
||||
private final Context appContext;
|
||||
private final SharedPreferences prefs;
|
||||
|
||||
private ConfigStore(Context context) {
|
||||
appContext = context.getApplicationContext();
|
||||
prefs = appContext.getSharedPreferences(STORE_NAME, Context.MODE_PRIVATE);
|
||||
migrateLegacyIfNeeded();
|
||||
}
|
||||
|
||||
public static synchronized ConfigStore of(Context context) {
|
||||
if (singleton == null) singleton = new ConfigStore(context);
|
||||
return singleton;
|
||||
}
|
||||
|
||||
public String getString(String key, String fallback) { return prefs.getString(key, fallback); }
|
||||
public boolean getBoolean(String key, boolean fallback) { return prefs.getBoolean(key, fallback); }
|
||||
public int getInt(String key, int fallback) { return prefs.getInt(key, fallback); }
|
||||
public long getLong(String key, long fallback) { return prefs.getLong(key, fallback); }
|
||||
public float getFloat(String key, float fallback) { return prefs.getFloat(key, fallback); }
|
||||
public boolean contains(String key) { return prefs.contains(key); }
|
||||
public Map<String, ?> snapshot() { return new HashMap<String, Object>(prefs.getAll()); }
|
||||
/** Number of user-visible keys (internal migration metadata excluded). */
|
||||
public int visibleKeyCount() {
|
||||
int count = 0;
|
||||
for (String key : prefs.getAll().keySet()) if (isExportableKey(key)) count++;
|
||||
return count;
|
||||
}
|
||||
public SharedPreferences sharedPreferences() { return prefs; }
|
||||
|
||||
/** Export all settings to a versioned, diffable JSON document. */
|
||||
public String exportJson() throws JSONException {
|
||||
// Existing screens in older releases still write their legacy preference
|
||||
// file directly. Pull those values in immediately before exporting so
|
||||
// the document always reflects the live app state.
|
||||
refreshFromLegacy();
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", SCHEMA_VERSION);
|
||||
root.put("store", STORE_NAME);
|
||||
JSONObject settings = new JSONObject();
|
||||
for (Map.Entry<String, ?> e : prefs.getAll().entrySet()) {
|
||||
if (isExportableKey(e.getKey())) settings.put(e.getKey(), e.getValue());
|
||||
}
|
||||
root.put("settings", settings);
|
||||
return root.toString(2);
|
||||
}
|
||||
|
||||
public void exportTo(OutputStream out) throws IOException, JSONException {
|
||||
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
|
||||
writer.write(exportJson());
|
||||
writer.flush();
|
||||
writer.close();
|
||||
}
|
||||
|
||||
/** Replace current settings with values from a JSON export. */
|
||||
public ImportResult importJson(String json) throws JSONException {
|
||||
JSONObject root = new JSONObject(json);
|
||||
int schema = root.optInt("schema", -1);
|
||||
if (schema != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported config schema " + schema);
|
||||
JSONObject settings = root.optJSONObject("settings");
|
||||
SharedPreferences.Editor editor = prefs.edit().clear();
|
||||
int count = 0;
|
||||
if (settings != null) {
|
||||
java.util.Iterator<String> keys = settings.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = settings.get(key);
|
||||
if (value instanceof Boolean) editor.putBoolean(key, ((Boolean) value).booleanValue());
|
||||
else if (value instanceof Integer) editor.putInt(key, ((Integer) value).intValue());
|
||||
else if (value instanceof Long) editor.putLong(key, ((Long) value).longValue());
|
||||
else if (value instanceof Number) editor.putFloat(key, ((Number) value).floatValue());
|
||||
else if (value instanceof JSONArray || value instanceof JSONObject) editor.putString(key, value.toString());
|
||||
else if (value != JSONObject.NULL) editor.putString(key, String.valueOf(value));
|
||||
count++;
|
||||
}
|
||||
}
|
||||
editor.putBoolean(KEY_MIGRATED, true).putInt(KEY_SCHEMA, SCHEMA_VERSION).apply();
|
||||
syncToLegacy();
|
||||
return new ImportResult(count);
|
||||
}
|
||||
|
||||
public ImportResult importFrom(InputStream in) throws IOException, JSONException {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
|
||||
StringBuilder json = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) json.append(line).append('\n');
|
||||
reader.close();
|
||||
return importJson(json.toString());
|
||||
}
|
||||
|
||||
public static final class ImportResult {
|
||||
public final int keysApplied;
|
||||
public ImportResult(int keysApplied) { this.keysApplied = keysApplied; }
|
||||
}
|
||||
|
||||
public void resetAll() {
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
for (String key : prefs.getAll().keySet()) if (!key.startsWith("__")) editor.remove(key);
|
||||
editor.apply();
|
||||
// Keep older runtime code (which may still read a legacy file) in sync
|
||||
// with the reset so defaults take effect immediately on every screen.
|
||||
for (String name : LEGACY_FILES) {
|
||||
if (STORE_NAME.equals(name)) continue;
|
||||
appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().apply();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Integer> sectionSummary() {
|
||||
Map<String, Integer> result = new HashMap<String, Integer>();
|
||||
for (String key : prefs.getAll().keySet()) {
|
||||
if (key.startsWith("__")) continue;
|
||||
String section = sectionFor(key);
|
||||
Integer count = result.get(section);
|
||||
result.put(section, count == null ? 1 : count + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<String> sections() {
|
||||
ArrayList<String> sections = new ArrayList<String>();
|
||||
Collections.addAll(sections, "Appearance", "Pinned apps", "Home screen", "Trip tracker",
|
||||
"Audio", "Charging automation", "Vehicle defaults", "Key remapping", "Map cache", "0–100 leaderboard");
|
||||
return Collections.unmodifiableList(sections);
|
||||
}
|
||||
|
||||
public static String sectionFor(String key) {
|
||||
if (key == null) return "Other";
|
||||
int separator = key.indexOf("::");
|
||||
if (separator >= 0) key = key.substring(separator + 2);
|
||||
if (key.equals("theme") || key.equals("theme_id") || key.equals("custom_themes") || key.equals("font_scale") || key.startsWith("custom_color_") || key.startsWith("page_")) return "Appearance";
|
||||
if (key.equals("launcher_pins")) return "Pinned apps";
|
||||
if (key.startsWith("home_") || key.equals("apps_reorder_enabled")) return "Home screen";
|
||||
if (key.startsWith("trip_") || key.startsWith("arrival_")) return "Trip tracker";
|
||||
if (key.startsWith("soundboard") || key.startsWith("speed_") || key.startsWith("adaptive_") || key.startsWith("music_")) return "Audio";
|
||||
if (key.startsWith("charging_") || key.contains("automation")) return "Charging automation";
|
||||
if (key.startsWith("vehicle_") || key.equals("drive_mode") || key.equals("regenerative_level")) return "Vehicle defaults";
|
||||
if (key.startsWith("key_") || key.contains("remap")) return "Key remapping";
|
||||
if (key.startsWith("map_") || key.contains("tile")) return "Map cache";
|
||||
return "Other";
|
||||
}
|
||||
|
||||
private void migrateLegacyIfNeeded() {
|
||||
if (prefs.getBoolean(KEY_MIGRATED, false)) return;
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
for (String name : LEGACY_FILES) {
|
||||
if (STORE_NAME.equals(name)) continue;
|
||||
for (Map.Entry<String, ?> e : appContext.getSharedPreferences(name, Context.MODE_PRIVATE).getAll().entrySet()) {
|
||||
String key = scopedKey(name, e.getKey());
|
||||
if (prefs.contains(key)) continue;
|
||||
Object v = e.getValue();
|
||||
if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue());
|
||||
else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue());
|
||||
else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue());
|
||||
else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue());
|
||||
else editor.putString(key, String.valueOf(v));
|
||||
}
|
||||
}
|
||||
editor.putBoolean(KEY_MIGRATED, true).putInt(KEY_SCHEMA, SCHEMA_VERSION).apply();
|
||||
}
|
||||
|
||||
/** Merge values from legacy files, allowing newer edits made by old call sites. */
|
||||
private void refreshFromLegacy() {
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
for (String name : LEGACY_FILES) {
|
||||
if (STORE_NAME.equals(name)) continue;
|
||||
for (Map.Entry<String, ?> e : appContext.getSharedPreferences(name, Context.MODE_PRIVATE).getAll().entrySet()) {
|
||||
String key = scopedKey(name, e.getKey());
|
||||
Object v = e.getValue();
|
||||
if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue());
|
||||
else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue());
|
||||
else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue());
|
||||
else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue());
|
||||
else editor.putString(key, String.valueOf(v));
|
||||
}
|
||||
}
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
/** Mirror imported values back to every legacy file so existing screens update immediately. */
|
||||
private void syncToLegacy() {
|
||||
Map<String, ?> values = prefs.getAll();
|
||||
for (String name : LEGACY_FILES) {
|
||||
if (STORE_NAME.equals(name)) continue;
|
||||
SharedPreferences.Editor editor = appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit();
|
||||
for (Map.Entry<String, ?> e : values.entrySet()) {
|
||||
if (!isExportableKey(e.getKey())) continue;
|
||||
int separator = e.getKey().indexOf("::");
|
||||
if (separator <= 0) continue;
|
||||
String target = e.getKey().substring(0, separator);
|
||||
String key = e.getKey().substring(separator + 2);
|
||||
if (!name.equals(target)) continue;
|
||||
Object v = e.getValue();
|
||||
if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue());
|
||||
else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue());
|
||||
else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue());
|
||||
else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue());
|
||||
else editor.putString(key, String.valueOf(v));
|
||||
}
|
||||
editor.apply();
|
||||
}
|
||||
}
|
||||
|
||||
private static String scopedKey(String file, String key) { return file + "::" + key; }
|
||||
|
||||
/** Internal migration metadata is excluded, plus transient energy baseline. */
|
||||
private static boolean isExportableKey(String key) {
|
||||
if (key == null || key.startsWith("__")) return false;
|
||||
return !key.startsWith("energy::");
|
||||
}
|
||||
}
|
||||
@@ -508,6 +508,12 @@ final class ControlPanelOverlay extends FrameLayout {
|
||||
|
||||
private void applySliderValue(String id, int target) {
|
||||
if ("brightness".equals(id)) {
|
||||
// A deliberate slider move temporarily wins over the automatic
|
||||
// schedule, then normal scheduling resumes after 30 minutes.
|
||||
if (activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE)
|
||||
.getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false)) {
|
||||
BrightnessScheduler.pauseForManualOverride(activity);
|
||||
}
|
||||
int system = Math.max(0, Math.min(255, Math.round(target * 255f / 100f)));
|
||||
MgServiceBridge bridge = MgServiceBridge.get();
|
||||
try { bridge.ensureBound(activity); } catch (Exception ignored) { }
|
||||
|
||||
@@ -249,6 +249,7 @@ public final class CustomThemeEditActivity extends AnimatedActivity {
|
||||
sliderLabel.setPadding(6, 12, 0, 4);
|
||||
rightContent.addView(sliderLabel, new LinearLayout.LayoutParams(-1, 28));
|
||||
SeekBar slider = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(100);
|
||||
slider.setProgress(42);
|
||||
slider.setPadding(0, 4, 0, 12);
|
||||
|
||||
@@ -52,6 +52,15 @@ public class EnergyActivity extends AnimatedActivity {
|
||||
* compile-time dependency on the OEM APK while still using its exported service.
|
||||
*/
|
||||
static class VehicleGateway {
|
||||
/**
|
||||
* The condition-service speed is the unrounded road-speed signal. MG's
|
||||
* instrument cluster intentionally displays a small positive speedometer
|
||||
* tolerance, so showing the raw value makes the dashboard appear 1–3 km/h
|
||||
* slow at normal motorway speeds. Keep the correction at the telemetry
|
||||
* boundary so the home gauge, drive logger, exports, and speed tools all
|
||||
* use the same value.
|
||||
*/
|
||||
static final float DISPLAY_SPEED_FACTOR = 1.03f;
|
||||
static final String HUB_TOKEN="com.saicmotor.sdk.vehiclesettings.IHubService";
|
||||
static final String SETTING_TOKEN="com.saicmotor.sdk.vehiclesettings.IVehicleSettingService";
|
||||
static final String CHARGING_TOKEN="com.saicmotor.sdk.vehiclesettings.IVehicleChargingService";
|
||||
@@ -250,7 +259,7 @@ public class EnergyActivity extends AnimatedActivity {
|
||||
|
||||
Sample read(){
|
||||
float soc=f(charging,CHARGING_TOKEN,3),
|
||||
speed=f(condition,CONDITION_TOKEN,3),
|
||||
speed=calibratedSpeed(f(condition,CONDITION_TOKEN,3)),
|
||||
volts=f(charging,CHARGING_TOKEN,64),
|
||||
total=f(charging,CHARGING_TOKEN,75),
|
||||
regenEnergyStart=f(charging,CHARGING_TOKEN,
|
||||
@@ -283,7 +292,12 @@ public class EnergyActivity extends AnimatedActivity {
|
||||
}
|
||||
|
||||
/** Fast, read-only speed signal used by the dashboard's 100 ms instrument loop. */
|
||||
float readSpeed(){ return f(condition, CONDITION_TOKEN, 3); }
|
||||
float readSpeed(){ return calibratedSpeed(f(condition, CONDITION_TOKEN, 3)); }
|
||||
|
||||
static float calibratedSpeed(float value) {
|
||||
if (Float.isNaN(value) || Float.isInfinite(value) || value < 0f) return value;
|
||||
return Math.min(300f, value * DISPLAY_SPEED_FACTOR);
|
||||
}
|
||||
|
||||
private static boolean validCounter(float value){
|
||||
return !Float.isNaN(value) && !Float.isInfinite(value) && value >= 0f;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,10 @@ public final class MusicPlayerManager {
|
||||
private static final Handler MAIN = new Handler(Looper.getMainLooper());
|
||||
private static MediaController.Callback callback;
|
||||
private static MediaController watching;
|
||||
private static MediaController clockController;
|
||||
private static long clockPositionMs;
|
||||
private static long clockPositionAt;
|
||||
private static long lastReportedPositionMs;
|
||||
private static final Runnable FLUSH = new Runnable() {
|
||||
@Override public void run() {
|
||||
notifyImmediate();
|
||||
@@ -51,8 +55,11 @@ public final class MusicPlayerManager {
|
||||
public final String title, artist;
|
||||
public final Bitmap art;
|
||||
public final boolean playing;
|
||||
State(String title, String artist, Bitmap art, boolean playing) {
|
||||
public final long positionMs, durationMs;
|
||||
State(String title, String artist, Bitmap art, boolean playing, long positionMs, long durationMs) {
|
||||
this.title = title; this.artist = artist; this.art = art; this.playing = playing;
|
||||
this.positionMs = Math.max(0L, positionMs);
|
||||
this.durationMs = Math.max(0L, durationMs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,16 +106,65 @@ public final class MusicPlayerManager {
|
||||
}
|
||||
public static State state() {
|
||||
synchronized (LOCK) {
|
||||
if (controller == null) return new State("NO MEDIA PLAYING", "", null, false);
|
||||
if (controller == null) return new State("NO MEDIA PLAYING", "", null, false, 0L, 0L);
|
||||
MediaMetadata metadata = controller.getMetadata();
|
||||
String title = metadata == null ? "NOW PLAYING" : metadata.getString(MediaMetadata.METADATA_KEY_TITLE);
|
||||
String artist = metadata == null ? "" : metadata.getString(MediaMetadata.METADATA_KEY_ARTIST);
|
||||
if (TextUtils.isEmpty(title)) title = "NOW PLAYING";
|
||||
if (TextUtils.isEmpty(artist)) artist = controller.getPackageName();
|
||||
Bitmap art = metadata == null ? null : metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
|
||||
Bitmap art = null;
|
||||
if (metadata != null) {
|
||||
art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
|
||||
if (art == null) art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ART);
|
||||
if (art == null) art = metadata.getBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON);
|
||||
}
|
||||
PlaybackState playback = controller.getPlaybackState();
|
||||
boolean playing = playback != null && playback.getState() == PlaybackState.STATE_PLAYING;
|
||||
return new State(title, artist, art, playing);
|
||||
boolean playing = playback != null && (playback.getState() == PlaybackState.STATE_PLAYING
|
||||
|| playback.getState() == PlaybackState.STATE_BUFFERING);
|
||||
long duration = metadata == null ? 0L : metadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
|
||||
long reportedPosition = playback == null ? 0L : Math.max(0L, playback.getPosition());
|
||||
long position = reportedPosition;
|
||||
long now = android.os.SystemClock.elapsedRealtime();
|
||||
if (playing) {
|
||||
float speed = playback == null ? 1f : playback.getPlaybackSpeed();
|
||||
if (speed <= 0f) speed = 1f;
|
||||
long updateTime = playback == null ? 0L : playback.getLastPositionUpdateTime();
|
||||
if (updateTime > 0L && now >= updateTime && now - updateTime < 120000L) {
|
||||
// This is the authoritative path. Do not mix it with the
|
||||
// fallback anchor or the position can oscillate backwards.
|
||||
position = reportedPosition + (long) ((now - updateTime) * speed);
|
||||
clockController = controller;
|
||||
clockPositionMs = position;
|
||||
clockPositionAt = now;
|
||||
lastReportedPositionMs = reportedPosition;
|
||||
} else {
|
||||
// A few players omit lastPositionUpdateTime and return the
|
||||
// same position forever. Advance a local clock, re-anchoring
|
||||
// only for an actual seek/track jump (not normal stale reads).
|
||||
boolean newController = clockController != controller || clockPositionAt == 0L;
|
||||
long localPosition = newController ? reportedPosition
|
||||
: clockPositionMs + (long) ((now - clockPositionAt) * speed);
|
||||
boolean seekOrTrackJump = !newController
|
||||
&& (Math.abs(reportedPosition - lastReportedPositionMs) > 3000L
|
||||
|| Math.abs(reportedPosition - localPosition) > 3000L);
|
||||
if (newController || seekOrTrackJump) {
|
||||
clockController = controller;
|
||||
clockPositionMs = reportedPosition;
|
||||
clockPositionAt = now;
|
||||
localPosition = reportedPosition;
|
||||
}
|
||||
position = localPosition;
|
||||
lastReportedPositionMs = reportedPosition;
|
||||
}
|
||||
} else {
|
||||
position = reportedPosition;
|
||||
clockController = controller;
|
||||
clockPositionMs = position;
|
||||
clockPositionAt = now;
|
||||
lastReportedPositionMs = reportedPosition;
|
||||
}
|
||||
if (duration > 0L) position = Math.min(position, duration);
|
||||
return new State(title, artist, art, playing, position, duration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,15 +199,31 @@ public final class MusicPlayerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Seek the active media session to an absolute position in milliseconds. */
|
||||
public static void seekTo(long positionMs) {
|
||||
synchronized (LOCK) {
|
||||
if (controller == null) return;
|
||||
controller.getTransportControls().seekTo(Math.max(0L, positionMs));
|
||||
}
|
||||
}
|
||||
|
||||
private static void choose(List<MediaController> values) {
|
||||
MediaController next;
|
||||
synchronized (LOCK) {
|
||||
controller = null;
|
||||
next = null;
|
||||
long nextUpdate = Long.MIN_VALUE;
|
||||
if (values != null) for (MediaController value : values) {
|
||||
PlaybackState state = value.getPlaybackState();
|
||||
if (state != null && state.getState() == PlaybackState.STATE_PLAYING) { next = value; break; }
|
||||
if (next == null) next = value;
|
||||
boolean active = state != null && (state.getState() == PlaybackState.STATE_PLAYING
|
||||
|| state.getState() == PlaybackState.STATE_BUFFERING);
|
||||
long update = state == null ? Long.MIN_VALUE : state.getLastPositionUpdateTime();
|
||||
if (active && (next == null || nextUpdate == Long.MIN_VALUE || update > nextUpdate)) {
|
||||
next = value;
|
||||
nextUpdate = update;
|
||||
} else if (next == null) {
|
||||
next = value;
|
||||
}
|
||||
}
|
||||
controller = next;
|
||||
if (watching != null && watching != next) {
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.graphics.Typeface;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TableLayout;
|
||||
import android.widget.TableRow;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Full-page raw sample viewer with a sticky header. */
|
||||
public final class RawSamplesActivity extends AnimatedActivity {
|
||||
static final String EXTRA_TRIP_ID = "trip_id";
|
||||
private static final String[] HEADERS = {
|
||||
"TIME", "SPEED (km/h)", "SOC (%)", "VOLTS (V)", "ENERGY (kWh)",
|
||||
"REGEN (kWh)", "RANGE (km)", "Δ REGEN (kWh)", "REGEN EVENT"
|
||||
};
|
||||
private static final int[] COLUMN_WEIGHTS = { 12, 12, 8, 8, 12, 12, 12, 14, 24 };
|
||||
private TripDatabase database;
|
||||
private final Handler handler = new Handler();
|
||||
private TableLayout bodyTable;
|
||||
private TextView statusView;
|
||||
private long renderedThemeVersion;
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
UiTheme.applyFontScale(this);
|
||||
immersive();
|
||||
database = new TripDatabase(this);
|
||||
setContentView(buildUi());
|
||||
renderedThemeVersion = UiTheme.version();
|
||||
load();
|
||||
}
|
||||
|
||||
@Override public void onDestroy() {
|
||||
if (database != null) database.close();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
UiTheme.refreshTheme(this);
|
||||
if (UiTheme.version() != renderedThemeVersion && bodyTable != null) {
|
||||
setContentView(buildUi());
|
||||
renderedThemeVersion = UiTheme.version();
|
||||
load();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
root.setPadding(24, 14, 24, 18);
|
||||
LinearLayout bar = new LinearLayout(this);
|
||||
bar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
bar.addView(UiTheme.title(this, "RAW SAMPLE LOG", 26), new LinearLayout.LayoutParams(0, 56, 1));
|
||||
Button back = UiTheme.backButton(this, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { finish(); }
|
||||
});
|
||||
LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(130, 56);
|
||||
bp.setMargins(10, 0, 0, 0);
|
||||
bar.addView(back, bp);
|
||||
root.addView(bar);
|
||||
TextView subtitle = UiTheme.text(this,
|
||||
"Per-sample vehicle counters • green rows are regeneration events",
|
||||
12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
root.addView(subtitle, new LinearLayout.LayoutParams(-1, -2));
|
||||
statusView = UiTheme.text(this, "Loading samples…", 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
statusView.setPadding(0, 8, 0, 8);
|
||||
root.addView(statusView, new LinearLayout.LayoutParams(-1, -2));
|
||||
|
||||
TableLayout headerTable = new TableLayout(this);
|
||||
headerTable.setBackgroundColor(UiTheme.SURFACE);
|
||||
headerTable.setPadding(0, 12, 0, 12);
|
||||
headerTable.addView(buildHeaderRow());
|
||||
root.addView(headerTable, new LinearLayout.LayoutParams(-1, -2));
|
||||
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.setFillViewport(true);
|
||||
bodyTable = new TableLayout(this);
|
||||
bodyTable.setBackgroundColor(UiTheme.SURFACE);
|
||||
scroll.addView(bodyTable, new ScrollView.LayoutParams(-1, -2));
|
||||
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
return root;
|
||||
}
|
||||
|
||||
private TableRow buildHeaderRow() {
|
||||
TableRow row = new TableRow(this);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
for (int i = 0; i < HEADERS.length; i++) {
|
||||
TextView cell = new TextView(this);
|
||||
cell.setText(HEADERS[i]);
|
||||
cell.setTextSize(11 * 1.25f);
|
||||
cell.setTextColor(UiTheme.MUTED);
|
||||
cell.setTypeface(Typeface.create("sans-serif", Typeface.BOLD));
|
||||
cell.setGravity(i == 0 || i == HEADERS.length - 1 ? Gravity.LEFT : Gravity.RIGHT);
|
||||
cell.setPadding(12, 6, 12, 6);
|
||||
row.addView(cell, weightedColumn(i));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private void load() {
|
||||
final long tripId = getIntent().getLongExtra(EXTRA_TRIP_ID, TripDatabase.NO_TRIP);
|
||||
if (tripId == TripDatabase.NO_TRIP) {
|
||||
statusView.setText("No drive selected");
|
||||
return;
|
||||
}
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final List<TripDatabase.TripSample> samples = database.getSamples(tripId);
|
||||
final List<TripDatabase.RegenEvent> events = database.getRegenEvents(tripId);
|
||||
handler.post(new Runnable() { @Override public void run() {
|
||||
renderBody(samples, events);
|
||||
} });
|
||||
} }, "mg-trip-raw-full").start();
|
||||
}
|
||||
|
||||
private void renderBody(List<TripDatabase.TripSample> samples, List<TripDatabase.RegenEvent> events) {
|
||||
bodyTable.removeAllViews();
|
||||
if (samples == null || samples.isEmpty()) {
|
||||
statusView.setText("No raw samples recorded for this drive.");
|
||||
return;
|
||||
}
|
||||
statusView.setText(samples.size() + " samples • " + (events == null ? 0 : events.size()) + " regen events");
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss", Locale.US);
|
||||
boolean[] shown = new boolean[events == null ? 0 : events.size()];
|
||||
TripDatabase.TripSample previous = null;
|
||||
for (int i = 0; i < samples.size(); i++) {
|
||||
TripDatabase.TripSample sample = samples.get(i);
|
||||
double delta = 0d;
|
||||
if (previous != null && !Double.isNaN(previous.regenEnergyKwh) && !Double.isNaN(sample.regenEnergyKwh)) {
|
||||
delta = sample.regenEnergyKwh - previous.regenEnergyKwh;
|
||||
}
|
||||
previous = sample;
|
||||
String eventText = "";
|
||||
int eventIndex = -1;
|
||||
if (events != null) {
|
||||
for (int j = 0; j < events.size(); j++) {
|
||||
TripDatabase.RegenEvent event = events.get(j);
|
||||
if (sample.timestamp >= event.startTime && sample.timestamp <= event.endTime) {
|
||||
eventIndex = j;
|
||||
if (!shown[j]) {
|
||||
shown[j] = true;
|
||||
eventText = String.format(Locale.US, "#%d +%.4f kWh\n+%.3f km range",
|
||||
j + 1, event.energyKwh, event.rangeKm);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
bodyTable.addView(buildSampleRow(fmt, sample, delta, i, eventText,
|
||||
eventIndex >= 0 || delta > 0.0001d));
|
||||
}
|
||||
if (events != null) {
|
||||
for (int i = 0; i < events.size(); i++) if (!shown[i]) {
|
||||
bodyTable.addView(buildEventOnlyRow(events.get(i), i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TableRow buildSampleRow(SimpleDateFormat fmt, TripDatabase.TripSample sample,
|
||||
double delta, int index, String eventText, boolean highlighted) {
|
||||
String[] values = {
|
||||
fmt.format(new Date(sample.timestamp)), speed(sample.speedKph), percent(sample.soc),
|
||||
volts(sample.volts), energy(sample.energyKwh), energy(sample.regenEnergyKwh),
|
||||
range(sample.regenRangeKm), index == 0 ? "—" : deltaValue(delta), eventText
|
||||
};
|
||||
TableRow row = new TableRow(this);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
if (highlighted) row.setBackgroundColor(UiTheme.withAlpha(UiTheme.SUCCESS, 45));
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
TextView cell = new TextView(this);
|
||||
cell.setText(values[i]);
|
||||
cell.setTextSize(11 * 1.25f);
|
||||
cell.setTypeface(Typeface.MONOSPACE);
|
||||
cell.setGravity(i == 0 || i == values.length - 1 ? Gravity.LEFT : Gravity.RIGHT);
|
||||
cell.setPadding(12, 8, 12, 8);
|
||||
cell.setTextColor(highlighted ? UiTheme.SUCCESS : UiTheme.TEXT);
|
||||
row.addView(cell, weightedColumn(i));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private TableRow buildEventOnlyRow(TripDatabase.RegenEvent event, int index) {
|
||||
TableRow row = new TableRow(this);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
row.setBackgroundColor(UiTheme.withAlpha(UiTheme.SUCCESS, 45));
|
||||
for (int i = 0; i < HEADERS.length; i++) {
|
||||
TextView cell = new TextView(this);
|
||||
if (i == HEADERS.length - 1) {
|
||||
cell.setText(String.format(Locale.US, "#%d +%.4f kWh\n+%.3f km range",
|
||||
index + 1, event.energyKwh, event.rangeKm));
|
||||
} else if (i == 0) {
|
||||
cell.setText(new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date(event.startTime)));
|
||||
} else {
|
||||
cell.setText("");
|
||||
}
|
||||
cell.setTextSize(11 * 1.25f);
|
||||
cell.setTypeface(Typeface.MONOSPACE);
|
||||
cell.setTextColor(UiTheme.SUCCESS);
|
||||
cell.setGravity(i == 0 || i == HEADERS.length - 1 ? Gravity.LEFT : Gravity.RIGHT);
|
||||
cell.setPadding(12, 8, 12, 8);
|
||||
row.addView(cell, weightedColumn(i));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private TableRow.LayoutParams weightedColumn(int index) {
|
||||
return new TableRow.LayoutParams(0, -2, COLUMN_WEIGHTS[index]);
|
||||
}
|
||||
|
||||
private static String speed(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.0f km/h", v); }
|
||||
private static String percent(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.1f %%", v); }
|
||||
private static String volts(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.2f V", v); }
|
||||
private static String energy(double v) { return Double.isNaN(v) ? "—" : String.format(Locale.US, "%.4f kWh", v); }
|
||||
private static String range(double v) { return Double.isNaN(v) ? "—" : String.format(Locale.US, "%.3f km", v); }
|
||||
private static String deltaValue(double delta) {
|
||||
if (Double.isNaN(delta) || delta == 0d) return "0.0000 kWh";
|
||||
return String.format(Locale.US, "%+.4f kWh", delta);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ import android.widget.SeekBar;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
import android.app.TimePickerDialog;
|
||||
import android.widget.TimePicker;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -43,8 +45,10 @@ import java.util.Locale;
|
||||
|
||||
/** Categorized settings hub styled after the SAIC head-unit Settings experience. */
|
||||
public final class SettingsActivity extends AnimatedActivity {
|
||||
private static final String[] CATEGORIES = { "Driving", "Charging", "Misc", "Appearance", "Apps" };
|
||||
private static final String[] CATEGORIES = { "Driving", "Charging", "Misc", "Appearance", "Apps", "Config" };
|
||||
private static final String PREF_APPS_REORDER = "apps_reorder_enabled";
|
||||
private static final int REQUEST_EXPORT = 8801;
|
||||
private static final int REQUEST_IMPORT = 8802;
|
||||
private LinearLayout content;
|
||||
private LinearLayout tabs;
|
||||
private GridLayout appsGrid;
|
||||
@@ -154,7 +158,78 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
else if (category == 1) charging();
|
||||
else if (category == 2) misc();
|
||||
else if (category == 3) appearance();
|
||||
else apps();
|
||||
else if (category == 4) apps();
|
||||
else config();
|
||||
}
|
||||
|
||||
/** Centralized settings export/import and reset controls. */
|
||||
private void config() {
|
||||
section("Config", "Export, import, or reset every MG Utility setting");
|
||||
ConfigStore store = ConfigStore.of(this);
|
||||
int keyCount = store.visibleKeyCount();
|
||||
subsection("Transfer", "Move settings between MG Utility installations");
|
||||
content.addView(row("⇧", "Export settings", "Save a versioned JSON file (" + keyCount + " keys)", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("application/json");
|
||||
intent.putExtra(Intent.EXTRA_TITLE, "mg-utility-settings.json");
|
||||
try { startActivityForResult(intent, REQUEST_EXPORT); }
|
||||
catch (Exception e) { Toast.makeText(SettingsActivity.this, "No file picker available", Toast.LENGTH_LONG).show(); }
|
||||
}
|
||||
}));
|
||||
content.addView(row("⇩", "Import settings", "Restore a previously exported JSON file", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("application/json");
|
||||
try { startActivityForResult(intent, REQUEST_IMPORT); }
|
||||
catch (Exception e) { Toast.makeText(SettingsActivity.this, "No file picker available", Toast.LENGTH_LONG).show(); }
|
||||
}
|
||||
}));
|
||||
content.addView(row("↺", "Reset settings", "Clear saved settings and return to defaults", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
UiTheme.dialog(SettingsActivity.this)
|
||||
.setTitle("RESET SETTINGS?")
|
||||
.setMessage("This clears themes, pinned apps, vehicle defaults, automations, and every other saved preference. This cannot be undone.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("RESET", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
ConfigStore.of(SettingsActivity.this).resetAll();
|
||||
Toast.makeText(SettingsActivity.this, "Settings reset", Toast.LENGTH_SHORT).show();
|
||||
recreate();
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
}));
|
||||
subsection("Included", "The export contains all user-visible configuration");
|
||||
for (String name : ConfigStore.sections()) {
|
||||
content.addView(row("•", name, "Included in export", null));
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (resultCode != RESULT_OK || data == null || data.getData() == null) return;
|
||||
try {
|
||||
if (requestCode == REQUEST_EXPORT) {
|
||||
java.io.OutputStream out = getContentResolver().openOutputStream(data.getData());
|
||||
if (out == null) throw new java.io.IOException("Unable to open destination");
|
||||
ConfigStore.of(this).exportTo(out);
|
||||
Toast.makeText(this, "Settings exported", Toast.LENGTH_SHORT).show();
|
||||
} else if (requestCode == REQUEST_IMPORT) {
|
||||
java.io.InputStream in = getContentResolver().openInputStream(data.getData());
|
||||
if (in == null) throw new java.io.IOException("Unable to open file");
|
||||
ConfigStore.ImportResult result = ConfigStore.of(this).importFrom(in);
|
||||
Toast.makeText(this, "Imported " + result.keysApplied + " settings", Toast.LENGTH_SHORT).show();
|
||||
UiTheme.refreshTheme(this);
|
||||
recreate();
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
Toast.makeText(this, "Unsupported settings file", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception e) {
|
||||
Toast.makeText(this, "Settings transfer failed", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void section(String title, String subtitle) {
|
||||
@@ -168,8 +243,21 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
}
|
||||
}
|
||||
|
||||
/** A compact heading used for feature groups inside a top-level category. */
|
||||
private void subsection(String title, String subtitle) {
|
||||
TextView heading = UiTheme.label(this, title.toUpperCase(Locale.US));
|
||||
heading.setPadding(18, 12, 0, 3);
|
||||
content.addView(heading, new LinearLayout.LayoutParams(-1, 24 + Math.round(8 * UiTheme.fontScale(this))));
|
||||
if (subtitle != null) {
|
||||
TextView hint = UiTheme.text(this, subtitle, 11, UiTheme.MUTED, Typeface.NORMAL);
|
||||
hint.setPadding(18, 0, 0, 5);
|
||||
content.addView(hint, new LinearLayout.LayoutParams(-1, 24 + Math.round(6 * UiTheme.fontScale(this))));
|
||||
}
|
||||
}
|
||||
|
||||
private void driving() {
|
||||
section("Driving", "Vehicle defaults and driving tools");
|
||||
section("Driving", "Vehicle defaults, performance, and trip history");
|
||||
subsection("Vehicle defaults", "Choose the profile applied when driving starts");
|
||||
content.addView(row("V", "Vehicle settings", "Capability-gated startup profile", open(VehicleSettingsActivity.class)));
|
||||
content.addView(row("D", "Default drive mode", driveModeName(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); }
|
||||
@@ -177,22 +265,39 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
content.addView(row("R", "Default recovery level", regenName(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); }
|
||||
}));
|
||||
subsection("Performance", "Tools for measuring acceleration");
|
||||
content.addView(row("0", "0–100 tester", "Open performance timer", open(SpeedTestActivity.class)));
|
||||
subsection("Trip tracking", "Choose how drive samples are collected and reviewed");
|
||||
content.addView(row("T", "Trip reports", "View saved drives", open(TripsActivity.class)));
|
||||
content.addView(row("A", "Arrival areas", "Configure geofences and price-window briefings", open(ArrivalGeofenceActivity.class)));
|
||||
content.addView(row("S", "Drive log sample interval", sampleIntervalLabel(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseSampleInterval(); }
|
||||
}));
|
||||
subsection("Maps", "Manage offline map tiles used by trip reports");
|
||||
content.addView(row("M", "Map tile cache storage", tileCacheLabel(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseTileCache(); }
|
||||
}));
|
||||
content.addView(row("◆", "Map cache current use", MapTileCache.usageLabel(this), null));
|
||||
}
|
||||
|
||||
private void charging() {
|
||||
section("Charging", "Charging tools and energy monitoring");
|
||||
subsection("Charging management", "Automations and live energy information");
|
||||
content.addView(row("⚡", "Charging automation", "Rules and price triggers", open(ChargingActivity.class)));
|
||||
content.addView(row("E", "Energy dashboard", "Live consumption and recovery", open(EnergyActivity.class)));
|
||||
subsection("Vehicle charging", "Open the original SAIC charging controls");
|
||||
content.addView(row("C", "Vehicle charging settings", "Open OEM settings", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.vehicleconfig.ui.VehicleSettingsActivity"); }
|
||||
@Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.chargemanagement.ui.ChargeManagementActivity"); }
|
||||
}));
|
||||
}
|
||||
|
||||
private void misc() {
|
||||
section("Misc", "Head-unit and application tools");
|
||||
subsection("Audio", "Configure event sounds and speed-aware playback");
|
||||
content.addView(row("♫", "Soundboard", "Configure event audio", open(SoundboardActivity.class)));
|
||||
content.addView(row("♪", "Speed reactive audio", "Looping clip that reacts to driving speed", open(SpeedAudioActivity.class)));
|
||||
content.addView(row("≈", "Adaptive audio leveling", "Scale media volume smoothly with vehicle speed", open(AdaptiveAudioLevelingActivity.class)));
|
||||
subsection("Setup", "Review the first-time configuration");
|
||||
content.addView(row("★", "Run setup wizard", "Reopen the first-time setup review", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
Intent intent = new Intent(SettingsActivity.this, SetupWizardActivity.class);
|
||||
@@ -200,11 +305,11 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
startActivity(intent);
|
||||
}
|
||||
}));
|
||||
content.addView(row("♪", "Speed reactive audio", "Looping clip that reacts to driving speed", open(SpeedAudioActivity.class)));
|
||||
subsection("Diagnostics", "Troubleshooting and input customization");
|
||||
content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class)));
|
||||
content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class)));
|
||||
|
||||
section("OEM Apps", "Original SAIC launchers and tools");
|
||||
subsection("OEM Apps", "Original SAIC launchers and tools");
|
||||
content.addView(row("⌂", "Official SAIC launcher", "Open OEM home screen", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { launchOemLauncher(); }
|
||||
}));
|
||||
@@ -224,31 +329,51 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
|
||||
private void appearance() {
|
||||
section("Appearance", "Personalise the MG Utility dashboard");
|
||||
subsection("Theme", "Choose colours and text sizing");
|
||||
content.addView(fontScaleControl());
|
||||
content.addView(row("◈", "Theme", themeName(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, CustomThemeEditorActivity.class)); }
|
||||
}));
|
||||
section("Navigation", "Choose how pages open and close");
|
||||
subsection("Navigation", "Choose how pages open and close");
|
||||
content.addView(toggleRow("→", "Page animations", "Slide transitions between MG Utility pages",
|
||||
UiTheme.UI_PREFS, AnimatedActivity.PREF_PAGE_ANIMATIONS_ENABLED, true));
|
||||
section("Home screen", "Choose what appears on the dashboard");
|
||||
subsection("Music player", "Show currently playing music on the dashboard");
|
||||
content.addView(toggleRow("♫", "Music Player", "Show current song, artist, and album art", UiTheme.UI_PREFS, MusicPlayerManager.PREF_ENABLED, false));
|
||||
content.addView(toggleRow("≋", "Music Visualizer", "Live full-width playback spectrum", "ui_state", "home_visualizer_enabled", true));
|
||||
subsection("App drawer", "Control the swipe-up launcher and its appearance");
|
||||
content.addView(toggleRow("⌃", "App Drawer", "Swipe up from the home screen to reveal your pinned apps", "ui_state", MainActivity.PREF_APP_DRAWER_ENABLED, false));
|
||||
content.addView(appDrawerOpacityControl());
|
||||
subsection("Control panel", "Choose the quick controls available from the dashboard");
|
||||
content.addView(toggleRow("⌄", "Control panel", "Swipe down from the home screen for quick controls", "ui_state", ControlPanelCatalog.PREF_ENABLED, true));
|
||||
content.addView(row("◈", "Configure control panel", "Add, remove, and reorder quick controls", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
startActivity(new Intent(SettingsActivity.this, ControlPanelSettingsActivity.class));
|
||||
}
|
||||
}));
|
||||
content.addView(appDrawerOpacityControl());
|
||||
subsection("Screen brightness", "Follow a daily peak/dark schedule with a smooth fade");
|
||||
content.addView(toggleRow("☼", "Automatic brightness", "Apply the schedule while the head unit is on",
|
||||
UiTheme.UI_PREFS, UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false, new Runnable() {
|
||||
@Override public void run() { BrightnessScheduler.rearm(SettingsActivity.this); }
|
||||
}));
|
||||
content.addView(row("↑", "Peak brightness time", BrightnessSchedule.formatMinutes(brightnessPeakMinutes()),
|
||||
new View.OnClickListener() { @Override public void onClick(View v) { chooseBrightnessTime(true); } }));
|
||||
content.addView(row("↓", "Dark brightness time", BrightnessSchedule.formatMinutes(brightnessDarkMinutes()),
|
||||
new View.OnClickListener() { @Override public void onClick(View v) { chooseBrightnessTime(false); } }));
|
||||
content.addView(brightnessSchedulePercentControl("P", "Peak brightness", UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_PERCENT,
|
||||
BrightnessSchedule.DEFAULT_PEAK_PERCENT));
|
||||
content.addView(brightnessSchedulePercentControl("D", "Dark brightness", UiTheme.PREF_AUTO_BRIGHTNESS_DARK_PERCENT,
|
||||
BrightnessSchedule.DEFAULT_DARK_PERCENT));
|
||||
content.addView(brightnessTransitionControl());
|
||||
subsection("Widgets panel", "Choose whether the dashboard exposes widgets");
|
||||
content.addView(toggleRow("←", "Widgets Panel", "Swipe right from the home screen for widgets", "ui_state", MainActivity.PREF_WIDGETS_PANEL_ENABLED, false));
|
||||
subsection("Music visualizer", "Choose how live playback is drawn on the dashboard");
|
||||
content.addView(toggleRow("≋", "Music Visualizer", "Show a live playback effect", "ui_state", "home_visualizer_enabled", true));
|
||||
content.addView(row("F", "Visualizer framerate", visualizerFps() + " FPS", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseVisualizerFps(); }
|
||||
}));
|
||||
content.addView(row("M", "Map tile cache storage", tileCacheLabel(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseTileCache(); }
|
||||
content.addView(row("∿", "Visualizer effect", visualizerEffectName(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseVisualizerEffect(); }
|
||||
}));
|
||||
content.addView(row("◆", "Map cache current use", MapTileCache.usageLabel(this), null));
|
||||
content.addView(visualizerOpacityControl());
|
||||
}
|
||||
|
||||
private void apps() {
|
||||
@@ -256,6 +381,7 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
final boolean reorderEnabled = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE)
|
||||
.getBoolean(PREF_APPS_REORDER, false);
|
||||
section("Apps", "Pinned apps shown in the app drawer");
|
||||
subsection("Pinned apps", "Add, remove, or reorder shortcuts");
|
||||
content.addView(toggleRow("↕", "Reorder", "Drag apps to change their order", UiTheme.UI_PREFS,
|
||||
PREF_APPS_REORDER, false, new Runnable() {
|
||||
@Override public void run() { showCategory(selectedCategory); }
|
||||
@@ -1055,6 +1181,103 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
.show();
|
||||
}
|
||||
|
||||
private int brightnessPeakMinutes() {
|
||||
return getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(
|
||||
UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES, BrightnessSchedule.DEFAULT_PEAK_MINUTES);
|
||||
}
|
||||
|
||||
private int brightnessDarkMinutes() {
|
||||
return getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(
|
||||
UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, BrightnessSchedule.DEFAULT_DARK_MINUTES);
|
||||
}
|
||||
|
||||
private void chooseBrightnessTime(final boolean peak) {
|
||||
int initial = peak ? brightnessPeakMinutes() : brightnessDarkMinutes();
|
||||
TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
|
||||
@Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
|
||||
int value = hourOfDay * 60 + minute;
|
||||
getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit()
|
||||
.putInt(peak ? UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES : UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, value)
|
||||
.apply();
|
||||
BrightnessScheduler.rearm(SettingsActivity.this);
|
||||
rebuildCategory();
|
||||
}
|
||||
}, initial / 60, initial % 60, true);
|
||||
dialog.setTitle(peak ? "Peak brightness time" : "Dark brightness time");
|
||||
dialog.show();
|
||||
}
|
||||
|
||||
private View brightnessSchedulePercentControl(String iconText, String label, final String prefKey, int fallback) {
|
||||
final LinearLayout item = new LinearLayout(this);
|
||||
item.setGravity(Gravity.CENTER_VERTICAL);
|
||||
item.setPadding(18, 0, 18, 0);
|
||||
item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0));
|
||||
TextView icon = UiTheme.text(this, iconText, 18, UiTheme.CYAN, Typeface.BOLD);
|
||||
icon.setGravity(Gravity.CENTER);
|
||||
item.addView(icon, new LinearLayout.LayoutParams(46, 68));
|
||||
LinearLayout copy = new LinearLayout(this);
|
||||
copy.setOrientation(LinearLayout.VERTICAL);
|
||||
copy.setGravity(Gravity.CENTER_VERTICAL);
|
||||
TextView name = UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL);
|
||||
final int initial = Math.max(0, Math.min(100, getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(prefKey, fallback)));
|
||||
final TextView value = UiTheme.text(this, initial + "%", 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
copy.addView(name); copy.addView(value);
|
||||
item.addView(copy, new LinearLayout.LayoutParams(330, 68));
|
||||
SeekBar slider = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(100); slider.setProgress(initial); slider.setContentDescription(label);
|
||||
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { value.setText(progress + "%"); }
|
||||
@Override public void onStartTrackingTouch(SeekBar bar) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar bar) {
|
||||
getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit().putInt(prefKey, bar.getProgress()).apply();
|
||||
BrightnessScheduler.rearm(SettingsActivity.this);
|
||||
}
|
||||
});
|
||||
item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1));
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68);
|
||||
p.setMargins(0, 0, 0, 2); item.setLayoutParams(p);
|
||||
return item;
|
||||
}
|
||||
|
||||
private View brightnessTransitionControl() {
|
||||
final LinearLayout item = new LinearLayout(this);
|
||||
item.setGravity(Gravity.CENTER_VERTICAL);
|
||||
item.setPadding(18, 0, 18, 0);
|
||||
item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0));
|
||||
TextView icon = UiTheme.text(this, "⇄", 18, UiTheme.CYAN, Typeface.BOLD);
|
||||
icon.setGravity(Gravity.CENTER);
|
||||
item.addView(icon, new LinearLayout.LayoutParams(46, 68));
|
||||
LinearLayout copy = new LinearLayout(this);
|
||||
copy.setOrientation(LinearLayout.VERTICAL); copy.setGravity(Gravity.CENTER_VERTICAL);
|
||||
TextView name = UiTheme.text(this, "Transition duration", 16, UiTheme.TEXT, Typeface.NORMAL);
|
||||
final int initial = Math.max(BrightnessSchedule.MIN_TRANSITION_MINUTES, Math.min(BrightnessSchedule.MAX_TRANSITION_MINUTES,
|
||||
getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES,
|
||||
BrightnessSchedule.DEFAULT_TRANSITION_MINUTES)));
|
||||
final TextView value = UiTheme.text(this, initial + " min", 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
copy.addView(name); copy.addView(value);
|
||||
item.addView(copy, new LinearLayout.LayoutParams(330, 68));
|
||||
SeekBar slider = new SeekBar(this); UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(BrightnessSchedule.MAX_TRANSITION_MINUTES - BrightnessSchedule.MIN_TRANSITION_MINUTES);
|
||||
slider.setProgress(initial - BrightnessSchedule.MIN_TRANSITION_MINUTES);
|
||||
slider.setContentDescription("Brightness transition duration");
|
||||
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
|
||||
value.setText((progress + BrightnessSchedule.MIN_TRANSITION_MINUTES) + " min");
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar bar) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar bar) {
|
||||
getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit().putInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES,
|
||||
bar.getProgress() + BrightnessSchedule.MIN_TRANSITION_MINUTES).apply();
|
||||
BrightnessScheduler.rearm(SettingsActivity.this);
|
||||
}
|
||||
});
|
||||
item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1));
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68);
|
||||
p.setMargins(0, 0, 0, 2); item.setLayoutParams(p);
|
||||
return item;
|
||||
}
|
||||
|
||||
private View fontScaleControl() {
|
||||
final LinearLayout item = new LinearLayout(this);
|
||||
item.setGravity(Gravity.CENTER_VERTICAL);
|
||||
@@ -1071,6 +1294,7 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
copy.addView(name); copy.addView(value);
|
||||
item.addView(copy, new LinearLayout.LayoutParams(330, 68));
|
||||
final SeekBar slider = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(70); slider.setProgress(fontScaleProgress());
|
||||
slider.setContentDescription("Font size scale");
|
||||
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@@ -1109,6 +1333,7 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
copy.addView(name); copy.addView(value);
|
||||
item.addView(copy, new LinearLayout.LayoutParams(330, 68));
|
||||
final SeekBar slider = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(100);
|
||||
slider.setProgress(Math.max(0, Math.min(100, initial)));
|
||||
slider.setContentDescription("App Drawer opacity");
|
||||
@@ -1128,6 +1353,44 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
return item;
|
||||
}
|
||||
|
||||
private View visualizerOpacityControl() {
|
||||
final LinearLayout item = new LinearLayout(this);
|
||||
item.setGravity(Gravity.CENTER_VERTICAL);
|
||||
item.setPadding(18, 0, 18, 0);
|
||||
item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0));
|
||||
TextView icon = UiTheme.text(this, "◐", 18, UiTheme.CYAN, Typeface.BOLD);
|
||||
icon.setGravity(Gravity.CENTER);
|
||||
item.addView(icon, new LinearLayout.LayoutParams(46, 68));
|
||||
LinearLayout copy = new LinearLayout(this);
|
||||
copy.setOrientation(LinearLayout.VERTICAL);
|
||||
copy.setGravity(Gravity.CENTER_VERTICAL);
|
||||
TextView name = UiTheme.text(this, "Visualizer opacity", 16, UiTheme.TEXT, Typeface.NORMAL);
|
||||
final int initial = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE)
|
||||
.getInt(MainActivity.PREF_VISUALIZER_OPACITY, 80);
|
||||
final TextView value = UiTheme.text(this, Math.max(0, Math.min(100, initial)) + "%", 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
copy.addView(name); copy.addView(value);
|
||||
item.addView(copy, new LinearLayout.LayoutParams(330, 68));
|
||||
final SeekBar slider = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(slider);
|
||||
slider.setMax(100);
|
||||
slider.setProgress(Math.max(0, Math.min(100, initial)));
|
||||
slider.setContentDescription("Visualizer opacity");
|
||||
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
|
||||
value.setText(progress + "%");
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar bar) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar bar) {
|
||||
getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit()
|
||||
.putInt(MainActivity.PREF_VISUALIZER_OPACITY, bar.getProgress()).apply();
|
||||
}
|
||||
});
|
||||
item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1));
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68);
|
||||
p.setMargins(0, 0, 0, 2); item.setLayoutParams(p);
|
||||
return item;
|
||||
}
|
||||
|
||||
private int fontScaleProgress() {
|
||||
return Math.max(0, Math.min(70, Math.round((UiTheme.fontScale(this) - .80f) * 100f)));
|
||||
}
|
||||
@@ -1152,6 +1415,22 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
.getInt(MainActivity.PREF_VISUALIZER_FPS, 30));
|
||||
}
|
||||
|
||||
private String visualizerEffectName() {
|
||||
int effect = getSharedPreferences("ui_state", MODE_PRIVATE)
|
||||
.getInt(MainActivity.PREF_VISUALIZER_EFFECT, MainActivity.VISUALIZER_EFFECT_SPECTRUM);
|
||||
if (effect == MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE) return "Oscilloscope";
|
||||
if (effect == MainActivity.VISUALIZER_EFFECT_SPEED_RING) return "Speed Gauge Ring";
|
||||
if (effect == MainActivity.VISUALIZER_EFFECT_FERROFLUID) return "Ferrofluid";
|
||||
return "Spectrum Bars";
|
||||
}
|
||||
|
||||
private String sampleIntervalLabel() {
|
||||
int seconds = getSharedPreferences("trip_tracker", MODE_PRIVATE)
|
||||
.getInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS,
|
||||
TripTrackingService.DEFAULT_SAMPLE_INTERVAL_SECONDS);
|
||||
return seconds + (seconds == 1 ? " second" : " seconds");
|
||||
}
|
||||
|
||||
private String themeName() {
|
||||
String customId = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getString("theme_id", "");
|
||||
if (customId.length() > 0) {
|
||||
@@ -1185,6 +1464,51 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void chooseVisualizerEffect() {
|
||||
final String[] values = { "Spectrum Bars", "Oscilloscope", "Speed Gauge Ring", "Ferrofluid" };
|
||||
final int[] effects = {
|
||||
MainActivity.VISUALIZER_EFFECT_SPECTRUM,
|
||||
MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE,
|
||||
MainActivity.VISUALIZER_EFFECT_SPEED_RING,
|
||||
MainActivity.VISUALIZER_EFFECT_FERROFLUID
|
||||
};
|
||||
int current = getSharedPreferences("ui_state", MODE_PRIVATE)
|
||||
.getInt(MainActivity.PREF_VISUALIZER_EFFECT, MainActivity.VISUALIZER_EFFECT_SPECTRUM);
|
||||
int selected = current == MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE ? 1
|
||||
: current == MainActivity.VISUALIZER_EFFECT_SPEED_RING ? 2
|
||||
: current == MainActivity.VISUALIZER_EFFECT_FERROFLUID ? 3 : 0;
|
||||
UiTheme.dialog(this).setTitle("VISUALIZER EFFECT").setSingleChoiceItems(values, selected,
|
||||
new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
getSharedPreferences("ui_state", MODE_PRIVATE).edit()
|
||||
.putInt(MainActivity.PREF_VISUALIZER_EFFECT, effects[which]).apply();
|
||||
dialog.dismiss(); showCategory(selectedCategory);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void chooseSampleInterval() {
|
||||
final int[] seconds = { 1, 2, 5, 10, 15, 30, 60 };
|
||||
final String[] values = new String[seconds.length];
|
||||
int current = getSharedPreferences("trip_tracker", MODE_PRIVATE)
|
||||
.getInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS,
|
||||
TripTrackingService.DEFAULT_SAMPLE_INTERVAL_SECONDS);
|
||||
int selected = 2;
|
||||
for (int i = 0; i < seconds.length; i++) {
|
||||
values[i] = seconds[i] + (seconds[i] == 1 ? " second" : " seconds");
|
||||
if (seconds[i] == current) selected = i;
|
||||
}
|
||||
UiTheme.dialog(this).setTitle("DRIVE LOG SAMPLE INTERVAL")
|
||||
.setSingleChoiceItems(values, selected, new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
getSharedPreferences("trip_tracker", MODE_PRIVATE).edit()
|
||||
.putInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS, seconds[which]).apply();
|
||||
dialog.dismiss();
|
||||
showCategory(selectedCategory);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void chooseDriveMode() {
|
||||
final String[] values = { "Snow", "Eco", "Normal", "Sport", "Custom" };
|
||||
UiTheme.dialog(this).setTitle("DRIVE MODE").setSingleChoiceItems(values,
|
||||
|
||||
@@ -139,6 +139,7 @@ public final class SoundboardActivity extends AnimatedActivity {
|
||||
file.setEllipsize(android.text.TextUtils.TruncateAt.MIDDLE);
|
||||
|
||||
volume = new SeekBar(SoundboardActivity.this);
|
||||
UiTheme.tintSeekBar(volume);
|
||||
volume.setMax(100);
|
||||
volume.setProgress(saved.volumePercent);
|
||||
volumeValue = text(saved.volumePercent + "%", 12, UiTheme.RED, Typeface.BOLD);
|
||||
|
||||
@@ -124,6 +124,7 @@ public final class SpeedAudioActivity extends AnimatedActivity {
|
||||
list.addView(row("SOUND FILE", fileRow));
|
||||
|
||||
volume = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(volume);
|
||||
volume.setMax(100);
|
||||
volume.setProgress(cfg.volumePercent);
|
||||
volumeValue = text(cfg.volumePercent + "%", 12, UiTheme.RED, Typeface.BOLD);
|
||||
|
||||
@@ -4,9 +4,14 @@ import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Typeface;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -14,32 +19,316 @@ import java.util.Locale;
|
||||
/** Dashboard charts that always render with whatever raw samples the trip has. */
|
||||
final class TripCharts extends View {
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint guidePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint tooltipPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private List<TripDatabase.TripSample> samples = new ArrayList<>();
|
||||
private boolean overview;
|
||||
private boolean scrubbing;
|
||||
private float scrubRatio = -1f;
|
||||
private boolean overviewScrubbing;
|
||||
private int overviewScrubGraph;
|
||||
private TripDatabase.Summary overviewSummary;
|
||||
private List<TripDatabase.TripSummary> overviewTrips = new ArrayList<>();
|
||||
|
||||
TripCharts(Context context) {
|
||||
super(context);
|
||||
UiTheme.loadTheme(context);
|
||||
setBackground(UiTheme.surface(UiTheme.SURFACE, 12));
|
||||
paint.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL));
|
||||
guidePaint.setColor(UiTheme.withAlpha(UiTheme.CYAN, 200));
|
||||
guidePaint.setStyle(Paint.Style.STROKE);
|
||||
guidePaint.setStrokeWidth(2f);
|
||||
markerPaint.setColor(UiTheme.CYAN);
|
||||
markerPaint.setStyle(Paint.Style.FILL);
|
||||
tooltipPaint.setColor(UiTheme.withAlpha(UiTheme.SURFACE_HIGH, 245));
|
||||
tooltipPaint.setStyle(Paint.Style.FILL);
|
||||
setClickable(true);
|
||||
}
|
||||
|
||||
void setSamples(List<TripDatabase.TripSample> values, boolean isOverview) {
|
||||
samples = values == null ? new ArrayList<TripDatabase.TripSample>() : new ArrayList<>(values);
|
||||
overview = isOverview;
|
||||
scrubbing = false;
|
||||
scrubRatio = -1f;
|
||||
overviewScrubbing = false;
|
||||
overviewScrubGraph = -1;
|
||||
invalidate();
|
||||
}
|
||||
|
||||
void setOverviewData(TripDatabase.Summary summary, List<TripDatabase.TripSummary> trips) {
|
||||
overviewSummary = summary;
|
||||
overviewTrips = trips == null ? new ArrayList<TripDatabase.TripSummary>() : new ArrayList<>(trips);
|
||||
overview = true;
|
||||
scrubbing = false;
|
||||
scrubRatio = -1f;
|
||||
overviewScrubbing = false;
|
||||
overviewScrubGraph = -1;
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@Override public boolean onTouchEvent(MotionEvent event) {
|
||||
if (overview) return onOverviewTouch(event);
|
||||
if (samples.size() < 2) return super.onTouchEvent(event);
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
scrubbing = true;
|
||||
int gap = 12;
|
||||
int cardWidth = (getWidth() - gap * 2 - 28) / 3;
|
||||
int chartIndex = Math.max(0, Math.min(2,
|
||||
(int) ((event.getX() - 14) / (float) Math.max(1, cardWidth + gap))));
|
||||
int chartLeft = 14 + (cardWidth + gap) * chartIndex;
|
||||
scrubRatio = Math.max(0f, Math.min(1f,
|
||||
(event.getX() - chartLeft - 14) / (float) Math.max(1, cardWidth - 28)));
|
||||
if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(true);
|
||||
invalidate();
|
||||
return true;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
scrubbing = false;
|
||||
scrubRatio = -1f;
|
||||
if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(false);
|
||||
invalidate();
|
||||
return true;
|
||||
default:
|
||||
return super.onTouchEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean onOverviewTouch(MotionEvent event) {
|
||||
if (overviewTrips.isEmpty()) return super.onTouchEvent(event);
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
int width = getWidth(), height = getHeight();
|
||||
int graphTop = overviewGraphTop();
|
||||
int graphHeight = overviewGraphHeight(height, graphTop);
|
||||
int graphWidth = Math.max(1, (width - 56) / 2 - 6);
|
||||
int secondLeft = 28 + (width - 56) / 2 + 6;
|
||||
float x = event.getX();
|
||||
if (event.getY() < graphTop || event.getY() > graphTop + graphHeight) return true;
|
||||
if (x >= 28 && x <= 28 + graphWidth) overviewScrubGraph = 0;
|
||||
else if (x >= secondLeft && x <= secondLeft + graphWidth) overviewScrubGraph = 1;
|
||||
else return true;
|
||||
int left = overviewScrubGraph == 0 ? 28 : secondLeft;
|
||||
overviewScrubRatio = Math.max(0f, Math.min(1f,
|
||||
(x - left - 12f) / Math.max(1f, graphWidth - 24f)));
|
||||
overviewScrubbing = true;
|
||||
if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(true);
|
||||
invalidate();
|
||||
return true;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
overviewScrubbing = false;
|
||||
overviewScrubGraph = -1;
|
||||
overviewScrubRatio = -1f;
|
||||
if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(false);
|
||||
invalidate();
|
||||
return true;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private float overviewScrubRatio = -1f;
|
||||
|
||||
private int overviewGraphTop() {
|
||||
return 24 + 2 * (76 + 10) + 16;
|
||||
}
|
||||
|
||||
private int overviewGraphHeight(int height, int graphTop) {
|
||||
return Math.max(1, height - graphTop - 28);
|
||||
}
|
||||
|
||||
@Override protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas);
|
||||
int width = getWidth(), height = getHeight();
|
||||
if (width < 100 || height < 80) return;
|
||||
if (overview) {
|
||||
drawOverview(canvas, width, height);
|
||||
return;
|
||||
}
|
||||
int gap = 12;
|
||||
int cardWidth = (width - gap * 2 - 28) / 3;
|
||||
int top = 14;
|
||||
drawChart(canvas, 14, top, cardWidth, height - 28, "SPEED", "km/h", UiTheme.CYAN, 0, false);
|
||||
drawChart(canvas, 14 + cardWidth + gap, top, cardWidth, height - 28, "BATTERY", "%", UiTheme.SUCCESS, 1, false);
|
||||
drawChart(canvas, 14 + (cardWidth + gap) * 2, top, cardWidth, height - 28, overview ? "ENERGY COUNTER" : "ENERGY", "kWh", UiTheme.WARNING, 2, true);
|
||||
if (scrubbing && scrubRatio >= 0f) drawScrubOverlay(canvas, width, height, cardWidth, gap, top);
|
||||
}
|
||||
|
||||
private void drawOverview(Canvas canvas, int width, int height) {
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
paint.setColor(UiTheme.SURFACE_HIGH);
|
||||
canvas.drawRoundRect(14, 14, width - 14, height - 14, 10, 10, paint);
|
||||
TripDatabase.Summary summary = overviewSummary;
|
||||
if (summary == null) {
|
||||
paint.setColor(UiTheme.MUTED);
|
||||
paint.setTextSize(13);
|
||||
canvas.drawText("No drive history recorded yet", 30, height / 2f, paint);
|
||||
return;
|
||||
}
|
||||
double highestRange = 0d;
|
||||
double topSpeed = 0d;
|
||||
for (TripDatabase.TripSummary trip : overviewTrips) {
|
||||
if (trip.startRangeKm >= 0) highestRange = Math.max(highestRange, trip.startRangeKm);
|
||||
if (trip.endRangeKm >= 0) highestRange = Math.max(highestRange, trip.endRangeKm);
|
||||
if (Double.isFinite(trip.topSpeedKph)) topSpeed = Math.max(topSpeed, trip.topSpeedKph);
|
||||
}
|
||||
// distance is stored in metres and movingMillis in milliseconds.
|
||||
// Convert m/ms to km/h by multiplying by 3,600.
|
||||
double averageSpeed = summary.movingMillis > 0
|
||||
? summary.distanceMeters / summary.movingMillis * 3600d : 0d;
|
||||
String[] labels = { "TOTAL DRIVES", "TOP LOGGED SPEED", "BEST REGEN RECORD", "TOTAL DISTANCE",
|
||||
"TOTAL DRIVE TIME", "AVERAGE DRIVING SPEED", "HIGHEST BATTERY RANGE" };
|
||||
String[] values = {
|
||||
String.format(Locale.US, "%d", summary.tripCount),
|
||||
formatUnit(topSpeed, "km/h", "%.0f"),
|
||||
String.format(Locale.US, "+%.2f km", summary.bestRegenRangeKm),
|
||||
String.format(Locale.US, "%.1f km", summary.distanceMeters / 1000d),
|
||||
formatDuration(summary.movingMillis),
|
||||
formatUnit(averageSpeed, "km/h", "%.1f"),
|
||||
highestRange > 0d ? String.format(Locale.US, "%.0f km", highestRange) : "—"
|
||||
};
|
||||
int columns = 4;
|
||||
int cardGap = 10;
|
||||
int cardWidth = (width - 28 - cardGap * (columns - 1)) / columns;
|
||||
int cardHeight = 76;
|
||||
for (int i = 0; i < labels.length; i++) {
|
||||
int col = i % columns;
|
||||
int row = i / columns;
|
||||
float left = 14 + col * (cardWidth + cardGap);
|
||||
float top = 24 + row * (cardHeight + cardGap);
|
||||
paint.setColor(UiTheme.SURFACE);
|
||||
canvas.drawRoundRect(left, top, left + cardWidth, top + cardHeight, 8, 8, paint);
|
||||
paint.setTextSize(10);
|
||||
paint.setColor(UiTheme.MUTED);
|
||||
canvas.drawText(labels[i], left + 12, top + 20, paint);
|
||||
paint.setTextSize(19);
|
||||
paint.setColor(i == 2 ? UiTheme.SUCCESS : UiTheme.TEXT);
|
||||
canvas.drawText(values[i], left + 12, top + 51, paint);
|
||||
}
|
||||
int graphTop = overviewGraphTop();
|
||||
int graphHeight = overviewGraphHeight(height, graphTop);
|
||||
int historyWidth = Math.max(1, (width - 56) / 2 - 6);
|
||||
drawHistoryGraph(canvas, 28, graphTop, historyWidth, graphHeight,
|
||||
"CUMULATIVE DISTANCE", false);
|
||||
drawHistoryGraph(canvas, 28 + (width - 56) / 2 + 6, graphTop,
|
||||
historyWidth, graphHeight, "TOP SPEED BY DRIVE", true);
|
||||
if (overviewScrubbing && overviewScrubGraph >= 0 && overviewScrubRatio >= 0f)
|
||||
drawOverviewScrubOverlay(canvas, width, graphTop, graphHeight);
|
||||
}
|
||||
|
||||
private void drawHistoryGraph(Canvas canvas, int left, int top, int width, int height,
|
||||
String title, boolean speedGraph) {
|
||||
paint.setColor(UiTheme.SURFACE);
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
canvas.drawRoundRect(left, top, left + width, top + height, 8, 8, paint);
|
||||
paint.setColor(UiTheme.MUTED);
|
||||
paint.setTextSize(11);
|
||||
canvas.drawText(title, left + 12, top + 20, paint);
|
||||
if (width < 30 || height < 30) return;
|
||||
int plotLeft = left + 12, plotRight = left + width - 12, plotTop = top + 30, plotBottom = top + height - 14;
|
||||
paint.setColor(UiTheme.withAlpha(UiTheme.DIVIDER, 150));
|
||||
paint.setStyle(Paint.Style.STROKE);
|
||||
canvas.drawLine(plotLeft, plotBottom, plotRight, plotBottom, paint);
|
||||
if (overviewTrips.isEmpty()) {
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
canvas.drawText("Record a drive to build history", plotLeft, (plotTop + plotBottom) / 2f, paint);
|
||||
return;
|
||||
}
|
||||
int count = Math.min(24, overviewTrips.size());
|
||||
double baseline = 0d;
|
||||
for (int i = count; i < overviewTrips.size(); i++) {
|
||||
if (!speedGraph) baseline += Math.max(0d, overviewTrips.get(i).distanceKm());
|
||||
}
|
||||
double max = speedGraph ? 0d : baseline;
|
||||
if (speedGraph) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
double value = overviewTrips.get(i).topSpeedKph;
|
||||
if (Double.isFinite(value)) max = Math.max(max, value);
|
||||
}
|
||||
} else {
|
||||
// The line is cumulative; scale against the final cumulative value,
|
||||
// rather than the largest single trip distance.
|
||||
double cumulativeMax = baseline;
|
||||
for (int i = count - 1; i >= 0; i--)
|
||||
cumulativeMax += Math.max(0d, overviewTrips.get(i).distanceKm());
|
||||
if (Double.isFinite(cumulativeMax)) max = Math.max(max, cumulativeMax);
|
||||
}
|
||||
if (max <= 0d) max = 1d;
|
||||
paint.setStyle(speedGraph ? Paint.Style.FILL : Paint.Style.STROKE);
|
||||
paint.setStrokeWidth(2.5f);
|
||||
paint.setColor(speedGraph ? UiTheme.CYAN : UiTheme.SUCCESS);
|
||||
Path path = new Path();
|
||||
double cumulative = baseline;
|
||||
for (int i = 0; i < count; i++) {
|
||||
TripDatabase.TripSummary trip = overviewTrips.get(count - 1 - i);
|
||||
double raw = speedGraph ? trip.topSpeedKph : (cumulative += Math.max(0d, trip.distanceKm()));
|
||||
if (!Double.isFinite(raw)) raw = 0d;
|
||||
float x = count == 1 ? plotLeft : plotLeft + (plotRight - plotLeft) * i / (float) (count - 1);
|
||||
float y = (float) (plotBottom - (plotBottom - plotTop) * raw / max);
|
||||
y = Math.max(plotTop, Math.min(plotBottom, y));
|
||||
if (speedGraph) canvas.drawRect(x - 4, y, x + 4, plotBottom, paint);
|
||||
else if (i == 0) path.moveTo(x, y); else path.lineTo(x, y);
|
||||
}
|
||||
if (!speedGraph) canvas.drawPath(path, paint);
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
paint.setColor(UiTheme.MUTED);
|
||||
paint.setTextSize(10);
|
||||
canvas.drawText(speedGraph ? "km/h" : "km", plotLeft, plotBottom - 4, paint);
|
||||
}
|
||||
|
||||
private void drawOverviewScrubOverlay(Canvas canvas, int width, int graphTop, int graphHeight) {
|
||||
int graphWidth = Math.max(1, (width - 56) / 2 - 6);
|
||||
int left = overviewScrubGraph == 0 ? 28 : 28 + (width - 56) / 2 + 6;
|
||||
int plotLeft = left + 12, plotRight = left + graphWidth - 12;
|
||||
int count = Math.min(24, overviewTrips.size());
|
||||
if (count == 0 || plotRight <= plotLeft) return;
|
||||
int index = Math.round(overviewScrubRatio * (count - 1));
|
||||
index = Math.max(0, Math.min(count - 1, index));
|
||||
TripDatabase.TripSummary trip = overviewTrips.get(count - 1 - index);
|
||||
float cursorX = count == 1 ? plotLeft : plotLeft + (plotRight - plotLeft) * index / (float) (count - 1);
|
||||
int plotTop = graphTop + 30, plotBottom = graphTop + graphHeight - 14;
|
||||
guidePaint.setColor(UiTheme.CYAN);
|
||||
canvas.drawLine(cursorX, plotTop, cursorX, plotBottom, guidePaint);
|
||||
String value = overviewScrubGraph == 0
|
||||
? String.format(Locale.US, "%.1f km cumulative", cumulativeDistanceAt(count, index))
|
||||
: String.format(Locale.US, "%.0f km/h top speed", finiteOrZero(trip.topSpeedKph));
|
||||
String detail = new SimpleDateFormat("EEE d MMM HH:mm", Locale.US).format(new Date(trip.startTime));
|
||||
paint.setTextSize(11);
|
||||
float padding = 8f;
|
||||
float boxWidth = Math.max(paint.measureText(value), paint.measureText(detail)) + padding * 2;
|
||||
float boxLeft = cursorX + 12f + boxWidth > left + graphWidth ? cursorX - 12f - boxWidth : cursorX + 12f;
|
||||
boxLeft = Math.max(left + 6f, Math.min(left + graphWidth - boxWidth - 6f, boxLeft));
|
||||
float boxTop = plotTop + 4f, boxHeight = paint.getTextSize() * 2f + padding * 1.5f;
|
||||
canvas.drawRoundRect(new RectF(boxLeft, boxTop, boxLeft + boxWidth, boxTop + boxHeight), 6f, 6f, tooltipPaint);
|
||||
paint.setColor(UiTheme.CYAN); canvas.drawText(value, boxLeft + padding, boxTop + paint.getTextSize() + 2f, paint);
|
||||
paint.setColor(UiTheme.MUTED); canvas.drawText(detail, boxLeft + padding, boxTop + paint.getTextSize() * 2f + 4f, paint);
|
||||
}
|
||||
|
||||
private double cumulativeDistanceAt(int count, int index) {
|
||||
double cumulative = 0d;
|
||||
for (int i = count; i < overviewTrips.size(); i++)
|
||||
cumulative += Math.max(0d, overviewTrips.get(i).distanceKm());
|
||||
for (int i = count - 1; i >= count - 1 - index; i--)
|
||||
cumulative += Math.max(0d, overviewTrips.get(i).distanceKm());
|
||||
return cumulative;
|
||||
}
|
||||
|
||||
private static double finiteOrZero(double value) {
|
||||
return Double.isFinite(value) ? Math.max(0d, value) : 0d;
|
||||
}
|
||||
|
||||
private static String formatUnit(double value, String unit, String pattern) {
|
||||
return String.format(Locale.US, pattern + " %s", value, unit);
|
||||
}
|
||||
|
||||
private static String formatDuration(long millis) {
|
||||
long minutes = Math.max(0, millis / 60000L);
|
||||
return minutes < 60 ? String.format(Locale.US, "%dm", minutes)
|
||||
: String.format(Locale.US, "%dh %02dm", minutes / 60, minutes % 60);
|
||||
}
|
||||
|
||||
private void drawChart(Canvas canvas, int left, int top, int width, int height, String title, String unit, int color, int metric, boolean showSecondary) {
|
||||
@@ -85,14 +374,19 @@ final class TripCharts extends View {
|
||||
|
||||
private void line(Canvas canvas, int left, int top, int right, int bottom, int color, int metric, List<TripDatabase.TripSample> series) {
|
||||
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
|
||||
for (TripDatabase.TripSample sample : series) { double value = value(sample, metric); if (Double.isNaN(value)) continue; min = Math.min(min, value); max = Math.max(max, value); }
|
||||
for (TripDatabase.TripSample sample : series) {
|
||||
double value = value(sample, metric);
|
||||
if (!Double.isFinite(value)) continue;
|
||||
min = Math.min(min, value); max = Math.max(max, value);
|
||||
}
|
||||
if (!Double.isFinite(min) || !Double.isFinite(max)) return;
|
||||
if (max - min < 0.5) { max += 0.5; min -= 0.5; }
|
||||
Path path = new Path(); boolean started = false;
|
||||
for (int i = 0; i < series.size(); i++) {
|
||||
double value = value(series.get(i), metric); if (Double.isNaN(value)) continue;
|
||||
double value = value(series.get(i), metric); if (!Double.isFinite(value)) continue;
|
||||
float x = left + (right - left) * i / (float) Math.max(1, series.size() - 1);
|
||||
float y = (float) (bottom - (bottom - top) * (value - min) / (max - min));
|
||||
y = Math.max(top, Math.min(bottom, y));
|
||||
if (!started) { path.moveTo(x, y); started = true; } else path.lineTo(x, y);
|
||||
}
|
||||
paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(3f); paint.setStrokeCap(Paint.Cap.ROUND); paint.setColor(color);
|
||||
@@ -112,4 +406,75 @@ final class TripCharts extends View {
|
||||
private static String format(double value) {
|
||||
return Double.isNaN(value) ? "—" : String.format(Locale.US, "%.2f", value);
|
||||
}
|
||||
private void drawScrubOverlay(Canvas canvas, int width, int height, int cardWidth, int gap, int top) {
|
||||
List<TripDatabase.TripSample> points = downsample(samples);
|
||||
if (points.size() < 2) return;
|
||||
int index = Math.round(scrubRatio * (points.size() - 1));
|
||||
index = Math.max(0, Math.min(points.size() - 1, index));
|
||||
TripDatabase.TripSample sample = points.get(index);
|
||||
String[] titles = { "SPEED", "BATTERY", overview ? "ENERGY COUNTER" : "ENERGY" };
|
||||
String[] units = { "km/h", "%", "kWh" };
|
||||
int[] colors = { UiTheme.CYAN, UiTheme.SUCCESS, UiTheme.WARNING };
|
||||
double[] values = { value(sample, 0), value(sample, 1), value(sample, 2) };
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss", Locale.US);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int chartLeft = 14 + (cardWidth + gap) * i;
|
||||
int plotLeft = chartLeft + 14;
|
||||
int plotRight = chartLeft + cardWidth - 14;
|
||||
float cursorX = plotLeft + (plotRight - plotLeft) * scrubRatio;
|
||||
int plotTop = top + 36;
|
||||
int plotBottom = top + height - 28 - 26;
|
||||
canvas.drawLine(cursorX, plotTop, cursorX, plotBottom, guidePaint);
|
||||
drawChartMarker(canvas, chartLeft, plotTop, plotBottom, cardWidth, i,
|
||||
cursorX, titles[i], units[i], colors[i], values[i], fmt.format(new Date(sample.timestamp)));
|
||||
}
|
||||
}
|
||||
|
||||
private void drawChartMarker(Canvas canvas, int chartLeft, int plotTop, int plotBottom,
|
||||
int chartWidth, int metricIndex, float scrubX, String title, String unit, int color,
|
||||
double value, String timeText) {
|
||||
List<TripDatabase.TripSample> points = downsample(samples);
|
||||
if (points.size() < 2) return;
|
||||
int plotLeft = chartLeft + 14;
|
||||
int plotRight = chartLeft + chartWidth - 14;
|
||||
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
|
||||
int currentMetric = metricIndex == 2 ? 2 : metricIndex;
|
||||
for (TripDatabase.TripSample sample : points) {
|
||||
double v = value(sample, currentMetric);
|
||||
if (Double.isNaN(v)) continue;
|
||||
min = Math.min(min, v);
|
||||
max = Math.max(max, v);
|
||||
}
|
||||
if (!Double.isFinite(min) || !Double.isFinite(max)) return;
|
||||
if (max - min < 0.5) { max += 0.5; min -= 0.5; }
|
||||
int index = Math.round((scrubX - plotLeft) / (float) (plotRight - plotLeft) * (points.size() - 1));
|
||||
index = Math.max(0, Math.min(points.size() - 1, index));
|
||||
double sampleValue = value(points.get(index), currentMetric);
|
||||
float markerY;
|
||||
if (Double.isNaN(sampleValue)) {
|
||||
markerY = (plotTop + plotBottom) / 2f;
|
||||
} else {
|
||||
markerY = (float) (plotBottom - (plotBottom - plotTop) * (sampleValue - min) / (max - min));
|
||||
}
|
||||
markerPaint.setColor(color);
|
||||
canvas.drawCircle(scrubX, markerY, 5f, markerPaint);
|
||||
String valueText = Double.isNaN(value) ? "—" : String.format(Locale.US, "%.2f %s", value, unit);
|
||||
String line1 = title + " " + valueText;
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
paint.setTextSize(11);
|
||||
float padding = 8f;
|
||||
float textWidth = Math.max(paint.measureText(line1), paint.measureText(timeText));
|
||||
float boxWidth = textWidth + padding * 2;
|
||||
float boxHeight = paint.getTextSize() * 2f + padding * 1.5f;
|
||||
float boxLeft = scrubX + 12f + boxWidth > chartLeft + chartWidth
|
||||
? scrubX - 12f - boxWidth
|
||||
: scrubX + 12f;
|
||||
if (boxLeft < chartLeft + 6f) boxLeft = chartLeft + 6f;
|
||||
float boxTop = plotTop + 4f;
|
||||
canvas.drawRoundRect(new RectF(boxLeft, boxTop, boxLeft + boxWidth, boxTop + boxHeight), 6f, 6f, tooltipPaint);
|
||||
paint.setColor(color);
|
||||
canvas.drawText(line1, boxLeft + padding, boxTop + paint.getTextSize() + 2f, paint);
|
||||
paint.setColor(UiTheme.MUTED);
|
||||
canvas.drawText(timeText, boxLeft + padding, boxTop + paint.getTextSize() * 2f + 4f, paint);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -15,7 +19,7 @@ import java.util.List;
|
||||
*/
|
||||
final class TripDatabase extends SQLiteOpenHelper {
|
||||
private static final String NAME = "mg_trips.db";
|
||||
private static final int VERSION = 3;
|
||||
private static final int VERSION = 4;
|
||||
|
||||
static final long NO_TRIP = -1L;
|
||||
|
||||
@@ -24,6 +28,226 @@ final class TripDatabase extends SQLiteOpenHelper {
|
||||
setWriteAheadLoggingEnabled(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export recorded drives only. Configuration is intentionally kept out of
|
||||
* this document; the Config screen has a separate settings export.
|
||||
*/
|
||||
synchronized String exportJson() throws JSONException {
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", 1);
|
||||
root.put("type", "mg-utility-drive-log");
|
||||
root.put("database", NAME);
|
||||
root.put("overview", overviewJson(NO_TRIP));
|
||||
JSONObject tables = new JSONObject();
|
||||
SQLiteDatabase db = getReadableDatabase();
|
||||
exportTable(db, "trips", tables);
|
||||
exportTable(db, "trip_points", tables);
|
||||
exportTable(db, "trip_samples", tables);
|
||||
exportTable(db, "regen_events", tables);
|
||||
root.put("tables", tables);
|
||||
return root.toString(2);
|
||||
}
|
||||
|
||||
synchronized String exportJson(long tripId) throws JSONException {
|
||||
if (tripId == NO_TRIP) return exportJson();
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", 1);
|
||||
root.put("type", "mg-utility-drive-log");
|
||||
root.put("scope", "single-drive");
|
||||
root.put("trip_id", tripId);
|
||||
root.put("overview", overviewJson(tripId));
|
||||
JSONObject tables = new JSONObject();
|
||||
SQLiteDatabase db = getReadableDatabase();
|
||||
exportTable(db, "trips", tables, "id = " + tripId);
|
||||
exportTable(db, "trip_points", tables, "trip_id = " + tripId);
|
||||
exportTable(db, "trip_samples", tables, "trip_id = " + tripId);
|
||||
exportTable(db, "regen_events", tables, "trip_id = " + tripId);
|
||||
root.put("tables", tables);
|
||||
return root.toString(2);
|
||||
}
|
||||
|
||||
synchronized String exportCsv(long tripId) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
appendCsvOverview(out, tripId);
|
||||
SQLiteDatabase db = getReadableDatabase();
|
||||
appendCsvTable(db, "trips", out, tripId == NO_TRIP ? null : "id = " + tripId);
|
||||
appendCsvTable(db, "trip_points", out, tripId == NO_TRIP ? null : "trip_id = " + tripId);
|
||||
appendCsvTable(db, "trip_samples", out, tripId == NO_TRIP ? null : "trip_id = " + tripId);
|
||||
appendCsvTable(db, "regen_events", out, tripId == NO_TRIP ? null : "trip_id = " + tripId);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
synchronized String exportHtml(long tripId) throws JSONException {
|
||||
StringBuilder html = new StringBuilder();
|
||||
html.append("<!doctype html><html><head><meta charset=\"utf-8\"><title>MG Utility Drive Log</title>")
|
||||
.append("<style>body{font-family:system-ui;background:#0b1118;color:#f4f7f9;margin:24px}h1,h2{color:#2ddbeb}section{margin:24px 0;padding:16px;background:#141c24}table{border-collapse:collapse;width:100%;font-size:12px}th,td{padding:6px;border:1px solid #31414d;text-align:left}th{color:#9bb0bd}svg{width:100%;height:180px;background:#0d151d}</style></head><body>")
|
||||
.append("<h1>MG Utility Drive Log</h1><p>Recorded vehicle data export</p>");
|
||||
JSONObject all = new JSONObject(exportJson(tripId));
|
||||
JSONObject tables = all.optJSONObject("tables");
|
||||
if (tables != null) {
|
||||
java.util.Iterator<String> names = tables.keys();
|
||||
while (names.hasNext()) {
|
||||
String table = names.next();
|
||||
html.append("<section><h2>").append(escapeHtml(table)).append("</h2>");
|
||||
JSONArray rows = tables.optJSONArray(table);
|
||||
appendHtmlTable(html, rows);
|
||||
html.append("</section>");
|
||||
}
|
||||
}
|
||||
html.append("<section><h2>Route preview</h2>");
|
||||
JSONArray points = tables == null ? null : tables.optJSONArray("trip_points");
|
||||
appendRouteSvg(html, points);
|
||||
html.append("</section><section><h2>Speed graph</h2>");
|
||||
JSONArray samples = tables == null ? null : tables.optJSONArray("trip_samples");
|
||||
appendSpeedSvg(html, samples);
|
||||
html.append("</section></body></html>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static void appendCsvTable(SQLiteDatabase db, String table, StringBuilder out, String where) {
|
||||
Cursor cursor = db.query(table, null, where, null, null, null, "id ASC");
|
||||
try {
|
||||
String[] columns = cursor.getColumnNames();
|
||||
out.append("# ").append(table).append('\n');
|
||||
for (int i = 0; i < columns.length; i++) { if (i > 0) out.append(','); out.append(csv(columns[i])); }
|
||||
out.append('\n');
|
||||
while (cursor.moveToNext()) {
|
||||
for (int i = 0; i < columns.length; i++) {
|
||||
if (i > 0) out.append(',');
|
||||
out.append(csv(cursor.isNull(i) ? "" : cursor.getString(i)));
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
} finally { cursor.close(); }
|
||||
}
|
||||
|
||||
private void appendCsvOverview(StringBuilder out, long tripId) {
|
||||
Summary summary = tripId == NO_TRIP ? summary() : summaryForTrip(tripId);
|
||||
out.append("# overview\nmetric,value\n")
|
||||
.append("trip_count,").append(summary.tripCount).append('\n')
|
||||
.append("distance_meters,").append(summary.distanceMeters).append('\n')
|
||||
.append("moving_millis,").append(summary.movingMillis).append('\n')
|
||||
.append("energy_kwh,").append(summary.energyKwh).append('\n')
|
||||
.append("regen_energy_kwh,").append(summary.regenEnergyKwh).append('\n')
|
||||
.append("regen_range_km,").append(summary.regenRangeKm).append('\n')
|
||||
.append("regen_event_count,").append(summary.regenEventCount).append('\n');
|
||||
}
|
||||
|
||||
private JSONObject overviewJson(long tripId) throws JSONException {
|
||||
Summary summary = tripId == NO_TRIP ? summary() : summaryForTrip(tripId);
|
||||
JSONObject object = new JSONObject();
|
||||
object.put("trip_count", summary.tripCount);
|
||||
object.put("distance_meters", summary.distanceMeters);
|
||||
object.put("moving_millis", summary.movingMillis);
|
||||
object.put("energy_kwh", summary.energyKwh);
|
||||
object.put("regen_energy_kwh", summary.regenEnergyKwh);
|
||||
object.put("regen_range_km", summary.regenRangeKm);
|
||||
object.put("regen_event_count", summary.regenEventCount);
|
||||
return object;
|
||||
}
|
||||
|
||||
private static String csv(String value) {
|
||||
String text = value == null ? "" : value;
|
||||
return "\"" + text.replace("\"", "\"\"") + "\"";
|
||||
}
|
||||
|
||||
private static void appendHtmlTable(StringBuilder html, JSONArray rows) throws JSONException {
|
||||
if (rows == null || rows.length() == 0) { html.append("<p>No rows</p>"); return; }
|
||||
JSONObject first = rows.optJSONObject(0);
|
||||
if (first == null) return;
|
||||
java.util.List<String> columns = new java.util.ArrayList<String>();
|
||||
java.util.Iterator<String> keys = first.keys();
|
||||
while (keys.hasNext()) columns.add(keys.next());
|
||||
html.append("<table><thead><tr>");
|
||||
for (String column : columns) html.append("<th>").append(escapeHtml(column)).append("</th>");
|
||||
html.append("</tr></thead><tbody>");
|
||||
for (int i = 0; i < rows.length(); i++) {
|
||||
JSONObject row = rows.optJSONObject(i); if (row == null) continue;
|
||||
html.append("<tr>");
|
||||
for (String column : columns) html.append("<td>").append(escapeHtml(String.valueOf(row.opt(column)))).append("</td>");
|
||||
html.append("</tr>");
|
||||
}
|
||||
html.append("</tbody></table>");
|
||||
}
|
||||
|
||||
private static void appendRouteSvg(StringBuilder html, JSONArray points) throws JSONException {
|
||||
if (points == null || points.length() < 2) { html.append("<p>No GPS route recorded.</p>"); 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("<svg viewBox=\"0 0 800 180\" role=\"img\" aria-label=\"GPS route\"><path d=\"").append(path).append("\" fill=\"none\" stroke=\"#2ddbeb\" stroke-width=\"3\"/></svg>");
|
||||
}
|
||||
|
||||
private static void appendSpeedSvg(StringBuilder html, JSONArray samples) throws JSONException {
|
||||
if (samples == null || samples.length() < 2) { html.append("<p>No speed samples recorded.</p>"); 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("<svg viewBox=\"0 0 800 180\" role=\"img\" aria-label=\"Speed over time\"><path d=\"").append(path).append("\" fill=\"none\" stroke=\"#40cf99\" stroke-width=\"3\"/></svg>");
|
||||
}
|
||||
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
@@ -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<TripDatabase.TripPoint> route = database.getRoute(tripId);
|
||||
runOnUiThread(new Runnable() { @Override public void run() { if (map != null) map.setRoute(route); } });
|
||||
} }, "mg-trip-map-full").start();
|
||||
}
|
||||
}
|
||||
@@ -37,10 +37,17 @@ public final class TripTrackingService extends Service {
|
||||
static final String ACTION_RESTART = "cloud.molberg.mgutility.RESTART_TRACKING";
|
||||
static final String CHANNEL_ID = "mg_trip_tracking";
|
||||
static final int NOTIFICATION_ID = 1404;
|
||||
private static final int ARRIVAL_NOTIFICATION_ID = 1406;
|
||||
|
||||
private static final long SAMPLE_INTERVAL_MS = 5000L;
|
||||
static final String PREF_SAMPLE_INTERVAL_SECONDS = "sample_interval_seconds";
|
||||
static final int DEFAULT_SAMPLE_INTERVAL_SECONDS = 5;
|
||||
private static final int MIN_SAMPLE_INTERVAL_SECONDS = 1;
|
||||
private static final int MAX_SAMPLE_INTERVAL_SECONDS = 60;
|
||||
private static final long SPEED_AUDIO_INTERVAL_MS = 200L;
|
||||
private static final long STOP_GRACE_MS = 5 * 60 * 1000L;
|
||||
private static final long PARKED_GRACE_MS = 45 * 1000L;
|
||||
/** SAIC VehicleConstant.CarGearValue.CAR_GEAR_PARK_RANGE is 1. */
|
||||
private static final int PARK_GEAR_VALUE = 1;
|
||||
private static final float PARKED_SPEED_KPH = 0.5f;
|
||||
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;
|
||||
@@ -68,6 +75,7 @@ public final class TripTrackingService extends Service {
|
||||
private Location lastDistanceLocation;
|
||||
private Location lastStoredLocation;
|
||||
private long stoppedSince;
|
||||
private long parkedSince;
|
||||
private String lastNotificationText = "";
|
||||
private int settingsApplyGeneration;
|
||||
private int lastIgnition = Integer.MIN_VALUE;
|
||||
@@ -97,16 +105,19 @@ public final class TripTrackingService extends Service {
|
||||
private final Runnable poll = new Runnable() {
|
||||
@Override public void run() {
|
||||
collect();
|
||||
if (worker != null) worker.postDelayed(this, SAMPLE_INTERVAL_MS);
|
||||
if (worker != null) worker.postDelayed(this, sampleIntervalMs());
|
||||
}
|
||||
};
|
||||
|
||||
private final Runnable speedAudioPoll = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (SpeedAudioManager.shouldPoll(TripTrackingService.this)) pollSpeedAudio();
|
||||
else SpeedAudioManager.stopReactive();
|
||||
boolean reactiveAudio = SpeedAudioManager.shouldPoll(TripTrackingService.this);
|
||||
boolean adaptiveLeveling = AdaptiveAudioLevelingManager.shouldPoll(TripTrackingService.this);
|
||||
if (reactiveAudio || adaptiveLeveling) pollSpeedAudio(reactiveAudio, adaptiveLeveling);
|
||||
if (!reactiveAudio) SpeedAudioManager.stopReactive();
|
||||
if (!adaptiveLeveling) AdaptiveAudioLevelingManager.stopAndRestore(TripTrackingService.this);
|
||||
if (worker != null) worker.postDelayed(this,
|
||||
SpeedAudioManager.shouldPoll(TripTrackingService.this) ? SPEED_AUDIO_INTERVAL_MS : 1000L);
|
||||
reactiveAudio || adaptiveLeveling ? SPEED_AUDIO_INTERVAL_MS : 1000L);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -150,6 +161,8 @@ public final class TripTrackingService extends Service {
|
||||
.putBoolean("gps_ready", true)
|
||||
.putLong("last_fix", System.currentTimeMillis())
|
||||
.putString("gps_provider", location.getProvider() == null ? "unknown" : location.getProvider())
|
||||
.putString("last_latitude", String.valueOf(location.getLatitude()))
|
||||
.putString("last_longitude", String.valueOf(location.getLongitude()))
|
||||
.apply();
|
||||
updateStatus("GPS route ready");
|
||||
}
|
||||
@@ -245,7 +258,7 @@ public final class TripTrackingService extends Service {
|
||||
bindVehicleService();
|
||||
configureLocation();
|
||||
collect();
|
||||
worker.postDelayed(poll, SAMPLE_INTERVAL_MS);
|
||||
worker.postDelayed(poll, sampleIntervalMs());
|
||||
worker.post(speedAudioPoll);
|
||||
}
|
||||
});
|
||||
@@ -274,6 +287,7 @@ public final class TripTrackingService extends Service {
|
||||
try { unregisterReceiver(soundboardReceiver); } catch (Exception ignored) { }
|
||||
vehicle = null;
|
||||
SpeedAudioManager.stopReactive();
|
||||
AdaptiveAudioLevelingManager.stopAndRestore(this);
|
||||
if (workerThread != null) workerThread.quitSafely();
|
||||
finishRegenEvent(System.currentTimeMillis());
|
||||
if (database != null) database.close();
|
||||
@@ -359,6 +373,10 @@ public final class TripTrackingService extends Service {
|
||||
Location last = locationManager.getLastKnownLocation(provider);
|
||||
if (last != null && (latestLocation == null || last.getTime() > latestLocation.getTime())) {
|
||||
latestLocation = new Location(last);
|
||||
getSharedPreferences("trip_tracker", MODE_PRIVATE).edit()
|
||||
.putString("last_latitude", String.valueOf(last.getLatitude()))
|
||||
.putString("last_longitude", String.valueOf(last.getLongitude()))
|
||||
.apply();
|
||||
}
|
||||
providerFound = true;
|
||||
} catch (SecurityException ignored) {
|
||||
@@ -399,13 +417,22 @@ public final class TripTrackingService extends Service {
|
||||
processSample(sample, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private void pollSpeedAudio() {
|
||||
private void pollSpeedAudio(boolean reactiveAudio, boolean adaptiveLeveling) {
|
||||
EnergyActivity.VehicleGateway gateway = vehicle;
|
||||
if (gateway == null) return;
|
||||
float speed;
|
||||
try { speed = gateway.readSpeed(); }
|
||||
catch (Exception ignored) { return; }
|
||||
SpeedAudioManager.updateSpeed(this, validSpeed(speed));
|
||||
float validSpeed = validSpeed(speed);
|
||||
if (reactiveAudio) SpeedAudioManager.updateSpeed(this, validSpeed);
|
||||
if (adaptiveLeveling) AdaptiveAudioLevelingManager.updateSpeed(this, validSpeed);
|
||||
}
|
||||
|
||||
private int readGearSafely() {
|
||||
VehicleSettingsGateway gateway = vehicleSettingsGateway;
|
||||
if (gateway == null) return -1;
|
||||
try { return gateway.getGear(); }
|
||||
catch (Exception ignored) { return -1; }
|
||||
}
|
||||
|
||||
private void processSample(EnergyActivity.Sample sample, long now) {
|
||||
@@ -414,7 +441,7 @@ public final class TripTrackingService extends Service {
|
||||
}
|
||||
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,
|
||||
final long elapsed = lastSampleAt == 0 ? 0 : Math.min(maxDistanceIntervalMs(),
|
||||
Math.max(0, now - lastSampleAt));
|
||||
float distance = distanceDelta(speed, elapsed);
|
||||
long movingMillis = moving ? elapsed : 0;
|
||||
@@ -431,10 +458,18 @@ public final class TripTrackingService extends Service {
|
||||
|
||||
trackRegeneration(sample, now, elapsed);
|
||||
|
||||
int gear = readGearSafely();
|
||||
boolean parked = speed <= PARKED_SPEED_KPH && gear == PARK_GEAR_VALUE;
|
||||
if (parked) { if (parkedSince == 0) parkedSince = now; }
|
||||
else parkedSince = 0;
|
||||
|
||||
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;
|
||||
// If the process was restarted while the car was already parked, start a
|
||||
// fresh 45-second Park observation for the recovered open trip.
|
||||
if (lastSampleAt == 0 && !moving) {
|
||||
stoppedSince = now;
|
||||
if (parkedSince == 0) parkedSince = now;
|
||||
}
|
||||
database.addSample(activeTripId, now, sample, distance, movingMillis, routePoint);
|
||||
|
||||
if (moving) {
|
||||
@@ -442,16 +477,28 @@ public final class TripTrackingService extends Service {
|
||||
updateStatus("Drive recording");
|
||||
} else {
|
||||
if (stoppedSince == 0) stoppedSince = now;
|
||||
if (now - stoppedSince >= STOP_GRACE_MS) {
|
||||
long parkedDuration = parkedSince == 0 ? 0 : now - parkedSince;
|
||||
// Trip finalises once the car is parked (gear == Park and speed ~0)
|
||||
// for the full 45 s window. A stopped car in Neutral/Drive must
|
||||
// remain an open trip until Park is reported.
|
||||
boolean finishNow = parkedSince != 0 && parkedDuration >= PARKED_GRACE_MS;
|
||||
if (finishNow) {
|
||||
finishRegenEvent(now);
|
||||
database.finishTrip(activeTripId, lastSampleAt == 0 ? now : stoppedSince, sample);
|
||||
long finishedTripId = activeTripId;
|
||||
Location arrivalLocation = usableLocation();
|
||||
database.finishTrip(finishedTripId, parkedSince + PARKED_GRACE_MS, sample);
|
||||
publishArrivalBriefing(finishedTripId, arrivalLocation);
|
||||
activeTripId = TripDatabase.NO_TRIP;
|
||||
lastDistanceLocation = null;
|
||||
lastStoredLocation = null;
|
||||
stoppedSince = 0;
|
||||
parkedSince = 0;
|
||||
updateStatus("Parked • trip saved");
|
||||
} else if (parkedSince != 0) {
|
||||
updateStatus("Parked • finishing trip in " +
|
||||
Math.max(0L, (PARKED_GRACE_MS - parkedDuration) / 1000L) + "s");
|
||||
} else {
|
||||
updateStatus("Parked • finishing trip timer");
|
||||
updateStatus("Stationary • waiting for park");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -513,7 +560,7 @@ public final class TripTrackingService extends Service {
|
||||
}
|
||||
if (regenEventTripId == TripDatabase.NO_TRIP) {
|
||||
regenEventTripId = activeTripId;
|
||||
long lookback = elapsed > 0 ? Math.min(elapsed, MAX_DISTANCE_INTERVAL_MS) : SAMPLE_INTERVAL_MS;
|
||||
long lookback = elapsed > 0 ? Math.min(elapsed, maxDistanceIntervalMs()) : sampleIntervalMs();
|
||||
regenEventStartedAt = Math.max(0L, now - lookback);
|
||||
regenEventEnergyKwh = 0d;
|
||||
regenEventRangeKm = 0d;
|
||||
@@ -524,11 +571,28 @@ public final class TripTrackingService extends Service {
|
||||
regenEventPeakSpeedKph = Math.max(regenEventPeakSpeedKph, validSpeed(sample.speed));
|
||||
regenEventLastIncreaseAt = now;
|
||||
} else if (regenEventTripId != TripDatabase.NO_TRIP &&
|
||||
now - regenEventLastIncreaseAt >= REGEN_EVENT_GAP_MS) {
|
||||
now - regenEventLastIncreaseAt >= regenEventGapMs()) {
|
||||
finishRegenEvent(now);
|
||||
}
|
||||
}
|
||||
|
||||
private long sampleIntervalMs() {
|
||||
int seconds = getSharedPreferences("trip_tracker", MODE_PRIVATE)
|
||||
.getInt(PREF_SAMPLE_INTERVAL_SECONDS, DEFAULT_SAMPLE_INTERVAL_SECONDS);
|
||||
seconds = Math.max(MIN_SAMPLE_INTERVAL_SECONDS, Math.min(MAX_SAMPLE_INTERVAL_SECONDS, seconds));
|
||||
return seconds * 1000L;
|
||||
}
|
||||
|
||||
private long maxDistanceIntervalMs() {
|
||||
return Math.max(15000L, sampleIntervalMs() * 3L);
|
||||
}
|
||||
|
||||
private long regenEventGapMs() {
|
||||
// Close a regen event after two missed counter increases so short brakes
|
||||
// are still grouped, even when the user has raised the sample interval.
|
||||
return Math.max(REGEN_EVENT_GAP_MS, sampleIntervalMs() * 2L);
|
||||
}
|
||||
|
||||
private void finishRegenEvent(long endedAt) {
|
||||
if (regenEventTripId == TripDatabase.NO_TRIP) return;
|
||||
boolean personalBest = false;
|
||||
@@ -614,6 +678,48 @@ public final class TripTrackingService extends Service {
|
||||
if (manager != null) manager.notify(NOTIFICATION_ID, notification(text));
|
||||
}
|
||||
|
||||
private void publishArrivalBriefing(final long tripId, Location location) {
|
||||
if (database == null) return;
|
||||
final java.util.List<ArrivalGeofence> matches = location == null
|
||||
? java.util.Collections.<ArrivalGeofence>emptyList()
|
||||
: ArrivalGeofence.matches(this, location.getLatitude(), location.getLongitude());
|
||||
final TripDatabase.TripSummary trip = database.getTrip(tripId);
|
||||
if (trip == null) return;
|
||||
final String locationName = matches.isEmpty() ? null : matches.get(0).name;
|
||||
notifyArrival(ArrivalBriefing.tripText(trip, locationName));
|
||||
// A price forecast is meaningful only for a named geofenced arrival.
|
||||
if (matches.isEmpty()) return;
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
java.util.List<ChargingAutomation.PricePoint> prices = ChargingAutomation.loadPriceSeries(TripTrackingService.this);
|
||||
ChargingAutomation.Prediction prediction = ChargingAutomation.predictNext(
|
||||
TripTrackingService.this, prices, System.currentTimeMillis());
|
||||
StringBuilder text = new StringBuilder(ArrivalBriefing.tripText(trip, locationName));
|
||||
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("HH:mm", Locale.US);
|
||||
if (prediction.nextStartAt != Long.MAX_VALUE) {
|
||||
text.append("\nCharge price window: START ").append(format.format(new java.util.Date(prediction.nextStartAt)));
|
||||
if (prediction.nextStopAt != Long.MAX_VALUE) text.append(" – STOP ").append(format.format(new java.util.Date(prediction.nextStopAt)));
|
||||
} else text.append("\nNo matching price window found in the available forecast");
|
||||
notifyArrival(text.toString());
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
}, "mg-arrival-prices").start();
|
||||
}
|
||||
|
||||
private void notifyArrival(String text) {
|
||||
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||
if (manager == null) return;
|
||||
Notification.Builder builder = Build.VERSION.SDK_INT >= 26
|
||||
? new Notification.Builder(this, CHANNEL_ID) : new Notification.Builder(this);
|
||||
builder.setSmallIcon(R.drawable.ic_mg_utility)
|
||||
.setContentTitle("MG Utility arrival briefing")
|
||||
.setContentText(text.replace('\n', ' '))
|
||||
.setStyle(new Notification.BigTextStyle().bigText(text))
|
||||
.setOnlyAlertOnce(true).setAutoCancel(true).setCategory(Notification.CATEGORY_STATUS);
|
||||
manager.notify(ARRIVAL_NOTIFICATION_ID, builder.build());
|
||||
}
|
||||
|
||||
private Notification notification(String text) {
|
||||
Intent open = new Intent(this, MainActivity.class);
|
||||
PendingIntent pending = PendingIntent.getActivity(this, 0, open,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.content.DialogInterface;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
@@ -9,11 +11,11 @@ import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.text.Spannable;
|
||||
import android.text.SpannableString;
|
||||
import android.text.TextUtils;
|
||||
import android.text.style.ForegroundColorSpan;
|
||||
import android.text.style.RelativeSizeSpan;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
@@ -28,13 +30,15 @@ import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Trip history with a clean overview landing page and drive-specific reports.
|
||||
* Stats are rendered as compact pills rather than free-form labels; the
|
||||
* regenerating-event list lives inside the raw-samples dialog.
|
||||
* Stats are rendered as compact pills rather than free-form labels; the raw
|
||||
* sample table and fullscreen map are opened as dedicated pages so the
|
||||
* per-drive header row can stay visible while scrolling.
|
||||
*/
|
||||
public final class TripsActivity extends AnimatedActivity {
|
||||
private static final int REQUEST_EXPORT_DRIVE_LOG = 8901;
|
||||
private final Handler handler = new Handler();
|
||||
private TripDatabase database;
|
||||
private LinearLayout tripList, overviewPills, drivePills, overviewExtras, driveExtras;
|
||||
private LinearLayout tripList, drivePills, driveExtras;
|
||||
private TextView trackerStatus, reportTitle, reportSubtitle, dashboardEmpty;
|
||||
private TripCharts charts;
|
||||
private long selectedTripId = TripDatabase.NO_TRIP;
|
||||
@@ -73,6 +77,10 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
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));
|
||||
exportButton = actionButton("EXPORT", new View.OnClickListener() { @Override public void onClick(View v) { promptExportOptions(); } });
|
||||
LinearLayout.LayoutParams exportHeaderParams = new LinearLayout.LayoutParams(130, 56);
|
||||
exportHeaderParams.setMargins(10, 0, 0, 0);
|
||||
header.addView(exportButton, exportHeaderParams);
|
||||
Button back = UiTheme.backButton(this, 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);
|
||||
|
||||
@@ -80,7 +88,9 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
LinearLayout sidebar = new LinearLayout(this); sidebar.setOrientation(LinearLayout.VERTICAL); sidebar.setPadding(18, 16, 18, 12); sidebar.setBackground(UiTheme.surface(UiTheme.SURFACE, 12));
|
||||
Button overviewButton = sidebarButton("OVERVIEW • ALL DRIVES"); overviewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showOverview(); } });
|
||||
sidebar.addView(overviewButton, new LinearLayout.LayoutParams(-1, 56));
|
||||
TextView history = text("RECENT DRIVES", 11, UiTheme.MUTED, Typeface.BOLD); history.setPadding(0, 10, 0, 8); sidebar.addView(history, new LinearLayout.LayoutParams(-1, 32));
|
||||
TextView history = text("RECENT DRIVES", 11, UiTheme.MUTED, Typeface.BOLD);
|
||||
history.setPadding(0, 6, 0, 4);
|
||||
sidebar.addView(history, new LinearLayout.LayoutParams(-1, -2));
|
||||
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(360, -1));
|
||||
|
||||
@@ -88,8 +98,6 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
reportTitle = text("OVERVIEW", 23, UiTheme.TEXT, Typeface.BOLD); report.addView(reportTitle, new LinearLayout.LayoutParams(-1, 38));
|
||||
reportSubtitle = text("All drives ever recorded", 12, UiTheme.MUTED, Typeface.NORMAL); report.addView(reportSubtitle, new LinearLayout.LayoutParams(-1, 22));
|
||||
|
||||
overviewPills = new LinearLayout(this); overviewPills.setOrientation(LinearLayout.HORIZONTAL); overviewPills.setPadding(0, 12, 0, 0); report.addView(overviewPills, new LinearLayout.LayoutParams(-1, -2));
|
||||
overviewExtras = new LinearLayout(this); overviewExtras.setOrientation(LinearLayout.HORIZONTAL); overviewExtras.setPadding(0, 8, 0, 0); report.addView(overviewExtras, new LinearLayout.LayoutParams(-1, -2));
|
||||
drivePills = new LinearLayout(this); drivePills.setOrientation(LinearLayout.HORIZONTAL); drivePills.setPadding(0, 12, 0, 0); drivePills.setVisibility(View.GONE); report.addView(drivePills, new LinearLayout.LayoutParams(-1, -2));
|
||||
driveExtras = new LinearLayout(this); driveExtras.setOrientation(LinearLayout.HORIZONTAL); driveExtras.setPadding(0, 8, 0, 0); driveExtras.setVisibility(View.GONE); report.addView(driveExtras, new LinearLayout.LayoutParams(-1, -2));
|
||||
|
||||
@@ -98,9 +106,9 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
report.addView(dashboardEmpty, new LinearLayout.LayoutParams(-1, -2));
|
||||
|
||||
LinearLayout actions = new LinearLayout(this); actions.setGravity(Gravity.CENTER_VERTICAL);
|
||||
Button mapButton = actionButton("OPEN FULLSCREEN MAP", new View.OnClickListener() { @Override public void onClick(View v) { openFullscreenMap(); } });
|
||||
Button mapButton = actionButton("OPEN FULLSCREEN MAP", new View.OnClickListener() { @Override public void onClick(View v) { openTripMapPage(); } });
|
||||
mapButton.setEnabled(false); actions.addView(mapButton, new LinearLayout.LayoutParams(0, 50, 1));
|
||||
Button rawButton = actionButton("VIEW RAW SAMPLES", new View.OnClickListener() { @Override public void onClick(View v) { openRawSamples(); } });
|
||||
Button rawButton = actionButton("VIEW RAW SAMPLES", new View.OnClickListener() { @Override public void onClick(View v) { openRawSamplesPage(); } });
|
||||
rawButton.setEnabled(false); LinearLayout.LayoutParams rp = new LinearLayout.LayoutParams(0, 50, 1); rp.setMargins(12, 0, 0, 0); actions.addView(rawButton, rp);
|
||||
report.addView(actions, new LinearLayout.LayoutParams(-1, 60));
|
||||
overviewActions = mapButton; driveActions = rawButton;
|
||||
@@ -109,7 +117,7 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
return root;
|
||||
}
|
||||
|
||||
private Button overviewActions, driveActions;
|
||||
private Button overviewActions, driveActions, exportButton;
|
||||
|
||||
private void loadTrips() {
|
||||
if (trackerStatus != null) trackerStatus.setText(trackerStatusText());
|
||||
@@ -129,15 +137,14 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
private void showOverview() {
|
||||
selectedTripId = TripDatabase.NO_TRIP;
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final TripDatabase.Summary summary = database.summary(); List<TripDatabase.TripSample> loaded = database.getAllSamples();
|
||||
final List<TripDatabase.TripSample> samples = loaded.size() < 2 ? routeAsSamples(database.getAllRoutePoints()) : loaded;
|
||||
final TripDatabase.Summary summary = database.summary();
|
||||
final List<TripDatabase.TripSummary> trips = database.listTrips();
|
||||
handler.post(new Runnable() { @Override public void run() {
|
||||
reportTitle.setText("OVERVIEW"); reportSubtitle.setText("All drives ever recorded");
|
||||
overviewActions.setEnabled(false); driveActions.setEnabled(false);
|
||||
setDrivePillsVisibility(false);
|
||||
renderOverviewPills(summary, samples);
|
||||
charts.setSamples(samples, true);
|
||||
dashboardEmpty.setVisibility(samples.size() < 2 ? View.VISIBLE : View.GONE);
|
||||
charts.setOverviewData(summary, trips);
|
||||
dashboardEmpty.setVisibility(View.GONE);
|
||||
} });
|
||||
} }, "mg-trip-overview").start();
|
||||
loadTripsRowsOnly();
|
||||
@@ -168,17 +175,6 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
driveExtras.setVisibility(drive ? View.VISIBLE : View.GONE);
|
||||
}
|
||||
|
||||
private void renderOverviewPills(TripDatabase.Summary summary, List<TripDatabase.TripSample> samples) {
|
||||
overviewPills.removeAllViews(); overviewExtras.removeAllViews();
|
||||
addPill(overviewPills, "DRIVES", String.format(Locale.US, "%d", summary.tripCount));
|
||||
addPill(overviewPills, "DISTANCE", String.format(Locale.US, "%.0f km", summary.distanceMeters / 1000d));
|
||||
addPill(overviewPills, "DRIVE TIME", formatDuration(summary.movingMillis));
|
||||
addPill(overviewExtras, "ENERGY", String.format(Locale.US, "%.1f kWh", summary.energyKwh));
|
||||
addPill(overviewExtras, "REGEN", String.format(Locale.US, "%.1f kWh", summary.regenEnergyKwh));
|
||||
addPill(overviewExtras, "TOP SPEED", topSpeed(samples) > 0f ? String.format(Locale.US, "%.0f km/h", topSpeed(samples)) : "—");
|
||||
addPill(overviewExtras, "BEST REGEN", summary.bestRegenEnergyKwh > 0d ? String.format(Locale.US, "%.2f kWh", summary.bestRegenEnergyKwh) : "—");
|
||||
}
|
||||
|
||||
private void renderDrivePills(TripDatabase.TripSummary trip, List<TripDatabase.TripSample> samples) {
|
||||
drivePills.removeAllViews(); driveExtras.removeAllViews();
|
||||
addPill(drivePills, "DISTANCE", String.format(Locale.US, "%.1f km", trip.distanceKm()));
|
||||
@@ -186,7 +182,8 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
addPill(drivePills, "TOP SPEED", String.format(Locale.US, "%.0f km/h", trip.topSpeedKph));
|
||||
addPill(driveExtras, "ENERGY", Double.isNaN(trip.reportedEnergyUsed()) ? "—" : String.format(Locale.US, "%.2f kWh", trip.reportedEnergyUsed()));
|
||||
addPill(driveExtras, "REGEN", String.format(Locale.US, "%.2f kWh", trip.regenEnergyKwh));
|
||||
addPill(driveExtras, "BEST REGEN", trip.regenEventCount > 0 ? String.format(Locale.US, "%.2f kWh", trip.bestRegenEnergyKwh) : "—");
|
||||
addPill(driveExtras, "BEST REGEN", trip.regenEventCount > 0 && trip.bestRegenRangeKm > 0d
|
||||
? String.format(Locale.US, "+%.2f km", trip.bestRegenRangeKm) : "—");
|
||||
addPill(driveExtras, "GPS POINTS", String.format(Locale.US, "%d", trip.gpsPoints));
|
||||
}
|
||||
|
||||
@@ -239,79 +236,122 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
return span;
|
||||
}
|
||||
|
||||
private void openFullscreenMap() {
|
||||
private void openTripMapPage() {
|
||||
if (selectedTripId == TripDatabase.NO_TRIP) return;
|
||||
final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||
LinearLayout box = new LinearLayout(this); box.setOrientation(LinearLayout.VERTICAL); box.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
RouteMapView fullscreen = new RouteMapView(this); box.addView(fullscreen, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
LinearLayout bar = new LinearLayout(this); bar.setGravity(Gravity.CENTER_VERTICAL); bar.setPadding(20, 0, 20, 0);
|
||||
bar.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
TextView hint = text("Drag to pan • pinch to zoom", 11, UiTheme.MUTED, Typeface.NORMAL); bar.addView(hint, new LinearLayout.LayoutParams(0, 58, 1));
|
||||
Button close = actionButton("CLOSE MAP", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } });
|
||||
bar.addView(close, new LinearLayout.LayoutParams(150, 44));
|
||||
box.addView(bar, new LinearLayout.LayoutParams(-1, 58));
|
||||
dialog.setContentView(box); Window window = dialog.getWindow(); if (window != null) window.setLayout(-1, -1);
|
||||
dialog.show(); if (window != null) window.setLayout(-1, -1);
|
||||
new Thread(new Runnable() { @Override public void run() { final List<TripDatabase.TripPoint> route = database.getRoute(selectedTripId); handler.post(new Runnable() { @Override public void run() { fullscreen.setRoute(route); } }); } }, "mg-trip-map").start();
|
||||
Intent intent = new Intent(this, TripMapActivity.class);
|
||||
intent.putExtra(TripMapActivity.EXTRA_TRIP_ID, selectedTripId);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
private void openRawSamples() {
|
||||
private void openRawSamplesPage() {
|
||||
if (selectedTripId == TripDatabase.NO_TRIP) return;
|
||||
final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||
LinearLayout box = new LinearLayout(this); box.setOrientation(LinearLayout.VERTICAL); box.setPadding(22, 18, 22, 12); box.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
TextView title = text("RAW SAMPLE LOG", 19, UiTheme.TEXT, Typeface.BOLD); box.addView(title, new LinearLayout.LayoutParams(-1, 36));
|
||||
TextView subtitle = text("Tab-separated, monospace", 11, UiTheme.MUTED, Typeface.NORMAL); box.addView(subtitle, new LinearLayout.LayoutParams(-1, 22));
|
||||
TextView regenHeader = text("", 12, UiTheme.TEXT, Typeface.BOLD); regenHeader.setPadding(0, 12, 0, 6); box.addView(regenHeader, new LinearLayout.LayoutParams(-1, -2));
|
||||
TextView regenView = text("", 11, UiTheme.MUTED, Typeface.NORMAL); regenView.setTypeface(Typeface.MONOSPACE); regenView.setLineSpacing(1, 1f); box.addView(regenView, new LinearLayout.LayoutParams(-1, -2));
|
||||
final TextView content = text("Loading samples…", 11, UiTheme.TEXT, Typeface.NORMAL); content.setTypeface(Typeface.MONOSPACE);
|
||||
content.setPadding(12, 12, 12, 12); content.setBackgroundColor(UiTheme.SURFACE);
|
||||
ScrollView scroll = new ScrollView(this); scroll.addView(content); box.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
Button close = actionButton("CLOSE", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } });
|
||||
LinearLayout.LayoutParams cl = new LinearLayout.LayoutParams(130, 46); cl.setMargins(0, 12, 0, 0); box.addView(close, cl);
|
||||
dialog.setContentView(box); Window window = dialog.getWindow(); if (window != null) window.setLayout(-1, -1);
|
||||
dialog.show(); if (window != null) window.setLayout(-1, -1);
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final List<TripDatabase.TripSample> samples = database.getSamples(selectedTripId);
|
||||
final List<TripDatabase.RegenEvent> events = database.getRegenEvents(selectedTripId);
|
||||
handler.post(new Runnable() { @Override public void run() { regenHeader.setText("REGENERATION EVENTS"); regenView.setText(renderRegenText(events)); content.setText(rawText(samples)); } });
|
||||
} }, "mg-trip-raw").start();
|
||||
Intent intent = new Intent(this, RawSamplesActivity.class);
|
||||
intent.putExtra(RawSamplesActivity.EXTRA_TRIP_ID, selectedTripId);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
private static String renderRegenText(List<TripDatabase.RegenEvent> events) {
|
||||
if (events == null || events.isEmpty()) return "No measurable regeneration events recorded for this drive.";
|
||||
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss", Locale.US);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < events.size(); i++) {
|
||||
TripDatabase.RegenEvent event = events.get(i);
|
||||
out.append('#').append(i + 1).append(' ').append(time.format(new Date(event.startTime)))
|
||||
.append(" +").append(String.format(Locale.US, "%.3f kWh +%.2f km range", event.energyKwh, event.rangeKm));
|
||||
if (event.peakSpeedKph > 0f) out.append(String.format(Locale.US, " (%.0f km/h)", event.peakSpeedKph));
|
||||
out.append('\n');
|
||||
}
|
||||
return out.toString().trim();
|
||||
/** Two-step export prompt: choose format, then choose scope, then launch SAF. */
|
||||
private void promptExportOptions() {
|
||||
final String[] formats = { "JSON", "CSV", "HTML" };
|
||||
final String[] formatExtensions = { "json", "csv", "html" };
|
||||
final String[] formatMime = { "application/json", "text/csv", "text/html" };
|
||||
UiTheme.dialog(this)
|
||||
.setTitle("EXPORT DRIVE LOG")
|
||||
.setSingleChoiceItems(formats, 0, new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
dialog.dismiss();
|
||||
promptExportScope(which, formatExtensions[which], formatMime[which]);
|
||||
}
|
||||
})
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.show();
|
||||
}
|
||||
|
||||
private String rawText(List<TripDatabase.TripSample> samples) {
|
||||
if (samples.isEmpty()) return "No raw samples recorded for this drive.";
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("timestamp speed_kph soc_pct volts energy_kwh regen_kwh regen_range_km\n");
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
|
||||
for (TripDatabase.TripSample s : samples) {
|
||||
out.append(fmt.format(new Date(s.timestamp))).append(' ')
|
||||
.append(pad(speed(s.speedKph))).append(' ')
|
||||
.append(pad(percent(s.soc))).append(' ')
|
||||
.append(pad(decimal(s.volts))).append(' ')
|
||||
.append(pad(decimal(s.energyKwh))).append(' ')
|
||||
.append(pad(decimal(s.regenEnergyKwh))).append(' ')
|
||||
.append(pad(decimal(s.regenRangeKm))).append('\n');
|
||||
private void promptExportScope(final int formatIndex, final String extension, final String mime) {
|
||||
final String[] scopes;
|
||||
if (selectedTripId == TripDatabase.NO_TRIP) {
|
||||
scopes = new String[] { "All drives (overview + every trip)" };
|
||||
} else {
|
||||
scopes = new String[] {
|
||||
"All drives (overview + every trip)",
|
||||
"Selected drive only"
|
||||
};
|
||||
}
|
||||
return out.toString();
|
||||
AlertDialog dialog = UiTheme.dialog(this)
|
||||
.setTitle("EXPORT SCOPE")
|
||||
.setSingleChoiceItems(scopes, 0, new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int which) {
|
||||
d.dismiss();
|
||||
long scopeTripId = which == 1 ? selectedTripId : TripDatabase.NO_TRIP;
|
||||
launchExport(formatIndex, extension, mime, scopeTripId);
|
||||
}
|
||||
})
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.create();
|
||||
dialog.show();
|
||||
if (dialog.getListView() != null) dialog.getListView().setItemChecked(0, true);
|
||||
}
|
||||
private static String pad(String value) { String s = value; while (s.length() < 9) s += ' '; return s; }
|
||||
private static String speed(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.0f", v); }
|
||||
private static String percent(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.1f", v); }
|
||||
private static String decimal(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.3f", v); }
|
||||
private static String decimal(double v) { return Double.isNaN(v) ? "-" : String.format(Locale.US, "%.3f", v); }
|
||||
|
||||
private void launchExport(int formatIndex, String extension, String mime, long scopeTripId) {
|
||||
String stem = scopeTripId == TripDatabase.NO_TRIP ? "mg-utility-drive-log" : "mg-utility-drive-" + scopeTripId;
|
||||
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType(mime);
|
||||
intent.putExtra(Intent.EXTRA_TITLE, stem + "." + extension);
|
||||
try {
|
||||
currentExportFormat = formatIndex;
|
||||
currentExportScope = scopeTripId;
|
||||
startActivityForResult(intent, REQUEST_EXPORT_DRIVE_LOG);
|
||||
} catch (Exception e) {
|
||||
android.widget.Toast.makeText(this, "No file picker available", android.widget.Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
private int currentExportFormat = -1;
|
||||
private long currentExportScope = TripDatabase.NO_TRIP;
|
||||
|
||||
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode != REQUEST_EXPORT_DRIVE_LOG || resultCode != RESULT_OK || data == null || data.getData() == null) return;
|
||||
final java.io.OutputStream out;
|
||||
try {
|
||||
out = getContentResolver().openOutputStream(data.getData());
|
||||
} catch (Exception e) {
|
||||
android.widget.Toast.makeText(this, "Drive log export failed", android.widget.Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
if (out == null) { android.widget.Toast.makeText(this, "Drive log export failed", android.widget.Toast.LENGTH_LONG).show(); return; }
|
||||
final int formatIndex = currentExportFormat;
|
||||
final long scopeTripId = currentExportScope;
|
||||
exportButton.setEnabled(false);
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final boolean[] ok = new boolean[]{false};
|
||||
try {
|
||||
String payload;
|
||||
switch (formatIndex) {
|
||||
case 1: payload = database.exportCsv(scopeTripId); break;
|
||||
case 2: payload = database.exportHtml(scopeTripId); break;
|
||||
case 0:
|
||||
default: payload = database.exportJson(scopeTripId); break;
|
||||
}
|
||||
java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(out, java.nio.charset.StandardCharsets.UTF_8);
|
||||
writer.write(payload); writer.flush(); writer.close();
|
||||
ok[0] = true;
|
||||
} catch (Exception e) {
|
||||
try { out.close(); } catch (Exception ignored) { }
|
||||
}
|
||||
handler.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
exportButton.setEnabled(true);
|
||||
android.widget.Toast.makeText(TripsActivity.this, ok[0] ? "Drive log exported" : "Drive log export failed",
|
||||
android.widget.Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "mg-trip-export").start();
|
||||
}
|
||||
|
||||
private static float topSpeed(List<TripDatabase.TripSample> samples) { float max = 0; for (TripDatabase.TripSample s : samples) if (!Float.isNaN(s.speedKph)) max = Math.max(max, s.speedKph); return max; }
|
||||
|
||||
private void loadTripsRowsOnly() { new Thread(new Runnable() { @Override public void run() { final List<TripDatabase.TripSummary> 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, 72)); } } }); } }, "mg-trip-list-refresh").start(); }
|
||||
@@ -320,6 +360,8 @@ public final class TripsActivity extends AnimatedActivity {
|
||||
String distance = trip.distanceKm() >= 0.1 ? String.format(Locale.US, "%.1f km", trip.distanceKm()) : "<0.1 km";
|
||||
TextView row = text(date + " • " + distance + " • top " + String.format(Locale.US, "%.0f km/h", trip.topSpeedKph), 12, UiTheme.TEXT, Typeface.NORMAL);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL); row.setPadding(14, 0, 10, 0);
|
||||
row.setSingleLine(true);
|
||||
row.setEllipsize(TextUtils.TruncateAt.END);
|
||||
row.setBackground(UiTheme.surface(trip.id == selectedTripId ? UiTheme.SURFACE_PRESSED : UiTheme.SURFACE_HIGH, 8));
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
/** Shared visual language for the MG/SAIC head-unit screens. */
|
||||
@@ -46,6 +47,16 @@ final class UiTheme {
|
||||
static int withAlpha(int color, int alpha) {
|
||||
return Color.argb(Math.max(0, Math.min(255, alpha)), Color.red(color), Color.green(color), Color.blue(color));
|
||||
}
|
||||
|
||||
/** Apply the active palette's primary accent to a standard platform SeekBar. */
|
||||
static void tintSeekBar(SeekBar seekBar) {
|
||||
if (seekBar == null) return;
|
||||
// AppTheme's platform accent is only a fallback. Explicitly tint controls
|
||||
// so switching to a custom/preset palette also updates the slider track/thumb.
|
||||
ColorStateList colors = ColorStateList.valueOf(RED);
|
||||
seekBar.setProgressTintList(colors);
|
||||
seekBar.setThumbTintList(colors);
|
||||
}
|
||||
static final String PREF_THEME = "theme";
|
||||
static final String PREF_CUSTOM_PREFIX = "custom_color_";
|
||||
static final int THEME_DEFAULT = 0;
|
||||
@@ -58,6 +69,15 @@ final class UiTheme {
|
||||
static final int THEME_DARK_MAGENTA = 7;
|
||||
static final int PAGE_HEADER_HEIGHT = 56;
|
||||
static final int BACK_BUTTON_WIDTH = 120;
|
||||
static final String PREF_AUTO_BRIGHTNESS_ENABLED = "auto_brightness_enabled";
|
||||
static final String PREF_AUTO_BRIGHTNESS_PEAK_MINUTES = "auto_brightness_peak_minutes";
|
||||
static final String PREF_AUTO_BRIGHTNESS_DARK_MINUTES = "auto_brightness_dark_minutes";
|
||||
static final String PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES = "auto_brightness_transition_minutes";
|
||||
static final String PREF_AUTO_BRIGHTNESS_PEAK_PERCENT = "auto_brightness_peak_percent";
|
||||
static final String PREF_AUTO_BRIGHTNESS_DARK_PERCENT = "auto_brightness_dark_percent";
|
||||
static final String PREF_AUTO_BRIGHTNESS_LAST_TICK_AT = "auto_brightness_last_tick_at";
|
||||
static final String PREF_AUTO_BRIGHTNESS_LAST_VALUE = "auto_brightness_last_value";
|
||||
static final String PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL = "auto_brightness_user_override_until";
|
||||
|
||||
static int dp(Context c, int value) {
|
||||
return Math.round(value * c.getResources().getDisplayMetrics().density);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.graphics.Typeface;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
/** Swipe-right panel reserved for home-screen widgets. */
|
||||
final class WidgetsPanelOverlay extends FrameLayout {
|
||||
private static final float SWIPE_THRESHOLD = 80f;
|
||||
|
||||
private final Activity activity;
|
||||
private final FrameLayout panel;
|
||||
private final int animationDuration = 230;
|
||||
private boolean open;
|
||||
private float downX;
|
||||
private float downY;
|
||||
private float panelWidth;
|
||||
|
||||
WidgetsPanelOverlay(Activity activity) {
|
||||
super(activity);
|
||||
this.activity = activity;
|
||||
setClickable(true);
|
||||
setVisibility(GONE);
|
||||
panel = new FrameLayout(activity);
|
||||
panel.setVisibility(INVISIBLE);
|
||||
panel.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
panel.addView(buildContent(), new FrameLayout.LayoutParams(-1, -1));
|
||||
addView(panel, new FrameLayout.LayoutParams(-1, -1, Gravity.LEFT));
|
||||
}
|
||||
|
||||
boolean panelEnabled() {
|
||||
return activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE)
|
||||
.getBoolean(MainActivity.PREF_WIDGETS_PANEL_ENABLED, false);
|
||||
}
|
||||
|
||||
boolean isOpen() { return open; }
|
||||
|
||||
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
panelWidth = w;
|
||||
if (!open) panel.setTranslationX(w > 0 ? -w : -Math.max(1, getWidth()));
|
||||
}
|
||||
|
||||
@Override public boolean onTouchEvent(MotionEvent event) {
|
||||
if (!panelEnabled()) return false;
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
downX = event.getX();
|
||||
downY = event.getY();
|
||||
return true;
|
||||
case MotionEvent.ACTION_UP:
|
||||
float dx = event.getX() - downX;
|
||||
float dy = event.getY() - downY;
|
||||
if (Math.abs(dx) > SWIPE_THRESHOLD && Math.abs(dx) > Math.abs(dy)) {
|
||||
if (!open && dx > 0f) openPanel();
|
||||
else if (open && dx < 0f) closePanel();
|
||||
}
|
||||
return true;
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
return true;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void openPanel() {
|
||||
if (open || !panelEnabled()) return;
|
||||
open = true;
|
||||
setVisibility(VISIBLE);
|
||||
panel.setVisibility(VISIBLE);
|
||||
panel.setTranslationX(panelWidth > 0 ? -panelWidth : -Math.max(1, getWidth()));
|
||||
panel.animate().translationX(0f).setDuration(animationDuration).start();
|
||||
}
|
||||
|
||||
void closePanel() {
|
||||
if (!open) return;
|
||||
open = false;
|
||||
int end = panelWidth > 0 ? -(int) panelWidth : -Math.max(1, getWidth());
|
||||
panel.animate().translationX(end).setDuration(animationDuration)
|
||||
.withEndAction(new Runnable() {
|
||||
@Override public void run() {
|
||||
panel.setVisibility(INVISIBLE);
|
||||
setVisibility(GONE);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
private View buildContent() {
|
||||
LinearLayout column = new LinearLayout(activity);
|
||||
column.setOrientation(LinearLayout.VERTICAL);
|
||||
int pad = UiTheme.dp(activity, 24);
|
||||
column.setPadding(pad, UiTheme.dp(activity, 18), pad, pad);
|
||||
|
||||
TextView title = UiTheme.title(activity, "WIDGETS", 24);
|
||||
title.setGravity(Gravity.CENTER_VERTICAL);
|
||||
column.addView(title, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 48)));
|
||||
|
||||
TextView hint = UiTheme.text(activity,
|
||||
"Swipe left to return to the home screen", 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
hint.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
|
||||
column.addView(hint, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 30)));
|
||||
|
||||
TextView empty = UiTheme.text(activity,
|
||||
"Widgets will appear here in a future update.", 18, UiTheme.MUTED, Typeface.NORMAL);
|
||||
empty.setGravity(Gravity.CENTER);
|
||||
column.addView(empty, new LinearLayout.LayoutParams(-1, 0, 1f));
|
||||
return column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import cloud.molberg.mgutility.AdaptiveAudioCurve;
|
||||
|
||||
public final class AdaptiveAudioCurveTest {
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static void close(float actual, float expected, String message) {
|
||||
if (Math.abs(actual - expected) > 0.001f) {
|
||||
throw new AssertionError(message + ": expected " + expected + ", got " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
close(AdaptiveAudioCurve.multiplierPercent(0, 20, 90, 70, 100, 110, 110),
|
||||
90, "below level 1");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(20, 20, 90, 70, 100, 110, 110),
|
||||
90, "at level 1");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(45, 20, 90, 70, 100, 110, 110),
|
||||
95, "between levels 1 and 2");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(70, 20, 90, 70, 100, 110, 110),
|
||||
100, "at level 2");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(90, 20, 90, 70, 100, 110, 110),
|
||||
105, "between levels 2 and 3");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(140, 20, 90, 70, 100, 110, 110),
|
||||
110, "above level 3");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(300, 20, 90, 70, 100, 110, 110),
|
||||
110, "level 3 is a hard plateau");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(Float.NaN, 20, 90, 70, 100, 110, 110),
|
||||
90, "invalid speed is stationary");
|
||||
|
||||
check(AdaptiveAudioCurve.targetVolume(10, 0, 20, 90) == 9,
|
||||
"90 percent scales the base volume");
|
||||
check(AdaptiveAudioCurve.targetVolume(10, 0, 20, 110) == 11,
|
||||
"110 percent scales the base volume");
|
||||
check(AdaptiveAudioCurve.targetVolume(19, 0, 20, 150) == 20,
|
||||
"target clamps to stream maximum");
|
||||
check(AdaptiveAudioCurve.targetVolume(7, 2, 12, 50) == 5,
|
||||
"nonzero stream minimum is respected");
|
||||
check(AdaptiveAudioCurve.stepToward(5, 12, 0, 20) == 6,
|
||||
"automatic increase is one notch");
|
||||
check(AdaptiveAudioCurve.stepToward(12, 5, 0, 20) == 11,
|
||||
"automatic decrease is one notch");
|
||||
check(AdaptiveAudioCurve.stepToward(8, 8, 0, 20) == 8,
|
||||
"settled volume does not move");
|
||||
|
||||
float at80 = AdaptiveAudioCurve.multiplierPercent(80, 20, 90, 70, 100, 110, 110);
|
||||
float afterTwoNotches = 12f / 20f;
|
||||
float newReference = AdaptiveAudioCurve.referenceFraction(afterTwoNotches, at80);
|
||||
close(newReference * at80 / 100f, afterTwoNotches,
|
||||
"manual two-notch change remains authoritative at 80 km/h");
|
||||
close(AdaptiveAudioCurve.multiplierPercent(180, 20, 90, 70, 100, 110, 110),
|
||||
110f, "speed above level 3 cannot increase multiplier further");
|
||||
|
||||
System.out.println("AdaptiveAudioCurveTest: OK");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import cloud.molberg.mgutility.BrightnessSchedule;
|
||||
import java.util.Calendar;
|
||||
|
||||
public final class BrightnessScheduleTest {
|
||||
private static long at(int hour, int minute) { return at(2026, 9, 6, hour, minute); }
|
||||
private static long at(int year, int month, int day, int hour, int minute) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.set(year, month - 1, day, hour, minute, 0);
|
||||
c.set(Calendar.MILLISECOND, 0);
|
||||
return c.getTimeInMillis();
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Outside both transition windows: should land on the most recently completed anchor.
|
||||
check(BrightnessSchedule.compute(at(12, 0), 7 * 60, 21 * 60, 10, 100, 0, 50) == 100,
|
||||
"midday is fully peak");
|
||||
check(BrightnessSchedule.compute(at(3, 0), 7 * 60, 21 * 60, 10, 100, 0, 50) == 0,
|
||||
"deep night is fully dark");
|
||||
|
||||
// The configured anchor is fully reached; the preceding minutes fade into it.
|
||||
check(BrightnessSchedule.compute(at(7, 0), 7 * 60, 21 * 60, 10, 100, 0, 5) == 100,
|
||||
"peak anchor is fully bright");
|
||||
int midMorning = BrightnessSchedule.compute(at(6, 55), 7 * 60, 21 * 60, 10, 100, 0, 5);
|
||||
check(midMorning > 0 && midMorning < 100, "morning peak is interpolated: " + midMorning);
|
||||
int midAfternoon = BrightnessSchedule.compute(at(20, 55), 7 * 60, 21 * 60, 10, 100, 0, 100);
|
||||
check(midAfternoon > 0 && midAfternoon < 100, "evening dark is interpolated: " + midAfternoon);
|
||||
|
||||
// Midnight wrap-around: at 23:55 the schedule should still be in dark territory.
|
||||
check(BrightnessSchedule.compute(at(23, 55), 7 * 60, 21 * 60, 10, 100, 0, 100) == 0,
|
||||
"late night is fully dark after wrap");
|
||||
|
||||
// Custom peak/dark percentages propagate.
|
||||
check(BrightnessSchedule.compute(at(12, 0), 7 * 60, 21 * 60, 10, 80, 20, 50) == 80,
|
||||
"custom peak percent applied");
|
||||
|
||||
// Zero transition still snaps at the anchor without throwing.
|
||||
int snapPeak = BrightnessSchedule.compute(at(7, 0), 7 * 60, 21 * 60, 1, 100, 0, 5);
|
||||
check(snapPeak == 100, "anchor is fully peak at peak time: " + snapPeak);
|
||||
int snapDark = BrightnessSchedule.compute(at(21, 0), 7 * 60, 21 * 60, 1, 100, 0, 100);
|
||||
check(snapDark == 0, "anchor is fully dark at dark time: " + snapDark);
|
||||
|
||||
// Anchor after midnight with dark before peak should still work (custom config).
|
||||
check(BrightnessSchedule.compute(at(10, 0), 1 * 60, 11 * 60, 10, 100, 0, 50) == 100,
|
||||
"custom peak/dark with both daytime hours works");
|
||||
check(BrightnessSchedule.compute(at(14, 0), 1 * 60, 11 * 60, 10, 100, 0, 50) == 0,
|
||||
"custom peak/dark with both daytime hours is dark outside");
|
||||
|
||||
// Format helper round-trips minutes-of-day.
|
||||
check("07:30".equals(BrightnessSchedule.formatMinutes(7 * 60 + 30)), "format peak");
|
||||
check("00:00".equals(BrightnessSchedule.formatMinutes(0)), "format midnight");
|
||||
|
||||
System.out.println("BrightnessScheduleTest: OK");
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -8,8 +8,12 @@ javac -source 8 -target 8 -d "$OUT" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsProfile.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/SpeedAudioCurve.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java" \
|
||||
"$ROOT/tests/VehicleSettingsCatalogTest.java" "$ROOT/tests/VehicleSettingsCoordinatorTest.java" \
|
||||
"$ROOT/tests/SpeedAudioCurveTest.java"
|
||||
"$ROOT/tests/SpeedAudioCurveTest.java" "$ROOT/tests/AdaptiveAudioCurveTest.java" "$ROOT/src/cloud/molberg/mgutility/BrightnessSchedule.java" \
|
||||
"$ROOT/tests/BrightnessScheduleTest.java"
|
||||
java -cp "$OUT" VehicleSettingsCatalogTest
|
||||
java -cp "$OUT" VehicleSettingsCoordinatorTest
|
||||
java -cp "$OUT" SpeedAudioCurveTest
|
||||
java -cp "$OUT" AdaptiveAudioCurveTest
|
||||
java -cp "$OUT" BrightnessScheduleTest
|
||||
Reference in new issue
Block a user