diff --git a/AndroidManifest.xml b/AndroidManifest.xml index d696d73..ebe666c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -44,6 +44,7 @@ + @@ -52,6 +53,7 @@ + @@ -65,6 +67,7 @@ + diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 087f777..2988836 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -26,3 +26,12 @@ 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. + +## QR Code generator library + +`src/io/nayuki/qrcodegen/` is the unmodified Java QR Code generator library by +Project Nayuki (https://www.nayuki.io/page/qr-code-generator-library), used to +draw the Hermes pairing QR code. + +MIT License. Copyright (c) Project Nayuki. The full license text is retained in +each source file header. diff --git a/docs/HERMES_AGENT.md b/docs/HERMES_AGENT.md index 8334bcd..228149b 100644 --- a/docs/HERMES_AGENT.md +++ b/docs/HERMES_AGENT.md @@ -9,25 +9,33 @@ models, skills, and toolsets through an authenticated HTTP API. The dashboard uses a browser-oriented JSON-RPC WebSocket with short-lived authentication tickets and does not add agent capabilities needed by this feature. -## Running Hermes instance +## Connecting your own Hermes (pair with phone) -The development Hermes instance is configured as: +MG Utility works with any Hermes Agent that has the API server platform enabled +(`API_SERVER_KEY` set; default port 8642). Nothing about a specific Hermes +instance is built into the app. -```text -API server: http://10.0.0.74:18793 -API key: API_SERVER_KEY in ~/.hermes/.env -Dashboard: https://gateway.bonzi.cc -``` +1. In MG Utility open **Settings → Misc → Hermes agent assistant** and select + **Pair with phone**. The car shows a QR code, a pairing code, and a + 4-character check code. +2. Scan the QR code with your phone, or open `analytics.molberg.cloud/pair` and + type the pairing code. +3. On the phone, enter your Hermes server URL and `API_SERVER_KEY` (paste it + from a password manager), check that the check code matches the car, and tap + **Send to car**. +4. The car decrypts the details, stores the key with Android Keystore, runs the + connection test, and the phone shows **Connected**. -The dashboard is useful for inspecting the resulting `MG car voice assistant` -session, but the app talks to port `18793` directly. The car must be able to -reach `10.0.0.74` on the local network. Use an HTTPS reverse proxy or VPN when -connecting across an untrusted network. +The phone encrypts the URL and key for that car's one-time key (ECDH P-256 + +HKDF-SHA256 + AES-256-GCM). The pairing relay only forwards ciphertext, keeps it +in memory for at most 5 minutes, and cannot read it. Codes are single-use. -In MG Utility, open **Settings → Misc → Hermes agent assistant**, enter the API -server address and `API_SERVER_KEY`, enable the integration, and select **Test -connection**. The key is encrypted at rest using Android Keystore and is not -included in MG Utility settings exports. +The car itself must be able to reach the Hermes URL. A LAN address like +`http://192.168.1.20:8642` only works while the car is on that network. Use an +HTTPS reverse proxy or VPN for use elsewhere. + +**Advanced / manual setup** on the same screen still lets you type the server +URL and key directly. The key is not included in MG Utility settings exports. ## Conversation behavior @@ -76,7 +84,19 @@ Pressing the key opens the listening screen. Android's speech recognizer shows partial text live; releasing the key finalizes the transcript and sends it to the persistent Hermes session. Microphone permission must be granted. -### Head units without Android speech recognition +### Head units without Android speech recognition (automatic on-device fallback) + +With the default **Automatic** voice engine, MG Utility uses Android's speech +recognizer when the head unit has one. If it has no recognizer, or it fails, +MG Utility switches to the bundled offline English sherpa-onnx model and the +microphone. No extra setup is needed beyond microphone permission. The MG4 has no +Android recognizer, so it always uses this path. The model is copied to app +storage in the background at app start (once Hermes is enabled) and after +pairing, so the first press doesn't wait for the 43 MB copy. Model loading and +decoding run on their own worker thread; audio captured while the model loads is +queued and decoded once it is ready. + +### Optional transcription server If the head unit has no Android recognition service, configure a separate **Transcription endpoint**, **Transcription API key**, and **Transcription model** @@ -123,7 +143,7 @@ The API follows the official Hermes API-server contract: ```bash curl -H "Authorization: Bearer $API_SERVER_KEY" \ - http://10.0.0.74:18793/v1/capabilities + https://your-hermes-server/v1/capabilities ``` MG Utility requires the server to advertise `features.session_chat: true`, then diff --git a/res/drawable/ic_seat_heat.xml b/res/drawable/ic_seat_heat.xml new file mode 100644 index 0000000..13ba3c8 --- /dev/null +++ b/res/drawable/ic_seat_heat.xml @@ -0,0 +1,4 @@ + + + + diff --git a/res/drawable/ic_wheel_heat.xml b/res/drawable/ic_wheel_heat.xml new file mode 100644 index 0000000..783c810 --- /dev/null +++ b/res/drawable/ic_wheel_heat.xml @@ -0,0 +1,4 @@ + + + + diff --git a/src/cloud/molberg/mgutility/ArrivalBriefing.java b/src/cloud/molberg/mgutility/ArrivalBriefing.java index 9a5d065..5e95844 100644 --- a/src/cloud/molberg/mgutility/ArrivalBriefing.java +++ b/src/cloud/molberg/mgutility/ArrivalBriefing.java @@ -14,7 +14,8 @@ final class ArrivalBriefing { 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))); + .append(String.format(Locale.US, "%.0f km", + Math.max(0.0, (double) (trip.startRangeKm - trip.endRangeKm)))); } double energy = trip.reportedEnergyUsed(); if (!Double.isNaN(energy)) text.append("\nEnergy used: ").append(String.format(Locale.US, "%.2f kWh", energy)); diff --git a/src/cloud/molberg/mgutility/BootReceiver.java b/src/cloud/molberg/mgutility/BootReceiver.java index 26bf91b..27602a0 100644 --- a/src/cloud/molberg/mgutility/BootReceiver.java +++ b/src/cloud/molberg/mgutility/BootReceiver.java @@ -20,11 +20,20 @@ public final class BootReceiver extends BroadcastReceiver { // JobScheduler jobs are persisted on API 24+, but a few automotive ROMs // clear them during an update. Re-arm the update check on every boot and // package replacement without coupling it to trip tracking startup. - if (UpdateManager.notifyEnabled(context)) UpdateScheduler.schedule(context); + // ConfigStore backs onto credential-encrypted storage, which is not + // available for LOCKED_BOOT_COMPLETED / early PACKAGE_REPLACED broadcasts; + // skip until the user unlocks, when this receiver runs again anyway. + if (userUnlocked(context)) { + try { + if (UpdateManager.notifyEnabled(context)) UpdateScheduler.schedule(context); + } catch (IllegalStateException locked) { + Log.w(TAG, "update check storage unavailable at boot", locked); + } + } 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); + BrightnessScheduler.rearmAfterBoot(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 diff --git a/src/cloud/molberg/mgutility/BrightnessSchedule.java b/src/cloud/molberg/mgutility/BrightnessSchedule.java index d4bf5a4..6be18a1 100644 --- a/src/cloud/molberg/mgutility/BrightnessSchedule.java +++ b/src/cloud/molberg/mgutility/BrightnessSchedule.java @@ -13,7 +13,14 @@ public final class BrightnessSchedule { 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; + public static final long USER_OVERRIDE_PAUSE_MS = 60L * 60L * 1000L; + /** Difference on the 0..255 scale that counts as someone else changing the brightness. */ + static final int MANUAL_CHANGE_THRESHOLD = 10; + + /** True when the panel brightness moved away from what the schedule last applied. */ + public static boolean isManualChange(int lastApplied, int actual) { + return lastApplied >= 0 && actual >= 0 && Math.abs(actual - lastApplied) > MANUAL_CHANGE_THRESHOLD; + } /** Return the target brightness percentage for an epoch timestamp. */ public static int compute(long nowMillis, int peakMinutes, int darkMinutes, int transitionMinutes, diff --git a/src/cloud/molberg/mgutility/BrightnessScheduler.java b/src/cloud/molberg/mgutility/BrightnessScheduler.java index fa0c00d..e265222 100644 --- a/src/cloud/molberg/mgutility/BrightnessScheduler.java +++ b/src/cloud/molberg/mgutility/BrightnessScheduler.java @@ -7,6 +7,8 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import android.provider.Settings; /** Alarm-driven automatic display brightness controller. */ @@ -14,6 +16,13 @@ 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; + /** Last 0..255 value the schedule confirmed on the panel (-1 = unknown). */ + static final String PREF_LAST_APPLIED_SYSTEM = "auto_brightness_last_applied_system"; + /** Until this time the head unit is still settling after boot: re-apply, never infer manual changes. */ + static final String PREF_SETTLE_UNTIL = "auto_brightness_settle_until"; + private static final long SETTLE_MS = 90_000L; + private static final long[] STARTUP_RETRIES_MS = { 2_000L, 5_000L, 10_000L, 20_000L, 40_000L, 75_000L }; + private static final Handler MAIN = new Handler(Looper.getMainLooper()); /** Rebuild the minute alarm; safe to call after every settings edit or boot. */ public static void rearm(Context context) { @@ -33,7 +42,26 @@ public final class BrightnessScheduler extends BroadcastReceiver { 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(); + System.currentTimeMillis() + BrightnessSchedule.USER_OVERRIDE_PAUSE_MS) + .putInt(PREF_LAST_APPLIED_SYSTEM, -1).apply(); + } + + /** + * Boot/startup path. The SAIC settings service binds asynchronously and restores its own + * brightness after boot, so a single write right away either fails or gets overwritten + * (the slider then shows the scheduled 0% while the panel is at 100%). Re-apply a few times + * while the unit settles; manual-change detection is off during that window. + */ + public static void rearmAfterBoot(final Context context) { + if (context == null) return; + final Context app = context.getApplicationContext(); + prefs(app).edit().putLong(PREF_SETTLE_UNTIL, System.currentTimeMillis() + SETTLE_MS) + .putInt(PREF_LAST_APPLIED_SYSTEM, -1).apply(); + try { MgServiceBridge.get().ensureBound(app); } catch (Exception ignored) { } + rearm(app); + for (long delay : STARTUP_RETRIES_MS) { + MAIN.postDelayed(new Runnable() { @Override public void run() { rearm(app); } }, delay); + } } @Override public void onReceive(Context context, Intent intent) { @@ -45,6 +73,18 @@ public final class BrightnessScheduler extends BroadcastReceiver { SharedPreferences p = prefs(context); long overrideUntil = p.getLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL, 0L); if (overrideUntil > now) return; + MgServiceBridge bridge = MgServiceBridge.get(); + try { bridge.ensureBound(context); } catch (Exception ignored) { } + boolean settling = now < p.getLong(PREF_SETTLE_UNTIL, 0L); + // Someone changed the brightness since our last write (OEM settings, steering-wheel + // keys, another app): respect it for the next hour instead of fighting it. + if (!settling && bridge.hasBrightnessService()) { + int actual = bridge.getBrightness(); + if (BrightnessSchedule.isManualChange(p.getInt(PREF_LAST_APPLIED_SYSTEM, -1), actual)) { + pauseForManualOverride(context); + 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), @@ -53,9 +93,20 @@ public final class BrightnessScheduler extends BroadcastReceiver { 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)) { + SharedPreferences.Editor edit = p.edit(); + // While settling after boot the SAIC service can already report the target value while + // the panel is still at its boot level, so a same-value write is ignored. Nudge one step + // away first so the service always pushes a real change to the panel. + if (settling && bridge.hasBrightnessService()) bridge.setBrightness(system > 0 ? system - 1 : system + 1); + if (bridge.setBrightness(system)) { + // Record what the panel really reports so later comparisons use its own scale. + int confirmed = bridge.getBrightness(); + edit.putInt(PREF_LAST_APPLIED_SYSTEM, confirmed >= 0 ? confirmed : system); + } else { + // The SAIC service is not bound yet (typical right after boot). Writing only the + // Android setting would make the slider show the target while the panel stays at + // its old level, so keep the fallback but retry shortly through the real service. + edit.putInt(PREF_LAST_APPLIED_SYSTEM, -1); try { if (Build.VERSION.SDK_INT < 23 || Settings.System.canWrite(context)) { Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, system); @@ -63,8 +114,10 @@ public final class BrightnessScheduler extends BroadcastReceiver { Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); } } catch (Exception ignored) { } + final Context app = context.getApplicationContext(); + MAIN.postDelayed(new Runnable() { @Override public void run() { rearm(app); } }, 3_000L); } - p.edit().putInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, target) + edit.putInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, target) .putLong(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_TICK_AT, now).apply(); } diff --git a/src/cloud/molberg/mgutility/CarHvacAccess.java b/src/cloud/molberg/mgutility/CarHvacAccess.java new file mode 100644 index 0000000..552b416 --- /dev/null +++ b/src/cloud/molberg/mgutility/CarHvacAccess.java @@ -0,0 +1,121 @@ +package cloud.molberg.mgutility; + +import android.content.ComponentName; +import android.content.Context; +import android.content.ServiceConnection; +import android.os.IBinder; +import android.util.Log; +import java.lang.reflect.Method; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Direct float access to the HVAC vehicle properties through android.car's CarHvacManager. + * + * SAIC's IAirConditionService only exposes whole-degree temperatures, but underneath it writes + * the float VHAL property HVAC_DRVTEMP_SET (0x1560250b, area 0x31), where 17.5 means LO and + * 32.5 means HI. MG Utility runs as android.uid.system, which passes CarService's + * CONTROL_CAR_CLIMATE check, so it can read and write that property directly. That is what + * allows 0.5 degree steps and the cabin/outside sensor readings. + * + * The android.car API is on this unit's boot classpath but not in android.jar, so it is + * reached by reflection. Every call is blocking and best-effort: never call on the UI thread. + */ +final class CarHvacAccess { + private static final String TAG = "CarHvacAccess"; + + static final int PROP_DRIVER_SET = 0x1560250b, AREA_DRIVER = 0x31; + static final int PROP_PASSENGER_SET = 0x1560250c, AREA_PASSENGER = 0x44; + static final int PROP_OUTSIDE = 0x15602511; + static final int PROP_CABIN = 0x1560252a; // HVAC_AMBIENT_TEMPERATURE, read-only + static final int AREA_GLOBAL = 0x75; + + static final float SET_LO = 17.5f, SET_HI = 32.5f; + static final float SET_MIN = 18.0f, SET_MAX = 32.0f; + + private static final Object LOCK = new Object(); + private static Object car; + private static Object hvac; + + private CarHvacAccess() { } + + /** Next setpoint after one 0.5 degree step. Below 18 becomes LO and above 32 becomes HI. */ + static float step(float current, int direction) { + float base = Float.isNaN(current) ? 21.0f : current; + if (base <= SET_LO) base = direction > 0 ? SET_MIN - 0.5f : SET_LO; + if (base >= SET_HI) base = direction < 0 ? SET_MAX + 0.5f : SET_HI; + float next = Math.round((base + 0.5f * direction) * 2f) / 2f; + if (next < SET_MIN) return SET_LO; + if (next > SET_MAX) return SET_HI; + return next; + } + + static String label(float value) { + if (Float.isNaN(value) || value < 10f || value > 40f) return "--"; + if (value <= SET_LO) return "LO"; + if (value >= SET_HI) return "HI"; + return (value == Math.floor(value) ? String.valueOf((int) value) : String.valueOf(value)) + "\u00B0"; + } + + static float get(Context context, int prop, int area) { + Object manager = manager(context); + if (manager == null) return Float.NaN; + try { + Object value = manager.getClass().getMethod("getFloatProperty", int.class, int.class) + .invoke(manager, prop, area); + float f = value instanceof Float ? (Float) value : Float.NaN; + return f <= -1000f || f >= 1000f ? Float.NaN : f; // OEM -10000 = invalid + } catch (Throwable error) { + Log.w(TAG, "getFloatProperty 0x" + Integer.toHexString(prop) + " failed", error); + return Float.NaN; + } + } + + static boolean set(Context context, int prop, int area, float value) { + Object manager = manager(context); + if (manager == null) return false; + try { + manager.getClass().getMethod("setFloatProperty", int.class, int.class, float.class) + .invoke(manager, prop, area, value); + return true; + } catch (Throwable error) { + Log.w(TAG, "setFloatProperty 0x" + Integer.toHexString(prop) + " failed", error); + return false; + } + } + + private static Object manager(Context context) { + synchronized (LOCK) { if (hvac != null) return hvac; } + final CountDownLatch connected = new CountDownLatch(1); + try { + Class carClass = Class.forName("android.car.Car"); + Object instance; + synchronized (LOCK) { + instance = car; + if (instance == null) { + ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder service) { connected.countDown(); } + @Override public void onServiceDisconnected(ComponentName name) { + synchronized (LOCK) { hvac = null; car = null; } + } + }; + instance = carClass.getMethod("createCar", Context.class, ServiceConnection.class) + .invoke(null, context.getApplicationContext(), connection); + carClass.getMethod("connect").invoke(instance); + car = instance; + } else connected.countDown(); + } + Method isConnected = null; + try { isConnected = carClass.getMethod("isConnected"); } catch (Throwable ignored) { } + boolean ready = connected.await(1500, TimeUnit.MILLISECONDS); + if (!ready && isConnected != null) ready = Boolean.TRUE.equals(isConnected.invoke(instance)); + if (!ready) return null; + Object manager = carClass.getMethod("getCarManager", String.class).invoke(instance, "hvac"); + synchronized (LOCK) { hvac = manager; } + return manager; + } catch (Throwable error) { + Log.w(TAG, "CarHvacManager unavailable", error); + return null; + } + } +} diff --git a/src/cloud/molberg/mgutility/ClimateActivity.java b/src/cloud/molberg/mgutility/ClimateActivity.java new file mode 100644 index 0000000..2086997 --- /dev/null +++ b/src/cloud/molberg/mgutility/ClimateActivity.java @@ -0,0 +1,354 @@ +package cloud.molberg.mgutility; + +import android.content.pm.ActivityInfo; +import android.graphics.Typeface; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; +import java.util.Locale; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** Climate, seat heating and steering-wheel heating through SAIC's air-condition service. */ +public final class ClimateActivity extends AnimatedActivity { + private static final long POLL_MS = 1500; + + private final Handler ui = new Handler(Looper.getMainLooper()); + private final ExecutorService worker = Executors.newSingleThreadExecutor(); + private ClimateLink link; + private ClimateGateway.State state = new ClimateGateway.State(); + private boolean running; + private long renderedThemeVersion; + + private TextView status, outside; + private TextView driverTemp, passengerTemp, fanValue, blowerValue; + private Button power, ac, auto, recirc, econ, frontDefrost, rearDefrost, wheel; + private final Button[] driverSeat = new Button[4]; + private final Button[] passengerSeat = new Button[4]; + + private final Runnable poll = new Runnable() { + @Override public void run() { + if (!running) return; + refresh(); + ui.postDelayed(this, POLL_MS); + } + }; + + @Override public void onCreate(Bundle saved) { + super.onCreate(saved); + UiTheme.applyFontScale(this); + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + setContentView(buildUi()); + renderedThemeVersion = UiTheme.version(); + link = ClimateLink.get(this); + link.setListener(new ClimateLink.Listener() { + @Override public void onClimateAvailable() { + ui.post(new Runnable() { @Override public void run() { refresh(); } }); + } + }); + } + + @Override protected void onResume() { + super.onResume(); + UiTheme.refreshTheme(this); + if (UiTheme.version() != renderedThemeVersion) { + setContentView(buildUi()); + renderedThemeVersion = UiTheme.version(); + render(); + } + running = true; + ui.removeCallbacks(poll); + ui.post(poll); + } + + @Override protected void onPause() { + running = false; + ui.removeCallbacks(poll); + super.onPause(); + } + + @Override protected void onDestroy() { + if (link != null) link.setListener(null); + worker.shutdownNow(); + super.onDestroy(); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + // ------------------------------------------------------------------ UI + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(dp(24), dp(10), dp(24), dp(14)); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "CLIMATE", 26), new LinearLayout.LayoutParams(dp(220), dp(56))); + status = UiTheme.text(this, "Connecting to vehicle service\u2026", 12, UiTheme.MUTED, Typeface.NORMAL); + status.setGravity(Gravity.CENTER_VERTICAL); + header.addView(status, new LinearLayout.LayoutParams(0, dp(56), 1f)); + outside = UiTheme.text(this, "OUTSIDE --", 14, UiTheme.TEXT, Typeface.BOLD); + outside.setGravity(Gravity.CENTER); + header.addView(outside, new LinearLayout.LayoutParams(dp(200), dp(56))); + Button back = UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }); + header.addView(back, new LinearLayout.LayoutParams(dp(112), dp(48))); + root.addView(header); + + LinearLayout body = new LinearLayout(this); + body.setOrientation(LinearLayout.HORIZONTAL); + body.addView(zone(ClimateGateway.Seat.DRIVER), weight(1f, 0, 0)); + body.addView(center(), weight(1.6f, 12, 12)); + body.addView(zone(ClimateGateway.Seat.PASSENGER), weight(1f, 0, 0)); + root.addView(body, new LinearLayout.LayoutParams(-1, 0, 1f)); + return root; + } + + private View zone(final ClimateGateway.Seat seat) { + boolean driver = seat == ClimateGateway.Seat.DRIVER; + LinearLayout col = panel(); + col.addView(UiTheme.label(this, driver ? "DRIVER" : "PASSENGER")); + + LinearLayout tempRow = new LinearLayout(this); + tempRow.setGravity(Gravity.CENTER); + tempRow.addView(UiTheme.button(this, "\u2212", new View.OnClickListener() { + @Override public void onClick(View v) { stepTemperature(seat, -1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(84))); + TextView temp = UiTheme.text(this, "--", 40, UiTheme.TEXT, Typeface.BOLD); + temp.setGravity(Gravity.CENTER); + tempRow.addView(temp, new LinearLayout.LayoutParams(0, dp(110), 1f)); + tempRow.addView(UiTheme.button(this, "+", new View.OnClickListener() { + @Override public void onClick(View v) { stepTemperature(seat, 1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(84))); + col.addView(tempRow, new LinearLayout.LayoutParams(-1, dp(130))); + if (driver) driverTemp = temp; else passengerTemp = temp; + + TextView seatLabel = UiTheme.label(this, "SEAT HEATING"); + seatLabel.setPadding(0, dp(16), 0, dp(8)); + col.addView(seatLabel); + LinearLayout seats = new LinearLayout(this); + Button[] target = driver ? driverSeat : passengerSeat; + String[] labels = { "OFF", "1", "2", "3" }; + for (int i = 0; i < 4; i++) { + final int level = i; + Button b = UiTheme.button(this, labels[i], new View.OnClickListener() { + @Override public void onClick(View v) { setSeat(seat, level); } + }, false); + target[i] = b; + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, dp(84), 1f); + if (i > 0) p.setMargins(dp(6), 0, 0, 0); + seats.addView(b, p); + } + col.addView(seats); + return col; + } + + private View center() { + LinearLayout col = panel(); + col.addView(UiTheme.label(this, "CLIMATE")); + + LinearLayout row1 = new LinearLayout(this); + power = toggle(row1, "POWER", new Runnable() { @Override public void run() { gw().pressPower(); } }); + ac = toggle(row1, "A/C", new Runnable() { @Override public void run() { gw().pressAc(); } }); + auto = toggle(row1, "AUTO", new Runnable() { @Override public void run() { gw().pressAuto(); } }); + econ = toggle(row1, "ECON", new Runnable() { @Override public void run() { gw().pressEcon(); } }); + col.addView(row1, rowParams()); + + LinearLayout row2 = new LinearLayout(this); + recirc = toggle(row2, "RECIRC", new Runnable() { @Override public void run() { gw().pressRecirculation(); } }); + frontDefrost = toggle(row2, "FRONT DEFROST", new Runnable() { + @Override public void run() { gw().setFrontDefrost(state.frontDefrost != 1); } + }); + rearDefrost = toggle(row2, "REAR DEFROST", new Runnable() { + @Override public void run() { gw().setRearDefrost(state.rearDefrost != 1); } + }); + wheel = toggle(row2, "WHEEL HEAT", new Runnable() { + @Override public void run() { gw().setSteeringWheelHeat(!(state.wheel > 0)); } + }); + col.addView(row2, rowParams()); + + LinearLayout fanRow = new LinearLayout(this); + fanRow.setGravity(Gravity.CENTER_VERTICAL); + TextView fanLabel = UiTheme.label(this, "FAN"); + fanRow.addView(fanLabel, new LinearLayout.LayoutParams(dp(110), -2)); + fanRow.addView(UiTheme.button(this, "\u2212", new View.OnClickListener() { + @Override public void onClick(View v) { stepFan(-1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(72))); + fanValue = UiTheme.text(this, "--", 22, UiTheme.TEXT, Typeface.BOLD); + fanValue.setGravity(Gravity.CENTER); + fanRow.addView(fanValue, new LinearLayout.LayoutParams(0, dp(72), 1f)); + fanRow.addView(UiTheme.button(this, "+", new View.OnClickListener() { + @Override public void onClick(View v) { stepFan(1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(72))); + col.addView(fanRow, rowParams()); + + LinearLayout airRow = new LinearLayout(this); + airRow.setGravity(Gravity.CENTER_VERTICAL); + airRow.addView(UiTheme.label(this, "AIRFLOW"), new LinearLayout.LayoutParams(dp(110), -2)); + airRow.addView(UiTheme.button(this, "\u2039", new View.OnClickListener() { + @Override public void onClick(View v) { stepBlower(-1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(72))); + blowerValue = UiTheme.text(this, "--", 18, UiTheme.TEXT, Typeface.BOLD); + blowerValue.setGravity(Gravity.CENTER); + airRow.addView(blowerValue, new LinearLayout.LayoutParams(0, dp(72), 1f)); + airRow.addView(UiTheme.button(this, "\u203A", new View.OnClickListener() { + @Override public void onClick(View v) { stepBlower(1); } + }, false), new LinearLayout.LayoutParams(dp(84), dp(72))); + col.addView(airRow, rowParams()); + return col; + } + + private Button toggle(LinearLayout row, String label, final Runnable action) { + Button b = UiTheme.button(this, label, new View.OnClickListener() { + @Override public void onClick(View v) { command(action); } + }, false); + b.setTextSize(13); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, dp(76), 1f); + if (row.getChildCount() > 0) p.setMargins(dp(8), 0, 0, 0); + row.addView(b, p); + return b; + } + + private LinearLayout panel() { + LinearLayout col = new LinearLayout(this); + col.setOrientation(LinearLayout.VERTICAL); + col.setPadding(dp(18), dp(14), dp(18), dp(14)); + col.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + return col; + } + + private LinearLayout.LayoutParams weight(float w, int left, int right) { + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, -1, w); + p.setMargins(dp(left), dp(8), dp(right), 0); + return p; + } + + private LinearLayout.LayoutParams rowParams() { + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, -2); + p.setMargins(0, dp(10), 0, 0); + return p; + } + + private int dp(int v) { return UiTheme.dp(this, v); } + + // ------------------------------------------------------------- actions + + private ClimateGateway gw() { return link == null ? null : link.gateway(); } + + private void stepTemperature(final ClimateGateway.Seat zone, int delta) { + int current = zone == ClimateGateway.Seat.PASSENGER ? state.passengerTemp : state.driverTemp; + if (current < ClimateGateway.TEMP_LO) current = 22; + final int next = Math.max(ClimateGateway.TEMP_LO, Math.min(ClimateGateway.TEMP_HI, current + delta)); + if (zone == ClimateGateway.Seat.PASSENGER) state.passengerTemp = next; else state.driverTemp = next; + render(); + command(new Runnable() { @Override public void run() { gw().setTemperature(zone, next); } }); + } + + private void stepFan(int delta) { + int current = state.fan >= ClimateGateway.FAN_MIN && state.fan <= ClimateGateway.FAN_MAX ? state.fan : 0; + final int next = Math.max(ClimateGateway.FAN_MIN, Math.min(ClimateGateway.FAN_MAX, current + delta)); + state.fan = next; + render(); + command(new Runnable() { @Override public void run() { gw().setFanLevel(next); } }); + } + + private void stepBlower(int delta) { + int count = ClimateGateway.BLOWER_LABELS.length; + int current = state.blower >= 0 && state.blower < count ? state.blower : 0; + final int next = (current + delta + count) % count; + state.blower = next; + render(); + command(new Runnable() { @Override public void run() { gw().setBlowerDirection(next); } }); + } + + private void setSeat(final ClimateGateway.Seat seat, final int level) { + command(new Runnable() { @Override public void run() { gw().setSeatHeatLevel(seat, level); } }); + } + + /** Runs a car command on the worker thread, then re-reads the real state. */ + private void command(final Runnable action) { + if (gw() == null) { + Toast.makeText(this, "Climate service not connected", Toast.LENGTH_SHORT).show(); + return; + } + worker.execute(new Runnable() { + @Override public void run() { + try { action.run(); } catch (Exception ignored) { } + try { Thread.sleep(250); } catch (InterruptedException e) { return; } + readAndPost(); + } + }); + } + + private void refresh() { + if (gw() == null) { render(); return; } + try { + worker.execute(new Runnable() { @Override public void run() { readAndPost(); } }); + } catch (Exception ignored) { } + } + + private void readAndPost() { + ClimateGateway g = gw(); + if (g == null) return; + final ClimateGateway.State next = g.read(); + ui.post(new Runnable() { @Override public void run() { state = next; render(); } }); + } + + // -------------------------------------------------------------- render + + private void render() { + if (status == null) return; + boolean connected = gw() != null; + status.setText(connected ? "LIVE \u2022 SAIC climate service" : "Vehicle climate service not connected"); + status.setTextColor(connected ? UiTheme.SUCCESS : UiTheme.WARNING); + outside.setText(Float.isNaN(state.outside) ? "OUTSIDE --" + : String.format(Locale.US, "OUTSIDE %.1f\u00B0", state.outside)); + driverTemp.setText(ClimateGateway.temperatureLabel(state.driverTemp)); + passengerTemp.setText(ClimateGateway.temperatureLabel(state.passengerTemp)); + fanValue.setText(state.fan == ClimateGateway.FAN_AUTO ? "AUTO" + : state.fan >= 0 ? state.fan + " / " + ClimateGateway.FAN_MAX : "--"); + blowerValue.setText(state.blower >= 0 && state.blower < ClimateGateway.BLOWER_LABELS.length + ? ClimateGateway.BLOWER_LABELS[state.blower].toUpperCase(Locale.US) : "--"); + paint(power, state.power == 1); + paint(ac, state.ac == 1); + paint(auto, state.auto == 1); + paint(econ, state.econ == 1); + paint(recirc, state.loop == 1); + paint(frontDefrost, state.frontDefrost == 1); + paint(rearDefrost, state.rearDefrost == 1); + paint(wheel, state.wheel > 0); + for (int i = 0; i < 4; i++) { + paint(driverSeat[i], state.driverSeat == i); + paint(passengerSeat[i], state.passengerSeat == i); + } + } + + private void paint(Button b, boolean on) { + if (b == null) return; + b.setBackground(on ? UiTheme.surface(UiTheme.CYAN, 0) : UiTheme.outline(UiTheme.DIVIDER, dp(1), 0)); + b.setTextColor(on ? UiTheme.BACKGROUND : UiTheme.TEXT); + } +} diff --git a/src/cloud/molberg/mgutility/ClimateGateway.java b/src/cloud/molberg/mgutility/ClimateGateway.java new file mode 100644 index 0000000..231b3f7 --- /dev/null +++ b/src/cloud/molberg/mgutility/ClimateGateway.java @@ -0,0 +1,267 @@ +package cloud.molberg.mgutility; + +import android.os.IBinder; +import android.os.Parcel; + +/** + * Raw-Binder gateway for SAIC's exported IAirConditionService ("aircondition" on the + * vehicle hub). Transaction numbers and value semantics come from the MG4 Luxury 2022 + * dump (com.saicmotor.service.vehicle AirConditionBinder + com.saicmotor.hmi.hvac): + * + * - Seat heat, steering-wheel heat, HVAC power, A/C, AUTO, recirculation and ECON are + * "button press" signals. The OEM climate app always sends the value 1 and the car + * advances its own state (seat heat cycles OFF -> 3 -> 2 -> 1 -> OFF). We do the same + * and reach a requested level by pressing and reading back. + * - Temperature (17..33, where 17 = LO and 33 = HI), fan level (1..11) and blower + * direction (0..6) are absolute values, exactly as the OEM app sends them. + * + * Every getter returns -1 when the signal is unavailable. + */ +public class ClimateGateway { + public static final String HUB_TOKEN = "com.saicmotor.sdk.vehiclesettings.IHubService"; + public static final String TOKEN = "com.saicmotor.sdk.vehiclesettings.IAirConditionService"; + public static final String SERVICE_NAME = "aircondition"; + + // IAirConditionService transactions + static final int CLOSE_BACK_DEFROST = 0x33, OPEN_BACK_DEFROST = 0x32; + static final int CLOSE_FRONT_DEFROST = 0x31, OPEN_FRONT_DEFROST = 0x30; + static final int SET_HVAC_POWER = 0x04, SET_AUTO = 0x07, SET_AC = 0x08, SET_LOOP = 0x09; + static final int SET_ECON = 0x0d, SET_BLOWER_DIRECTION = 0x0e, SET_AIR_VOLUME = 0x0f; + static final int SET_DRV_SEAT_HEAT = 0x21, SET_PSG_SEAT_HEAT = 0x25; + static final int SET_DRV_TEMP = 0x29, SET_PSG_TEMP = 0x2a; + static final int SET_STEERING_WHEEL_HEAT = 0x34; + static final int GET_HVAC_POWER = 0x35, GET_AUTO = 0x36, GET_AC = 0x37, GET_LOOP = 0x38; + static final int GET_ECON = 0x39, GET_BLOWER_DIRECTION = 0x3a, GET_AIR_VOLUME = 0x3b; + static final int GET_DRV_SEAT_HEAT = 0x4d, GET_PSG_SEAT_HEAT = 0x4f; + static final int GET_DRV_TEMP = 0x51, GET_PSG_TEMP = 0x52; + static final int GET_DUAL_ZONE = 0x57, GET_OUTSIDE_TEMP = 0x58; + static final int GET_FRONT_DEFROST = 0x5c, GET_BACK_DEFROST = 0x5d; + static final int GET_STEERING_WHEEL_HEAT = 0x5e; + + public static final int PRESS = 1; + public static final int TEMP_LO = 17, TEMP_HI = 33; + public static final int FAN_MIN = 1, FAN_MAX = 11, FAN_AUTO = 15; + public static final int BLOWER_MIN = 0, BLOWER_MAX = 6; + public static final String[] BLOWER_LABELS = { + "Face", "Face + feet", "Feet", "Feet + windscreen", "Windscreen", "All", "Face + windscreen" + }; + + /** OEM seat-heat cycle order for one press, starting from OFF. */ + static final int[] SEAT_CYCLE = { 0, 3, 2, 1 }; + + public enum Seat { DRIVER, PASSENGER } + + /** Value object for one atomic read of every climate signal. */ + public static final class State { + public int power = -1, ac = -1, auto = -1, loop = -1, econ = -1; + public int driverTemp = -1, passengerTemp = -1, dualZone = -1; + public int fan = -1, blower = -1; + public int driverSeat = -1, passengerSeat = -1, wheel = -1; + public int frontDefrost = -1, rearDefrost = -1; + public float outside = Float.NaN; + } + + /** Sleeps between seat-heat presses; replaceable for tests. */ + public interface Sleeper { void sleep(long millis) throws InterruptedException; } + + private final IBinder service; + private Sleeper sleeper = new Sleeper() { + @Override public void sleep(long millis) throws InterruptedException { Thread.sleep(millis); } + }; + + public ClimateGateway(IBinder hub) { this.service = lookup(hub); } + + void setSleeper(Sleeper sleeper) { if (sleeper != null) this.sleeper = sleeper; } + + public boolean available() { return service != null; } + + private static IBinder lookup(IBinder hub) { + if (hub == null) return null; + Parcel data = Parcel.obtain(), reply = Parcel.obtain(); + try { + data.writeInterfaceToken(HUB_TOKEN); + data.writeString(SERVICE_NAME); + if (!hub.transact(0x01, data, reply, 0)) return null; + reply.readException(); + return reply.readStrongBinder(); + } catch (Exception ignored) { return null; } + finally { data.recycle(); reply.recycle(); } + } + + public State read() { + State s = new State(); + if (service == null) return s; + s.power = readInt(GET_HVAC_POWER); + s.ac = readInt(GET_AC); + s.auto = readInt(GET_AUTO); + s.loop = readInt(GET_LOOP); + s.econ = readInt(GET_ECON); + s.driverTemp = readInt(GET_DRV_TEMP); + s.passengerTemp = readInt(GET_PSG_TEMP); + s.dualZone = readInt(GET_DUAL_ZONE); + s.fan = readInt(GET_AIR_VOLUME); + s.blower = readInt(GET_BLOWER_DIRECTION); + s.driverSeat = readInt(GET_DRV_SEAT_HEAT); + s.passengerSeat = readInt(GET_PSG_SEAT_HEAT); + s.wheel = readInt(GET_STEERING_WHEEL_HEAT); + s.frontDefrost = readInt(GET_FRONT_DEFROST); + s.rearDefrost = readInt(GET_BACK_DEFROST); + s.outside = readFloat(GET_OUTSIDE_TEMP); + return s; + } + + public int seatHeat(Seat seat) { return readInt(seat == Seat.PASSENGER ? GET_PSG_SEAT_HEAT : GET_DRV_SEAT_HEAT); } + public int steeringWheelHeat() { return readInt(GET_STEERING_WHEEL_HEAT); } + public int power() { return readInt(GET_HVAC_POWER); } + + // ---- Button-press controls (same signal the OEM climate app sends) ---- + public boolean pressPower() { return writeInt(SET_HVAC_POWER, PRESS); } + public boolean pressAc() { return writeInt(SET_AC, PRESS); } + public boolean pressAuto() { return writeInt(SET_AUTO, PRESS); } + public boolean pressRecirculation() { return writeInt(SET_LOOP, PRESS); } + public boolean pressEcon() { return writeInt(SET_ECON, PRESS); } + public boolean pressSteeringWheelHeat() { return writeInt(SET_STEERING_WHEEL_HEAT, PRESS); } + public boolean pressSeatHeat(Seat seat) { + return writeInt(seat == Seat.PASSENGER ? SET_PSG_SEAT_HEAT : SET_DRV_SEAT_HEAT, PRESS); + } + + public boolean setFrontDefrost(boolean on) { return call(on ? OPEN_FRONT_DEFROST : CLOSE_FRONT_DEFROST); } + public boolean setRearDefrost(boolean on) { return call(on ? OPEN_BACK_DEFROST : CLOSE_BACK_DEFROST); } + + // ---- Absolute-value controls ---- + public boolean setTemperature(Seat zone, int value) { + if (value < TEMP_LO || value > TEMP_HI) return false; + return writeInt(zone == Seat.PASSENGER ? SET_PSG_TEMP : SET_DRV_TEMP, value); + } + public boolean setFanLevel(int level) { + if (level < FAN_MIN || level > FAN_MAX) return false; + return writeInt(SET_AIR_VOLUME, level); + } + public boolean setBlowerDirection(int mode) { + if (mode < BLOWER_MIN || mode > BLOWER_MAX) return false; + return writeInt(SET_BLOWER_DIRECTION, mode); + } + + /** Number of OEM button presses needed to move from {@code current} to {@code target} (0..3). */ + public static int pressesBetween(int current, int target) { + int from = indexOf(current), to = indexOf(target); + if (from < 0 || to < 0) return -1; + return (to - from + SEAT_CYCLE.length) % SEAT_CYCLE.length; + } + + private static int indexOf(int level) { + for (int i = 0; i < SEAT_CYCLE.length; i++) if (SEAT_CYCLE[i] == level) return i; + return -1; + } + + /** + * Presses the seat-heat button until the car reports {@code target}. Reads back after + * every press and never presses more than one full cycle, so a stuck signal cannot + * spin forever. Blocking: call off the UI thread. Returns the final reported level. + */ + public int setSeatHeatLevel(Seat seat, int target) { + if (indexOf(target) < 0) return seatHeat(seat); + int current = seatHeat(seat); + for (int attempt = 0; attempt < SEAT_CYCLE.length && current != target; attempt++) { + if (indexOf(current) < 0) return current; // unknown signal: never press blind + int previous = current; + if (!pressSeatHeat(seat)) return current; + current = waitForChange(seat, previous); + if (current == previous) return current; // car ignored the press: stop, don't re-press blind + } + return current; + } + + /** Turns the steering-wheel heater on or off with one press only when needed. */ + public int setSteeringWheelHeat(boolean on) { + int current = steeringWheelHeat(); + if (current < 0 || (current > 0) == on) return current; + if (!pressSteeringWheelHeat()) return current; + for (int i = 0; i < 8; i++) { + if (!pause(150)) break; + int now = steeringWheelHeat(); + if (now != current) return now; + } + return steeringWheelHeat(); + } + + private int waitForChange(Seat seat, int previous) { + int now = previous; + for (int i = 0; i < 8; i++) { + if (!pause(150)) break; + now = seatHeat(seat); + if (now != previous) return now; + } + return now; + } + + private boolean pause(long millis) { + try { sleeper.sleep(millis); return true; } + catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } + } + + // ---- Binder plumbing ---- + private int readInt(int code) { + if (service == null) return -1; + Parcel data = Parcel.obtain(), reply = Parcel.obtain(); + try { + data.writeInterfaceToken(TOKEN); + if (!service.transact(code, data, reply, 0)) return -1; + reply.readException(); + return reply.readInt(); + } catch (Exception ignored) { return -1; } + finally { data.recycle(); reply.recycle(); } + } + + private float readFloat(int code) { + if (service == null) return Float.NaN; + Parcel data = Parcel.obtain(), reply = Parcel.obtain(); + try { + data.writeInterfaceToken(TOKEN); + if (!service.transact(code, data, reply, 0)) return Float.NaN; + reply.readException(); + float value = reply.readFloat(); + return value <= -1000f ? Float.NaN : value; // OEM "invalid" sentinel is -10000 + } catch (Exception ignored) { return Float.NaN; } + finally { data.recycle(); reply.recycle(); } + } + + private boolean writeInt(int code, int value) { + if (service == null) return false; + Parcel data = Parcel.obtain(), reply = Parcel.obtain(); + try { + data.writeInterfaceToken(TOKEN); + data.writeInt(value); + if (!service.transact(code, data, reply, 0)) return false; + reply.readException(); + return true; + } catch (Exception ignored) { return false; } + finally { data.recycle(); reply.recycle(); } + } + + private boolean call(int code) { + if (service == null) return false; + Parcel data = Parcel.obtain(), reply = Parcel.obtain(); + try { + data.writeInterfaceToken(TOKEN); + if (!service.transact(code, data, reply, 0)) return false; + reply.readException(); + return true; + } catch (Exception ignored) { return false; } + finally { data.recycle(); reply.recycle(); } + } + + /** Human label for a temperature value. */ + public static String temperatureLabel(int value) { + if (value == TEMP_LO) return "LO"; + if (value == TEMP_HI) return "HI"; + if (value < TEMP_LO || value > TEMP_HI) return "--"; + return value + "\u00B0"; + } + + public static String seatLabel(int level) { + if (level == 0) return "OFF"; + if (level >= 1 && level <= 3) return String.valueOf(level); + return "--"; + } +} diff --git a/src/cloud/molberg/mgutility/ClimateLink.java b/src/cloud/molberg/mgutility/ClimateLink.java new file mode 100644 index 0000000..dbfc3a9 --- /dev/null +++ b/src/cloud/molberg/mgutility/ClimateLink.java @@ -0,0 +1,58 @@ +package cloud.molberg.mgutility; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.IBinder; + +/** + * Process-wide binding to the SAIC vehicle hub for climate controls, so the control + * panel and the Climate page share one connection instead of each binding its own. + */ +final class ClimateLink { + interface Listener { void onClimateAvailable(); } + + private static ClimateLink instance; + + private final Context app; + private volatile ClimateGateway gateway; + private boolean requested; + private Listener listener; + + private final ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder binder) { + final ClimateGateway next = new ClimateGateway(binder); + gateway = next.available() ? next : null; + Listener l; + synchronized (ClimateLink.this) { l = listener; } + if (l != null && gateway != null) l.onClimateAvailable(); + } + @Override public void onServiceDisconnected(ComponentName name) { + gateway = null; + synchronized (ClimateLink.this) { requested = false; } + } + }; + + private ClimateLink(Context context) { app = context.getApplicationContext(); } + + static synchronized ClimateLink get(Context context) { + if (instance == null) instance = new ClimateLink(context); + instance.ensureBound(); + return instance; + } + + synchronized void setListener(Listener l) { listener = l; } + + /** The current gateway, or null while the vehicle service is not (yet) bound. */ + ClimateGateway gateway() { return gateway; } + + private synchronized void ensureBound() { + if (requested) return; + try { + Intent intent = new Intent("com.saicmotor.service.vehicle.VehicleService") + .setPackage("com.saicmotor.service.vehicle"); + requested = app.bindService(intent, connection, Context.BIND_AUTO_CREATE); + } catch (Exception ignored) { requested = false; } + } +} diff --git a/src/cloud/molberg/mgutility/ControlPanelCatalog.java b/src/cloud/molberg/mgutility/ControlPanelCatalog.java index b8de87d..89b1f48 100644 --- a/src/cloud/molberg/mgutility/ControlPanelCatalog.java +++ b/src/cloud/molberg/mgutility/ControlPanelCatalog.java @@ -20,7 +20,7 @@ public final class ControlPanelCatalog { public static final String PREF_ORDER = "home_control_panel_order"; public static final String PREF_VALUES = "home_control_panel_values"; private static final String PREF_CATALOG_VERSION = "home_control_panel_catalog_version"; - private static final int CATALOG_VERSION = 1; + private static final int CATALOG_VERSION = 2; public enum Kind { SLIDER, TOGGLE, SHORTCUT } @@ -47,6 +47,11 @@ public final class ControlPanelCatalog { new Control("liquid_sound_balance", "Liquid Sound Balance", "balance", Kind.TOGGLE, "MG Utility"), new Control("adaptive_audio", "Adaptive audio leveling", "media", Kind.TOGGLE, "MG Utility"), new Control("camping_mode", "Camping mode", "camping", Kind.TOGGLE, "MG Utility"), + new Control("driver_seat_heat", "Driver seat heat", "seat_heat", Kind.TOGGLE, "Climate"), + new Control("passenger_seat_heat", "Passenger seat heat", "seat_heat", Kind.TOGGLE, "Climate"), + new Control("steering_wheel_heat", "Steering wheel heat", "wheel_heat", Kind.TOGGLE, "Climate"), + new Control("climate_ac", "A/C", "air", Kind.TOGGLE, "Climate"), + new Control("climate", "Climate", "thermostat", Kind.SHORTCUT, "Climate"), new Control("saic_launcher", "Official SAIC Launcher", "home", Kind.SHORTCUT, "System"), new Control("software_update", "Software Update", "update", Kind.SHORTCUT, "MG Utility"), new Control("vehicle_settings", "Vehicle settings", "settings", Kind.SHORTCUT, "MG Utility"), @@ -58,7 +63,14 @@ public final class ControlPanelCatalog { private static final String[] DEFAULT_ORDER = { "brightness", "media_volume", "phone_volume", "voice_volume", "bluetooth", "wifi", "auto_brightness", "liquid_sound_balance", "adaptive_audio", "camping_mode", - "saic_launcher", "software_update", "vehicle_settings" + "driver_seat_heat", "passenger_seat_heat", "steering_wheel_heat", + "saic_launcher", "software_update", "vehicle_settings", "climate" + }; + + /** Controls appended once to existing non-empty layouts, keyed by the catalog version that introduced them. */ + private static final String[][] MIGRATION_ADDITIONS = { + { "camping_mode" }, + { "driver_seat_heat", "passenger_seat_heat", "steering_wheel_heat", "climate" } }; public static List all() { return ALL; } @@ -91,7 +103,11 @@ public final class ControlPanelCatalog { int catalogVersion = prefs.getInt(PREF_CATALOG_VERSION, 0); if (catalogVersion < CATALOG_VERSION) { if (raw.length() == 0) result.addAll(defaultOrder()); - else if (!result.isEmpty() && seen.add("camping_mode")) result.add("camping_mode"); + else if (!result.isEmpty()) { + for (int v = catalogVersion; v < CATALOG_VERSION && v < MIGRATION_ADDITIONS.length; v++) { + for (String id : MIGRATION_ADDITIONS[v]) if (seen.add(id)) result.add(id); + } + } SharedPreferences.Editor editor = prefs.edit().putInt(PREF_CATALOG_VERSION, CATALOG_VERSION); if (raw.length() == 0 || !result.isEmpty()) { JSONArray migrated = new JSONArray(); diff --git a/src/cloud/molberg/mgutility/ControlPanelOverlay.java b/src/cloud/molberg/mgutility/ControlPanelOverlay.java index da87767..a7e8e3d 100644 --- a/src/cloud/molberg/mgutility/ControlPanelOverlay.java +++ b/src/cloud/molberg/mgutility/ControlPanelOverlay.java @@ -108,6 +108,8 @@ final class ControlPanelOverlay extends FrameLayout { } catch (Exception ignored) { } refreshContent(); open = true; + handler.removeCallbacks(livePoll); + handler.post(livePoll); setVisibility(VISIBLE); panel.setVisibility(VISIBLE); panel.setTranslationY(panelHeight > 0 ? -panelHeight : -Math.max(1, getHeight())); @@ -118,6 +120,7 @@ final class ControlPanelOverlay extends FrameLayout { if (!open) return; open = false; if (pendingRefresh != null) { handler.removeCallbacks(pendingRefresh); pendingRefresh = null; } + handler.removeCallbacks(livePoll); int end = panelHeight > 0 ? -(int)panelHeight : -Math.max(1, getHeight()); panel.animate().translationY(end).setDuration(animationDuration) .withEndAction(new Runnable() { @@ -168,55 +171,70 @@ final class ControlPanelOverlay extends FrameLayout { }, 1400); } + /** Per-tile render callbacks so live climate reads update tiles in place instead of rebuilding. */ + private final ArrayList liveRenders = new ArrayList(); + private static final long LIVE_POLL_MS = 3000; + private final Runnable livePoll = new Runnable() { + @Override public void run() { + if (!open) return; + requestClimateRead(); + handler.postDelayed(this, LIVE_POLL_MS); + } + }; + + private int dp(int v) { return UiTheme.dp(activity, v); } + private View buildContent() { - ScrollView scroll = new ScrollView(activity); - scroll.setFillViewport(true); + liveRenders.clear(); LinearLayout column = new LinearLayout(activity); column.setOrientation(LinearLayout.VERTICAL); - int pad = UiTheme.dp(activity, 20); - column.setPadding(pad, UiTheme.dp(activity, 12), pad, pad); + column.setPadding(dp(18), dp(12), dp(18), dp(6)); - // Header row: title on the left, a proper SETTINGS text button on - // the right. The button opens the normal app settings (not the - // control panel settings editor) so the user can reach the - // category hub from the panel. + // Header: title, subtle hint, settings action. One compact row. LinearLayout headerRow = new LinearLayout(activity); headerRow.setOrientation(LinearLayout.HORIZONTAL); headerRow.setGravity(Gravity.CENTER_VERTICAL); - TextView title = UiTheme.title(activity, "CONTROL PANEL", 22); - title.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); + View accent = new View(activity); + accent.setBackground(UiTheme.pill(UiTheme.CYAN_BRIGHT)); + LinearLayout.LayoutParams accentLp = new LinearLayout.LayoutParams(dp(4), dp(24)); + accentLp.setMargins(dp(6), 0, dp(12), 0); + headerRow.addView(accent, accentLp); + TextView title = UiTheme.title(activity, "CONTROL PANEL", 20); title.setSingleLine(true); - headerRow.addView(title, new LinearLayout.LayoutParams(0, UiTheme.dp(activity, 38), 1f)); + headerRow.addView(title, new LinearLayout.LayoutParams(-2, dp(40))); + title.setGravity(Gravity.CENTER_VERTICAL); + TextView hint = UiTheme.text(activity, "Tap to toggle \u2022 Hold for settings \u2022 Swipe up to close", + 11, UiTheme.MUTED, Typeface.NORMAL); + hint.setGravity(Gravity.CENTER_VERTICAL); + hint.setSingleLine(true); + hint.setEllipsize(TextUtils.TruncateAt.END); + LinearLayout.LayoutParams hintLp = new LinearLayout.LayoutParams(0, dp(40), 1f); + hintLp.setMargins(dp(20), 0, dp(12), 0); + headerRow.addView(hint, hintLp); Button settingsBtn = UiTheme.button(activity, "SETTINGS", new View.OnClickListener() { @Override public void onClick(View v) { - try { - Intent intent = new Intent(activity, SettingsActivity.class); - activity.startActivity(intent); - } catch (Exception e) { - Toast.makeText(activity, "Settings unavailable", Toast.LENGTH_SHORT).show(); - } + try { activity.startActivity(new Intent(activity, SettingsActivity.class)); } + catch (Exception e) { Toast.makeText(activity, "Settings unavailable", Toast.LENGTH_SHORT).show(); } } }, false); settingsBtn.setTextSize(13); - settingsBtn.setMinHeight(0); - settingsBtn.setMinimumHeight(0); - settingsBtn.setPadding(UiTheme.dp(activity, 14), 0, UiTheme.dp(activity, 14), 0); + settingsBtn.setPadding(dp(16), 0, dp(16), 0); settingsBtn.setContentDescription("Open settings"); - LinearLayout.LayoutParams settingsLp = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.WRAP_CONTENT, UiTheme.dp(activity, 38)); - settingsLp.gravity = Gravity.END | Gravity.CENTER_VERTICAL; - headerRow.addView(settingsBtn, settingsLp); - column.addView(headerRow, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 38))); + headerRow.addView(settingsBtn, new LinearLayout.LayoutParams(-2, dp(40))); + LinearLayout.LayoutParams headerLp = new LinearLayout.LayoutParams(-1, dp(40)); + headerLp.setMargins(0, 0, 0, dp(10)); + column.addView(headerRow, headerLp); - TextView hint = UiTheme.text(activity, - "Swipe up to close \u2022 Tap a toggle \u2022 Hold a toggle for settings", - 11, UiTheme.MUTED, Typeface.NORMAL); - hint.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); - column.addView(hint, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 26))); + // Body fills the remaining height. Nothing in the panel scrolls. + column.addView(buildTiles(), new LinearLayout.LayoutParams(-1, 0, 1f)); - column.addView(buildTiles()); - scroll.addView(column); - return scroll; + // Grab handle: a visual cue that the panel closes with an upward swipe. + FrameLayout handleRow = new FrameLayout(activity); + View grab = new View(activity); + grab.setBackground(UiTheme.pill(UiTheme.withAlpha(UiTheme.MUTED, 140))); + handleRow.addView(grab, new FrameLayout.LayoutParams(dp(96), dp(4), Gravity.CENTER)); + column.addView(handleRow, new LinearLayout.LayoutParams(-1, dp(18))); + return column; } private void refreshContent() { @@ -225,10 +243,16 @@ final class ControlPanelOverlay extends FrameLayout { panel.addView(buildContent(), new FrameLayout.LayoutParams(-1, -1)); } + /** Re-renders tiles and the climate card in place from the latest cached state. */ + private void renderLive() { + for (Runnable r : new ArrayList(liveRenders)) { + try { r.run(); } catch (Exception ignored) { } + } + } + private View buildTiles() { LinearLayout container = new LinearLayout(activity); container.setOrientation(LinearLayout.HORIZONTAL); - container.setGravity(Gravity.TOP); List order = ControlPanelCatalog.loadOrder(activity); ArrayList sliderIds = new ArrayList(); ArrayList toggles = new ArrayList(); @@ -236,76 +260,241 @@ final class ControlPanelOverlay extends FrameLayout { for (String id : order) { ControlPanelCatalog.Control control = ControlPanelCatalog.find(id); if (control == null) continue; - if (control.kind == ControlPanelCatalog.Kind.SLIDER) { - sliderIds.add(control.id); - } else if (control.kind == ControlPanelCatalog.Kind.TOGGLE) { - toggles.add(control); - } else { - shortcuts.add(control); - } + if (control.kind == ControlPanelCatalog.Kind.SLIDER) sliderIds.add(control.id); + else if (control.kind == ControlPanelCatalog.Kind.TOGGLE) toggles.add(control); + else shortcuts.add(control); } - if (!sliderIds.isEmpty()) { - LinearLayout levels = sectionColumn("LEVELS"); - for (String id : sliderIds) { - ControlPanelCatalog.Control control = ControlPanelCatalog.find(id); - if (control != null) levels.addView(buildSliderTile(control)); - } - // Sliders take 1/3 of the panel width, toggles take 2/3 so the - // owner can place custom widgets and toggles in the wider area. - addColumn(container, levels, 1f); + + // Left: level sliders with the cabin-temperature controller underneath. + LinearLayout levels = sectionColumn("LEVELS"); + for (String id : sliderIds) { + ControlPanelCatalog.Control control = ControlPanelCatalog.find(id); + if (control != null) levels.addView(buildSliderTile(control)); } + View climate = buildClimateCard(); + LinearLayout.LayoutParams climateLp = new LinearLayout.LayoutParams(-1, 0, 1f); + climateLp.setMargins(0, dp(sliderIds.isEmpty() ? 0 : 6), 0, 0); + levels.addView(climate, climateLp); + addColumn(container, levels, 1.1f); + if (!toggles.isEmpty()) { - LinearLayout togglesColumn = sectionColumn("TOGGLES"); - togglesColumn.addView(buildToggleGrid(toggles)); + LinearLayout togglesColumn = sectionColumn("QUICK TOGGLES"); + togglesColumn.addView(buildToggleGrid(toggles), new LinearLayout.LayoutParams(-1, 0, 1f)); addColumn(container, togglesColumn, 2f); } if (!shortcuts.isEmpty()) { - LinearLayout shortcutsColumn = sectionColumn("MG UTILITY"); - for (ControlPanelCatalog.Control control : shortcuts) { - shortcutsColumn.addView(buildShortcutRow(control)); - } - addColumn(container, shortcutsColumn, 1f); + LinearLayout shortcutsColumn = sectionColumn("SHORTCUTS"); + for (ControlPanelCatalog.Control control : shortcuts) shortcutsColumn.addView(buildShortcutRow(control)); + addColumn(container, shortcutsColumn, 0.95f); } return container; } private void addColumn(LinearLayout parent, View child, float weight) { LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, -1, weight); - p.setMargins(UiTheme.dp(activity, 6), 0, UiTheme.dp(activity, 6), 0); + p.setMargins(dp(6), 0, dp(6), 0); parent.addView(child, p); } private LinearLayout sectionColumn(String heading) { LinearLayout column = new LinearLayout(activity); column.setOrientation(LinearLayout.VERTICAL); - TextView title = UiTheme.text(activity, heading, 14, UiTheme.MUTED, Typeface.BOLD); - title.setTypeface(UiTheme.pixelTypeface()); - title.setPadding(UiTheme.dp(activity, 4), 0, 0, UiTheme.dp(activity, 8)); - title.setLetterSpacing(0.14f); - column.addView(title, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 28))); + column.setPadding(dp(12), dp(10), dp(12), dp(12)); + column.setBackground(UiTheme.surface(UiTheme.withAlpha(UiTheme.BACKGROUND, 150), 0)); + TextView title = UiTheme.label(activity, heading); + title.setTextColor(UiTheme.CYAN); + title.setPadding(dp(2), 0, 0, 0); + title.setGravity(Gravity.CENTER_VERTICAL); + column.addView(title, new LinearLayout.LayoutParams(-1, dp(26))); return column; } + /** + * Fixed four-column grid. Rows share the available height equally, so the grid always fits + * the panel (four rows for up to 16 toggles) instead of making the panel scroll. + */ private View buildToggleGrid(List controls) { - GridLayout grid = new GridLayout(activity); - grid.setColumnCount(2); - grid.setAlignmentMode(GridLayout.ALIGN_BOUNDS); - int rowHeight = UiTheme.dp(activity, 156); - int row = 0, column = 0; - for (ControlPanelCatalog.Control control : controls) { - View tile = buildToggleTile(control); - GridLayout.LayoutParams p = new GridLayout.LayoutParams(); - p.width = 0; p.height = rowHeight; - p.rowSpec = GridLayout.spec(row); p.columnSpec = GridLayout.spec(column, 1f); - p.setMargins(UiTheme.dp(activity, 4), UiTheme.dp(activity, 4), - UiTheme.dp(activity, 4), UiTheme.dp(activity, 4)); - grid.addView(tile, p); - column++; - if (column >= 2) { column = 0; row++; } + final int columns = 4; + int rows = Math.max(4, (controls.size() + columns - 1) / columns); + LinearLayout grid = new LinearLayout(activity); + grid.setOrientation(LinearLayout.VERTICAL); + int index = 0; + for (int r = 0; r < rows; r++) { + LinearLayout row = new LinearLayout(activity); + row.setOrientation(LinearLayout.HORIZONTAL); + for (int c = 0; c < columns; c++) { + View cell = index < controls.size() ? buildToggleTile(controls.get(index)) : new View(activity); + index++; + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, -1, 1f); + p.setMargins(dp(4), dp(4), dp(4), dp(4)); + row.addView(cell, p); + } + grid.addView(row, new LinearLayout.LayoutParams(-1, 0, 1f)); } return grid; } + // ------------------------------------------------------------------ climate card + + /** Setpoint shown while a +/- change is waiting to be sent (NaN when none). */ + private float pendingSetpoint = Float.NaN; + private long pendingSetpointUntil; + private volatile float liveSetpoint = Float.NaN, liveOutside = Float.NaN; + private final Runnable commitSetpoint = new Runnable() { + @Override public void run() { + final float target = pendingSetpoint; + if (Float.isNaN(target)) return; + new Thread(new Runnable() { + @Override public void run() { + boolean ok = CarHvacAccess.set(activity, CarHvacAccess.PROP_DRIVER_SET, CarHvacAccess.AREA_DRIVER, target); + if (!ok) { + // Fallback: whole degrees through SAIC's air-condition service. + ClimateGateway g = ClimateLink.get(activity).gateway(); + int whole = target <= CarHvacAccess.SET_LO ? ClimateGateway.TEMP_LO + : target >= CarHvacAccess.SET_HI ? ClimateGateway.TEMP_HI : Math.round(target); + ok = g != null && g.setTemperature(ClimateGateway.Seat.DRIVER, whole); + } + final boolean sent = ok; + try { Thread.sleep(600); } catch (InterruptedException ignored) { } + handler.post(new Runnable() { + @Override public void run() { + if (!sent) Toast.makeText(activity, "Temperature change was not accepted", Toast.LENGTH_SHORT).show(); + requestClimateRead(); + } + }); + } + }, "climate-setpoint").start(); + } + }; + + private float displayedSetpoint() { + if (!Float.isNaN(pendingSetpoint) && System.currentTimeMillis() < pendingSetpointUntil) return pendingSetpoint; + if (!Float.isNaN(liveSetpoint)) return liveSetpoint; + int whole = climateState.driverTemp; + if (whole == ClimateGateway.TEMP_LO) return CarHvacAccess.SET_LO; + if (whole == ClimateGateway.TEMP_HI) return CarHvacAccess.SET_HI; + return whole > 0 ? whole : Float.NaN; + } + + private void stepSetpoint(int direction) { + float next = CarHvacAccess.step(displayedSetpoint(), direction); + pendingSetpoint = next; + pendingSetpointUntil = System.currentTimeMillis() + 4000; + renderLive(); + // Coalesce rapid taps into one write. + handler.removeCallbacks(commitSetpoint); + handler.postDelayed(commitSetpoint, 450); + } + + private View buildClimateCard() { + LinearLayout card = new LinearLayout(activity); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(dp(14), dp(10), dp(14), dp(12)); + card.setBackground(UiTheme.surface(UiTheme.withAlpha(UiTheme.SURFACE, 230), 0)); + card.setClickable(true); + card.setOnLongClickListener(new View.OnLongClickListener() { + @Override public boolean onLongClick(View v) { + try { activity.startActivity(new Intent(activity, ClimateActivity.class)); closePanel(); } + catch (Exception ignored) { } + return true; + } + }); + + // Header: label on the left, live climate state chip on the right. + LinearLayout top = new LinearLayout(activity); + top.setGravity(Gravity.CENTER_VERTICAL); + top.addView(UiTheme.label(activity, "CLIMATE"), new LinearLayout.LayoutParams(0, -2, 1f)); + final TextView status = UiTheme.text(activity, "", 10, UiTheme.CYAN, Typeface.BOLD); + status.setLetterSpacing(0.12f); + status.setGravity(Gravity.CENTER); + status.setPadding(dp(10), dp(3), dp(10), dp(3)); + top.addView(status, new LinearLayout.LayoutParams(-2, -2)); + card.addView(top, new LinearLayout.LayoutParams(-1, dp(24))); + + // Setpoint row: round - and + buttons around a large temperature. + LinearLayout control = new LinearLayout(activity); + control.setGravity(Gravity.CENTER); + control.addView(roundStepButton("remove", -1), new LinearLayout.LayoutParams(dp(60), dp(60))); + LinearLayout middle = new LinearLayout(activity); + middle.setOrientation(LinearLayout.VERTICAL); + middle.setGravity(Gravity.CENTER); + final TextView setpoint = UiTheme.text(activity, "--", 30, UiTheme.TEXT, Typeface.BOLD); + setpoint.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL)); + setpoint.setGravity(Gravity.CENTER); + setpoint.setIncludeFontPadding(false); + middle.addView(setpoint, new LinearLayout.LayoutParams(-1, -2)); + final TextView setLabel = UiTheme.text(activity, "TARGET", 9, UiTheme.MUTED, Typeface.BOLD); + setLabel.setLetterSpacing(0.24f); + setLabel.setGravity(Gravity.CENTER); + middle.addView(setLabel, new LinearLayout.LayoutParams(-1, -2)); + control.addView(middle, new LinearLayout.LayoutParams(0, -2, 1f)); + control.addView(roundStepButton("add", 1), new LinearLayout.LayoutParams(dp(60), dp(60))); + card.addView(control, new LinearLayout.LayoutParams(-1, 0, 1f)); + + // Outside temperature chip. The car exposes no separate cabin sensor: the HVAC + // "ambient" signal is the same outside sensor, so only one reading is shown. + LinearLayout chip = new LinearLayout(activity); + chip.setGravity(Gravity.CENTER_VERTICAL); + chip.setPadding(dp(12), 0, dp(12), 0); + chip.setBackground(UiTheme.surface(UiTheme.withAlpha(UiTheme.BACKGROUND, 170), 0)); + chip.addView(UiTheme.icon(activity, "thermostat", UiTheme.MUTED, 18)); + TextView outsideName = UiTheme.text(activity, "Outside", 12, UiTheme.MUTED, Typeface.NORMAL); + LinearLayout.LayoutParams onLp = new LinearLayout.LayoutParams(0, -2, 1f); + onLp.setMargins(dp(8), 0, 0, 0); + chip.addView(outsideName, onLp); + final TextView outside = UiTheme.text(activity, "--", 14, UiTheme.TEXT, Typeface.BOLD); + chip.addView(outside, new LinearLayout.LayoutParams(-2, -2)); + LinearLayout.LayoutParams chipLp = new LinearLayout.LayoutParams(-1, dp(38)); + chipLp.setMargins(0, dp(4), 0, 0); + card.addView(chip, chipLp); + + liveRenders.add(new Runnable() { + @Override public void run() { + ClimateGateway.State s = climateState; + setpoint.setText(CarHvacAccess.label(displayedSetpoint())); + boolean pending = !Float.isNaN(pendingSetpoint) && System.currentTimeMillis() < pendingSetpointUntil; + setpoint.setTextColor(pending ? UiTheme.CYAN_BRIGHT : UiTheme.TEXT); + setLabel.setText(pending ? "SENDING\u2026" : "TARGET"); + float out = !Float.isNaN(liveOutside) ? liveOutside : s.outside; + outside.setText(degrees(out)); + String text = s.power == 0 ? "OFF" + : s.power < 0 ? "" + : (s.auto == 1 ? "AUTO" : "") + (s.ac == 1 ? (s.auto == 1 ? " \u2022 A/C" : "A/C") : "") + + (s.auto != 1 && s.ac != 1 ? "ON" : ""); + status.setText(text); + status.setVisibility(text.length() == 0 ? View.GONE : View.VISIBLE); + int tone = s.power == 0 ? UiTheme.WARNING : UiTheme.CYAN; + status.setTextColor(tone); + status.setBackground(UiTheme.pill(UiTheme.withAlpha(tone, 40))); + } + }); + return card; + } + + /** Circular step button with a vector glyph, matching the shared pressed-state language. */ + private View roundStepButton(String icon, final int direction) { + FrameLayout button = new FrameLayout(activity); + android.graphics.drawable.GradientDrawable normal = UiTheme.pill(UiTheme.SURFACE_HIGH); + normal.setStroke(Math.max(1, dp(1)), UiTheme.withAlpha(UiTheme.CYAN, 120)); + android.graphics.drawable.GradientDrawable pressed = UiTheme.pill(UiTheme.withAlpha(UiTheme.CYAN, 90)); + pressed.setStroke(Math.max(1, dp(1)), UiTheme.CYAN_BRIGHT); + button.setBackground(UiTheme.pressable(normal, pressed)); + button.addView(UiTheme.icon(activity, icon, UiTheme.CYAN_BRIGHT, 28), + new FrameLayout.LayoutParams(dp(28), dp(28), Gravity.CENTER)); + button.setClickable(true); + button.setFocusable(true); + button.setContentDescription(direction > 0 ? "Temperature up 0.5 degrees" : "Temperature down 0.5 degrees"); + button.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { stepSetpoint(direction); } + }); + return button; + } + + private static String degrees(float value) { + if (Float.isNaN(value)) return "--"; + return String.format(java.util.Locale.US, "%.1f\u00B0C", value); + } + private View buildSliderTile(final ControlPanelCatalog.Control control) { // Tall inline slider — no enclosing box. The label sits inside the // cyan-filled portion of the track, the percent sits inside the dark @@ -313,14 +502,14 @@ final class ControlPanelOverlay extends FrameLayout { LinearLayout tile = new LinearLayout(activity); tile.setOrientation(LinearLayout.VERTICAL); // No padding or background — the bar itself is the visual element. - tile.setPadding(0, UiTheme.dp(activity, 6), 0, UiTheme.dp(activity, 6)); + tile.setPadding(0, UiTheme.dp(activity, 3), 0, UiTheme.dp(activity, 3)); final SeekBar slider = new SeekBar(activity); slider.setMax(100); slider.setContentDescription(control.label); slider.setPadding(0, 0, 0, 0); // Tall track — easy to grab with a finger on the head unit. - slider.setMinimumHeight(UiTheme.dp(activity, 64)); + slider.setMinimumHeight(UiTheme.dp(activity, 52)); InlineSliderDrawable drawable = new InlineSliderDrawable(activity, control.label, UiTheme.CYAN_BRIGHT); slider.setProgressDrawable(drawable); @@ -362,7 +551,7 @@ final class ControlPanelOverlay extends FrameLayout { int initial = readSliderValue(control.id); drawable.setPercent(initial); slider.setProgress(initial); - tile.addView(slider, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 64))); + tile.addView(slider, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 52))); return tile; } @@ -417,14 +606,23 @@ final class ControlPanelOverlay extends FrameLayout { float w = bounds.width(), h = bounds.height(); // Track fills the full drawable height. RectF track = new RectF(bounds.left, bounds.top, bounds.right, bounds.bottom); - canvas.drawRect(track, trackPaint); + float radius = Math.min(h * 0.5f, UiTheme.radiusPx(UiTheme.RADIUS_DP)); + canvas.drawRoundRect(track, radius, radius, trackPaint); int p = Math.max(0, Math.min(getLevel(), 10000)); float fillRight = bounds.left + w * (p / 10000f); if (fillRight > bounds.left) { - RectF fill = new RectF(bounds.left, bounds.top, fillRight, bounds.bottom); - canvas.drawRect(fill, fillPaint); + // Clip to the rounded track so the fill keeps the same corners at any level. + int save = canvas.save(); + android.graphics.Path clip = new android.graphics.Path(); + clip.addRoundRect(track, radius, radius, android.graphics.Path.Direction.CW); + canvas.clipPath(clip); + canvas.drawRect(new RectF(bounds.left, bounds.top, fillRight, bounds.bottom), fillPaint); + canvas.restoreToCount(save); } - canvas.drawRect(track, edgePaint); + RectF edge = new RectF(track); + float inset = edgePaint.getStrokeWidth() * 0.5f; + edge.inset(inset, inset); + canvas.drawRoundRect(edge, radius, radius, edgePaint); // Pick a font size that fits inside the bar height. float size = Math.max(14f, Math.min(h * 0.45f, 28f)); labelPaint.setTextSize(size); @@ -508,8 +706,8 @@ 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. + // A deliberate slider move wins over the automatic schedule for the + // next hour, then normal scheduling resumes. if (activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) .getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false)) { BrightnessScheduler.pauseForManualOverride(activity); @@ -580,45 +778,50 @@ final class ControlPanelOverlay extends FrameLayout { final LinearLayout tile = new LinearLayout(activity); tile.setOrientation(LinearLayout.VERTICAL); tile.setGravity(Gravity.CENTER); - tile.setPadding(UiTheme.dp(activity, 4), UiTheme.dp(activity, 12), - UiTheme.dp(activity, 4), UiTheme.dp(activity, 8)); + tile.setPadding(dp(6), dp(6), dp(6), dp(6)); tile.setClickable(true); tile.setFocusable(true); tile.setLongClickable(true); - // Circular ring around the icon, matching the official MG quick-control toggle. FrameLayout ring = new FrameLayout(activity); - int ringSize = UiTheme.dp(activity, 70); - LinearLayout.LayoutParams ringParams = new LinearLayout.LayoutParams(ringSize, ringSize); - ring.setLayoutParams(ringParams); - + int ringSize = dp(54); final ToggleRingView ringView = new ToggleRingView(activity); ring.addView(ringView, new FrameLayout.LayoutParams(-1, -1)); - final ControlIconView icon = new ControlIconView(activity, control.iconKey); - int iconSize = UiTheme.dp(activity, 34); - FrameLayout.LayoutParams iconParams = new FrameLayout.LayoutParams(iconSize, iconSize, Gravity.CENTER); - ring.addView(icon, iconParams); + ring.addView(icon, new FrameLayout.LayoutParams(dp(26), dp(26), Gravity.CENTER)); + tile.addView(ring, new LinearLayout.LayoutParams(ringSize, ringSize)); - tile.addView(ring); - - TextView name = UiTheme.text(activity, control.label, 12, UiTheme.TEXT, Typeface.BOLD); + final TextView name = UiTheme.text(activity, control.label, 11, UiTheme.TEXT, Typeface.BOLD); name.setGravity(Gravity.CENTER); name.setMaxLines(2); name.setEllipsize(TextUtils.TruncateAt.END); - name.setPadding(0, UiTheme.dp(activity, 8), 0, 0); - tile.addView(name, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 48))); + name.setIncludeFontPadding(false); + LinearLayout.LayoutParams nameLp = new LinearLayout.LayoutParams(-1, -2); + nameLp.setMargins(0, dp(6), 0, 0); + tile.addView(name, nameLp); + final TextView detail = UiTheme.text(activity, "", 10, UiTheme.CYAN, Typeface.BOLD); + detail.setGravity(Gravity.CENTER); + detail.setLetterSpacing(0.12f); + detail.setSingleLine(true); + tile.addView(detail, new LinearLayout.LayoutParams(-1, -2)); final Runnable render = new Runnable() { @Override public void run() { boolean current = readToggleState(control.id); + String level = climateLevelSuffix(control.id); + detail.setText(level == null ? (current ? "ON" : "") : level); + detail.setVisibility(detail.getText().length() == 0 ? View.GONE : View.VISIBLE); ringView.setOn(current); icon.setColor(current ? UiTheme.CYAN_BRIGHT : UiTheme.MUTED); name.setTextColor(current ? UiTheme.TEXT : UiTheme.MUTED); + tile.setBackground(current + ? tileBackground(UiTheme.withAlpha(UiTheme.CYAN, 38), UiTheme.withAlpha(UiTheme.CYAN, 150)) + : tileBackground(UiTheme.withAlpha(UiTheme.SURFACE, 200), UiTheme.withAlpha(UiTheme.DIVIDER, 200))); tile.setContentDescription(control.label + (current ? ", on" : ", off")); } }; render.run(); + liveRenders.add(render); tile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleToggleState(control); } }); @@ -631,6 +834,18 @@ final class ControlPanelOverlay extends FrameLayout { return tile; } + /** Square tile surface with a hairline border and a pressed state. */ + private android.graphics.drawable.Drawable tileBackground(int fill, int border) { + android.graphics.drawable.GradientDrawable normal = UiTheme.surface(fill, 0); + normal.setStroke(Math.max(1, dp(1)), border); + android.graphics.drawable.GradientDrawable pressed = UiTheme.surface(UiTheme.SURFACE_PRESSED, 0); + pressed.setStroke(Math.max(1, dp(1)), UiTheme.CYAN_BRIGHT); + android.graphics.drawable.StateListDrawable states = new android.graphics.drawable.StateListDrawable(); + states.addState(new int[] { android.R.attr.state_pressed }, pressed); + states.addState(new int[0], normal); + return states; + } + /** Plain ring with a small status dot at the upper-right; toggles between muted and cyan. */ private static final class ToggleRingView extends View { private final Paint ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -852,8 +1067,71 @@ final class ControlPanelOverlay extends FrameLayout { } } + private static boolean isClimateToggle(String id) { + return "driver_seat_heat".equals(id) || "passenger_seat_heat".equals(id) + || "steering_wheel_heat".equals(id) || "climate_ac".equals(id); + } + + /** Last climate values read from the car; refreshed asynchronously so the UI thread never blocks on Binder. */ + private volatile ClimateGateway.State climateState = new ClimateGateway.State(); + private boolean climateReadPending; + + private ClimateGateway climateGateway() { + ClimateLink link = ClimateLink.get(activity); + if (link.gateway() == null) { + link.setListener(new ClimateLink.Listener() { + @Override public void onClimateAvailable() { requestClimateRead(); } + }); + } + return link.gateway(); + } + + private void requestClimateRead() { + final ClimateGateway gateway = climateGateway(); + if (gateway == null || climateReadPending) return; + climateReadPending = true; + new Thread(new Runnable() { + @Override public void run() { + final ClimateGateway.State next = gateway.read(); + final float set = CarHvacAccess.get(activity, CarHvacAccess.PROP_DRIVER_SET, CarHvacAccess.AREA_DRIVER); + final float outside = CarHvacAccess.get(activity, CarHvacAccess.PROP_OUTSIDE, CarHvacAccess.AREA_GLOBAL); + handler.post(new Runnable() { + @Override public void run() { + climateReadPending = false; + climateState = next; + liveSetpoint = set; liveOutside = outside; + if (open) renderLive(); + } + }); + } + }, "climate-read").start(); + } + + private String climateLevelSuffix(String id) { + if ("auto_brightness".equals(id)) { + long until = activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL, 0L); + long left = until - System.currentTimeMillis(); + boolean enabled = activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false); + if (enabled && left > 0) return "PAUSED " + Math.max(1, (left + 59999L) / 60000L) + " MIN"; + return null; + } + ClimateGateway.State s = climateState; + if ("driver_seat_heat".equals(id)) return s.driverSeat > 0 ? "LEVEL " + s.driverSeat : null; + if ("passenger_seat_heat".equals(id)) return s.passengerSeat > 0 ? "LEVEL " + s.passengerSeat : null; + return null; + } + private boolean readToggleState(String id) { Context context = activity.getApplicationContext(); + if (isClimateToggle(id)) { + ClimateGateway.State s = climateState; + if ("driver_seat_heat".equals(id)) return s.driverSeat > 0; + if ("passenger_seat_heat".equals(id)) return s.passengerSeat > 0; + if ("steering_wheel_heat".equals(id)) return s.wheel > 0; + return s.ac == 1; + } if ("camping_mode".equals(id)) return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) .getBoolean(CampingModePolicy.PREF_ENABLED, false); if ("auto_brightness".equals(id)) return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) @@ -888,6 +1166,26 @@ final class ControlPanelOverlay extends FrameLayout { catch (Exception e) { current = false; } final boolean target = !current; + if (isClimateToggle(id)) { + final ClimateGateway gateway = climateGateway(); + if (gateway == null) { + Toast.makeText(activity, "Climate service not connected", Toast.LENGTH_SHORT).show(); + return; + } + new Thread(new Runnable() { + @Override public void run() { + // Seat heat follows the OEM button: each tap steps OFF -> 3 -> 2 -> 1 -> OFF. + if ("driver_seat_heat".equals(id)) gateway.pressSeatHeat(ClimateGateway.Seat.DRIVER); + else if ("passenger_seat_heat".equals(id)) gateway.pressSeatHeat(ClimateGateway.Seat.PASSENGER); + else if ("steering_wheel_heat".equals(id)) gateway.setSteeringWheelHeat(target); + else gateway.pressAc(); + try { Thread.sleep(350); } catch (InterruptedException ignored) { } + handler.post(new Runnable() { @Override public void run() { requestClimateRead(); } }); + } + }, "climate-write").start(); + return; + } + if ("camping_mode".equals(id)) { if (activity instanceof MainActivity) { ((MainActivity) activity).setCampingModeEnabled(target); @@ -1020,6 +1318,8 @@ final class ControlPanelOverlay extends FrameLayout { intent = new Intent(activity, AdaptiveAudioLevelingActivity.class); } else if ("camping_mode".equals(id)) { intent = new Intent(activity, CampingModeSettingsActivity.class); + } else if (isClimateToggle(id)) { + intent = new Intent(activity, ClimateActivity.class); } if (intent == null) return; try { @@ -1082,6 +1382,7 @@ final class ControlPanelOverlay extends FrameLayout { else if ("settings".equals(id)) target = ControlPanelSettingsActivity.class; else if ("software_update".equals(id)) target = UpdateActivity.class; else if ("vehicle_settings".equals(id)) target = VehicleSettingsActivity.class; + else if ("climate".equals(id)) target = ClimateActivity.class; if (target == null) return; try { Intent intent = new Intent(activity, target); diff --git a/src/cloud/molberg/mgutility/HermesAudioCapture.java b/src/cloud/molberg/mgutility/HermesAudioCapture.java index 7902f8b..0480a32 100644 --- a/src/cloud/molberg/mgutility/HermesAudioCapture.java +++ b/src/cloud/molberg/mgutility/HermesAudioCapture.java @@ -20,6 +20,8 @@ final class HermesAudioCapture { private final File wavFile; private final SampleListener sampleListener; + private final android.content.Context context; + private MicAccess.Lease lease; private AudioRecord recorder; private Thread captureThread; @@ -28,7 +30,8 @@ final class HermesAudioCapture { private boolean released; private boolean failed; - HermesAudioCapture(File wavFile, SampleListener sampleListener) { + HermesAudioCapture(android.content.Context context, File wavFile, SampleListener sampleListener) { + this.context = context.getApplicationContext(); this.wavFile = wavFile; this.sampleListener = sampleListener; } @@ -47,7 +50,7 @@ final class HermesAudioCapture { wavOutput = new FileOutputStream(wavFile); writeWavHeader(wavOutput, 0); totalBytes = 0; - recorder.startRecording(); + // Mic borrowing (voice focus, OEM wake-word pause) blocks, so it runs on the capture thread. captureThread = new Thread(new Runnable() { @Override public void run() { captureLoop(); } }, "hermes-audio-capture"); captureThread.start(); @@ -68,6 +71,7 @@ final class HermesAudioCapture { try { recorder.release(); } catch (Throwable ignored) { } recorder = null; } + releaseLease(); if (wavOutput != null) { try { wavOutput.flush(); } catch (IOException ignored) { } try { @@ -91,6 +95,7 @@ final class HermesAudioCapture { void cancel() { released = true; + releaseLease(); if (recorder != null) { try { if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) recorder.stop(); } catch (Throwable ignored) { } try { recorder.release(); } catch (Throwable ignored) { } @@ -101,6 +106,23 @@ final class HermesAudioCapture { } private void captureLoop() { + AudioRecord active = recorder; + if (active == null) return; + lease = MicAccess.acquire(context); + if (!MicAccess.startRecording(context, active)) { + android.util.Log.w("HermesAudioCapture", "mic busy: " + MicAccess.lastNote()); + fail("Microphone is busy"); + releaseLease(); + return; + } + try { captureFrames(); } finally { releaseLease(); } + } + + private synchronized void releaseLease() { + if (lease != null) { lease.release(); lease = null; } + } + + private void captureFrames() { short[] pcm = new short[2048]; while (!released && recorder != null) { int read = recorder.read(pcm, 0, pcm.length); diff --git a/src/cloud/molberg/mgutility/HermesConfig.java b/src/cloud/molberg/mgutility/HermesConfig.java index 73c9efa..6548cac 100644 --- a/src/cloud/molberg/mgutility/HermesConfig.java +++ b/src/cloud/molberg/mgutility/HermesConfig.java @@ -17,7 +17,6 @@ import javax.crypto.spec.GCMParameterSpec; /** Private configuration for the Hermes native API integration. */ final class HermesConfig { - static final String DEFAULT_SERVER_URL = "http://10.0.0.74:18793"; private static final String PREFS = "hermes_agent"; private static final String KEY_ALIAS = "mg_utility_hermes_credentials"; private static final String URL = "api_server_url"; diff --git a/src/cloud/molberg/mgutility/HermesLocalRecognizer.java b/src/cloud/molberg/mgutility/HermesLocalRecognizer.java index 60f85f4..fe65ed8 100644 --- a/src/cloud/molberg/mgutility/HermesLocalRecognizer.java +++ b/src/cloud/molberg/mgutility/HermesLocalRecognizer.java @@ -24,13 +24,54 @@ final class HermesLocalRecognizer { private final Context context; private OnlineRecognizer recognizer; private OnlineStream stream; - private Listener listener; - private boolean released; + private volatile Listener listener; + private volatile boolean released; + // One worker thread owns the native recognizer. Audio, finish and cancel are queued to it, so + // neither the UI thread nor the microphone thread ever waits for model loading or decoding. + private final java.util.concurrent.LinkedBlockingQueue queue = + new java.util.concurrent.LinkedBlockingQueue(4000); + private static final float[] FINISH = new float[0]; + private static final float[] CANCEL = new float[0]; HermesLocalRecognizer(Context context) { this.context = context.getApplicationContext(); } - boolean start(Listener listener) { + /** Copies the bundled model to app storage ahead of time (call from a background thread). */ + static void prepareModel(Context context) { + try { + HermesLocalRecognizer warm = new HermesLocalRecognizer(context); + File modelDir = new File(warm.context.getFilesDir(), "sherpa-en"); + modelDir.mkdirs(); + for (String name : new String[]{"encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"}) + warm.copyAsset("sherpa-en/" + name, new File(modelDir, name)); + } catch (Throwable ignored) { } + } + + /** Starts the worker; the model loads there while audio is already being queued. */ + void start(Listener listener) { this.listener = listener; + new Thread(new Runnable() { + @Override public void run() { work(); } + }, "hermes-sherpa").start(); + } + + private void work() { + if (!init()) { queue.clear(); return; } + try { + while (true) { + float[] chunk = queue.take(); + if (chunk == CANCEL) return; + if (chunk == FINISH) { finishNow(); return; } + feed(chunk); + if (released) return; + } + } catch (InterruptedException ignored) { + } finally { + queue.clear(); + release(); + } + } + + private boolean init() { try { File modelDir = new File(context.getFilesDir(), "sherpa-en"); modelDir.mkdirs(); @@ -56,16 +97,30 @@ final class HermesLocalRecognizer { private String copyAsset(String asset, File destination) throws java.io.IOException { if (!destination.isFile() || destination.length() == 0) { - java.io.InputStream input = context.getAssets().open(asset); - java.io.FileOutputStream output = new java.io.FileOutputStream(destination); - byte[] buffer = new byte[65536]; int count; - while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count); - input.close(); output.close(); + synchronized (HermesLocalRecognizer.class) { + if (!destination.isFile() || destination.length() == 0) { + // Write to a temp file first so an interrupted copy is never mistaken for a model. + File partial = new File(destination.getPath() + ".part"); + java.io.InputStream input = context.getAssets().open(asset); + java.io.FileOutputStream output = new java.io.FileOutputStream(partial); + byte[] buffer = new byte[65536]; int count; + while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count); + input.close(); output.close(); + if (!partial.renameTo(destination)) throw new java.io.IOException("Could not store " + asset); + } + } } return destination.getAbsolutePath(); } + /** Called from the microphone thread; never blocks. */ void acceptSamples(float[] samples, int count) { + if (released) return; + float[] chunk = count == samples.length ? samples.clone() : java.util.Arrays.copyOf(samples, count); + queue.offer(chunk); // bounded (~4 min of audio); overflow is dropped rather than blocking + } + + private void feed(float[] samples) { if (released || recognizer == null || stream == null) return; try { stream.acceptWaveform(samples, 16000); @@ -76,8 +131,11 @@ final class HermesLocalRecognizer { } catch (Throwable error) { deliverError("Local recognizer error: " + safeMessage(error)); release(); } } - void finish() { - if (released || recognizer == null || stream == null) { release(); return; } + /** Release of the button: decodes the rest on the worker and delivers the final transcript. */ + void finish() { if (!released) queue.offer(FINISH); } + + private void finishNow() { + if (released || recognizer == null || stream == null) return; try { // The upstream example supplies 600 ms trailing silence before final decode. stream.acceptWaveform(new float[9600], 16000); @@ -86,10 +144,10 @@ final class HermesLocalRecognizer { OnlineRecognizerResult result = recognizer.getResult(stream); deliverFinal(result == null || result.getText() == null ? "" : result.getText().trim()); } catch (Throwable error) { deliverError("Local recognizer finalization failed: " + safeMessage(error)); } - finally { release(); } } - void cancel() { release(); } + void cancel() { released = true; queue.clear(); queue.offer(CANCEL); } + private void release() { released = true; if (stream != null) { try { stream.release(); } catch (Throwable ignored) { } stream = null; } if (recognizer != null) { try { recognizer.release(); } catch (Throwable ignored) { } recognizer = null; } } private void deliverPartial(final String text) { MAIN.post(new Runnable() { public void run() { if (listener != null && !released) listener.onPartial(text); }}); } private void deliverFinal(final String text) { MAIN.post(new Runnable() { public void run() { if (listener != null) listener.onFinal(text); }}); } diff --git a/src/cloud/molberg/mgutility/HermesPairActivity.java b/src/cloud/molberg/mgutility/HermesPairActivity.java new file mode 100644 index 0000000..6fb8176 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesPairActivity.java @@ -0,0 +1,357 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Typeface; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.json.JSONObject; + +import io.nayuki.qrcodegen.QrCode; + +/** + * "Pair with phone": shows a QR code; the user enters their own Hermes server + key on the phone, + * which encrypts them for this car. Nothing is typed on the head unit. + */ +public final class HermesPairActivity extends AnimatedActivity { + private static final long POLL_MS = 2000; + + private final Handler main = new Handler(Looper.getMainLooper()); + private QrView qr; + private TextView code; + private TextView check; + private TextView status; + private TextView link; + private Button retry; + private volatile boolean active; + private volatile int generation; + private volatile HermesPairingClient.Started started; + private final HermesPairingClient client = new HermesPairingClient(HermesPairingClient.RELAY_URL); + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + immersive(); + setContentView(buildUi()); + } + + @Override protected void onResume() { + super.onResume(); + active = true; + if (started == null || System.currentTimeMillis() > started.expiresAtMs) begin(); + else schedulePoll(generation, 0); + } + + @Override protected void onPause() { + super.onPause(); + active = false; + } + + @Override protected void onDestroy() { + super.onDestroy(); + final HermesPairingClient.Started pending = started; + started = null; + generation++; + if (pending != null) background(new Runnable() { @Override public void run() { client.cancel(pending); } }); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(28, 12, 28, 18); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout header = new LinearLayout(this); + header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "PAIR WITH PHONE", 29), new LinearLayout.LayoutParams(0, 58, 1)); + header.addView(UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }), new LinearLayout.LayoutParams(120, 52)); + root.addView(header); + + LinearLayout body = new LinearLayout(this); + body.setOrientation(LinearLayout.HORIZONTAL); + body.setGravity(Gravity.CENTER_VERTICAL); + + qr = new QrView(this); + LinearLayout.LayoutParams qrParams = new LinearLayout.LayoutParams(0, -1); + qrParams.weight = 0; + qrParams.width = 520; + body.addView(qr, qrParams); + + LinearLayout side = new LinearLayout(this); + side.setOrientation(LinearLayout.VERTICAL); + side.setPadding(40, 0, 0, 0); + side.setGravity(Gravity.CENTER_VERTICAL); + side.addView(step("1", "Scan the code with your phone camera.")); + side.addView(step("2", "Enter your own Hermes server URL and API key on the phone.")); + side.addView(step("3", "Tap “Send to car”. This screen connects automatically.")); + + side.addView(spaced(UiTheme.label(this, "OR OPEN ON YOUR PHONE"), 22)); + link = UiTheme.text(this, HermesPairingClient.RELAY_URL.replace("https://", "") + "/pair", 17, UiTheme.TEXT, Typeface.NORMAL); + side.addView(link); + side.addView(spaced(UiTheme.label(this, "PAIRING CODE"), 14)); + code = UiTheme.text(this, "…", 40, UiTheme.CYAN_BRIGHT, Typeface.BOLD); + code.setTypeface(UiTheme.pixelTypeface()); + code.setLetterSpacing(.12f); + side.addView(code); + check = UiTheme.text(this, "", 13, UiTheme.MUTED, Typeface.NORMAL); + side.addView(check); + status = UiTheme.text(this, "Starting…", 16, UiTheme.MUTED, Typeface.BOLD); + side.addView(spaced(status, 18)); + retry = UiTheme.button(this, "NEW CODE", new View.OnClickListener() { + @Override public void onClick(View v) { begin(); } + }, false); + retry.setVisibility(View.GONE); + LinearLayout.LayoutParams retryParams = new LinearLayout.LayoutParams(200, 52); + retryParams.topMargin = 12; + side.addView(retry, retryParams); + TextView privacy = UiTheme.text(this, + "Your key is encrypted on the phone for this car only. The pairing service relays ciphertext and " + + "cannot read it. Codes expire after 5 minutes.", 12, UiTheme.MUTED, Typeface.NORMAL); + side.addView(spaced(privacy, 18)); + + body.addView(side, new LinearLayout.LayoutParams(0, -1, 1)); + root.addView(body, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private View step(String number, String text) { + LinearLayout row = new LinearLayout(this); + row.setGravity(Gravity.CENTER_VERTICAL); + row.setPadding(0, 6, 0, 6); + TextView n = UiTheme.text(this, number, 18, UiTheme.BACKGROUND, Typeface.BOLD); + n.setGravity(Gravity.CENTER); + n.setBackground(UiTheme.pill(UiTheme.CYAN)); + row.addView(n, new LinearLayout.LayoutParams(36, 36)); + TextView t = UiTheme.text(this, text, 17, UiTheme.TEXT, Typeface.NORMAL); + t.setPadding(14, 0, 0, 0); + row.addView(t, new LinearLayout.LayoutParams(0, -2, 1)); + return row; + } + + private View spaced(View view, int top) { + view.setPadding(view.getPaddingLeft(), top, view.getPaddingRight(), view.getPaddingBottom()); + return view; + } + + private void setStatus(String text, int color) { + status.setText(text); + status.setTextColor(color); + } + + private void begin() { + final int gen = ++generation; + final HermesPairingClient.Started previous = started; + started = null; + qr.setCode(null); + code.setText("…"); + check.setText(""); + retry.setVisibility(View.GONE); + setStatus("Creating a pairing code…", UiTheme.MUTED); + background(new Runnable() { + @Override public void run() { + if (previous != null) client.cancel(previous); + try { + final HermesPairingCrypto crypto = new HermesPairingCrypto(); + final HermesPairingClient.Started created = client.start(crypto.publicKey()); + final String url = created.pairUrl + "#k=" + crypto.publicKey(); + final QrCode matrix = QrCode.encodeText(url, QrCode.Ecc.MEDIUM); + final String fingerprint = crypto.fingerprint(); + main.post(new Runnable() { + @Override public void run() { + if (gen != generation) { background(new Runnable() { @Override public void run() { client.cancel(created); } }); return; } + started = created; + keys = crypto; + qr.setCode(matrix); + code.setText(created.code); + check.setText("Check code on phone: " + fingerprint); + setStatus("Waiting for your phone…", UiTheme.CYAN_BRIGHT); + schedulePoll(gen, POLL_MS); + } + }); + } catch (final Exception error) { + main.post(new Runnable() { + @Override public void run() { + if (gen != generation) return; + setStatus("Could not reach the pairing service: " + message(error) + + ". Check the car's internet connection.", UiTheme.WARNING); + retry.setVisibility(View.VISIBLE); + } + }); + } + } + }); + } + + private HermesPairingCrypto keys; + + private void schedulePoll(final int gen, long delay) { + main.postDelayed(new Runnable() { + @Override public void run() { if (active && gen == generation && started != null) pollOnce(gen); } + }, delay); + } + + private void pollOnce(final int gen) { + final HermesPairingClient.Started current = started; + final HermesPairingCrypto crypto = keys; + background(new Runnable() { + @Override public void run() { + HermesPairingClient.Poll poll; + try { poll = client.poll(current); } + catch (Exception error) { poll = null; } + final HermesPairingClient.Poll result = poll; + if (result != null && "ready".equals(result.state)) { + String plain; + try { plain = crypto.open(current.code, result.epk, result.iv, result.ct); } + catch (Exception error) { + client.result(current, false, "The car could not decrypt the details"); + post(gen, new Runnable() { @Override public void run() { + fail("Could not decrypt the details from your phone. Try a new code."); + } }); + return; + } + applyCredentials(gen, current, plain); + return; + } + post(gen, new Runnable() { + @Override public void run() { + if (result != null && "expired".equals(result.state)) { + started = null; + qr.setCode(null); + fail("This code expired. Tap NEW CODE to try again."); + } else if (result != null && !"waiting".equals(result.state)) { + fail("This code was already used. Tap NEW CODE to try again."); + } else { + if (current != null && System.currentTimeMillis() > current.expiresAtMs) { begin(); return; } + schedulePoll(gen, POLL_MS); + } + } + }); + } + }); + } + + private void applyCredentials(final int gen, final HermesPairingClient.Started current, String plain) { + final String url, key; + try { + JSONObject json = new JSONObject(plain); + url = HermesConfig.normalizeServerUrl(json.optString("url", "")); + key = json.optString("key", "").trim(); + java.net.URL parsed = new java.net.URL(url); + if (!("https".equalsIgnoreCase(parsed.getProtocol()) || "http".equalsIgnoreCase(parsed.getProtocol())) + || parsed.getHost().length() == 0 || parsed.getUserInfo() != null || key.length() == 0) + throw new IllegalArgumentException(); + } catch (Exception error) { + client.result(current, false, "The server URL or key was invalid"); + post(gen, new Runnable() { @Override public void run() { fail("The phone sent an invalid server URL or key."); } }); + return; + } + post(gen, new Runnable() { + @Override public void run() { + started = null; + setStatus("Received from phone. Testing connection to " + url + "…", UiTheme.CYAN_BRIGHT); + try { + HermesConfig.save(HermesPairActivity.this, true, url, key); + } catch (Exception error) { + background(new Runnable() { @Override public void run() { client.result(current, false, "The car could not store the key securely"); } }); + fail("Could not securely save the key on this car."); + return; + } + HermesApiClient.test(HermesConfig.load(HermesPairActivity.this), new HermesApiClient.Callback() { + @Override public void complete(final boolean success, final String message, String ignored) { + background(new Runnable() { @Override public void run() { client.result(current, success, message); } }); + if (gen != generation) return; + if (success) { + qr.setCode(null); + setStatus("✓ Connected to Hermes. You can go back now.", UiTheme.SUCCESS); + setResult(RESULT_OK); + } else { + fail("Saved, but the car could not connect: " + message + + ". The car must be able to reach " + url + "."); + } + } + }); + } + }); + } + + private void fail(String text) { + setStatus(text, UiTheme.WARNING); + retry.setVisibility(View.VISIBLE); + } + + private void post(final int gen, final Runnable runnable) { + main.post(new Runnable() { @Override public void run() { if (gen == generation) runnable.run(); } }); + } + + private static void background(Runnable runnable) { new Thread(runnable, "hermes-pairing").start(); } + + private static String message(Exception error) { + String value = error.getMessage(); + return value == null || value.trim().length() == 0 ? error.getClass().getSimpleName() : value; + } + + private void immersive() { + 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); + } + + /** Draws a QR matrix as crisp black-on-white modules with a quiet zone. */ + static final class QrView extends View { + private final Paint dark = new Paint(); + private final Paint light = new Paint(); + private QrCode code; + + QrView(Context context) { + super(context); + dark.setColor(Color.BLACK); + dark.setAntiAlias(false); + light.setColor(Color.WHITE); + setContentDescription("Pairing QR code"); + } + + void setCode(QrCode value) { code = value; invalidate(); } + + @Override protected void onDraw(Canvas canvas) { + int size = Math.min(getWidth(), getHeight()); + int left = (getWidth() - size) / 2, top = (getHeight() - size) / 2; + if (code == null) { + Paint placeholder = new Paint(); + placeholder.setColor(UiTheme.SURFACE); + canvas.drawRect(left, top, left + size, top + size, placeholder); + return; + } + int modules = code.size + 8; + int cell = Math.max(1, size / modules); + int drawn = cell * modules; + int x0 = left + (size - drawn) / 2, y0 = top + (size - drawn) / 2; + canvas.drawRect(x0, y0, x0 + drawn, y0 + drawn, light); + for (int y = 0; y < code.size; y++) + for (int x = 0; x < code.size; x++) + if (code.getModule(x, y)) { + int px = x0 + (x + 4) * cell, py = y0 + (y + 4) * cell; + canvas.drawRect(px, py, px + cell, py + cell, dark); + } + } + } +} diff --git a/src/cloud/molberg/mgutility/HermesPairingClient.java b/src/cloud/molberg/mgutility/HermesPairingClient.java new file mode 100644 index 0000000..d769e9d --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesPairingClient.java @@ -0,0 +1,125 @@ +package cloud.molberg.mgutility; + +import org.json.JSONObject; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * Blocking HTTP calls to the pairing relay. The relay only forwards ciphertext; the user's own + * Hermes server URL and key are decrypted on the car. Call from a background thread. + */ +final class HermesPairingClient { + /** Relay hosted with the MG Utility analytics service. It never sees readable credentials. */ + static final String RELAY_URL = "https://analytics.molberg.cloud"; + private static final int MAX_BODY = 32 * 1024; + + static final class Started { + final String code, pollToken, pairUrl; + final long expiresAtMs; + Started(String code, String pollToken, String pairUrl, long expiresAtMs) { + this.code = code; this.pollToken = pollToken; this.pairUrl = pairUrl; this.expiresAtMs = expiresAtMs; + } + } + + static final class Poll { + final String state; final String epk, iv, ct; + Poll(String state, String epk, String iv, String ct) { this.state = state; this.epk = epk; this.iv = iv; this.ct = ct; } + } + + private final String relay; + + HermesPairingClient(String relay) { this.relay = relay.endsWith("/") ? relay.substring(0, relay.length() - 1) : relay; } + + Started start(String publicKey) throws Exception { + JSONObject body = new JSONObject(); + body.put("publicKey", publicKey); + Response response = request("POST", "/v1/pair/start", null, body); + if (response.code == 429) throw new IllegalStateException("Too many pairing attempts. Wait a few minutes."); + if (response.code != 201) throw new IllegalStateException("Pairing service returned HTTP " + response.code); + JSONObject json = new JSONObject(response.body); + String code = json.getString("code"); + String pairUrl = json.getString("pairUrl"); + if (!pairUrl.startsWith("https://") && !pairUrl.startsWith("http://127.0.0.1") && !pairUrl.startsWith("http://localhost")) + throw new IllegalStateException("Pairing service returned an insecure link"); + long expires = System.currentTimeMillis() + 5 * 60 * 1000L; + return new Started(code, json.getString("pollToken"), pairUrl, expires); + } + + Poll poll(Started started) throws Exception { + Response response = request("GET", "/v1/pair/" + encode(started.code) + "/poll", started.pollToken, null); + if (response.code == 410) return new Poll("expired", null, null, null); + if (response.code == 429) return new Poll("waiting", null, null, null); + if (response.code != 200) throw new IllegalStateException("Pairing service returned HTTP " + response.code); + JSONObject json = new JSONObject(response.body); + String state = json.optString("state", ""); + if ("ready".equals(state)) { + if (json.optInt("v", 0) != 1) throw new IllegalStateException("Unsupported pairing format. Update MG Utility."); + return new Poll("ready", json.getString("epk"), json.getString("iv"), json.getString("ct")); + } + return new Poll(state, null, null, null); + } + + void result(Started started, boolean ok, String message) { + try { + JSONObject body = new JSONObject(); + body.put("ok", ok); + body.put("message", message == null ? "" : message); + request("POST", "/v1/pair/" + encode(started.code) + "/result", started.pollToken, body); + } catch (Exception ignored) { } + } + + void cancel(Started started) { + try { request("DELETE", "/v1/pair/" + encode(started.code), started.pollToken, null); } + catch (Exception ignored) { } + } + + private Response request(String method, String path, String bearer, JSONObject body) throws Exception { + HttpURLConnection connection = (HttpURLConnection) new URL(relay + path).openConnection(); + try { + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(8000); + connection.setReadTimeout(10000); + connection.setRequestMethod(method); + connection.setRequestProperty("Accept", "application/json"); + if (bearer != null) connection.setRequestProperty("Authorization", "Bearer " + bearer); + if (body != null) { + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + OutputStream out = connection.getOutputStream(); + out.write(body.toString().getBytes(StandardCharsets.UTF_8)); + out.close(); + } + int code = connection.getResponseCode(); + InputStream stream = code >= 200 && code < 400 ? connection.getInputStream() : connection.getErrorStream(); + return new Response(code, read(stream)); + } finally { + connection.disconnect(); + } + } + + private static String read(InputStream stream) throws Exception { + if (stream == null) return ""; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int n; + while ((n = stream.read(buffer)) > 0) { + out.write(buffer, 0, n); + if (out.size() > MAX_BODY) throw new IllegalStateException("Pairing response too large"); + } + stream.close(); + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } + + private static String encode(String value) throws Exception { return URLEncoder.encode(value, "UTF-8"); } + + private static final class Response { + final int code; final String body; + Response(int code, String body) { this.code = code; this.body = body; } + } +} diff --git a/src/cloud/molberg/mgutility/HermesPairingCrypto.java b/src/cloud/molberg/mgutility/HermesPairingCrypto.java new file mode 100644 index 0000000..6995296 --- /dev/null +++ b/src/cloud/molberg/mgutility/HermesPairingCrypto.java @@ -0,0 +1,159 @@ +package cloud.molberg.mgutility; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.interfaces.ECPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.util.Arrays; + +import javax.crypto.Cipher; +import javax.crypto.KeyAgreement; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * Car side of the Hermes phone-pairing scheme (v1). Pure java.security so it runs on the JVM in tests. + * + * The car keeps a one-time P-256 key pair in memory. The phone performs ephemeral ECDH against the + * car's public key, derives an AES-256 key with HKDF-SHA256 (empty salt, + * info = "mg-utility-hermes-pair-v1|" + code) and encrypts with AES-GCM using the pairing code as AAD. + * The relay only ever sees the public keys and ciphertext. + */ +final class HermesPairingCrypto { + static final String INFO_PREFIX = "mg-utility-hermes-pair-v1|"; + private static final String FINGERPRINT_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"; + + private final KeyPair keyPair; + + HermesPairingCrypto() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + keyPair = generator.generateKeyPair(); + } + + /** Uncompressed SEC1 point (0x04 || X || Y), base64url without padding: 87 characters. */ + String publicKey() { + return base64Url(encodePoint((ECPublicKey) keyPair.getPublic())); + } + + /** Four-character check code that the phone page also shows for this key. */ + String fingerprint() throws Exception { + return fingerprint(encodePoint((ECPublicKey) keyPair.getPublic())); + } + + static String fingerprint(byte[] rawPublicKey) throws Exception { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(rawPublicKey); + StringBuilder out = new StringBuilder(); + for (int i = 0; i < 4; i++) out.append(FINGERPRINT_ALPHABET.charAt((digest[i] & 0xff) % FINGERPRINT_ALPHABET.length())); + return out.toString(); + } + + /** Decrypts the phone's sealed payload; throws on any tampering or wrong code. */ + String open(String code, String ephemeralPublicKey, String iv, String ciphertext) throws Exception { + ECParameterSpec params = ((ECPublicKey) keyPair.getPublic()).getParams(); + PublicKey peer = decodePoint(base64UrlDecode(ephemeralPublicKey), params); + KeyAgreement agreement = KeyAgreement.getInstance("ECDH"); + agreement.init(keyPair.getPrivate()); + agreement.doPhase(peer, true); + byte[] shared = agreement.generateSecret(); + byte[] key = hkdfSha256(shared, new byte[0], (INFO_PREFIX + code).getBytes(StandardCharsets.UTF_8), 32); + Arrays.fill(shared, (byte) 0); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, base64UrlDecode(iv))); + cipher.updateAAD(code.getBytes(StandardCharsets.UTF_8)); + byte[] plain = cipher.doFinal(base64UrlDecode(ciphertext)); + Arrays.fill(key, (byte) 0); + String value = new String(plain, StandardCharsets.UTF_8); + Arrays.fill(plain, (byte) 0); + return value; + } + + static byte[] encodePoint(ECPublicKey key) { + byte[] out = new byte[65]; + out[0] = 0x04; + copyUnsigned(key.getW().getAffineX(), out, 1); + copyUnsigned(key.getW().getAffineY(), out, 33); + return out; + } + + static PublicKey decodePoint(byte[] raw, ECParameterSpec params) throws Exception { + if (raw.length != 65 || raw[0] != 0x04) throw new IllegalArgumentException("Invalid phone key"); + BigInteger x = new BigInteger(1, Arrays.copyOfRange(raw, 1, 33)); + BigInteger y = new BigInteger(1, Arrays.copyOfRange(raw, 33, 65)); + // The provider validates that the point lies on the curve during key agreement. + return KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), params)); + } + + private static void copyUnsigned(BigInteger value, byte[] out, int offset) { + byte[] bytes = value.toByteArray(); + int start = bytes.length > 32 ? bytes.length - 32 : 0; + int length = bytes.length - start; + System.arraycopy(bytes, start, out, offset + 32 - length, length); + } + + static byte[] hkdfSha256(byte[] ikm, byte[] salt, byte[] info, int length) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(salt.length == 0 ? new byte[32] : salt, "HmacSHA256")); + byte[] prk = mac.doFinal(ikm); + mac.init(new SecretKeySpec(prk, "HmacSHA256")); + byte[] out = new byte[length]; + byte[] block = new byte[0]; + int produced = 0; + for (int counter = 1; produced < length; counter++) { + mac.update(block); + mac.update(info); + mac.update((byte) counter); + block = mac.doFinal(); + int take = Math.min(block.length, length - produced); + System.arraycopy(block, 0, out, produced, take); + produced += take; + } + return out; + } + + // Minimal base64url codec (java.util.Base64 needs API 26 on Android; this keeps tests JVM-only). + private static final char[] B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray(); + + static String base64Url(byte[] data) { + StringBuilder out = new StringBuilder((data.length * 4 + 2) / 3); + for (int i = 0; i < data.length; i += 3) { + int b = (data[i] & 0xff) << 16; + if (i + 1 < data.length) b |= (data[i + 1] & 0xff) << 8; + if (i + 2 < data.length) b |= data[i + 2] & 0xff; + out.append(B64[(b >> 18) & 63]).append(B64[(b >> 12) & 63]); + if (i + 1 < data.length) out.append(B64[(b >> 6) & 63]); + if (i + 2 < data.length) out.append(B64[b & 63]); + } + return out.toString(); + } + + static byte[] base64UrlDecode(String text) { + String s = text == null ? "" : text.trim(); + int bits = 0, value = 0, n = 0; + byte[] out = new byte[s.length() * 3 / 4]; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + int v; + if (c >= 'A' && c <= 'Z') v = c - 'A'; + else if (c >= 'a' && c <= 'z') v = c - 'a' + 26; + else if (c >= '0' && c <= '9') v = c - '0' + 52; + else if (c == '-' || c == '+') v = 62; + else if (c == '_' || c == '/') v = 63; + else if (c == '=') break; + else throw new IllegalArgumentException("Invalid base64url"); + value = (value << 6) | v; + bits += 6; + if (bits >= 8) { bits -= 8; out[n++] = (byte) ((value >> bits) & 0xff); } + } + return Arrays.copyOf(out, n); + } +} diff --git a/src/cloud/molberg/mgutility/HermesSettingsActivity.java b/src/cloud/molberg/mgutility/HermesSettingsActivity.java index 5515195..673ad67 100644 --- a/src/cloud/molberg/mgutility/HermesSettingsActivity.java +++ b/src/cloud/molberg/mgutility/HermesSettingsActivity.java @@ -23,6 +23,8 @@ import java.net.URL; /** Configuration screen for the Hermes native API voice assistant. */ public final class HermesSettingsActivity extends AnimatedActivity { private static final int AUDIO_PERMISSION = 9401; + private static final int PAIR_REQUEST = 9402; + private LinearLayout advanced; private EditText url; private EditText apiKey; private EditText transcriptionUrl; @@ -67,10 +69,24 @@ public final class HermesSettingsActivity extends AnimatedActivity { form.setPadding(8, 8, 8, 12); TextView intro = UiTheme.text(this, - "Connect steering-wheel push-to-talk directly to the Hermes Agent session API.", + "Connect steering-wheel push-to-talk to your own Hermes Agent. Pair with your phone: scan a QR code, " + + "enter your Hermes server and API key on the phone, and this car connects automatically.", 14, UiTheme.TEXT, Typeface.NORMAL); - intro.setPadding(0, 2, 0, 14); + intro.setPadding(0, 2, 0, 10); form.addView(intro); + connectionSummary = UiTheme.text(this, summaryText(config), 14, + config.isReady() ? UiTheme.SUCCESS : UiTheme.MUTED, Typeface.BOLD); + connectionSummary.setPadding(0, 0, 0, 10); + form.addView(connectionSummary); + form.addView(UiTheme.button(this, config.isReady() ? "PAIR AGAIN WITH PHONE" : "PAIR WITH PHONE", + new View.OnClickListener() { + @Override public void onClick(View view) { + startActivityForResult(new android.content.Intent(HermesSettingsActivity.this, + HermesPairActivity.class), PAIR_REQUEST); + } + }, true), new LinearLayout.LayoutParams(-1, 60)); + TextView spacer = new TextView(this); + form.addView(spacer, new LinearLayout.LayoutParams(-1, 12)); form.addView(UiTheme.button(this, "ENABLE GLOBAL STEERING-WHEEL ACCESS", new View.OnClickListener() { @Override public void onClick(View view) { KeyRemappingAccessibilityService.openSettings(HermesSettingsActivity.this); } }, false), new LinearLayout.LayoutParams(-1, 48)); @@ -86,21 +102,34 @@ public final class HermesSettingsActivity extends AnimatedActivity { enabled.setChecked(config.enabled); form.addView(enabled, new LinearLayout.LayoutParams(-1, 52)); - url = field(HermesConfig.DEFAULT_SERVER_URL, - config.serverUrl.length() == 0 ? HermesConfig.DEFAULT_SERVER_URL : config.serverUrl, false); - form.addView(labeled("HERMES SERVER", url)); - apiKey = field("API_SERVER_KEY from ~/.hermes/.env", config.apiKey, true); - form.addView(labeled("API KEY", apiKey)); + final Button advancedToggle = UiTheme.button(this, "SHOW ADVANCED / MANUAL SETUP", null, false); + form.addView(advancedToggle, new LinearLayout.LayoutParams(-1, 48)); + advanced = new LinearLayout(this); + advanced.setOrientation(LinearLayout.VERTICAL); + advanced.setVisibility(View.GONE); + advancedToggle.setOnClickListener(new View.OnClickListener() { + @Override public void onClick(View v) { + boolean show = advanced.getVisibility() != View.VISIBLE; + advanced.setVisibility(show ? View.VISIBLE : View.GONE); + advancedToggle.setText(show ? "HIDE ADVANCED / MANUAL SETUP" : "SHOW ADVANCED / MANUAL SETUP"); + } + }); + form.addView(advanced); + LinearLayout manual = advanced; + url = field("https://your-hermes-server or http://192.168.1.20:8642", config.serverUrl, false); + manual.addView(labeled("HERMES SERVER", url)); + apiKey = field("API_SERVER_KEY of your Hermes Agent", config.apiKey, true); + manual.addView(labeled("API KEY", apiKey)); transcriptionUrl = field("https://your-speech-server/v1/audio/transcriptions", config.transcriptionUrl, false); - form.addView(labeled("TRANSCRIPTION ENDPOINT (OPTIONAL)", transcriptionUrl)); + manual.addView(labeled("TRANSCRIPTION ENDPOINT (OPTIONAL)", transcriptionUrl)); transcriptionKey = field("Speech server key (not the Hermes key)", config.transcriptionKey, true); - form.addView(labeled("TRANSCRIPTION API KEY", transcriptionKey)); + manual.addView(labeled("TRANSCRIPTION API KEY", transcriptionKey)); transcriptionModel = field("whisper-1", config.transcriptionModel, false); - form.addView(labeled("TRANSCRIPTION MODEL", transcriptionModel)); + manual.addView(labeled("TRANSCRIPTION MODEL", transcriptionModel)); form.addView(UiTheme.label(this, "VOICE ENGINE")); voiceEngine = new Spinner(this); String[] engines = new String[]{ - "System speech recognizer", + "Automatic (system recognizer, else on-device)", "Local sherpa-onnx (offline)", "Record + upload to transcription server"}; voiceEngine.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, engines)); @@ -110,19 +139,20 @@ public final class HermesSettingsActivity extends AnimatedActivity { sherpaModelDir = field("/data/data/cloud.molberg.mgutility/files/sherpa-en", config.sherpaModelDir, false); form.addView(labeled("LOCAL SHERPA MODEL DIRECTORY", sherpaModelDir)); form.addView(UiTheme.text(this, - "System uses the head unit recognizer. Local sherpa-onnx keeps speech on the car and needs the " + - "English streaming model files in the directory above. Upload mode sends recorded audio only to " + + "Automatic uses the head unit's Android recognizer when it has one and otherwise the built-in " + + "on-device English model, so it only needs microphone access. Local sherpa-onnx always uses the " + + "built-in on-device model. Upload mode sends recorded audio only to " + "the configured OpenAI-compatible transcription endpoint; the result is then sent to Hermes as text. " + "Hermes installations are not modified and do not receive arbitrary file attachments from this app.", 12, UiTheme.MUTED, Typeface.NORMAL)); TextView help = UiTheme.text(this, - "This machine's Hermes API is http://10.0.0.74:18793. Enter its API_SERVER_KEY; no webhook, " + - "route, HMAC secret, or dashboard login is needed. The app keeps one Hermes session so follow-up " + - "requests share conversation history. The API key is encrypted with Android Keystore.", + "Manual setup: enter your Hermes Agent API server address (the API server platform, default port 8642) " + + "and its API_SERVER_KEY. The car must be able to reach that address. The app keeps one Hermes session " + + "so follow-up requests share conversation history. The API key is encrypted with Android Keystore.", 12, UiTheme.MUTED, Typeface.NORMAL); help.setPadding(2, 12, 2, 12); - form.addView(help); + manual.addView(help); LinearLayout actions = new LinearLayout(this); actions.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); @@ -168,6 +198,27 @@ public final class HermesSettingsActivity extends AnimatedActivity { return root; } + private TextView connectionSummary; + + private static String summaryText(HermesConfig config) { + if (config.isReady()) return "CONNECTED TO " + config.serverUrl; + if (config.serverUrl.length() > 0 && config.apiKey.length() > 0) return "Paired with " + config.serverUrl + " (disabled)"; + return "Not paired yet"; + } + + @Override protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == PAIR_REQUEST) { + // Pairing saved new credentials; rebuild so the fields reflect them. + setContentView(buildUi()); + if (resultCode == RESULT_OK) { + requestMicrophone(); + final android.content.Context app = getApplicationContext(); + new Thread(new Runnable() { @Override public void run() { HermesLocalRecognizer.prepareModel(app); } }).start(); + } + } + } + private LinearLayout labeled(String label, EditText input) { LinearLayout block = new LinearLayout(this); block.setOrientation(LinearLayout.VERTICAL); diff --git a/src/cloud/molberg/mgutility/HermesVoiceActivity.java b/src/cloud/molberg/mgutility/HermesVoiceActivity.java index d5abbc5..6e6b341 100644 --- a/src/cloud/molberg/mgutility/HermesVoiceActivity.java +++ b/src/cloud/molberg/mgutility/HermesVoiceActivity.java @@ -166,7 +166,12 @@ public final class HermesVoiceActivity extends AnimatedActivity implements Recog if (HermesConfig.VOICE_ENGINE_SHERPA.equals(voiceConfig.voiceEngine)) { startLocalRecognition(); return; } if (HermesConfig.VOICE_ENGINE_UPLOAD.equals(voiceConfig.voiceEngine)) { startRecording(); return; } try { - if (!SpeechRecognizer.isRecognitionAvailable(this)) { startSystemRecognition(); return; } + if (!SpeechRecognizer.isRecognitionAvailable(this)) { + // No recognition service: use the system voice dialog if one exists, otherwise the + // bundled on-device recognizer, which only needs the microphone. + if (systemVoiceDialogAvailable()) startSystemRecognition(); else startLocalRecognition(); + return; + } if (recognizer == null) { recognizer = SpeechRecognizer.createSpeechRecognizer(this); recognizer.setRecognitionListener(this); @@ -179,16 +184,26 @@ public final class HermesVoiceActivity extends AnimatedActivity implements Recog recognitionStarted = true; recognizer.startListening(intent); } catch (SecurityException error) { - recognitionStarted = false; destroyRecognizer(); startSystemRecognition(); + recognitionStarted = false; destroyRecognizer(); + if (systemVoiceDialogAvailable()) startSystemRecognition(); else startLocalRecognition(); } catch (RuntimeException error) { recognitionStarted = false; destroyRecognizer(); - fail("The Android speech service is unavailable. Select Local sherpa-onnx or Upload in Hermes settings."); + startLocalRecognition(); + } + } + + private boolean systemVoiceDialogAvailable() { + try { + return getPackageManager().resolveActivity(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0) != null; + } catch (RuntimeException error) { + return false; } } private void startLocalRecognition() { + if (localRecognizer != null || audioCapture != null || released || submitted || inactive()) return; localRecognizer = new HermesLocalRecognizer(this); - audioCapture = new HermesAudioCapture(new File(getCacheDir(), "hermes-local-voice.wav"), + audioCapture = new HermesAudioCapture(this, new File(getCacheDir(), "hermes-local-voice.wav"), new HermesAudioCapture.SampleListener() { @Override public void onSamples(float[] samples, int count) { if (localRecognizer != null) localRecognizer.acceptSamples(samples, count); @@ -231,13 +246,10 @@ public final class HermesVoiceActivity extends AnimatedActivity implements Recog state.setText("SYSTEM VOICE INPUT • SPEAK NOW"); transcript.setText("The head unit voice dialog is listening. Finish speaking normally."); startActivityForResult(intent, SYSTEM_RECOGNITION); - } catch (android.content.ActivityNotFoundException error) { - systemRecognitionStarted = false; - fail("This head unit does not expose its OEM voice input to third-party apps. " + - "Android Auto/OEM voice can still work privately, but MG Utility cannot read that audio."); } catch (RuntimeException error) { + // Includes ActivityNotFoundException: no usable system voice input, so recognise on-device. systemRecognitionStarted = false; - fail("The head unit rejected Android system voice input. Try the OEM assistant once, then try Hermes again."); + startLocalRecognition(); } } @@ -388,7 +400,7 @@ public final class HermesVoiceActivity extends AnimatedActivity implements Recog private void fail(String message) { submitted = true; - state.setText("HERMES VOICE UNAVAILABLE"); + state.setText(message.startsWith("Nothing was heard") ? "DIDN'T CATCH THAT" : "HERMES VOICE UNAVAILABLE"); indicator.setText("!"); indicator.setTextColor(UiTheme.WARNING); transcript.setText(message); @@ -452,6 +464,10 @@ public final class HermesVoiceActivity extends AnimatedActivity implements Recog if (released) { submitBestTranscript(); return; } if (error == SpeechRecognizer.ERROR_NO_MATCH || error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) { MAIN.postDelayed(new Runnable() { @Override public void run() { startRecognition(); } }, 180L); + } else if (partial == null || partial.length() == 0) { + // A broken/offline system recognizer (client, network, busy, permission): switch to on-device. + destroyRecognizer(); + startLocalRecognition(); } else fail("Speech recognizer error " + error); } @Override public void onResults(Bundle results) { acceptResults(results, true); } diff --git a/src/cloud/molberg/mgutility/KeyRemappingManager.java b/src/cloud/molberg/mgutility/KeyRemappingManager.java index 54b44cc..aff73de 100644 --- a/src/cloud/molberg/mgutility/KeyRemappingManager.java +++ b/src/cloud/molberg/mgutility/KeyRemappingManager.java @@ -32,6 +32,10 @@ final class KeyRemappingManager { static final String ACTION_DASHBOARD = "NAV_DASHBOARD"; static final String ACTION_ENERGY = "NAV_ENERGY"; static final String ACTION_CHARGING = "NAV_CHARGING"; + static final String ACTION_CLIMATE = "NAV_CLIMATE"; + static final String ACTION_DRIVER_SEAT_HEAT = "CLIMATE_DRIVER_SEAT_HEAT"; + static final String ACTION_PASSENGER_SEAT_HEAT = "CLIMATE_PASSENGER_SEAT_HEAT"; + static final String ACTION_WHEEL_HEAT = "CLIMATE_WHEEL_HEAT"; static final String ACTION_TRIPS = "NAV_TRIPS"; static final String ACTION_SPEED_TEST = "NAV_SPEED_TEST"; static final String ACTION_SOUNDBOARD = "NAV_SOUNDBOARD"; @@ -57,6 +61,10 @@ final class KeyRemappingManager { new Action(ACTION_DASHBOARD, "Open dashboard", "MG Utility live dashboard"), new Action(ACTION_ENERGY, "Open energy dashboard", "Consumption and recovery readouts"), new Action(ACTION_CHARGING, "Open charging automation", "Charging rules and prices"), + new Action(ACTION_CLIMATE, "Open climate", "Temperature, fan, seat and wheel heating"), + new Action(ACTION_DRIVER_SEAT_HEAT, "Driver seat heat", "Step driver seat heating like the OEM button"), + new Action(ACTION_PASSENGER_SEAT_HEAT, "Passenger seat heat", "Step passenger seat heating like the OEM button"), + new Action(ACTION_WHEEL_HEAT, "Steering wheel heat", "Toggle steering wheel heating"), new Action(ACTION_TRIPS, "Open trip reports", "Saved drives and routes"), new Action(ACTION_SPEED_TEST, "Open 0–100 tester", "Performance timer"), new Action(ACTION_SOUNDBOARD, "Open soundboard", "Event audio configuration"), @@ -270,6 +278,18 @@ final class KeyRemappingManager { private static int eventKey(Mapping m) { return m.keyCode; } private static void cancelSingle(int code) { Runnable pending = SINGLE_PENDING.remove(code); if (pending != null) HANDLER.removeCallbacks(pending); } + private static void climateKey(final Context context, final String action) { + final ClimateGateway gateway = ClimateLink.get(context).gateway(); + if (gateway == null) { Toast.makeText(context, "Climate service not connected", Toast.LENGTH_SHORT).show(); return; } + new Thread(new Runnable() { + @Override public void run() { + if (ACTION_DRIVER_SEAT_HEAT.equals(action)) gateway.pressSeatHeat(ClimateGateway.Seat.DRIVER); + else if (ACTION_PASSENGER_SEAT_HEAT.equals(action)) gateway.pressSeatHeat(ClimateGateway.Seat.PASSENGER); + else gateway.pressSteeringWheelHeat(); + } + }, "climate-key").start(); + } + static void execute(Context context, String action) { Mapping mapping = new Mapping(); mapping.action = action; execute(context, mapping); } @@ -280,6 +300,9 @@ final class KeyRemappingManager { if (ACTION_DASHBOARD.equals(action)) { intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } else if (ACTION_ENERGY.equals(action)) intent = new Intent(context, EnergyActivity.class); else if (ACTION_CHARGING.equals(action)) intent = new Intent(context, ChargingActivity.class); + else if (ACTION_CLIMATE.equals(action)) intent = new Intent(context, ClimateActivity.class); + else if (ACTION_DRIVER_SEAT_HEAT.equals(action) || ACTION_PASSENGER_SEAT_HEAT.equals(action) + || ACTION_WHEEL_HEAT.equals(action)) { climateKey(context, action); return; } else if (ACTION_TRIPS.equals(action)) intent = new Intent(context, TripsActivity.class); else if (ACTION_SPEED_TEST.equals(action)) intent = new Intent(context, SpeedTestActivity.class); else if (ACTION_SOUNDBOARD.equals(action)) intent = new Intent(context, SoundboardActivity.class); diff --git a/src/cloud/molberg/mgutility/MainActivity.java b/src/cloud/molberg/mgutility/MainActivity.java index 2c76ec9..2b49eb3 100644 --- a/src/cloud/molberg/mgutility/MainActivity.java +++ b/src/cloud/molberg/mgutility/MainActivity.java @@ -182,7 +182,7 @@ public class MainActivity extends AnimatedActivity { // Keep the periodic Gitea check alive even when the user never opens // Settings. JobScheduler persists this across restarts and reboots. UpdateScheduler.schedule(this); - BrightnessScheduler.rearm(this); + BrightnessScheduler.rearmAfterBoot(this); UiTheme.applyFontScale(this); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); immersive(); @@ -1180,6 +1180,9 @@ public class MainActivity extends AnimatedActivity { startActivity(new Intent(MainActivity.this, ChargingActivity.class)); } }), tileParams()); + area.addView(quickButton("Climate", new View.OnClickListener() { + @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ClimateActivity.class)); } + }), tileParams()); area.addView(quickButton("Energy dashboard", new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, EnergyActivity.class)); } }), tileParams()); diff --git a/src/cloud/molberg/mgutility/MgApp.java b/src/cloud/molberg/mgutility/MgApp.java index 784f806..1eff7f6 100644 --- a/src/cloud/molberg/mgutility/MgApp.java +++ b/src/cloud/molberg/mgutility/MgApp.java @@ -7,5 +7,22 @@ public final class MgApp extends Application { @Override public void onCreate() { super.onCreate(); BackupManager.start(this); + // Put the OEM wake word back if a mic capture died while it was paused. + try { MicAccess.restoreIfPending(this); } catch (Throwable ignored) { } + final Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { + @Override public void uncaughtException(Thread thread, Throwable error) { + try { DiagnosticsClient.queueCrash(getApplicationContext(), error); } catch (Throwable ignored) { } + if (previous != null) previous.uncaughtException(thread, error); + } + }); + UsageDataReporter.start(this); + // Pre-copy the on-device speech model so the first Hermes press starts listening quickly. + final android.content.Context app = getApplicationContext(); + new Thread(new Runnable() { + @Override public void run() { + try { if (HermesConfig.load(app).enabled) HermesLocalRecognizer.prepareModel(app); } catch (Throwable ignored) { } + } + }, "hermes-model-prepare").start(); } } diff --git a/src/cloud/molberg/mgutility/MicAccess.java b/src/cloud/molberg/mgutility/MicAccess.java new file mode 100644 index 0000000..b71f623 --- /dev/null +++ b/src/cloud/molberg/mgutility/MicAccess.java @@ -0,0 +1,239 @@ +package cloud.molberg.mgutility; + +import android.content.ComponentName; +import android.content.Context; +import android.content.ServiceConnection; +import android.content.SharedPreferences; +import android.media.AudioRecord; +import android.os.IBinder; +import android.os.Looper; +import android.provider.Settings; +import android.util.Log; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Borrows the head unit's single microphone from SAIC's voice assistant. + * + * On the MG4 the OEM Nuance assistant (com.saicmotor.voiceservice / voicevui) keeps a + * wake-word capture open on the built-in mic whenever its wake word is enabled. Android 9's + * audio policy then refuses any second capture: {@code AudioRecord.startRecording()} returns + * silently but the recorder never enters RECORDING, and logcat shows + * {@code AudioRecord: start() status -38}. Reads fail or return silence. + * + * The OEM service already cooperates with other voice apps: VrSpeechService listens to + * CarAppFocusManager and calls stopWakeUpListening() when another app takes + * APP_FOCUS_TYPE_VOICE_COMMAND, and restarts it when focus is abandoned. That is the first + * strategy here. If the mic is still busy, the second strategy temporarily turns the OEM + * wake-word switch (Settings.System SAICMOTOR_VOICE_WAKE_SWITCH) off and restores it on + * release. A pending restore is persisted so a crash mid-capture cannot leave it off. + * + * Car API is used by reflection: android.car is on this unit's boot classpath, but the + * project builds against plain android.jar. + */ +final class MicAccess { + private static final String TAG = "MicAccess"; + static final String WAKE_SWITCH = "SAICMOTOR_VOICE_WAKE_SWITCH"; + private static final String PREFS = "mic_access"; + private static final String PREF_RESTORE_WAKE = "restore_wake_switch"; + private static final int APP_FOCUS_TYPE_VOICE_COMMAND = 2; + private static final int APP_FOCUS_REQUEST_SUCCEEDED = 1; + + private static final Object LOCK = new Object(); + private static Object car; // android.car.Car + private static Object focusManager; // android.car.CarAppFocusManager + private static Object focusCallback; // OnAppFocusOwnershipCallback proxy + private static int holders; + private static boolean wakeSwitchedOff; + private static String lastNote = ""; + + private MicAccess() { } + + /** A held borrow of the microphone. Always release it. */ + static final class Lease { + private final Context app; + private boolean released; + final boolean voiceFocus; + Lease(Context app, boolean voiceFocus) { this.app = app; this.voiceFocus = voiceFocus; } + void release() { + if (released) return; + released = true; + MicAccess.release(app); + } + } + + static String lastNote() { return lastNote; } + + /** Restores the OEM wake-word switch if a previous capture died before releasing it. */ + static void restoreIfPending(Context context) { + Context app = context.getApplicationContext(); + if (!prefs(app).getBoolean(PREF_RESTORE_WAKE, false)) return; + synchronized (LOCK) { if (holders > 0) return; } + writeWakeSwitch(app, 1); + prefs(app).edit().remove(PREF_RESTORE_WAKE).apply(); + } + + /** + * Requests voice-command focus so the OEM assistant pauses its wake-word capture. + * Blocks up to ~1.5 s waiting for the car service; never call on the main thread. + */ + static Lease acquire(Context context) { + Context app = context.getApplicationContext(); + if (Looper.myLooper() == Looper.getMainLooper()) { + Log.w(TAG, "acquire() on main thread; skipping blocking car-service connect"); + } + boolean focus; + synchronized (LOCK) { + holders++; + focus = focusManager != null && focusCallback != null && requestFocusLocked(); + } + if (!focus && Looper.myLooper() != Looper.getMainLooper()) { + Object manager = connectFocusManager(app); + synchronized (LOCK) { focus = manager != null && requestFocusLocked(); } + } + lastNote = focus ? "voice focus granted" : "voice focus unavailable"; + if (focus) sleep(350); // give VrSpeechService time to close its capture + return new Lease(app, focus); + } + + /** + * Starts {@code record}, escalating when the OEM assistant still owns the mic. + * Returns true only when the recorder actually reports RECORDSTATE_RECORDING. + */ + static boolean startRecording(Context context, AudioRecord record) { + if (tryStart(record)) return true; + sleep(400); + if (tryStart(record)) return true; + // Second strategy: pause the OEM wake word explicitly, then retry. + Context app = context.getApplicationContext(); + if (pauseWakeWord(app)) { + for (int i = 0; i < 4; i++) { + sleep(350); + if (tryStart(record)) { lastNote = lastNote + " + wake word paused"; return true; } + } + } + lastNote = lastNote + " + mic still busy (start() status -38?)"; + return false; + } + + private static boolean tryStart(AudioRecord record) { + try { + if (record.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) return true; + record.startRecording(); + return record.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING; + } catch (Throwable error) { + Log.w(TAG, "startRecording failed", error); + return false; + } + } + + private static boolean pauseWakeWord(Context app) { + synchronized (LOCK) { + if (wakeSwitchedOff) return true; + int current; + try { current = Settings.System.getInt(app.getContentResolver(), WAKE_SWITCH, 1); } + catch (Throwable error) { return false; } + if (current != 1) return false; // already off: nothing more we can do here + prefs(app).edit().putBoolean(PREF_RESTORE_WAKE, true).commit(); + if (!writeWakeSwitch(app, 0)) { + prefs(app).edit().remove(PREF_RESTORE_WAKE).apply(); + return false; + } + wakeSwitchedOff = true; + return true; + } + } + + private static void release(Context app) { + synchronized (LOCK) { + holders = Math.max(0, holders - 1); + if (holders > 0) return; + if (wakeSwitchedOff) { + writeWakeSwitch(app, 1); + wakeSwitchedOff = false; + prefs(app).edit().remove(PREF_RESTORE_WAKE).apply(); + } + if (focusManager != null && focusCallback != null) { + try { + focusManager.getClass().getMethod("abandonAppFocus", + Class.forName("android.car.CarAppFocusManager$OnAppFocusOwnershipCallback"), int.class) + .invoke(focusManager, focusCallback, APP_FOCUS_TYPE_VOICE_COMMAND); + } catch (Throwable error) { Log.w(TAG, "abandonAppFocus failed", error); } + } + } + } + + private static boolean writeWakeSwitch(Context app, int value) { + try { return Settings.System.putInt(app.getContentResolver(), WAKE_SWITCH, value); } + catch (Throwable error) { Log.w(TAG, "wake switch write failed", error); return false; } + } + + private static boolean requestFocusLocked() { + try { + Method request = focusManager.getClass().getMethod("requestAppFocus", int.class, + Class.forName("android.car.CarAppFocusManager$OnAppFocusOwnershipCallback")); + Object result = request.invoke(focusManager, APP_FOCUS_TYPE_VOICE_COMMAND, focusCallback); + return result instanceof Integer && (Integer) result == APP_FOCUS_REQUEST_SUCCEEDED; + } catch (Throwable error) { + Log.w(TAG, "requestAppFocus failed", error); + return false; + } + } + + private static Object connectFocusManager(Context app) { + synchronized (LOCK) { if (focusManager != null) return focusManager; } + final CountDownLatch connected = new CountDownLatch(1); + try { + Class carClass = Class.forName("android.car.Car"); + final Object[] holder = new Object[1]; + ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder service) { connected.countDown(); } + @Override public void onServiceDisconnected(ComponentName name) { + synchronized (LOCK) { focusManager = null; car = null; } + } + }; + Object instance; + synchronized (LOCK) { + instance = car; + if (instance == null) { + instance = carClass.getMethod("createCar", Context.class, ServiceConnection.class) + .invoke(null, app, connection); + holder[0] = instance; + carClass.getMethod("connect").invoke(instance); + car = instance; + } else connected.countDown(); + } + if (!connected.await(1500, TimeUnit.MILLISECONDS)) { + Log.w(TAG, "car service did not connect in time"); + return null; + } + Object manager = carClass.getMethod("getCarManager", String.class).invoke(instance, "app_focus"); + if (manager == null) return null; + Class callbackClass = Class.forName("android.car.CarAppFocusManager$OnAppFocusOwnershipCallback"); + Object callback = Proxy.newProxyInstance(callbackClass.getClassLoader(), new Class[] { callbackClass }, + new InvocationHandler() { + @Override public Object invoke(Object proxy, Method method, Object[] args) { + if ("hashCode".equals(method.getName())) return System.identityHashCode(proxy); + if ("equals".equals(method.getName())) return args != null && args.length == 1 && proxy == args[0]; + if ("toString".equals(method.getName())) return "MgUtilityMicFocus"; + Log.i(TAG, method.getName() + (args != null && args.length > 0 ? " " + args[0] : "")); + return null; + } + }); + synchronized (LOCK) { focusManager = manager; focusCallback = callback; } + return manager; + } catch (Throwable error) { + Log.w(TAG, "car app-focus unavailable", error); + return null; + } + } + + private static SharedPreferences prefs(Context app) { return app.getSharedPreferences(PREFS, Context.MODE_PRIVATE); } + + private static void sleep(long ms) { + try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } +} diff --git a/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java b/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java index 71f3ff0..2abe473 100644 --- a/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java +++ b/src/cloud/molberg/mgutility/MicRouteDiagnosticActivity.java @@ -72,13 +72,15 @@ public final class MicRouteDiagnosticActivity extends AnimatedActivity { int min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (min <= 0) min = 4096; AudioRecord record = null; + MicAccess.Lease lease = null; long samples = 0; double sum = 0; int peak = 0; try { record = new AudioRecord(source, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, min * 4); if (record.getState() != AudioRecord.STATE_INITIALIZED) return name + ": NOT_INITIALIZED"; - record.startRecording(); + lease = MicAccess.acquire(this); + if (!MicAccess.startRecording(this, record)) return name + ": NOT_RECORDING (" + MicAccess.lastNote() + ")"; short[] buffer = new short[2048]; long deadline = System.currentTimeMillis() + 3000L; while (System.currentTimeMillis() < deadline) { @@ -88,11 +90,12 @@ public final class MicRouteDiagnosticActivity extends AnimatedActivity { samples += count; } double rms = samples == 0 ? 0 : Math.sqrt(sum / samples) / 32768.0; - return String.format(java.util.Locale.US, "%s: samples=%d rms=%.5f peak=%.5f %s", name, samples, rms, peak / 32768.0, rms > 0.002 ? "AUDIO_DETECTED" : "SILENT"); + return String.format(java.util.Locale.US, "%s: samples=%d rms=%.5f peak=%.5f %s [%s]", name, samples, rms, peak / 32768.0, rms > 0.002 ? "AUDIO_DETECTED" : "SILENT", MicAccess.lastNote()); } catch (Throwable error) { return name + ": ERROR " + error.getClass().getSimpleName() + " — " + String.valueOf(error.getMessage()); } finally { if (record != null) { try { record.stop(); } catch (Throwable ignored) { } try { record.release(); } catch (Throwable ignored) { } } + if (lease != null) lease.release(); } } } \ No newline at end of file diff --git a/src/cloud/molberg/mgutility/MicTestActivity.java b/src/cloud/molberg/mgutility/MicTestActivity.java index 6b16461..aff4e81 100644 --- a/src/cloud/molberg/mgutility/MicTestActivity.java +++ b/src/cloud/molberg/mgutility/MicTestActivity.java @@ -173,13 +173,30 @@ public final class MicTestActivity extends AnimatedActivity { loopButton.setEnabled(true); } + private String routeName(AudioRecord record) { + try { + if (Build.VERSION.SDK_INT >= 24 && record.getRoutedDevice() != null) { + AudioDeviceInfo d = record.getRoutedDevice(); + return typeName(d.getType()) + " " + d.getProductName(); + } + } catch (Throwable ignored) { } + return "default input"; + } + private void meterLoop(int source) { AudioRecord record = null; + MicAccess.Lease lease = null; try { int min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); record = new AudioRecord(source, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Math.max(min, 4096) * 2); if (record.getState() != AudioRecord.STATE_INITIALIZED) { fail("Source did not initialise (busy or unsupported)"); return; } - record.startRecording(); + lease = MicAccess.acquire(this); + if (!MicAccess.startRecording(this, record)) { + fail("Mic busy: recorder never started (" + MicAccess.lastNote() + "). SAIC voice assistant may hold it."); + return; + } + final String route = routeName(record); + ui.post(new Runnable() { @Override public void run() { verdict.setText("Recording via " + route + " (" + MicAccess.lastNote() + ")"); } }); short[] buffer = new short[1600]; // 100 ms double sessionPeak = 0; long frames = 0; @@ -200,6 +217,7 @@ public final class MicTestActivity extends AnimatedActivity { fail(error.getClass().getSimpleName() + ": " + error.getMessage()); } finally { if (record != null) { try { record.stop(); } catch (Throwable ignored) { } try { record.release(); } catch (Throwable ignored) { } } + if (lease != null) lease.release(); ui.post(new Runnable() { @Override public void run() { if (!busy) stopMeter(); } }); } } @@ -235,13 +253,16 @@ public final class MicTestActivity extends AnimatedActivity { @Override public void run() { AudioRecord record = null; AudioTrack track = null; + MicAccess.Lease lease = null; final String[] result = { "" }; try { int min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); record = new AudioRecord(source, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, Math.max(min, 4096) * 2); if (record.getState() != AudioRecord.STATE_INITIALIZED) throw new IllegalStateException("Source did not initialise"); short[] pcm = new short[RATE * 4]; - record.startRecording(); + lease = MicAccess.acquire(MicTestActivity.this); + if (!MicAccess.startRecording(MicTestActivity.this, record)) + throw new IllegalStateException("Mic busy, recorder never started (" + MicAccess.lastNote() + ")"); int filled = 0; long deadline = System.currentTimeMillis() + 6000L; while (filled < pcm.length && System.currentTimeMillis() < deadline) { @@ -249,6 +270,7 @@ public final class MicTestActivity extends AnimatedActivity { if (n > 0) filled += n; } record.stop(); + if (lease != null) { lease.release(); lease = null; } if (filled == 0) throw new IllegalStateException("No audio frames captured"); final double peak = AudioLevel.peak(pcm, filled); final double rms = AudioLevel.rms(pcm, filled); @@ -263,6 +285,7 @@ public final class MicTestActivity extends AnimatedActivity { result[0] = "ERROR: " + error.getClass().getSimpleName() + ": " + error.getMessage(); } finally { if (record != null) { try { record.release(); } catch (Throwable ignored) { } } + if (lease != null) lease.release(); if (track != null) { try { track.stop(); } catch (Throwable ignored) { } try { track.release(); } catch (Throwable ignored) { } } } ui.post(new Runnable() { diff --git a/src/cloud/molberg/mgutility/SettingsActivity.java b/src/cloud/molberg/mgutility/SettingsActivity.java index 2dfd24f..58d97a9 100644 --- a/src/cloud/molberg/mgutility/SettingsActivity.java +++ b/src/cloud/molberg/mgutility/SettingsActivity.java @@ -455,6 +455,18 @@ public final class SettingsActivity extends AnimatedActivity { "remote_diagnostics", "share_usage_data", true, new Runnable() { @Override public void run() { UsageDataReporter.preferenceChanged(SettingsActivity.this); } })); + content.addView(row("↑", "Send usage data now", UsageDataReporter.status(this) + " • errors are also sent automatically in batches", new View.OnClickListener() { + @Override public void onClick(final View v) { + v.setEnabled(false); + Toast.makeText(SettingsActivity.this, "Sending…", Toast.LENGTH_SHORT).show(); + new Thread(new Runnable() { @Override public void run() { + final String result = UsageDataReporter.sendNow(SettingsActivity.this); + runOnUiThread(new Runnable() { @Override public void run() { + v.setEnabled(true); + Toast.makeText(SettingsActivity.this, result, Toast.LENGTH_LONG).show(); rebuildCategory(); } }); + } }, "mg-usage-send").start(); + } + })); content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class))); subsection("Keys and launcher", "Customize physical inputs and the home app"); content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class))); diff --git a/src/cloud/molberg/mgutility/TripsActivity.java b/src/cloud/molberg/mgutility/TripsActivity.java index cc11bdb..1ab0b4f 100644 --- a/src/cloud/molberg/mgutility/TripsActivity.java +++ b/src/cloud/molberg/mgutility/TripsActivity.java @@ -216,11 +216,7 @@ public final class TripsActivity extends AnimatedActivity { private void addPill(LinearLayout container, String label, String value) { TextView pill = new TextView(this); pill.setText(pillLabel(label, value)); pill.setGravity(Gravity.CENTER); pill.setPadding(20, 14, 20, 14); - GradientDrawable drawable = new GradientDrawable(); - drawable.setCornerRadius(dp(10)); - drawable.setColor(UiTheme.SURFACE_HIGH); - drawable.setStroke(dp(1), UiTheme.withAlpha(UiTheme.DIVIDER, 140)); - pill.setBackground(drawable); + pill.setBackground(UiTheme.outline(UiTheme.withAlpha(UiTheme.DIVIDER, 140), dp(1), 0)); pill.setTextColor(UiTheme.TEXT); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, -2, 1f); params.setMargins(0, 0, 10, 0); pill.setLayoutParams(params); @@ -369,9 +365,9 @@ public final class TripsActivity extends AnimatedActivity { Button button = new Button(this); button.setText(label); button.setTextSize(13); button.setAllCaps(false); button.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); button.setPadding(20, 0, 20, 0); button.setTextColor(UiTheme.CYAN); button.setMinHeight(0); button.setMinimumHeight(0); - GradientDrawable drawable = new GradientDrawable(); - drawable.setCornerRadius(dp(8)); drawable.setColor(UiTheme.SURFACE_HIGH); drawable.setStroke(dp(1), UiTheme.withAlpha(UiTheme.CYAN, 120)); - button.setBackground(drawable); return button; + GradientDrawable drawable = UiTheme.outline(UiTheme.withAlpha(UiTheme.CYAN, 120), dp(1), 0); + GradientDrawable pressed = UiTheme.outline(UiTheme.CYAN, dp(1), 0); pressed.setColor(UiTheme.SURFACE_PRESSED); + button.setBackground(UiTheme.pressable(drawable, pressed)); button.setStateListAnimator(null); return button; } private int dp(float value) { return Math.round(value * getResources().getDisplayMetrics().density); } private String trackerStatusText() { android.content.SharedPreferences prefs = getSharedPreferences("trip_tracker", MODE_PRIVATE); String status = prefs.getString("status", "Tracker starts automatically after boot"); boolean gps = prefs.getBoolean("gps_ready", false); return (gps ? "GPS READY" : "GPS WAITING") + " • " + status; } @@ -379,9 +375,9 @@ public final class TripsActivity extends AnimatedActivity { Button button = new Button(this); button.setText(label); button.setTextSize(13); button.setAllCaps(false); button.setTextColor(UiTheme.TEXT); button.setMinHeight(0); button.setMinimumHeight(0); button.setPadding(8, 0, 8, 0); - GradientDrawable drawable = new GradientDrawable(); - drawable.setCornerRadius(dp(8)); drawable.setColor(UiTheme.SURFACE_HIGH); drawable.setStroke(dp(1), UiTheme.withAlpha(UiTheme.DIVIDER, 140)); - button.setBackground(drawable); button.setOnClickListener(listener); return button; + GradientDrawable drawable = UiTheme.outline(UiTheme.withAlpha(UiTheme.DIVIDER, 140), dp(1), 0); + GradientDrawable pressed = UiTheme.outline(UiTheme.CYAN, dp(1), 0); pressed.setColor(UiTheme.SURFACE_PRESSED); + button.setBackground(UiTheme.pressable(drawable, pressed)); button.setStateListAnimator(null); button.setOnClickListener(listener); return button; } private TextView text(String value, int size, int color, int style) { TextView view = new TextView(this); view.setText(value); view.setTextSize(size * 1.25f); view.setTextColor(color); view.setTypeface(Typeface.create("sans-serif", style)); return view; } private static String formatDuration(long millis) { long minutes = Math.max(0, millis / 60000L); return minutes < 60 ? String.format(Locale.US, "%dm", minutes) : String.format(Locale.US, "%dh %02dm", minutes / 60, minutes % 60); } diff --git a/src/cloud/molberg/mgutility/UiTheme.java b/src/cloud/molberg/mgutility/UiTheme.java index d9b5568..edea9c7 100644 --- a/src/cloud/molberg/mgutility/UiTheme.java +++ b/src/cloud/molberg/mgutility/UiTheme.java @@ -198,13 +198,24 @@ final class UiTheme { }; } + /** One corner radius for every surface, button and dialog so all pages share one shape language. */ + static final int RADIUS_DP = 14; + /** Smaller radius for compact chips and slider tracks. */ + static final int RADIUS_SMALL_DP = 10; + + static float radiusPx(int dp) { + return dp * android.content.res.Resources.getSystem().getDisplayMetrics().density; + } + + /** + * Shared rounded surface. The radius argument is kept for source compatibility, but every + * caller gets the same corner so pages look unified: 0 or large values map to RADIUS_DP and + * small values (1..8) map to RADIUS_SMALL_DP. + */ static GradientDrawable surface(int color, int radiusDp) { GradientDrawable d = new GradientDrawable(); d.setColor(color); - // MG Utility deliberately uses a hard-edged instrument-panel language. - // Keep the radius argument for source compatibility, but render every - // shared surface as a square rectangle. - d.setCornerRadius(0f); + d.setCornerRadius(radiusPx(radiusDp > 0 && radiusDp <= 8 ? RADIUS_SMALL_DP : RADIUS_DP)); return d; } @@ -214,6 +225,29 @@ final class UiTheme { return d; } + /** Fully rounded (circle/pill) surface for round buttons and handles. */ + static GradientDrawable pill(int color) { + GradientDrawable d = new GradientDrawable(); + d.setColor(color); + d.setCornerRadius(radiusPx(999)); + return d; + } + + /** Normal/pressed state pair so every button gives the same touch feedback. */ + static Drawable pressable(Drawable normal, Drawable pressed) { + android.graphics.drawable.StateListDrawable states = new android.graphics.drawable.StateListDrawable(); + states.addState(new int[] { android.R.attr.state_pressed }, pressed); + states.addState(new int[] { -android.R.attr.state_enabled }, withAlphaDrawable(normal)); + states.addState(new int[0], normal); + return states; + } + + private static Drawable withAlphaDrawable(Drawable d) { + Drawable copy = d.getConstantState() != null ? d.getConstantState().newDrawable().mutate() : d; + copy.setAlpha(110); + return copy; + } + static Button button(Context c, String label, View.OnClickListener listener, boolean primary) { Button b = new Button(c); b.setText(label); @@ -226,8 +260,11 @@ final class UiTheme { b.setMinHeight(0); b.setMinimumHeight(0); b.setPadding(dp(c, 10), 0, dp(c, 10), 0); - b.setBackground(outline(primary ? RED : DIVIDER, primary ? 0 : dp(c, 1), 8)); - if (primary) b.setBackground(surface(RED, 8)); + GradientDrawable normal = primary ? surface(RED, 0) : outline(DIVIDER, dp(c, 1), 0); + GradientDrawable pressed = primary ? surface(RED_BRIGHT, 0) : outline(CYAN, dp(c, 1), 0); + if (!primary) pressed.setColor(SURFACE_PRESSED); + b.setBackground(pressable(normal, pressed)); + b.setStateListAnimator(null); if (listener != null) b.setOnClickListener(listener); return b; } @@ -327,7 +364,7 @@ final class UiTheme { android.view.Window window = dialog.getWindow(); if (window != null) { window.setBackgroundDrawable(surface(SURFACE, 0)); - window.getDecorView().setBackgroundColor(SURFACE); + window.getDecorView().setBackground(surface(SURFACE, 0)); } int titleId = dialog.getContext().getResources().getIdentifier("alertTitle", "id", "android"); if (titleId == 0) titleId = android.R.id.title; diff --git a/src/cloud/molberg/mgutility/UpdateActivity.java b/src/cloud/molberg/mgutility/UpdateActivity.java index c834942..32a1bd1 100644 --- a/src/cloud/molberg/mgutility/UpdateActivity.java +++ b/src/cloud/molberg/mgutility/UpdateActivity.java @@ -26,6 +26,7 @@ public final class UpdateActivity extends AnimatedActivity { private LinearLayout history; private TextView status; private Button download; + private Button saveButton; private UpdateManager.Release available; private File downloaded; private boolean downgradeConfirmed; @@ -67,6 +68,7 @@ public final class UpdateActivity extends AnimatedActivity { content.addView(toggleRow("●", "Notify on updates", "Check automatically and show a short notification when a release is ready", UpdateManager.notifyEnabled(this))); status = UiTheme.text(this, "Checking " + titleCase(UpdateManager.selectedChannel(this)) + " releases…", 13, UiTheme.MUTED, Typeface.NORMAL); status.setPadding(18, 14, 18, 14); content.addView(status); download = UiTheme.button(this, "DOWNLOAD UPDATE", null, false); download.setVisibility(View.GONE); download.setEnabled(false); content.addView(download, new LinearLayout.LayoutParams(-1, 52)); + saveButton = UiTheme.button(this, "SAVE APK TO DOWNLOADS", null, false); saveButton.setVisibility(View.GONE); content.addView(saveButton, new LinearLayout.LayoutParams(-1, 52)); content.addView(row("↻", "Check now", "Ask Gitea for the latest " + UpdateManager.selectedChannel(this) + " release", new View.OnClickListener() { @Override public void onClick(View v) { checkForUpdate(); } })); subsection("Available versions", "Current, newer, and up to five earlier " + UpdateManager.selectedChannel(this) + " builds"); history = new LinearLayout(this); history.setOrientation(LinearLayout.VERTICAL); content.addView(history, new LinearLayout.LayoutParams(-1, -2)); @@ -129,6 +131,33 @@ public final class UpdateActivity extends AnimatedActivity { showStatus((downgrade ? "Downgrade ready: " : "Update ready: ") + release.label(), downgrade ? UiTheme.WARNING : UiTheme.CYAN); download.setVisibility(View.VISIBLE); download.setText((downgrade ? "DOWNLOAD DOWNGRADE " : "DOWNLOAD ") + formatBytes(release.size)); download.setEnabled(true); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { downloadUpdate(); } }); + saveButton.setVisibility(View.VISIBLE); saveButton.setEnabled(true); saveButton.setText("SAVE APK TO DOWNLOADS"); + saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveToDownloads(); } }); + } + + private void saveToDownloads() { + final UpdateManager.Release release = available; if (release == null) return; + if (android.os.Build.VERSION.SDK_INT >= 23 && checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, 5104); + showStatus("Allow storage access, then tap SAVE again", UiTheme.WARNING); return; + } + saveButton.setEnabled(false); saveButton.setText("SAVING…"); showStatus("Downloading " + release.versionName + " to Downloads…", UiTheme.CYAN); + new Thread(new Runnable() { @Override public void run() { + String result; boolean ok = false; + try { + File apk = UpdateManager.download(UpdateActivity.this, release, null); + File dir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS); + if (!dir.isDirectory() && !dir.mkdirs()) throw new java.io.IOException("Cannot create " + dir); + File out = new File(dir, "MG-Utility-" + release.versionName + ".apk"); + java.io.FileInputStream in = new java.io.FileInputStream(apk); java.io.FileOutputStream os = new java.io.FileOutputStream(out); + byte[] buf = new byte[65536]; int n; while ((n = in.read(buf)) > 0) os.write(buf, 0, n); + os.getFD().sync(); os.close(); in.close(); + try { sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(out))); } catch (Throwable ignored) { } + result = "Saved " + out.getAbsolutePath() + " (" + out.length() + " bytes)"; ok = true; + } catch (Throwable e) { result = "Save failed: " + e.getClass().getSimpleName() + " " + e.getMessage(); } + final String shown = result; final boolean good = ok; + runOnUiThread(new Runnable() { @Override public void run() { showStatus(shown, good ? UiTheme.SUCCESS : UiTheme.WARNING); saveButton.setEnabled(true); saveButton.setText("SAVE APK TO DOWNLOADS"); } }); + } }, "mg-update-save").start(); } private void downloadUpdate() { @@ -138,8 +167,34 @@ public final class UpdateActivity extends AnimatedActivity { new Thread(new Runnable() { @Override public void run() { try { final File file = UpdateManager.download(UpdateActivity.this, release, new UpdateManager.Progress() { @Override public void onProgress(final long done, final long total) { runOnUiThread(new Runnable() { @Override public void run() { if (download != null) download.setText(total > 0 ? "DOWNLOADING " + (done * 100 / total) + "%" : "DOWNLOADING…"); } }); } }); runOnUiThread(new Runnable() { @Override public void run() { downloaded = file; showStatus("Download verified. Android is ready to install it.", UiTheme.SUCCESS); download.setText("INSTALL UPDATE"); download.setEnabled(true); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { installDownloaded(); } }); installDownloaded(); } }); } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { showStatus("Download rejected: " + (e.getMessage() == null ? "verification failed" : e.getMessage()), UiTheme.WARNING); download.setText("RETRY DOWNLOAD"); download.setEnabled(true); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { downloadUpdate(); } }); } }); } } }, "mg-update-download").start(); } + private boolean isDefaultHome() { + try { + Intent home = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME); + android.content.pm.ResolveInfo info = getPackageManager().resolveActivity(home, android.content.pm.PackageManager.MATCH_DEFAULT_ONLY); + return info != null && info.activityInfo != null && getPackageName().equals(info.activityInfo.packageName); + } catch (Throwable t) { return false; } + } + + private boolean homeWarningShown; + private void installDownloaded() { if (downloaded == null || !downloaded.exists()) return; + if (!homeWarningShown && isDefaultHome()) { + homeWarningShown = true; + UiTheme.dialog(this).setTitle("SWITCH LAUNCHER FIRST") + .setMessage("MG Utility is the current home app, and this head unit cannot replace the running launcher (the installer reports a package parse error). Switch the home app to the SAIC launcher, then tap INSTALL UPDATE again. You can switch back afterwards.") + .setNegativeButton("INSTALL ANYWAY", new android.content.DialogInterface.OnClickListener() { + @Override public void onClick(android.content.DialogInterface d, int w) { installDownloaded(); } + }) + .setPositiveButton("LAUNCHER SETTINGS", new android.content.DialogInterface.OnClickListener() { + @Override public void onClick(android.content.DialogInterface d, int w) { + homeWarningShown = false; + try { startActivity(new Intent(Settings.ACTION_HOME_SETTINGS)); } + catch (Throwable e) { try { startActivity(new Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)); } catch (Throwable ignored) { } } + } + }).show(); + return; + } if (android.os.Build.VERSION.SDK_INT >= 26 && !getPackageManager().canRequestPackageInstalls()) { waitingForInstallPermission = true; startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()))); return; } UpdateManager.install(this, downloaded); } diff --git a/src/cloud/molberg/mgutility/UpdateManager.java b/src/cloud/molberg/mgutility/UpdateManager.java index 79b7876..4b7cbab 100644 --- a/src/cloud/molberg/mgutility/UpdateManager.java +++ b/src/cloud/molberg/mgutility/UpdateManager.java @@ -240,7 +240,52 @@ public final class UpdateManager { public static File downloadedFile(Context context, int versionCode) { return new File(new File(context.getFilesDir(), "updates"), "mg-utility-" + versionCode + ".apk"); } + /** Installs through PackageInstaller so a failure reports the real reason instead of "problem parsing package". */ + public static void installWithSession(final Context context, File file) { + final Context app = context.getApplicationContext(); + try { + final android.content.pm.PackageInstaller installer = app.getPackageManager().getPackageInstaller(); + android.content.pm.PackageInstaller.SessionParams params = new android.content.pm.PackageInstaller.SessionParams( + android.content.pm.PackageInstaller.SessionParams.MODE_FULL_INSTALL); + params.setAppPackageName(app.getPackageName()); + int id = installer.createSession(params); + android.content.pm.PackageInstaller.Session session = installer.openSession(id); + InputStream in = new FileInputStream(file); + OutputStream out = session.openWrite("base.apk", 0, file.length()); + byte[] buf = new byte[65536]; int n; + while ((n = in.read(buf)) > 0) out.write(buf, 0, n); + session.fsync(out); out.close(); in.close(); + final String action = "cloud.molberg.mgutility.INSTALL_RESULT." + id; + app.registerReceiver(new android.content.BroadcastReceiver() { + @Override public void onReceive(Context c, Intent result) { + int status = result.getIntExtra(android.content.pm.PackageInstaller.EXTRA_STATUS, -999); + String msg = result.getStringExtra(android.content.pm.PackageInstaller.EXTRA_STATUS_MESSAGE); + if (status == android.content.pm.PackageInstaller.STATUS_PENDING_USER_ACTION) { + Intent confirm = (Intent) result.getParcelableExtra(Intent.EXTRA_INTENT); + if (confirm != null) { confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); c.startActivity(confirm); } + return; + } + try { c.unregisterReceiver(this); } catch (Throwable ignored) { } + if (status == android.content.pm.PackageInstaller.STATUS_SUCCESS) return; + String text = "Install failed (status " + status + "): " + msg; + prefs(c).edit().putString("last_install_error", text).apply(); + android.widget.Toast.makeText(c, text, android.widget.Toast.LENGTH_LONG).show(); + android.util.Log.w("MGUpdate", text); + } + }, new android.content.IntentFilter(action)); + int flags = PendingIntent.FLAG_UPDATE_CURRENT; + PendingIntent pending = PendingIntent.getBroadcast(app, id, new Intent(action).setPackage(app.getPackageName()), flags); + session.commit(pending.getIntentSender()); + session.close(); + } catch (Throwable error) { + String text = "Install could not start: " + error.getClass().getSimpleName() + " " + error.getMessage(); + prefs(app).edit().putString("last_install_error", text).apply(); + android.widget.Toast.makeText(app, text, android.widget.Toast.LENGTH_LONG).show(); + } + } + public static void install(Context context, File file) { + if (file != null && file.exists()) { installWithSession(context, file); return; } if (file == null || !file.exists()) return; if (Build.VERSION.SDK_INT >= 26 && !context.getPackageManager().canRequestPackageInstalls()) { Intent permission = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName())); permission.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(permission); return; diff --git a/src/cloud/molberg/mgutility/UsageDataPolicy.java b/src/cloud/molberg/mgutility/UsageDataPolicy.java index 10ada85..b280a28 100644 --- a/src/cloud/molberg/mgutility/UsageDataPolicy.java +++ b/src/cloud/molberg/mgutility/UsageDataPolicy.java @@ -22,8 +22,7 @@ public final class UsageDataPolicy { Matcher match = LOG_LINE.matcher(line); if (!match.matches() || !match.group(2).equals(String.valueOf(pid)) || Double.parseDouble(match.group(1)) <= after) return ""; String tag = match.group(4).trim(); - if (!(tag.equals("MgServiceBridge") || tag.equals("VehicleDataProvider") || tag.startsWith("VehicleSettings") - || tag.equals("EnergyActivity") || tag.equals("MGUtilityTracker") || tag.equals("MGUtilityBoot"))) return ""; + if (tag.equals("MGDiagnostics") || tag.equals("MGUsageReporter")) return ""; return redact(line, 1500); } diff --git a/src/cloud/molberg/mgutility/UsageDataReporter.java b/src/cloud/molberg/mgutility/UsageDataReporter.java index ed821c3..7bc10f5 100644 --- a/src/cloud/molberg/mgutility/UsageDataReporter.java +++ b/src/cloud/molberg/mgutility/UsageDataReporter.java @@ -45,6 +45,10 @@ public final class UsageDataReporter { WORKER.scheduleWithFixedDelay(new Runnable() { @Override public void run() { DiagnosticsClient.refreshConfig(app); } }, 15, 15, TimeUnit.MINUTES); + // Batched automatic delivery: first attempt shortly after launch, then every 30 minutes. + WORKER.scheduleWithFixedDelay(new Runnable() { + @Override public void run() { try { upload(app); } catch (Throwable ignored) { } } + }, 2, 30, TimeUnit.MINUTES); } WORKER.execute(new Runnable() { @Override public void run() { upload(app); } }); } @@ -116,11 +120,14 @@ public final class UsageDataReporter { return payload; } + private static volatile String outcome = ""; + private static void upload(Context context) { - if (!allowed(context)) return; + outcome = ""; + if (!allowed(context)) { outcome = "Usage sharing is off or not yet enabled by the server"; return; } SharedPreferences prefs = preferences(context); String endpoint = prefs.getString("upload_url", ""); - if (!endpoint.startsWith("https://")) return; + if (!endpoint.startsWith("https://")) { outcome = "Server address not loaded yet"; return; } String base = endpoint.endsWith("/") ? endpoint : endpoint + "/"; try { if (!prefs.getString("usage_registration_endpoint", "").equals(base)) { @@ -151,7 +158,8 @@ public final class UsageDataReporter { String errors = prefs.getString("pending_usage_errors", ""); if (errors.isEmpty()) { JSONObject batch = collectErrors(context); - if (batch == null || !allowed(context)) return; + if (batch == null) { outcome = "Nothing new to send"; return; } + if (!allowed(context)) return; errors = batch.toString(); synchronized (CONSENT_LOCK) { if (!allowed(context)) return; @@ -163,16 +171,43 @@ public final class UsageDataReporter { synchronized (CONSENT_LOCK) { if (!allowed(context)) return; double cursor = Math.max(Double.parseDouble(prefs.getString("usage_log_cursor", "0")), batch.getDouble("cursor")); - prefs.edit().remove("pending_usage_errors").putString("usage_log_cursor", String.valueOf(cursor)).apply(); + prefs.edit().remove("pending_usage_errors").putString("usage_log_cursor", String.valueOf(cursor)).putLong("last_send_at", System.currentTimeMillis()).apply(); } } } catch (Exception ignored) { } } + /** Manual "send now": refreshes server config, then uploads everything pending. Blocks; call off the UI thread. */ + public static String sendNow(final Context context) { + final Context app = context.getApplicationContext(); + if (!isEnabled(app)) return "Share usage data is switched off"; + final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); + DiagnosticsClient.refreshConfig(app, new DiagnosticsClient.Callback() { @Override public void complete(String m) { latch.countDown(); } }); + try { latch.await(12, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } + SharedPreferences prefs = preferences(app); + // Re-register even if the server forgot this install. + prefs.edit().remove("usage_registration_endpoint").apply(); + try { upload(app); } catch (Throwable error) { return "Send failed: " + error.getClass().getSimpleName(); } + boolean left = !prefs.getString("pending_crash", "").isEmpty() || !prefs.getString("pending_usage_errors", "").isEmpty(); + if (left) return "Could not reach the server - data kept and will retry automatically"; + long now = System.currentTimeMillis(); + String result = outcome.isEmpty() ? "Sent" : outcome; + if (outcome.isEmpty()) prefs.edit().putLong("last_send_at", now).apply(); + return result; + } + + public static String status(Context context) { + SharedPreferences p = preferences(context); + long at = p.getLong("last_send_at", 0L); + boolean pending = !p.getString("pending_crash", "").isEmpty() || !p.getString("pending_usage_errors", "").isEmpty(); + return (at == 0L ? "never sent" : "last sent " + new java.text.SimpleDateFormat("d MMM HH:mm", java.util.Locale.US).format(new java.util.Date(at))) + + (pending ? " • data waiting" : ""); + } + private static JSONObject collectErrors(Context context) throws Exception { double cursor = Double.parseDouble(preferences(context).getString("usage_log_cursor", "0")); StringBuilder lines = new StringBuilder(); - final Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "epoch", "--pid=" + android.os.Process.myPid(), "-t", "250", "*:W"}); + final Process process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "epoch", "--pid=" + android.os.Process.myPid(), "-t", "800", "*:W"}); Timer timeout = new Timer(true); timeout.schedule(new TimerTask() { @Override public void run() { process.destroy(); } }, 3000); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { diff --git a/src/io/nayuki/qrcodegen/BitBuffer.java b/src/io/nayuki/qrcodegen/BitBuffer.java new file mode 100644 index 0000000..624d129 --- /dev/null +++ b/src/io/nayuki/qrcodegen/BitBuffer.java @@ -0,0 +1,129 @@ +/* + * QR Code generator library (Java) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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. + */ + +package io.nayuki.qrcodegen; + +import java.util.BitSet; +import java.util.Objects; + + +/** + * An appendable sequence of bits (0s and 1s). Mainly used by {@link QrSegment}. + */ +public final class BitBuffer implements Cloneable { + + /*---- Fields ----*/ + + private BitSet data; + + private int bitLength; // Non-negative + + + + /*---- Constructor ----*/ + + /** + * Constructs an empty bit buffer (length 0). + */ + public BitBuffer() { + data = new BitSet(); + bitLength = 0; + } + + + + /*---- Methods ----*/ + + /** + * Returns the length of this sequence, which is a non-negative value. + * @return the length of this sequence + */ + public int bitLength() { + assert bitLength >= 0; + return bitLength; + } + + + /** + * Returns the bit at the specified index, yielding 0 or 1. + * @param index the index to get the bit at + * @return the bit at the specified index + * @throws IndexOutOfBoundsException if index < 0 or index ≥ bitLength + */ + public int getBit(int index) { + if (index < 0 || index >= bitLength) + throw new IndexOutOfBoundsException(); + return data.get(index) ? 1 : 0; + } + + + /** + * Appends the specified number of low-order bits of the specified value to this + * buffer. Requires 0 ≤ len ≤ 31 and 0 ≤ val < 2len. + * @param val the value to append + * @param len the number of low-order bits in the value to take + * @throws IllegalArgumentException if the value or number of bits is out of range + * @throws IllegalStateException if appending the data + * would make bitLength exceed Integer.MAX_VALUE + */ + public void appendBits(int val, int len) { + if (len < 0 || len > 31 || val >>> len != 0) + throw new IllegalArgumentException("Value out of range"); + if (Integer.MAX_VALUE - bitLength < len) + throw new IllegalStateException("Maximum length reached"); + for (int i = len - 1; i >= 0; i--, bitLength++) // Append bit by bit + data.set(bitLength, QrCode.getBit(val, i)); + } + + + /** + * Appends the content of the specified bit buffer to this buffer. + * @param bb the bit buffer whose data to append (not {@code null}) + * @throws NullPointerException if the bit buffer is {@code null} + * @throws IllegalStateException if appending the data + * would make bitLength exceed Integer.MAX_VALUE + */ + public void appendData(BitBuffer bb) { + Objects.requireNonNull(bb); + if (Integer.MAX_VALUE - bitLength < bb.bitLength) + throw new IllegalStateException("Maximum length reached"); + for (int i = 0; i < bb.bitLength; i++, bitLength++) // Append bit by bit + data.set(bitLength, bb.data.get(i)); + } + + + /** + * Returns a new copy of this buffer. + * @return a new copy of this buffer (not {@code null}) + */ + public BitBuffer clone() { + try { + BitBuffer result = (BitBuffer)super.clone(); + result.data = (BitSet)result.data.clone(); + return result; + } catch (CloneNotSupportedException e) { + throw new AssertionError(e); + } + } + +} diff --git a/src/io/nayuki/qrcodegen/DataTooLongException.java b/src/io/nayuki/qrcodegen/DataTooLongException.java new file mode 100644 index 0000000..f1453ef --- /dev/null +++ b/src/io/nayuki/qrcodegen/DataTooLongException.java @@ -0,0 +1,57 @@ +/* + * QR Code generator library (Java) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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. + */ + +package io.nayuki.qrcodegen; + + +/** + * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: + *
    + *
  • Decrease the error correction level if it was greater than {@code Ecc.LOW}.

  • + *
  • If the advanced {@code encodeSegments()} function with 6 arguments or the + * {@code makeSegmentsOptimally()} function was called, then increase the maxVersion argument + * if it was less than {@link QrCode#MAX_VERSION}. (This advice does not apply to the other + * factory functions because they search all versions up to {@code QrCode.MAX_VERSION}.)

  • + *
  • Split the text data into better or optimal segments in order to reduce the number of + * bits required. (See {@link QrSegmentAdvanced#makeSegmentsOptimally(CharSequence,QrCode.Ecc,int,int) + * QrSegmentAdvanced.makeSegmentsOptimally()}.)

  • + *
  • Change the text or binary data to be shorter.

  • + *
  • Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).

  • + *
  • Propagate the error upward to the caller/user.

  • + *
+ * @see QrCode#encodeText(CharSequence, QrCode.Ecc) + * @see QrCode#encodeBinary(byte[], QrCode.Ecc) + * @see QrCode#encodeSegments(java.util.List, QrCode.Ecc) + * @see QrCode#encodeSegments(java.util.List, QrCode.Ecc, int, int, int, boolean) + * @see QrSegmentAdvanced#makeSegmentsOptimally(CharSequence, QrCode.Ecc, int, int) + */ +public class DataTooLongException extends IllegalArgumentException { + + public DataTooLongException() {} + + + public DataTooLongException(String msg) { + super(msg); + } + +} diff --git a/src/io/nayuki/qrcodegen/QrCode.java b/src/io/nayuki/qrcodegen/QrCode.java new file mode 100644 index 0000000..f6244ad --- /dev/null +++ b/src/io/nayuki/qrcodegen/QrCode.java @@ -0,0 +1,815 @@ +/* + * QR Code generator library (Java) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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. + */ + +package io.nayuki.qrcodegen; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + + +/** + * A QR Code symbol, which is a type of two-dimensional barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + *

Instances of this class represent an immutable square grid of dark and light cells. + * The class provides static factory functions to create a QR Code from text or binary data. + * The class covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.

+ *

Ways to create a QR Code object:

+ *
    + *
  • High level: Take the payload data and call {@link QrCode#encodeText(CharSequence,Ecc)} + * or {@link QrCode#encodeBinary(byte[],Ecc)}.

  • + *
  • Mid level: Custom-make the list of {@link QrSegment segments} + * and call {@link QrCode#encodeSegments(List,Ecc)} or + * {@link QrCode#encodeSegments(List,Ecc,int,int,int,boolean)}

  • + *
  • Low level: Custom-make the array of data codeword bytes (including segment headers and + * final padding, excluding error correction codewords), supply the appropriate version number, + * and call the {@link QrCode#QrCode(int,Ecc,byte[],int) constructor}.

  • + *
+ *

(Note that all ways require supplying the desired error correction level.)

+ * @see QrSegment + */ +public final class QrCode { + + /*---- Static factory functions (high level) ----*/ + + /** + * Returns a QR Code representing the specified Unicode text string at the specified error correction level. + * As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer + * Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible + * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the + * ecl argument if it can be done without increasing the version. + * @param text the text to be encoded (not {@code null}), which can be any Unicode string + * @param ecl the error correction level to use (not {@code null}) (boostable) + * @return a QR Code (not {@code null}) representing the text + * @throws NullPointerException if the text or error correction level is {@code null} + * @throws DataTooLongException if the text fails to fit in the + * largest version QR Code at the ECL, which means it is too long + */ + public static QrCode encodeText(CharSequence text, Ecc ecl) { + Objects.requireNonNull(text); + Objects.requireNonNull(ecl); + List segs = QrSegment.makeSegments(text); + return encodeSegments(segs, ecl); + } + + + /** + * Returns a QR Code representing the specified binary data at the specified error correction level. + * This function always encodes using the binary segment mode, not any text mode. The maximum number of + * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. + * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. + * @param data the binary data to encode (not {@code null}) + * @param ecl the error correction level to use (not {@code null}) (boostable) + * @return a QR Code (not {@code null}) representing the data + * @throws NullPointerException if the data or error correction level is {@code null} + * @throws DataTooLongException if the data fails to fit in the + * largest version QR Code at the ECL, which means it is too long + */ + public static QrCode encodeBinary(byte[] data, Ecc ecl) { + Objects.requireNonNull(data); + Objects.requireNonNull(ecl); + QrSegment seg = QrSegment.makeBytes(data); + return encodeSegments(Arrays.asList(seg), ecl); + } + + + /*---- Static factory functions (mid level) ----*/ + + /** + * Returns a QR Code representing the specified segments at the specified error correction + * level. The smallest possible QR Code version is automatically chosen for the output. The ECC level + * of the result may be higher than the ecl argument if it can be done without increasing the version. + *

This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a mid-level API; the high-level API is {@link #encodeText(CharSequence,Ecc)} + * and {@link #encodeBinary(byte[],Ecc)}.

+ * @param segs the segments to encode + * @param ecl the error correction level to use (not {@code null}) (boostable) + * @return a QR Code (not {@code null}) representing the segments + * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null} + * @throws DataTooLongException if the segments fail to fit in the + * largest version QR Code at the ECL, which means they are too long + */ + public static QrCode encodeSegments(List segs, Ecc ecl) { + return encodeSegments(segs, ecl, MIN_VERSION, MAX_VERSION, -1, true); + } + + + /** + * Returns a QR Code representing the specified segments with the specified encoding parameters. + * The smallest possible QR Code version within the specified range is automatically + * chosen for the output. Iff boostEcl is {@code true}, then the ECC level of the + * result may be higher than the ecl argument if it can be done without increasing + * the version. The mask number is either between 0 to 7 (inclusive) to force that + * mask, or −1 to automatically choose an appropriate mask (which may be slow). + *

This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a mid-level API; the high-level API is {@link #encodeText(CharSequence,Ecc)} + * and {@link #encodeBinary(byte[],Ecc)}.

+ * @param segs the segments to encode + * @param ecl the error correction level to use (not {@code null}) (boostable) + * @param minVersion the minimum allowed version of the QR Code (at least 1) + * @param maxVersion the maximum allowed version of the QR Code (at most 40) + * @param mask the mask number to use (between 0 and 7 (inclusive)), or −1 for automatic mask + * @param boostEcl increases the ECC level as long as it doesn't increase the version number + * @return a QR Code (not {@code null}) representing the segments + * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null} + * @throws IllegalArgumentException if 1 ≤ minVersion ≤ maxVersion ≤ 40 + * or −1 ≤ mask ≤ 7 is violated + * @throws DataTooLongException if the segments fail to fit in + * the maxVersion QR Code at the ECL, which means they are too long + */ + public static QrCode encodeSegments(List segs, Ecc ecl, int minVersion, int maxVersion, int mask, boolean boostEcl) { + Objects.requireNonNull(segs); + Objects.requireNonNull(ecl); + if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) + throw new IllegalArgumentException("Invalid value"); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = QrSegment.getTotalBits(segs, version); + if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) { // All versions in the range could not fit the given data + String msg = "Segment too long"; + if (dataUsedBits != -1) + msg = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits); + throw new DataTooLongException(msg); + } + } + assert dataUsedBits != -1; + + // Increase the error correction level while the data still fits in the current version number + for (Ecc newEcl : Ecc.values()) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) + ecl = newEcl; + } + + // Concatenate all segments to create the data bit string + BitBuffer bb = new BitBuffer(); + for (QrSegment seg : segs) { + bb.appendBits(seg.mode.modeBits, 4); + bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version)); + bb.appendData(seg.data); + } + assert bb.bitLength() == dataUsedBits; + + // Add terminator and pad up to a byte if applicable + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; + assert bb.bitLength() <= dataCapacityBits; + bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength())); + bb.appendBits(0, (8 - bb.bitLength() % 8) % 8); + assert bb.bitLength() % 8 == 0; + + // Pad with alternating bytes until data capacity is reached + for (int padByte = 0xEC; bb.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + bb.appendBits(padByte, 8); + + // Pack bits into bytes in big endian + byte[] dataCodewords = new byte[bb.bitLength() / 8]; + for (int i = 0; i < bb.bitLength(); i++) + dataCodewords[i >>> 3] |= bb.getBit(i) << (7 - (i & 7)); + + // Create the QR Code object + return new QrCode(version, ecl, dataCodewords, mask); + } + + + + /*---- Instance fields ----*/ + + // Public immutable scalar parameters: + + /** The version number of this QR Code, which is between 1 and 40 (inclusive). + * This determines the size of this barcode. */ + public final int version; + + /** The width and height of this QR Code, measured in modules, between + * 21 and 177 (inclusive). This is equal to version × 4 + 17. */ + public final int size; + + /** The error correction level used in this QR Code, which is not {@code null}. */ + public final Ecc errorCorrectionLevel; + + /** The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). + *

Even if a QR Code is created with automatic masking requested (mask = + * −1), the resulting object still has a mask value between 0 and 7. */ + public final int mask; + + // Private grids of modules/pixels, with dimensions of size*size: + + // The modules of this QR Code (false = light, true = dark). + // Immutable after constructor finishes. Accessed through getModule(). + private boolean[][] modules; + + // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. + private boolean[][] isFunction; + + + + /*---- Constructor (low level) ----*/ + + /** + * Constructs a QR Code with the specified version number, + * error correction level, data codeword bytes, and mask number. + *

This is a low-level API that most users should not use directly. A mid-level + * API is the {@link #encodeSegments(List,Ecc,int,int,int,boolean)} function.

+ * @param ver the version number to use, which must be in the range 1 to 40 (inclusive) + * @param ecl the error correction level to use + * @param dataCodewords the bytes representing segments to encode (without ECC) + * @param msk the mask pattern to use, which is either −1 for automatic choice or from 0 to 7 for fixed choice + * @throws NullPointerException if the byte array or error correction level is {@code null} + * @throws IllegalArgumentException if the version or mask value is out of range, + * or if the data is the wrong length for the specified version and error correction level + */ + public QrCode(int ver, Ecc ecl, byte[] dataCodewords, int msk) { + // Check arguments and initialize fields + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw new IllegalArgumentException("Version value out of range"); + if (msk < -1 || msk > 7) + throw new IllegalArgumentException("Mask value out of range"); + version = ver; + size = ver * 4 + 17; + errorCorrectionLevel = Objects.requireNonNull(ecl); + Objects.requireNonNull(dataCodewords); + modules = new boolean[size][size]; // Initially all light + isFunction = new boolean[size][size]; + + // Compute ECC, draw modules, do masking + drawFunctionPatterns(); + byte[] allCodewords = addEccAndInterleave(dataCodewords); + drawCodewords(allCodewords); + + // Do masking + if (msk == -1) { // Automatically choose best mask + int minPenalty = Integer.MAX_VALUE; + for (int i = 0; i < 8; i++) { + applyMask(i); + drawFormatBits(i); + int penalty = getPenaltyScore(); + if (penalty < minPenalty) { + msk = i; + minPenalty = penalty; + } + applyMask(i); // Undoes the mask due to XOR + } + } + assert 0 <= msk && msk <= 7; + mask = msk; + applyMask(msk); // Apply the final choice of mask + drawFormatBits(msk); // Overwrite old format bits + + isFunction = null; + } + + + + /*---- Public instance methods ----*/ + + /** + * Returns the color of the module (pixel) at the specified coordinates, which is {@code false} + * for light or {@code true} for dark. The top left corner has the coordinates (x=0, y=0). + * If the specified coordinates are out of bounds, then {@code false} (light) is returned. + * @param x the x coordinate, where 0 is the left edge and size−1 is the right edge + * @param y the y coordinate, where 0 is the top edge and size−1 is the bottom edge + * @return {@code true} if the coordinates are in bounds and the module + * at that location is dark, or {@code false} (light) otherwise + */ + public boolean getModule(int x, int y) { + return 0 <= x && x < size && 0 <= y && y < size && modules[y][x]; + } + + + + /*---- Private helper methods for constructor: Drawing function modules ----*/ + + // Reads this object's version field, and draws and marks all function modules. + private void drawFunctionPatterns() { + // Draw horizontal and vertical timing patterns + for (int i = 0; i < size; i++) { + setFunctionModule(6, i, i % 2 == 0); + setFunctionModule(i, 6, i % 2 == 0); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + drawFinderPattern(3, 3); + drawFinderPattern(size - 4, 3); + drawFinderPattern(3, size - 4); + + // Draw numerous alignment patterns + int[] alignPatPos = getAlignmentPatternPositions(); + int numAlign = alignPatPos.length; + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) + drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); + } + } + + // Draw configuration data + drawFormatBits(0); // Dummy mask value; overwritten later in the constructor + drawVersion(); + } + + + // Draws two copies of the format bits (with its own error correction code) + // based on the given mask and this object's error correction level field. + private void drawFormatBits(int msk) { + // Calculate error correction code and pack bits + int data = errorCorrectionLevel.formatBits << 3 | msk; // errCorrLvl is uint2, mask is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >>> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert bits >>> 15 == 0; + + // Draw first copy + for (int i = 0; i <= 5; i++) + setFunctionModule(8, i, getBit(bits, i)); + setFunctionModule(8, 7, getBit(bits, 6)); + setFunctionModule(8, 8, getBit(bits, 7)); + setFunctionModule(7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setFunctionModule(14 - i, 8, getBit(bits, i)); + + // Draw second copy + for (int i = 0; i < 8; i++) + setFunctionModule(size - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setFunctionModule(8, size - 15 + i, getBit(bits, i)); + setFunctionModule(8, size - 8, true); // Always dark + } + + + // Draws two copies of the version bits (with its own error correction code), + // based on this object's version field, iff 7 <= version <= 40. + private void drawVersion() { + if (version < 7) + return; + + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); + int bits = version << 12 | rem; // uint18 + assert bits >>> 18 == 0; + + // Draw two copies + for (int i = 0; i < 18; i++) { + boolean bit = getBit(bits, i); + int a = size - 11 + i % 3; + int b = i / 3; + setFunctionModule(a, b, bit); + setFunctionModule(b, a, bit); + } + } + + + // Draws a 9*9 finder pattern including the border separator, + // with the center module at (x, y). Modules can be out of bounds. + private void drawFinderPattern(int x, int y) { + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm + int xx = x + dx, yy = y + dy; + if (0 <= xx && xx < size && 0 <= yy && yy < size) + setFunctionModule(xx, yy, dist != 2 && dist != 4); + } + } + } + + + // Draws a 5*5 alignment pattern, with the center module + // at (x, y). All modules must be in bounds. + private void drawAlignmentPattern(int x, int y) { + for (int dy = -2; dy <= 2; dy++) { + for (int dx = -2; dx <= 2; dx++) + setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1); + } + } + + + // Sets the color of a module and marks it as a function module. + // Only used by the constructor. Coordinates must be in bounds. + private void setFunctionModule(int x, int y, boolean isDark) { + modules[y][x] = isDark; + isFunction[y][x] = true; + } + + + /*---- Private helper methods for constructor: Codewords and masking ----*/ + + // Returns a new byte string representing the given data with the appropriate error correction + // codewords appended to it, based on this object's version and error correction level. + private byte[] addEccAndInterleave(byte[] data) { + Objects.requireNonNull(data); + if (data.length != getNumDataCodewords(version, errorCorrectionLevel)) + throw new IllegalArgumentException(); + + // Calculate parameter numbers + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [errorCorrectionLevel.ordinal()][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockLen = rawCodewords / numBlocks; + + // Split data into blocks and append ECC to each block + byte[][] blocks = new byte[numBlocks][]; + byte[] rsDiv = reedSolomonComputeDivisor(blockEccLen); + for (int i = 0, k = 0; i < numBlocks; i++) { + byte[] dat = Arrays.copyOfRange(data, k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); + k += dat.length; + byte[] block = Arrays.copyOf(dat, shortBlockLen + 1); + byte[] ecc = reedSolomonComputeRemainder(dat, rsDiv); + System.arraycopy(ecc, 0, block, block.length - blockEccLen, ecc.length); + blocks[i] = block; + } + + // Interleave (not concatenate) the bytes from every block into a single sequence + byte[] result = new byte[rawCodewords]; + for (int i = 0, k = 0; i < blocks[0].length; i++) { + for (int j = 0; j < blocks.length; j++) { + // Skip the padding byte in short blocks + if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) { + result[k] = blocks[j][i]; + k++; + } + } + } + return result; + } + + + // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire + // data area of this QR Code. Function modules need to be marked off before this is called. + private void drawCodewords(byte[] data) { + Objects.requireNonNull(data); + if (data.length != getNumRawDataModules(version) / 8) + throw new IllegalArgumentException(); + + int i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < size; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + int x = right - j; // Actual x coordinate + boolean upward = ((right + 1) & 2) == 0; + int y = upward ? size - 1 - vert : vert; // Actual y coordinate + if (!isFunction[y][x] && i < data.length * 8) { + modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert i == data.length * 8; + } + + + // XORs the codeword modules in this QR Code with the given mask pattern. + // The function modules must be marked and the codeword bits must be drawn + // before masking. Due to the arithmetic of XOR, calling applyMask() with + // the same mask value a second time will undo the mask. A final well-formed + // QR Code needs exactly one (not zero, two, etc.) mask applied. + private void applyMask(int msk) { + if (msk < 0 || msk > 7) + throw new IllegalArgumentException("Mask value out of range"); + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + boolean invert; + switch (msk) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: throw new AssertionError(); + } + modules[y][x] ^= invert & !isFunction[y][x]; + } + } + } + + + // Calculates and returns the penalty score based on state of this QR Code's current modules. + // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. + private int getPenaltyScore() { + int result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (int y = 0; y < size; y++) { + boolean runColor = false; + int runX = 0; + int[] runHistory = new int[7]; + for (int x = 0; x < size; x++) { + if (modules[y][x] == runColor) { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } else { + finderPenaltyAddHistory(runX, runHistory); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; + runColor = modules[y][x]; + runX = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (int x = 0; x < size; x++) { + boolean runColor = false; + int runY = 0; + int[] runHistory = new int[7]; + for (int y = 0; y < size; y++) { + if (modules[y][x] == runColor) { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } else { + finderPenaltyAddHistory(runY, runHistory); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; + runColor = modules[y][x]; + runY = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < size - 1; y++) { + for (int x = 0; x < size - 1; x++) { + boolean color = modules[y][x]; + if ( color == modules[y][x + 1] && + color == modules[y + 1][x] && + color == modules[y + 1][x + 1]) + result += PENALTY_N2; + } + } + + // Balance of dark and light modules + int dark = 0; + for (boolean[] row : modules) { + for (boolean color : row) { + if (color) + dark++; + } + } + int total = size * size; // Note that size is odd, so dark/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + int k = (Math.abs(dark * 20 - total * 10) + total - 1) / total - 1; + assert 0 <= k && k <= 9; + result += k * PENALTY_N4; + assert 0 <= result && result <= 2568888; // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; + } + + + + /*---- Private helper functions ----*/ + + // Returns an ascending list of positions of alignment patterns for this version number. + // Each position is in the range [0,177), and are used on both the x and y axes. + // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. + private int[] getAlignmentPatternPositions() { + if (version == 1) + return new int[]{}; + else { + int numAlign = version / 7 + 2; + int step = (version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4) * 2; + int[] result = new int[numAlign]; + result[0] = 6; + for (int i = result.length - 1, pos = size - 7; i >= 1; i--, pos -= step) + result[i] = pos; + return result; + } + } + + + // Returns the number of data bits that can be stored in a QR Code of the given version number, after + // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. + // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. + private static int getNumRawDataModules(int ver) { + if (ver < MIN_VERSION || ver > MAX_VERSION) + throw new IllegalArgumentException("Version number out of range"); + + int size = ver * 4 + 17; + int result = size * size; // Number of modules in the whole QR Code square + result -= 8 * 8 * 3; // Subtract the three finders with separators + result -= 15 * 2 + 1; // Subtract the format information and dark module + result -= (size - 16) * 2; // Subtract the timing patterns (excluding finders) + // The five lines above are equivalent to: int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (numAlign - 1) * (numAlign - 1) * 25; // Subtract alignment patterns not overlapping with timing patterns + result -= (numAlign - 2) * 2 * 20; // Subtract alignment patterns that overlap with timing patterns + // The two lines above are equivalent to: result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 6 * 3 * 2; // Subtract version information + } + assert 208 <= result && result <= 29648; + return result; + } + + + // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be + // implemented as a lookup table over all possible parameter values, instead of as an algorithm. + private static byte[] reedSolomonComputeDivisor(int degree) { + if (degree < 1 || degree > 255) + throw new IllegalArgumentException("Degree out of range"); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + byte[] result = new byte[degree]; + result[degree - 1] = 1; // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // and drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + int root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (int j = 0; j < result.length; j++) { + result[j] = (byte)reedSolomonMultiply(result[j] & 0xFF, root); + if (j + 1 < result.length) + result[j] ^= result[j + 1]; + } + root = reedSolomonMultiply(root, 0x02); + } + return result; + } + + + // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. + private static byte[] reedSolomonComputeRemainder(byte[] data, byte[] divisor) { + Objects.requireNonNull(data); + Objects.requireNonNull(divisor); + byte[] result = new byte[divisor.length]; + for (byte b : data) { // Polynomial division + int factor = (b ^ result[0]) & 0xFF; + System.arraycopy(result, 1, result, 0, result.length - 1); + result[result.length - 1] = 0; + for (int i = 0; i < result.length; i++) + result[i] ^= reedSolomonMultiply(divisor[i] & 0xFF, factor); + } + return result; + } + + + // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result + // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. + private static int reedSolomonMultiply(int x, int y) { + assert x >> 8 == 0 && y >> 8 == 0; + // Russian peasant multiplication + int z = 0; + for (int i = 7; i >= 0; i--) { + z = (z << 1) ^ ((z >>> 7) * 0x11D); + z ^= ((y >>> i) & 1) * x; + } + assert z >>> 8 == 0; + return z; + } + + + // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any + // QR Code of the given version number and error correction level, with remainder bits discarded. + // This stateless pure function could be implemented as a (40*4)-cell lookup table. + static int getNumDataCodewords(int ver, Ecc ecl) { + return getNumRawDataModules(ver) / 8 + - ECC_CODEWORDS_PER_BLOCK [ecl.ordinal()][ver] + * NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal()][ver]; + } + + + // Can only be called immediately after a light run is added, and + // returns either 0, 1, or 2. A helper function for getPenaltyScore(). + private int finderPenaltyCountPatterns(int[] runHistory) { + int n = runHistory[1]; + assert n <= size * 3; + boolean core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); + } + + + // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). + private int finderPenaltyTerminateAndCount(boolean currentRunColor, int currentRunLength, int[] runHistory) { + if (currentRunColor) { // Terminate dark run + finderPenaltyAddHistory(currentRunLength, runHistory); + currentRunLength = 0; + } + currentRunLength += size; // Add light border to final run + finderPenaltyAddHistory(currentRunLength, runHistory); + return finderPenaltyCountPatterns(runHistory); + } + + + // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). + private void finderPenaltyAddHistory(int currentRunLength, int[] runHistory) { + if (runHistory[0] == 0) + currentRunLength += size; // Add light border to initial run + System.arraycopy(runHistory, 0, runHistory, 1, runHistory.length - 1); + runHistory[0] = currentRunLength; + } + + + // Returns true iff the i'th bit of x is set to 1. + static boolean getBit(int x, int i) { + return ((x >>> i) & 1) != 0; + } + + + /*---- Constants and tables ----*/ + + /** The minimum version number (1) supported in the QR Code Model 2 standard. */ + public static final int MIN_VERSION = 1; + + /** The maximum version number (40) supported in the QR Code Model 2 standard. */ + public static final int MAX_VERSION = 40; + + + // For use in getPenaltyScore(), when evaluating which mask is best. + private static final int PENALTY_N1 = 3; + private static final int PENALTY_N2 = 3; + private static final int PENALTY_N3 = 40; + private static final int PENALTY_N4 = 10; + + + private static final byte[][] ECC_CODEWORDS_PER_BLOCK = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low + {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium + {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile + {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High + }; + + private static final byte[][] NUM_ERROR_CORRECTION_BLOCKS = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low + {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium + {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile + {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High + }; + + + + /*---- Public helper enumeration ----*/ + + /** + * The error correction level in a QR Code symbol. + */ + public enum Ecc { + // Must be declared in ascending order of error protection + // so that the implicit ordinal() and values() work properly + /** The QR Code can tolerate about 7% erroneous codewords. */ LOW(1), + /** The QR Code can tolerate about 15% erroneous codewords. */ MEDIUM(0), + /** The QR Code can tolerate about 25% erroneous codewords. */ QUARTILE(3), + /** The QR Code can tolerate about 30% erroneous codewords. */ HIGH(2); + + // In the range 0 to 3 (unsigned 2-bit integer). + final int formatBits; + + // Constructor. + private Ecc(int fb) { + formatBits = fb; + } + } + +} diff --git a/src/io/nayuki/qrcodegen/QrSegment.java b/src/io/nayuki/qrcodegen/QrSegment.java new file mode 100644 index 0000000..3a8b534 --- /dev/null +++ b/src/io/nayuki/qrcodegen/QrSegment.java @@ -0,0 +1,317 @@ +/* + * QR Code generator library (Java) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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. + */ + +package io.nayuki.qrcodegen; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + + +/** + * A segment of character/binary/control data in a QR Code symbol. + * Instances of this class are immutable. + *

The mid-level way to create a segment is to take the payload data and call a + * static factory function such as {@link QrSegment#makeNumeric(CharSequence)}. The low-level + * way to create a segment is to custom-make the bit buffer and call the {@link + * QrSegment#QrSegment(Mode,int,BitBuffer) constructor} with appropriate values.

+ *

This segment class imposes no length restrictions, but QR Codes have restrictions. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + * This class can represent kanji mode segments, but provides no help in encoding them + * - see {@link QrSegmentAdvanced} for full kanji support.

+ */ +public final class QrSegment { + + /*---- Static factory functions (mid level) ----*/ + + /** + * Returns a segment representing the specified binary data + * encoded in byte mode. All input byte arrays are acceptable. + *

Any text string can be converted to UTF-8 bytes ({@code + * s.getBytes(StandardCharsets.UTF_8)}) and encoded as a byte mode segment.

+ * @param data the binary data (not {@code null}) + * @return a segment (not {@code null}) containing the data + * @throws NullPointerException if the array is {@code null} + */ + public static QrSegment makeBytes(byte[] data) { + Objects.requireNonNull(data); + BitBuffer bb = new BitBuffer(); + for (byte b : data) + bb.appendBits(b & 0xFF, 8); + return new QrSegment(Mode.BYTE, data.length, bb); + } + + + /** + * Returns a segment representing the specified string of decimal digits encoded in numeric mode. + * @param digits the text (not {@code null}), with only digits from 0 to 9 allowed + * @return a segment (not {@code null}) containing the text + * @throws NullPointerException if the string is {@code null} + * @throws IllegalArgumentException if the string contains non-digit characters + */ + public static QrSegment makeNumeric(CharSequence digits) { + Objects.requireNonNull(digits); + if (!isNumeric(digits)) + throw new IllegalArgumentException("String contains non-numeric characters"); + + BitBuffer bb = new BitBuffer(); + for (int i = 0; i < digits.length(); ) { // Consume up to 3 digits per iteration + int n = Math.min(digits.length() - i, 3); + bb.appendBits(Integer.parseInt(digits.subSequence(i, i + n).toString()), n * 3 + 1); + i += n; + } + return new QrSegment(Mode.NUMERIC, digits.length(), bb); + } + + + /** + * Returns a segment representing the specified text string encoded in alphanumeric mode. + * The characters allowed are: 0 to 9, A to Z (uppercase only), space, + * dollar, percent, asterisk, plus, hyphen, period, slash, colon. + * @param text the text (not {@code null}), with only certain characters allowed + * @return a segment (not {@code null}) containing the text + * @throws NullPointerException if the string is {@code null} + * @throws IllegalArgumentException if the string contains non-encodable characters + */ + public static QrSegment makeAlphanumeric(CharSequence text) { + Objects.requireNonNull(text); + if (!isAlphanumeric(text)) + throw new IllegalArgumentException("String contains unencodable characters in alphanumeric mode"); + + BitBuffer bb = new BitBuffer(); + int i; + for (i = 0; i <= text.length() - 2; i += 2) { // Process groups of 2 + int temp = ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; + temp += ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); + bb.appendBits(temp, 11); + } + if (i < text.length()) // 1 character remaining + bb.appendBits(ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6); + return new QrSegment(Mode.ALPHANUMERIC, text.length(), bb); + } + + + /** + * Returns a list of zero or more segments to represent the specified Unicode text string. + * The result may use various segment modes and switch modes to optimize the length of the bit stream. + * @param text the text to be encoded, which can be any Unicode string + * @return a new mutable list (not {@code null}) of segments (not {@code null}) containing the text + * @throws NullPointerException if the text is {@code null} + */ + public static List makeSegments(CharSequence text) { + Objects.requireNonNull(text); + + // Select the most efficient segment encoding automatically + List result = new ArrayList<>(); + if (text.equals("")); // Leave result empty + else if (isNumeric(text)) + result.add(makeNumeric(text)); + else if (isAlphanumeric(text)) + result.add(makeAlphanumeric(text)); + else + result.add(makeBytes(text.toString().getBytes(StandardCharsets.UTF_8))); + return result; + } + + + /** + * Returns a segment representing an Extended Channel Interpretation + * (ECI) designator with the specified assignment value. + * @param assignVal the ECI assignment number (see the AIM ECI specification) + * @return a segment (not {@code null}) containing the data + * @throws IllegalArgumentException if the value is outside the range [0, 106) + */ + public static QrSegment makeEci(int assignVal) { + BitBuffer bb = new BitBuffer(); + if (assignVal < 0) + throw new IllegalArgumentException("ECI assignment value out of range"); + else if (assignVal < (1 << 7)) + bb.appendBits(assignVal, 8); + else if (assignVal < (1 << 14)) { + bb.appendBits(0b10, 2); + bb.appendBits(assignVal, 14); + } else if (assignVal < 1_000_000) { + bb.appendBits(0b110, 3); + bb.appendBits(assignVal, 21); + } else + throw new IllegalArgumentException("ECI assignment value out of range"); + return new QrSegment(Mode.ECI, 0, bb); + } + + + /** + * Tests whether the specified string can be encoded as a segment in numeric mode. + * A string is encodable iff each character is in the range 0 to 9. + * @param text the string to test for encodability (not {@code null}) + * @return {@code true} iff each character is in the range 0 to 9. + * @throws NullPointerException if the string is {@code null} + * @see #makeNumeric(CharSequence) + */ + public static boolean isNumeric(CharSequence text) { + return NUMERIC_REGEX.matcher(text).matches(); + } + + + /** + * Tests whether the specified string can be encoded as a segment in alphanumeric mode. + * A string is encodable iff each character is in the following set: 0 to 9, A to Z + * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + * @param text the string to test for encodability (not {@code null}) + * @return {@code true} iff each character is in the alphanumeric mode character set + * @throws NullPointerException if the string is {@code null} + * @see #makeAlphanumeric(CharSequence) + */ + public static boolean isAlphanumeric(CharSequence text) { + return ALPHANUMERIC_REGEX.matcher(text).matches(); + } + + + + /*---- Instance fields ----*/ + + /** The mode indicator of this segment. Not {@code null}. */ + public final Mode mode; + + /** The length of this segment's unencoded data. Measured in characters for + * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + * Always zero or positive. Not the same as the data's bit length. */ + public final int numChars; + + // The data bits of this segment. Not null. Accessed through getData(). + final BitBuffer data; + + + /*---- Constructor (low level) ----*/ + + /** + * Constructs a QR Code segment with the specified attributes and data. + * The character count (numCh) must agree with the mode and the bit buffer length, + * but the constraint isn't checked. The specified bit buffer is cloned and stored. + * @param md the mode (not {@code null}) + * @param numCh the data length in characters or bytes, which is non-negative + * @param data the data bits (not {@code null}) + * @throws NullPointerException if the mode or data is {@code null} + * @throws IllegalArgumentException if the character count is negative + */ + public QrSegment(Mode md, int numCh, BitBuffer data) { + mode = Objects.requireNonNull(md); + Objects.requireNonNull(data); + if (numCh < 0) + throw new IllegalArgumentException("Invalid value"); + numChars = numCh; + this.data = data.clone(); // Make defensive copy + } + + + /*---- Methods ----*/ + + /** + * Returns the data bits of this segment. + * @return a new copy of the data bits (not {@code null}) + */ + public BitBuffer getData() { + return data.clone(); // Make defensive copy + } + + + // Calculates the number of bits needed to encode the given segments at the given version. + // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too + // many characters to fit its length field, or the total bits exceeds Integer.MAX_VALUE. + static int getTotalBits(List segs, int version) { + Objects.requireNonNull(segs); + long result = 0; + for (QrSegment seg : segs) { + Objects.requireNonNull(seg); + int ccbits = seg.mode.numCharCountBits(version); + if (seg.numChars >= (1 << ccbits)) + return -1; // The segment's length doesn't fit the field's bit width + result += 4L + ccbits + seg.data.bitLength(); + if (result > Integer.MAX_VALUE) + return -1; // The sum will overflow an int type + } + return (int)result; + } + + + /*---- Constants ----*/ + + // Describes precisely all strings that are encodable in numeric mode. + private static final Pattern NUMERIC_REGEX = Pattern.compile("[0-9]*"); + + // Describes precisely all strings that are encodable in alphanumeric mode. + private static final Pattern ALPHANUMERIC_REGEX = Pattern.compile("[A-Z0-9 $%*+./:-]*"); + + // The set of all legal characters in alphanumeric mode, where + // each character value maps to the index in the string. + static final String ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + + + + /*---- Public helper enumeration ----*/ + + /** + * Describes how a segment's data bits are interpreted. + */ + public enum Mode { + + /*-- Constants --*/ + + NUMERIC (0x1, 10, 12, 14), + ALPHANUMERIC(0x2, 9, 11, 13), + BYTE (0x4, 8, 16, 16), + KANJI (0x8, 8, 10, 12), + ECI (0x7, 0, 0, 0); + + + /*-- Fields --*/ + + // The mode indicator bits, which is a uint4 value (range 0 to 15). + final int modeBits; + + // Number of character count bits for three different version ranges. + private final int[] numBitsCharCount; + + + /*-- Constructor --*/ + + private Mode(int mode, int... ccbits) { + modeBits = mode; + numBitsCharCount = ccbits; + } + + + /*-- Method --*/ + + // Returns the bit width of the character count field for a segment in this mode + // in a QR Code at the given version number. The result is in the range [0, 16]. + int numCharCountBits(int ver) { + assert QrCode.MIN_VERSION <= ver && ver <= QrCode.MAX_VERSION; + return numBitsCharCount[(ver + 7) / 17]; + } + + } + +} diff --git a/tests/BrightnessScheduleTest.java b/tests/BrightnessScheduleTest.java index 4ab67fa..f509420 100644 --- a/tests/BrightnessScheduleTest.java +++ b/tests/BrightnessScheduleTest.java @@ -29,6 +29,14 @@ public final class BrightnessScheduleTest { 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); + // Manual override: one hour, and only a real move away from our own write counts. + check(BrightnessSchedule.USER_OVERRIDE_PAUSE_MS == 60L * 60L * 1000L, "manual pause lasts one hour"); + check(!BrightnessSchedule.isManualChange(-1, 255), "unknown last write never counts as manual"); + check(!BrightnessSchedule.isManualChange(0, -1), "unreadable panel never counts as manual"); + check(!BrightnessSchedule.isManualChange(128, 133), "small rounding drift is not manual"); + check(BrightnessSchedule.isManualChange(0, 255), "user turning it up is manual"); + check(BrightnessSchedule.isManualChange(255, 40), "user turning it down is manual"); + // 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"); diff --git a/tests/ClimateGatewayTest.java b/tests/ClimateGatewayTest.java new file mode 100644 index 0000000..5fab972 --- /dev/null +++ b/tests/ClimateGatewayTest.java @@ -0,0 +1,116 @@ +package cloud.molberg.mgutility; + +import android.os.IBinder; +import android.os.Parcel; +import java.util.ArrayList; +import java.util.List; + +/** Verifies the IAirConditionService wire format and the seat-heat press loop against a fake car. */ +public final class ClimateGatewayTest { + /** Fake car that mirrors the OEM AirConditionBinder press semantics. */ + private static final class FakeCar implements IBinder { + int driverSeat, passengerSeat, wheel, power = 1, ac, temp = 22, fan = 3; + boolean stuck; + final List writes = new ArrayList(); + + @Override public String getInterfaceDescriptor() { return ClimateGateway.TOKEN; } + @Override public boolean transact(int code, Parcel data, Parcel reply, int flags) { + check(ClimateGateway.TOKEN.equals(data.readString()), "Air-condition interface token"); + check(flags == 0 && reply != null, "Climate calls are synchronous"); + switch (code) { + case ClimateGateway.SET_DRV_SEAT_HEAT: press(data, "drvSeat"); if (!stuck) driverSeat = next(driverSeat); break; + case ClimateGateway.SET_PSG_SEAT_HEAT: press(data, "psgSeat"); if (!stuck) passengerSeat = next(passengerSeat); break; + case ClimateGateway.SET_STEERING_WHEEL_HEAT: press(data, "wheel"); wheel = wheel == 0 ? 1 : 0; break; + case ClimateGateway.SET_AC: press(data, "ac"); ac = ac == 0 ? 1 : 0; break; + case ClimateGateway.SET_DRV_TEMP: temp = data.readInt(); writes.add("temp=" + temp); break; + case ClimateGateway.SET_AIR_VOLUME: fan = data.readInt(); writes.add("fan=" + fan); break; + case ClimateGateway.GET_DRV_SEAT_HEAT: reply.writeNoException(); reply.writeInt(driverSeat); return true; + case ClimateGateway.GET_PSG_SEAT_HEAT: reply.writeNoException(); reply.writeInt(passengerSeat); return true; + case ClimateGateway.GET_STEERING_WHEEL_HEAT: reply.writeNoException(); reply.writeInt(wheel); return true; + case ClimateGateway.GET_OUTSIDE_TEMP: reply.writeNoException(); reply.writeFloat(-10000f); return true; + case ClimateGateway.GET_DRV_TEMP: reply.writeNoException(); reply.writeInt(temp); return true; + case ClimateGateway.GET_AIR_VOLUME: reply.writeNoException(); reply.writeInt(fan); return true; + case ClimateGateway.GET_HVAC_POWER: reply.writeNoException(); reply.writeInt(power); return true; + case ClimateGateway.GET_AC: reply.writeNoException(); reply.writeInt(ac); return true; + default: + if (code >= 0x35) { reply.writeNoException(); reply.writeInt(-1); return true; } + throw new AssertionError("Unexpected transaction 0x" + Integer.toHexString(code)); + } + reply.writeNoException(); + return true; + } + private void press(Parcel data, String name) { + check(data.readInt() == ClimateGateway.PRESS, name + " must send the OEM press value 1"); + writes.add(name); + } + private static int next(int level) { return level == 0 ? 3 : level - 1; } + } + + private static ClimateGateway gateway(final FakeCar car) { + ClimateGateway g = new ClimateGateway(new IBinder() { + @Override public String getInterfaceDescriptor() { return ClimateGateway.HUB_TOKEN; } + @Override public boolean transact(int code, Parcel data, Parcel reply, int flags) { + check(code == 1, "Hub getService transaction"); + check(ClimateGateway.HUB_TOKEN.equals(data.readString()), "Hub token"); + check("aircondition".equals(data.readString()), "Hub service name"); + reply.writeNoException(); + reply.writeStrongBinder(car); + return true; + } + }); + g.setSleeper(new ClimateGateway.Sleeper() { @Override public void sleep(long ms) { } }); + return g; + } + + public static void main(String[] args) { + check(!new ClimateGateway(null).available(), "Null hub is unavailable"); + check(new ClimateGateway(null).read().driverSeat == -1, "Unavailable reads are -1"); + + check(ClimateGateway.pressesBetween(0, 3) == 1, "OFF -> 3 is one press"); + check(ClimateGateway.pressesBetween(0, 1) == 3, "OFF -> 1 is three presses"); + check(ClimateGateway.pressesBetween(1, 0) == 1, "1 -> OFF is one press"); + check(ClimateGateway.pressesBetween(2, 2) == 0, "Same level needs no press"); + check(ClimateGateway.pressesBetween(-1, 2) == -1, "Unknown level is rejected"); + + for (int target = 0; target <= 3; target++) { + for (int start = 0; start <= 3; start++) { + FakeCar car = new FakeCar(); + car.driverSeat = start; + ClimateGateway g = gateway(car); + int result = g.setSeatHeatLevel(ClimateGateway.Seat.DRIVER, target); + check(result == target, "Driver seat " + start + " -> " + target + " reached " + result); + check(car.writes.size() == ClimateGateway.pressesBetween(start, target), + "Minimal presses for " + start + " -> " + target); + check(car.passengerSeat == 0, "Driver change must not touch passenger seat"); + } + } + + FakeCar stuck = new FakeCar(); + stuck.stuck = true; + gateway(stuck).setSeatHeatLevel(ClimateGateway.Seat.PASSENGER, 2); + check(stuck.writes.size() == 1, "A seat that does not respond is pressed only once, got " + stuck.writes.size()); + + FakeCar car = new FakeCar(); + ClimateGateway g = gateway(car); + check(g.setSteeringWheelHeat(true) == 1 && car.writes.size() == 1, "Wheel heat on"); + check(g.setSteeringWheelHeat(true) == 1 && car.writes.size() == 1, "Wheel heat already on: no press"); + check(g.setSteeringWheelHeat(false) == 0 && car.writes.size() == 2, "Wheel heat off"); + + check(!g.setTemperature(ClimateGateway.Seat.DRIVER, 16) && !g.setTemperature(ClimateGateway.Seat.DRIVER, 34), + "Out-of-range temperatures are never sent"); + check(g.setTemperature(ClimateGateway.Seat.DRIVER, 24) && car.temp == 24, "Absolute temperature"); + check(!g.setFanLevel(0) && !g.setFanLevel(12) && g.setFanLevel(7) && car.fan == 7, "Fan bounds"); + check(g.pressAc() && car.ac == 1, "A/C press"); + + ClimateGateway.State s = g.read(); + check(s.driverTemp == 24 && s.fan == 7 && s.ac == 1 && s.power == 1, "State read-back"); + check(Float.isNaN(s.outside), "OEM -10000 outside temperature is reported as unknown"); + check("LO".equals(ClimateGateway.temperatureLabel(17)) && "HI".equals(ClimateGateway.temperatureLabel(33)), + "LO/HI labels"); + System.out.println("ClimateGatewayTest passed"); + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/tests/HermesPairingCryptoTest.java b/tests/HermesPairingCryptoTest.java new file mode 100644 index 0000000..554a050 --- /dev/null +++ b/tests/HermesPairingCryptoTest.java @@ -0,0 +1,97 @@ +package cloud.molberg.mgutility; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Verifies that the car decrypts exactly what the phone page's WebCrypto code produces. */ +public final class HermesPairingCryptoTest { + private static String script; + + public static void main(String[] args) throws Exception { + script = new File(args[0]).getAbsolutePath(); + base64RoundTrip(); + hkdfVector(); + phoneToCar(); + tamperingRejected(); + wrongCodeRejected(); + System.out.println("HermesPairingCryptoTest: all tests passed"); + } + + private static void base64RoundTrip() { + for (int n = 0; n < 70; n++) { + byte[] data = new byte[n]; + for (int i = 0; i < n; i++) data[i] = (byte) (i * 37 + n); + String text = HermesPairingCrypto.base64Url(data); + check(java.util.Arrays.equals(data, HermesPairingCrypto.base64UrlDecode(text)), "base64url round trip " + n); + check(text.equals(java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(data)), "base64url matches JDK " + n); + } + } + + /** RFC 5869 test case 3 (empty salt and info). */ + private static void hkdfVector() throws Exception { + byte[] ikm = new byte[22]; + java.util.Arrays.fill(ikm, (byte) 0x0b); + byte[] okm = HermesPairingCrypto.hkdfSha256(ikm, new byte[0], new byte[0], 42); + check(hex(okm).equals("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"), "HKDF RFC 5869 #3"); + } + + private static void phoneToCar() throws Exception { + HermesPairingCrypto car = new HermesPairingCrypto(); + check(car.publicKey().length() == 87, "public key is 87 chars"); + String plain = "{\"url\":\"https://hermes.example.com\",\"key\":\"sk-test-ÆØÅ-123\"}"; + String sealed = phone("ABCD-EF23", car.publicKey(), plain); + String opened = car.open("ABCD-EF23", field(sealed, "epk"), field(sealed, "iv"), field(sealed, "ct")); + check(opened.equals(plain), "car decrypts phone payload"); + check(field(sealed, "fingerprint").equals(car.fingerprint()), "phone and car show the same check code"); + } + + private static void tamperingRejected() throws Exception { + HermesPairingCrypto car = new HermesPairingCrypto(); + String sealed = phone("ABCD-EF23", car.publicKey(), "{\"url\":\"https://x\",\"key\":\"k\"}"); + String ct = field(sealed, "ct"); + char flipped = ct.charAt(3) == 'A' ? 'B' : 'A'; + String tampered = ct.substring(0, 3) + flipped + ct.substring(4); + expectFailure(car, "ABCD-EF23", field(sealed, "epk"), field(sealed, "iv"), tampered, "tampered ciphertext rejected"); + HermesPairingCrypto other = new HermesPairingCrypto(); + expectFailure(other, "ABCD-EF23", field(sealed, "epk"), field(sealed, "iv"), ct, "other car cannot decrypt"); + } + + private static void wrongCodeRejected() throws Exception { + HermesPairingCrypto car = new HermesPairingCrypto(); + String sealed = phone("ABCD-EF23", car.publicKey(), "{\"url\":\"https://x\",\"key\":\"k\"}"); + expectFailure(car, "ABCD-EF24", field(sealed, "epk"), field(sealed, "iv"), field(sealed, "ct"), "payload bound to pairing code"); + } + + private static void expectFailure(HermesPairingCrypto car, String code, String epk, String iv, String ct, String name) { + try { car.open(code, epk, iv, ct); } catch (Exception expected) { return; } + throw new AssertionError(name); + } + + private static String phone(String code, String key, String plain) throws Exception { + Process process = new ProcessBuilder("node", script, code, key, plain).redirectErrorStream(true).start(); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)); + StringBuilder out = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) out.append(line); + if (process.waitFor() != 0) throw new AssertionError("node encrypt failed: " + out); + return out.toString(); + } + + private static String field(String json, String name) { + Matcher m = Pattern.compile("\"" + name + "\":\"([^\"]*)\"").matcher(json); + if (!m.find()) throw new AssertionError("missing " + name + " in " + json); + return m.group(1); + } + + private static String hex(byte[] bytes) { + StringBuilder out = new StringBuilder(); + for (byte b : bytes) out.append(String.format("%02x", b & 0xff)); + return out.toString(); + } + + private static void check(boolean condition, String name) { if (!condition) throw new AssertionError(name); } +} diff --git a/tests/UsageDataPolicyTest.java b/tests/UsageDataPolicyTest.java index 7426039..0f8f536 100644 --- a/tests/UsageDataPolicyTest.java +++ b/tests/UsageDataPolicyTest.java @@ -6,7 +6,7 @@ public final class UsageDataPolicyTest { check(UsageDataPolicy.warning(line, 123, 0).contains("password=[REDACTED]"), "own warning redacted"); check(UsageDataPolicy.warning(line, 999, 0).isEmpty(), "other process excluded"); check(UsageDataPolicy.warning(line, 123, 1720000000.123).isEmpty(), "acknowledged warning excluded"); - check(UsageDataPolicy.warning(line.replace("MgServiceBridge", "OtherApp"), 123, 0).isEmpty(), "unknown tag excluded"); + check(!UsageDataPolicy.warning(line.replace("MgServiceBridge", "TripTrackingService"), 123, 0).isEmpty(), "any app tag included"); check(UsageDataPolicy.warning(line.replace("MgServiceBridge", "MGDiagnostics"), 123, 0).isEmpty(), "uploader errors excluded"); check(UsageDataPolicy.warning(line.replace(" W ", " I "), 123, 0).isEmpty(), "informational logs excluded"); check(UsageDataPolicy.warning("malformed", 123, 0).isEmpty(), "malformed line excluded"); diff --git a/tests/pair-encrypt.mjs b/tests/pair-encrypt.mjs new file mode 100644 index 0000000..6a31455 --- /dev/null +++ b/tests/pair-encrypt.mjs @@ -0,0 +1,18 @@ +// Encrypts like the phone page (public/js/pair.js in mg-utility-telemetry) using WebCrypto. +// Usage: node pair-encrypt.mjs +const [code, carKeyB64, plaintext] = process.argv.slice(2); +const { subtle } = globalThis.crypto; +const enc = new TextEncoder(); +const b64url = b => Buffer.from(new Uint8Array(b)).toString('base64url'); +const carKey = await subtle.importKey('raw', Buffer.from(carKeyB64, 'base64url'), { name: 'ECDH', namedCurve: 'P-256' }, false, []); +const eph = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']); +const shared = await subtle.deriveBits({ name: 'ECDH', public: carKey }, eph.privateKey, 256); +const hkdf = await subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey']); +const aes = await subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: enc.encode('mg-utility-hermes-pair-v1|' + code) }, + hkdf, { name: 'AES-GCM', length: 256 }, false, ['encrypt']); +const iv = globalThis.crypto.getRandomValues(new Uint8Array(12)); +const ct = await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: enc.encode(code), tagLength: 128 }, aes, enc.encode(plaintext)); +const digest = new Uint8Array(await subtle.digest('SHA-256', Buffer.from(carKeyB64, 'base64url'))); +const alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; +let fp = ''; for (let i = 0; i < 4; i++) fp += alphabet[digest[i] % alphabet.length]; +process.stdout.write(JSON.stringify({ v: 1, epk: b64url(await subtle.exportKey('raw', eph.publicKey)), iv: b64url(iv), ct: b64url(ct), fingerprint: fp })); diff --git a/tests/run_hermes_tests.sh b/tests/run_hermes_tests.sh index 7645f8a..a1e5357 100644 --- a/tests/run_hermes_tests.sh +++ b/tests/run_hermes_tests.sh @@ -19,4 +19,11 @@ javac -source 8 -target 8 -cp "$ANDROID_JAR:$SHERPA_CP" -d "$OUT" \ "$ROOT/src/cloud/molberg/mgutility/HermesConfig.java" \ "$ROOT/src/cloud/molberg/mgutility/HermesTranscriptionClient.java" \ "$ROOT/tests/HermesTranscriptionClientTest.java" -java -cp "$OUT:$ANDROID_JAR" cloud.molberg.mgutility.HermesTranscriptionClientTest \ No newline at end of file +java -cp "$OUT:$ANDROID_JAR" cloud.molberg.mgutility.HermesTranscriptionClientTest +# Phone (WebCrypto) -> car (java.security) pairing crypto interop. +PAIR_OUT="$OUT/pair" +mkdir -p "$PAIR_OUT" +javac -source 8 -target 8 -d "$PAIR_OUT" \ + "$ROOT/src/cloud/molberg/mgutility/HermesPairingCrypto.java" \ + "$ROOT/tests/HermesPairingCryptoTest.java" +java -cp "$PAIR_OUT" cloud.molberg.mgutility.HermesPairingCryptoTest "$ROOT/tests/pair-encrypt.mjs" diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 7c317b4..32b5c66 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -49,6 +49,12 @@ javac -source 8 -target 8 -cp "$OUT" -d "$OUT/vehicle-power" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsGateway.java" \ "$ROOT/tests/VehiclePowerOffGatewayTest.java" java -cp "$OUT/vehicle-power:$OUT" cloud.molberg.mgutility.VehiclePowerOffGatewayTest +mkdir -p "$OUT/climate" +javac -source 8 -target 8 -d "$OUT/climate" \ + $(find "$ROOT/tests/vehicle-power-stubs" -name '*.java') \ + "$ROOT/src/cloud/molberg/mgutility/ClimateGateway.java" \ + "$ROOT/tests/ClimateGatewayTest.java" +java -cp "$OUT/climate" cloud.molberg.mgutility.ClimateGatewayTest mkdir -p "$OUT/audio" javac -source 8 -target 8 -d "$OUT/audio" \ $(find "$ROOT/tests/audio-stubs" -name '*.java') \