From 1b4cfc863426ecbe2217aa6ca9bb763e4bd80cdf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 15:03:34 +0000 Subject: [PATCH 1/5] 2.5.25: switch between your cars (issue #52) A car button beside the style button lists the user's cars; tapping one switches to it and the app takes that car's own settings: the car, where it was sold, protocol, typed-in VIN, adapter, Dashboard tiles, graphs, custom readings and Android Auto readings. Units, styles and alerts stay shared. Add a car opens the car sheet (closing it without saving goes back to the previous car); Edit cars gives a nickname or removes a car. Switching while connected asks to disconnect first. The app's settings keep holding the chosen car's copy, so the rest of the app is unchanged; CarProfiles saves and swaps the per-car copies. Backups carry the list, every value checked with the backup's own rules (Bluetooth adapters never leave the phone; each car's VIN only when the user includes it). Restoring joins the backup's list with the phone's, keeping this phone's adapter for the same car; an older backup's car joins the list instead of replacing the chosen car. Tour: two cars via debug-only demo_car_add / demo_cars_clear extras, the list, a switch, and Add a car closed without saving. Live preview has the car button and sheet too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iBpQooTxKueeKXA8sku3b --- .github/scripts/install-test.sh | 43 +++- CHANGELOG.md | 4 + README.md | 1 + .../java/com/obdreader/app/MainActivity.kt | 2 + .../main/java/com/obdreader/app/MainCar.kt | 16 +- .../java/com/obdreader/app/MainCarSwitch.kt | 209 +++++++++++++++++ .../java/com/obdreader/app/obd/BackupFile.kt | 10 +- .../java/com/obdreader/app/obd/CarProfiles.kt | 203 +++++++++++++++++ .../java/com/obdreader/app/session/Backups.kt | 8 + .../com/obdreader/app/session/CarGarage.kt | 68 ++++++ app/src/main/res/drawable/ic_car.xml | 7 + app/src/main/res/layout/activity_main.xml | 47 ++++ app/src/main/res/values/strings.xml | 21 ++ .../com/obdreader/app/obd/CarProfilesTest.kt | 212 ++++++++++++++++++ gradle.properties | 2 +- preview/index.html | 109 ++++++++- 16 files changed, 952 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/obdreader/app/MainCarSwitch.kt create mode 100644 app/src/main/java/com/obdreader/app/obd/CarProfiles.kt create mode 100644 app/src/main/java/com/obdreader/app/session/CarGarage.kt create mode 100644 app/src/main/res/drawable/ic_car.xml create mode 100644 app/src/test/java/com/obdreader/app/obd/CarProfilesTest.kt diff --git a/.github/scripts/install-test.sh b/.github/scripts/install-test.sh index 3b3e1ddcc..2b3d36905 100755 --- a/.github/scripts/install-test.sh +++ b/.github/scripts/install-test.sh @@ -704,12 +704,53 @@ enhanced_unconfirmed() { # $1 style if [ $ok = 1 ] && grep -q "unconfirmed" "$OUT/ui-unconfirmed-$slug.xml"; then log "enhanced unconfirmed ($1): shown" else log "enhanced unconfirmed ($1): FAILED ($(tail -1 "$OUT/deep-unconfirmed-$slug.txt" 2>/dev/null | cut -c1-120))"; FAIL=1; fi } +# Your cars (the car switcher), for the design check: debug builds are given two cars without the +# car sheet (demo_car, and demo_car_add to start a second car first). Then the car button's list, +# a switch to the other car, and Add a car closed without saving, which must leave both cars as they were. +car_switcher() { # $1 style, $2 "add" to also try Add a car + local slug; slug=$(echo "$1" | tr ' A-Z' '-a-z') + app_front; disconnect_app; close_trip || true + if tap_text "Style"; then sleep 1; for i in 1 2 3 4 5 6; do tap_text "$1" && break; adb shell input swipe 540 1800 540 700 300; sleep 1; done; sleep 3; fi + adb shell am force-stop $PKG; sleep 2 + timeout 60 adb shell am start -W -n $PKG/.HomeActivity --es demo_car Subaru,2018,Forester --ez demo_cars_clear true > /dev/null 2>&1; sleep 4 + adb shell am force-stop $PKG; sleep 2 + timeout 60 adb shell am start -W -n $PKG/.HomeActivity --es demo_car Mazda,2006,Tribute --ez demo_car_add true > /dev/null 2>&1; sleep 4 + adb shell am force-stop $PKG; sleep 2 + timeout 60 adb shell am start -W -n $PKG/.HomeActivity > /dev/null 2>&1; sleep 4 + tap_tab Dashboard > /dev/null; sleep 1; scroll_top; shot "14a-car-button-$slug" + local ok=0 + if tap_id carSwitchButton; then + sleep 2; shot "14b-your-cars-$slug" + adb shell uiautomator dump /sdcard/ui.xml > /dev/null 2>&1; adb shell cat /sdcard/ui.xml > "$OUT/ui-cars-$slug.xml" 2>/dev/null + if grep -q "2006 Mazda Tribute" "$OUT/ui-cars-$slug.xml" && grep -q "2018 Subaru Forester" "$OUT/ui-cars-$slug.xml" && tap_contains "2018 Subaru Forester"; then + sleep 5; tap_tab Dashboard > /dev/null; sleep 1; scroll_top; shot "14c-switched-$slug" + adb shell uiautomator dump /sdcard/ui.xml > /dev/null 2>&1; adb shell cat /sdcard/ui.xml > "$OUT/ui-switched-$slug.xml" 2>/dev/null + grep -q "Chosen: 2018 Subaru Forester" "$OUT/ui-switched-$slug.xml" && ok=1 + fi + fi + if [ $ok = 1 ] && [ "$2" = add ]; then + ok=0 + if tap_id carSwitchButton && sleep 2 && tap_text "Add a car"; then + sleep 2; shot "14d-add-car-$slug" + # Back closes the car sheet without saving (a second Back only if the first just hid the keyboard). + adb shell input keyevent KEYCODE_BACK; sleep 2 + tap_id carSwitchButton || { adb shell input keyevent KEYCODE_BACK; sleep 2; tap_id carSwitchButton; } && { + sleep 2; adb shell uiautomator dump /sdcard/ui.xml > /dev/null 2>&1; adb shell cat /sdcard/ui.xml > "$OUT/ui-cars-after-add-$slug.xml" 2>/dev/null + grep -q "2006 Mazda Tribute" "$OUT/ui-cars-after-add-$slug.xml" && grep -q "2018 Subaru Forester" "$OUT/ui-cars-after-add-$slug.xml" \ + && ! grep -q "Car not chosen yet" "$OUT/ui-cars-after-add-$slug.xml" && ok=1 + adb shell input keyevent KEYCODE_BACK; sleep 1 + } + fi + fi + if [ $ok = 1 ]; then log "car switcher ($1): OK"; else log "car switcher ($1): FAILED"; FAIL=1; fi +} if adb shell dumpsys package $PKG 2>/dev/null | grep -m1 "pkgFlags=" | grep -q DEBUGGABLE; then enhanced_unconfirmed "Pit lane"; enhanced_unconfirmed "Asphalt" + car_switcher "Pit lane"; car_switcher "Asphalt" add # Back to no car chosen, as the rest of the tour expects. app_front; disconnect_app; close_trip || true adb shell am force-stop $PKG; sleep 2 - timeout 60 adb shell am start -W -n $PKG/.HomeActivity --es demo_car none > /dev/null 2>&1; sleep 4 + timeout 60 adb shell am start -W -n $PKG/.HomeActivity --es demo_car none --ez demo_cars_clear true > /dev/null 2>&1; sleep 4 # Diagnostics lays out its sections before that extra clears the car, so Car and connection # (open while no car is chosen) started closed: open the app once more with no car chosen. adb shell am force-stop $PKG; sleep 2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 001a451f7..dacaa6362 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ Every change to OBD2 Reader, newest first. Each GitHub release shows the entry for its version. +## 2.5.25 (1 December 2026) +- **Switch between your cars.** A new car button at the top of the home screen, next to the style button, lists your cars. Tap one to switch to it, and the app takes that car's own settings: the car itself, where it was sold, its protocol, its VIN if you typed one in, the adapter you use with it, and its Dashboard tiles, graphs, custom readings and Android Auto readings. Units and styles stay the same for all your cars. **Add a car** opens the car sheet for the new one; **Edit cars** gives a car a nickname or removes it. Code history was already kept for each car. Suggested by a user with five cars. +- **Backups keep all your cars.** A backup now holds each car's settings too, with each car's VIN only if you choose to include it. A Bluetooth adapter stays on the phone it was paired with, as before. + ## 2.5.24 (1 December 2026) - **Transmission temperature for Nissan and Infiniti.** Enhanced diagnostics now shows the CVT or automatic transmission fluid temperature on Nissans and Infinitis that give it, from the transmission computer on most cars up to about 2020, and on the 2021 and later X-Trail (Rogue). - **Transmission and oil temperature for Hyundai, Kia and Genesis.** Enhanced diagnostics now shows the transmission fluid temperature on older and newer models, and the engine oil temperature. diff --git a/README.md b/README.md index 8f6a12dc7..d8c404fda 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ After the first time, it reconnects by itself. Help is also inside the app, unde - **Deeper checks:** readiness monitors, self-test results, and codes from ABS, power steering and other modules (on CAN cars, and on 1996–2007 Fords and Mazdas). Airbag modules are never asked. On Fords and Mazdas it can also read the second network on pins 3 and 11, with adapters that support it such as OBDLink MX+. On 1996–2000 Volvo 850, S70, V70, C70 and XC70 it reads Volvo's own modules and the true mileage stored in the instrument cluster. - **VIN:** reads your car's VIN. You can enter the one on your plate if they differ. **VIN details** shows the model, trim, body, engine, drive, transmission and where it was built, from NHTSA's vPIC data inside the app, and can fill in your car choice from it. **Hide VIN** (hidden by default) keeps it off the screen, reports, shared files and logs, or hides just the last six characters. Tap the hidden VIN to see it on screen; tap again to hide it. - **What your car reports:** every reading your car offers, grouped by part of the car with its value now. +- **Your cars:** add each car you own and switch between them with the car button at the top of the home screen. Each car keeps its own adapter, protocol, Dashboard tiles, graphs and readings; units and styles are the same for all. - **Back up and restore:** settings, history and recorded drives in one file you keep, to move to a new phone. Routes and VIN only if you choose. - **Record and replay:** save what your car answers to the app's requests in a plain text file on your phone (VIN left out unless you choose to show it), then replay it later without the car, like the demo car. Handy for bug reports. diff --git a/app/src/main/java/com/obdreader/app/MainActivity.kt b/app/src/main/java/com/obdreader/app/MainActivity.kt index 50bb4637c..1a5a839ab 100644 --- a/app/src/main/java/com/obdreader/app/MainActivity.kt +++ b/app/src/main/java/com/obdreader/app/MainActivity.kt @@ -426,6 +426,7 @@ open class MainActivity : AppCompatActivity() { // And about once a day in the background, so a new version is announced even when the app isn't open. com.obdreader.app.session.UpdateCheckJob.schedule(applicationContext) findViewById(R.id.themeButton).setOnClickListener { showThemePicker() } + findViewById(R.id.carSwitchButton).setOnClickListener { showCarSwitcher() } findViewById(R.id.logShare).setOnClickListener { offerFile(Exports.adapterLog(this, ObdSession.fullLog(), ObdSession.state.value), "OBD2 Reader adapter log") } @@ -1073,6 +1074,7 @@ open class MainActivity : AppCompatActivity() { override fun onResume() { super.onResume() startStyleWatch() + updateCarSwitch() // the adapter shown for the chosen car may have changed while connecting showBatteryNight() // the overnight readings may have moved on while the app was away Updater.showPrompt = { confirm -> showInstallPrompt(confirm) } Updater.waitingPrompt?.let { Updater.waitingPrompt = null; showInstallPrompt(it) } diff --git a/app/src/main/java/com/obdreader/app/MainCar.kt b/app/src/main/java/com/obdreader/app/MainCar.kt index 10654cb15..f6f453582 100644 --- a/app/src/main/java/com/obdreader/app/MainCar.kt +++ b/app/src/main/java/com/obdreader/app/MainCar.kt @@ -72,14 +72,20 @@ internal fun MainActivity.updateCarSetting() { val car = savedCar() carSetting.text = car?.label ?: getString(R.string.car_not_set) findViewById(R.id.carExpect).visibility = if (car != null && CarSupport.expectations(car).isNotEmpty()) View.VISIBLE else View.GONE + updateCarSwitch() } /** * Debug builds: the test tour chooses a car without the car sheet ("Subaru,2018,Forester"), so it - * can check readings only some cars get, or clears it again ("none"). Commas, because adb passes the + * can check readings only some cars get, or clears it again ("none"), and the car switcher gets two + * cars to list (demo_car_add, demo_cars_clear). Commas, because adb passes the * extra through a shell, where "|" would split the command. Release builds ignore it. */ internal fun MainActivity.demoCarIfAsked(intent: android.content.Intent?) { if ((applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0 || intent?.hasExtra("demo_car") != true) return + // demo_cars_clear empties the list of cars first; demo_car_add starts a new car (as Add a car does) for demo_car to fill in. + if (intent.getBooleanExtra("demo_cars_clear", false)) prefs.edit().remove(com.obdreader.app.obd.CarProfiles.PREF).remove(com.obdreader.app.obd.CarProfiles.ACTIVE).commit() + if (intent.getBooleanExtra("demo_car_add", false)) com.obdreader.app.session.CarGarage.addCar(prefs) + intent.removeExtra("demo_cars_clear"); intent.removeExtra("demo_car_add") val parts = intent.getStringExtra("demo_car").orEmpty().split(",").map { it.trim() } intent.removeExtra("demo_car") val year = parts.getOrNull(1)?.toIntOrNull() @@ -92,10 +98,12 @@ internal fun MainActivity.demoCarIfAsked(intent: android.content.Intent?) { } /** No car chosen yet, and the user hasn't said theirs isn't listed. */ internal fun MainActivity.needsCar(): Boolean = savedCar() == null && !prefs.getBoolean(PREF_CAR_ASKED, false) -internal fun MainActivity.showCarPicker(firstRun: Boolean = false, prefill: VehicleCatalog.Car? = null, onDone: (() -> Unit)? = null) { +/** [onCancel] runs when the sheet is closed without Save or Clear. */ +internal fun MainActivity.showCarPicker(firstRun: Boolean = false, prefill: VehicleCatalog.Car? = null, onDone: (() -> Unit)? = null, onCancel: (() -> Unit)? = null) { val sheet = BottomSheetDialog(this) carPickerShowing = true - sheet.setOnDismissListener { carPickerShowing = false } + var answered = false + sheet.setOnDismissListener { carPickerShowing = false; if (!answered) onCancel?.invoke() } val view = layoutInflater.inflate(R.layout.sheet_car, null) view.applyTitleFonts() if (firstRun) { @@ -195,6 +203,7 @@ internal fun MainActivity.showCarPicker(firstRun: Boolean = false, prefill: Vehi refreshResult() view.findViewById(R.id.carSave).setOnClickListener { + answered = true val car = carNow() prefs.edit() .putString(PREF_CAR_MAKE, car.make) @@ -220,6 +229,7 @@ internal fun MainActivity.showCarPicker(firstRun: Boolean = false, prefill: Vehi if (!showExpectations(car, after)) after() } view.findViewById(R.id.carClear).setOnClickListener { + answered = true prefs.edit().remove(PREF_CAR_MAKE).remove(PREF_CAR_YEAR).remove(PREF_CAR_MODEL).remove(PREF_CAR_ENGINE) .putBoolean(PREF_CAR_ASKED, true).apply() updateCarSetting() diff --git a/app/src/main/java/com/obdreader/app/MainCarSwitch.kt b/app/src/main/java/com/obdreader/app/MainCarSwitch.kt new file mode 100644 index 000000000..ddf824006 --- /dev/null +++ b/app/src/main/java/com/obdreader/app/MainCarSwitch.kt @@ -0,0 +1,209 @@ +package com.obdreader.app + +import android.graphics.drawable.GradientDrawable +import android.text.InputFilter +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.TextView +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.textfield.TextInputEditText +import com.google.android.material.textfield.TextInputLayout +import com.obdreader.app.obd.CarProfiles +import com.obdreader.app.session.CarGarage +import com.obdreader.app.session.ObdSession +import com.obdreader.app.ui.themeColor +import com.obdreader.app.ui.uiTypeface + +// Your cars: the car button in the top bar, beside the style button. It opens a sheet listing the +// user's cars; tapping one switches to it, and the app takes that car's own settings (see +// CarProfiles). Add a car and Edit cars (nickname, remove) are at the bottom of the sheet. + +/** The car button's number and description, and the line under the status saying which car is chosen. */ +internal fun MainActivity.updateCarSwitch() { + val garage = CarProfiles.load(prefs.all) + val cars = garage.cars.size + val current = garage.current + val button = findViewById(R.id.carSwitchButton) ?: return + button.contentDescription = current?.title?.let { getString(R.string.your_cars_chosen, it) } ?: getString(R.string.your_cars) + findViewById(R.id.carCount)?.apply { + visibility = if (cars >= 2) View.VISIBLE else View.GONE + text = cars.toString() + background = GradientDrawable().apply { cornerRadius = dp(8f); setColor(themeColor(R.attr.obdAccent)) } + } + // Only for two or more cars: with one car the home screen stays as it was. + findViewById(R.id.carLine)?.apply { + val title = current?.title + visibility = if (cars >= 2 && title != null) View.VISIBLE else View.GONE + text = title?.let { getString(R.string.car_line, it, current.adapter ?: getString(R.string.car_no_adapter)) }.orEmpty() + } +} + +/** The car button: the list of cars, or straight to the car sheet while there are none. */ +internal fun MainActivity.showCarSwitcher() { + val garage = CarGarage.load(prefs) + if (garage.cars.isEmpty()) { showCarPicker(); return } + choiceSheet(getString(R.string.your_cars)) { body, sheet -> + sheetNote(body, getString(R.string.your_cars_note)) + garage.cars.forEach { car -> + carRow(body, car, chosen = car.id == garage.active) { + sheet.dismiss() + if (car.id != garage.active) switchCar(car.id, car.title ?: getString(R.string.car_unnamed)) + } + } + sheetButtons(body, + getString(R.string.cars_edit) to { sheet.dismiss(); showEditCars() }, + getString(R.string.car_add) to { sheet.dismiss(); addCar() }, + ) + } +} + +/** One car in the list: a car tile, its name with its adapter underneath, and a tick on the chosen one. */ +private fun MainActivity.carRow(body: LinearLayout, car: CarProfiles.Profile, chosen: Boolean, onClick: () -> Unit) { + val name = car.title ?: getString(R.string.car_unnamed) + val adapter = car.adapter ?: getString(R.string.car_no_adapter) + body.addView(LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL + if (chosen) background = sheetPanel() + val p = dp(10f).toInt(); setPadding(p, p, p, p) + minimumHeight = dp(60f).toInt() + isClickable = true; isFocusable = true + contentDescription = "$name, $adapter" + isSelected = chosen + addView(ImageView(this@carRow).apply { + setImageResource(R.drawable.ic_car) + imageTintList = android.content.res.ColorStateList.valueOf(themeColor(if (chosen) R.attr.obdAccent else R.attr.obdTextSecondary)) + background = GradientDrawable().apply { cornerRadius = dp(4f); setColor(themeColor(R.attr.obdSurfaceHigh)) } + val ip = dp(10f).toInt(); setPadding(ip, ip, ip, ip) + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + }, LinearLayout.LayoutParams(dp(44f).toInt(), dp(44f).toInt())) + addView(LinearLayout(this@carRow).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(12f).toInt(), 0, dp(8f).toInt(), 0) + addView(TextView(this@carRow).apply { + text = name; setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f); typeface = uiTypeface(600) + setTextColor(themeColor(R.attr.obdTextPrimary)); maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END + }) + addView(TextView(this@carRow).apply { + text = if (car.nickname != null && car.car != null) "${car.car!!.label} · $adapter" else adapter + setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f) + setTextColor(themeColor(R.attr.obdTextSecondary)); maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END + }) + }, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + addView(ImageView(this@carRow).apply { + setImageResource(R.drawable.ic_check) + imageTintList = android.content.res.ColorStateList.valueOf(themeColor(R.attr.obdAccent)) + visibility = if (chosen) View.VISIBLE else View.INVISIBLE + importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + }, LinearLayout.LayoutParams(dp(24f).toInt(), dp(24f).toInt())) + setOnClickListener { onClick() } + }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { topMargin = dp(6f).toInt() }) +} + +/** + * Runs [action] once the app isn't connected: while it is, asks first, since the settings about to + * change (adapter, protocol, readings) belong to the car it's talking to. + */ +private fun MainActivity.whenDisconnected(target: String?, action: () -> Unit) { + if (!ObdSession.isActive) { action(); return } + val now = CarProfiles.load(prefs.all).current?.title ?: getString(R.string.car_unnamed) + MaterialAlertDialogBuilder(this) + .setTitle(R.string.car_switch_disconnect_title) + .setMessage(if (target != null) getString(R.string.car_switch_disconnect, now, target) else getString(R.string.car_add_disconnect, now)) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(R.string.car_switch_disconnect_ok) { _, _ -> disconnect(); action() } + .show() +} + +/** Switches to car [id] and rebuilds the screen from its settings. */ +private fun MainActivity.switchCar(id: String, name: String) = whenDisconnected(name) { + CarGarage.switchTo(prefs, id) + toast(getString(R.string.car_switched, name)) + com.obdreader.app.widget.ObdWidget.refresh(this) + recreate() +} + +/** + * Add a car: starts an empty car and opens the car sheet for it. Saving keeps it (and the screen + * is rebuilt for it); closing the sheet without saving goes back to the car that was chosen. + */ +private fun MainActivity.addCar() { + val garage = CarGarage.load(prefs) + if (!garage.canAdd) { toast(getString(R.string.cars_full, CarProfiles.MAX)); return } + whenDisconnected(null) { + val from = garage.active + if (!CarGarage.addCar(prefs)) return@whenDisconnected + val added = prefs.getString(CarProfiles.ACTIVE, null) + showCarPicker( + onDone = { com.obdreader.app.widget.ObdWidget.refresh(this); recreate() }, + onCancel = { + if (from != null) CarGarage.switchTo(prefs, from) + if (added != null) CarGarage.remove(prefs, added) + updateCarSetting() + applyRedline() + }, + ) + } +} + +/** Edit cars: each car, tapped for its nickname or to remove it. */ +private fun MainActivity.showEditCars() { + val garage = CarGarage.load(prefs) + choiceSheet(getString(R.string.cars_edit)) { body, sheet -> + garage.cars.forEach { car -> + carRow(body, car, chosen = car.id == garage.active) { sheet.dismiss(); showEditCar(car) } + } + } +} + +private fun MainActivity.showEditCar(car: CarProfiles.Profile) { + val name = car.title ?: getString(R.string.car_unnamed) + choiceSheet(name) { body, sheet -> + car.car?.let { if (car.nickname != null) sheetNote(body, it.label) } + sheetStackedButtons(body, + listOf(getString(R.string.car_rename) to { sheet.dismiss(); renameCar(car) }), + danger = getString(R.string.car_remove) to { sheet.dismiss(); removeCar(car, name) }, + ) + } +} + +private fun MainActivity.renameCar(car: CarProfiles.Profile) { + val input = TextInputEditText(this).apply { + setText(car.nickname.orEmpty()) + filters = arrayOf(InputFilter.LengthFilter(CarProfiles.MAX_NICKNAME)) + setSingleLine() + } + val layout = TextInputLayout(this).apply { + hint = getString(R.string.car_rename_hint) + addView(input) + val p = dp(24f).toInt(); setPadding(p, dp(8f).toInt(), p, 0) + } + MaterialAlertDialogBuilder(this) + .setTitle(R.string.car_rename) + .setView(layout) + .setNegativeButton(android.R.string.cancel, null) + .setNeutralButton(R.string.car_rename_clear) { _, _ -> CarGarage.rename(prefs, car.id, null); updateCarSwitch() } + .setPositiveButton(R.string.save) { _, _ -> CarGarage.rename(prefs, car.id, input.text?.toString()); updateCarSwitch() } + .show() +} + +private fun MainActivity.removeCar(car: CarProfiles.Profile, name: String) { + val chosen = car.id == prefs.getString(CarProfiles.ACTIVE, null) + MaterialAlertDialogBuilder(this) + .setTitle(getString(R.string.car_remove_title, name)) + .setMessage(R.string.car_remove_body) + .setNegativeButton(android.R.string.cancel, null) + .setPositiveButton(R.string.car_remove) { _, _ -> + if (!chosen) { CarGarage.remove(prefs, car.id); updateCarSwitch(); return@setPositiveButton } + // Removing the chosen car switches to another one, so the screen is rebuilt. + whenDisconnected(name) { + CarGarage.remove(prefs, car.id) + com.obdreader.app.widget.ObdWidget.refresh(this) + recreate() + } + } + .show() +} diff --git a/app/src/main/java/com/obdreader/app/obd/BackupFile.kt b/app/src/main/java/com/obdreader/app/obd/BackupFile.kt index f1aa13c92..ca2de9ab9 100644 --- a/app/src/main/java/com/obdreader/app/obd/BackupFile.kt +++ b/app/src/main/java/com/obdreader/app/obd/BackupFile.kt @@ -116,6 +116,9 @@ object BackupFile { // The car. "car_make" to text(60), "car_year" to int(1975..2100), "car_model" to text(80), "car_engine" to text(80), "car_market" to text(40) { Market.byName(it) != null }, "car_asked" to bool(), + // Each car's own settings (CarProfiles), every value checked with the rules here, and which car is chosen. + "car_profiles" to Rule(Type.TEXT, 2 * 1024 * 1024, multiline = true) { v -> CarProfiles.forBackup(v as String, includeVin = true).ifEmpty { null } }, + "active_car" to id(), "protocol" to text(3) { it == ObdProtocols.AUTO || ObdProtocols.byCode(it) != null }, "last_protocol" to text(3) { ObdProtocols.byCode(it) != null }, "vin_privacy" to text(10) { VinPrivacy.of(it).key == it }, @@ -152,7 +155,7 @@ object BackupFile { fun isBackedUp(key: String): Boolean = ruleFor(key) != null /** Settings that are lists the phone builds up: a restore adds the backup's entries to the phone's. */ - val MERGED = setOf("trip_history", "code_history", "battery_checks", "perf_history") + val MERGED = setOf("trip_history", "code_history", "battery_checks", "perf_history", "car_profiles") /** Settings that identify the car itself, left out unless the user asks for them. */ val VIN_KEYS = setOf("user_vin", "user_vin_car") @@ -190,6 +193,7 @@ object BackupFile { "perf_history" -> PerformanceTimer.encode( (PerformanceTimer.decode(phone) + PerformanceTimer.decode(backup)).distinct().sortedBy { it.atMs }.takeLast(30), ) + "car_profiles" -> CarProfiles.merge(phone, backup) else -> backup } @@ -269,6 +273,8 @@ object BackupFile { includeVin: Boolean, ) { val kept = settings.entries + // The list of cars carries each car's VIN only when the user chose to include it. + .map { (k, v) -> java.util.AbstractMap.SimpleEntry(k, if (k == CarProfiles.PREF && v is String) CarProfiles.forBackup(v, includeVin) else v) } .filter { (k, v) -> v != null && isBackedUp(k) && (includeVin || k !in VIN_KEYS) } .mapNotNull { (k, v) -> check(k, v!!)?.let { Setting(k, it) } } .sortedBy { it.key } @@ -281,7 +287,7 @@ object BackupFile { append("app=").append(appVersion.filter { it.isLetterOrDigit() || it in ".-+ " }.take(40)).append('\n') append("made=").append(madeAtMs).append('\n') append("routes=").append(includeRoutes).append('\n') - append("vin=").append(includeVin && kept.any { it.key in VIN_KEYS }).append('\n') + append("vin=").append(includeVin && kept.any { it.key in VIN_KEYS || (it.key == CarProfiles.PREF && CarProfiles.hasVin(it.value as? String)) }).append('\n') append("settings=").append(kept.size).append('\n') append("drives=").append(usable.size).append('\n') }.toByteArray(Charsets.UTF_8)) diff --git a/app/src/main/java/com/obdreader/app/obd/CarProfiles.kt b/app/src/main/java/com/obdreader/app/obd/CarProfiles.kt new file mode 100644 index 000000000..7e977df55 --- /dev/null +++ b/app/src/main/java/com/obdreader/app/obd/CarProfiles.kt @@ -0,0 +1,203 @@ +package com.obdreader.app.obd + +import java.util.Base64 + +/** + * Your cars: each car the user adds keeps its own settings, so someone with several cars can swap + * between them from the home screen. What a car keeps: the car itself (make, year, model, engine), + * where it was sold new, the protocol setting, a typed-in VIN, the adapter used with it, and its + * dashboard tiles, graphs, custom readings and Android Auto readings ([KEYS]). Units, styles, + * alerts and the histories (codes, drives, battery) stay the same for every car; code history is + * already kept per car by its name. + * + * The app's own settings always hold the chosen car's copy, so the rest of the app reads them as it + * always has. Switching car saves the chosen car's copy into its entry here and puts the other car's + * copy in its place ([switchTo]). Nothing here talks to a car: it only moves the phone's own settings. + * + * Saved as one line per car, `id|nickname|values`, the nickname and values in Base64; the + * values are lines in the backup file's own setting format ([BackupFile.encodeSetting]), so a restore + * checks each one with the same rules as the settings themselves. + */ +object CarProfiles { + + /** The list of cars. */ + const val PREF = "car_profiles" + /** The id of the car the app's settings belong to now. */ + const val ACTIVE = "active_car" + /** At most this many cars. */ + const val MAX = 20 + /** A nickname's length: it has to fit the switcher's list and the home screen's line. */ + const val MAX_NICKNAME = 20 + + /** The settings each car keeps for itself (the names AppPrefs and MainActivity save them under). */ + val KEYS: Set = setOf( + // The car. + "car_make", "car_year", "car_model", "car_engine", "car_market", + "protocol", "last_protocol", "user_vin", "user_vin_car", + // The adapter used with it (the Bluetooth ones stay on this phone: a backup never carries them). + "last_type", "last_address", "last_name", "wifi_host", "wifi_port", + // Its tiles, graphs and readings. + "dash_slots", "graph_channels", "custom_readings", "car_readings", + ) + + private val ID = Regex("[a-z0-9]{1,40}") + + data class Profile(val id: String, val nickname: String? = null, val values: Map = emptyMap()) { + val car: VehicleCatalog.Car? + get() { + val make = values["car_make"] as? String ?: return null + val year = values["car_year"] as? Int ?: return null + if (year <= 0) return null + return VehicleCatalog.Car(make, year, values["car_model"] as? String, values["car_engine"] as? String) + } + + /** How the car is named in the list: its nickname, else "2006 Mazda Tribute". */ + val title: String? get() = nickname ?: car?.label + + /** The adapter last used with this car, by name ("OBDLink MX+"), or a Wi-Fi adapter's address. */ + val adapter: String? + get() = (values["last_name"] as? String)?.takeIf { it.isNotBlank() } + ?: (values["wifi_host"] as? String)?.takeIf { values["last_type"] == "wifi" } + } + + data class Garage(val cars: List, val active: String?) { + val current: Profile? get() = cars.firstOrNull { it.id == active } + val canAdd: Boolean get() = cars.size < MAX + } + + // ---------- Saving ---------- + + private fun b64(s: String) = Base64.getEncoder().encodeToString(s.toByteArray(Charsets.UTF_8)) + private fun unb64(s: String): String? = try { String(Base64.getDecoder().decode(s), Charsets.UTF_8) } catch (e: IllegalArgumentException) { null } + + fun encode(cars: List): String = cars.take(MAX).joinToString("\n") { p -> + val values = p.values.filterKeys { it in KEYS }.toSortedMap().entries + .joinToString("\n") { (k, v) -> BackupFile.encodeSetting(BackupFile.Setting(k, v)) } + listOf(p.id, b64(p.nickname.orEmpty()), b64(values)).joinToString("|") + } + + /** The saved list back, skipping anything malformed. Only [KEYS] are kept, as Strings or Ints. */ + fun decode(text: String?): List = text.orEmpty().lines().mapNotNull { line -> + val p = line.split("|") + if (p.size != 3 || !ID.matches(p[0])) return@mapNotNull null + val nickname = unb64(p[1])?.let { cleanNickname(it) } + val values = unb64(p[2])?.lines().orEmpty() + .mapNotNull { BackupFile.decodeSetting(it) } + .filter { it.key in KEYS && (it.value is String || it.value is Int) } + .associate { it.key to it.value } + Profile(p[0], nickname, values) + }.distinctBy { it.id }.take(MAX) + + /** A nickname as the app keeps it: letters, digits, spaces and a little punctuation, at most [MAX_NICKNAME] characters. */ + fun cleanNickname(text: String): String? = + text.filter { it.isLetterOrDigit() || it in " -'.&/" }.replace(Regex("\\s+"), " ").trim().take(MAX_NICKNAME).trim().ifEmpty { null } + + /** The chosen car's settings from the app's settings [all]. */ + fun snapshot(all: Map): Map = + KEYS.mapNotNull { k -> all[k]?.takeIf { it is String || it is Int }?.let { k to it } }.toMap() + + /** A new id not in [taken]. */ + fun newId(taken: Collection, random: java.util.Random = java.util.Random()): String { + while (true) { + val id = "c" + java.lang.Long.toString(random.nextLong() and Long.MAX_VALUE, 36).take(10) + if (id !in taken) return id + } + } + + // ---------- Reading the app's settings ---------- + + /** + * The cars, brought up to date with the app's settings [all]: the chosen car's entry takes the + * settings as they are now. When no car is chosen in the list yet but the app has a car (the first + * time, or after an older backup was restored), that car joins the list, or becomes the entry + * that already has the same car. Cars left without a make (an "Add a car" that was never finished) + * drop off, unless it's the chosen one. + */ + fun load(all: Map, random: java.util.Random = java.util.Random()): Garage { + var cars = decode(all[PREF] as? String) + var active = (all[ACTIVE] as? String)?.takeIf { id -> cars.any { it.id == id } } + val now = snapshot(all) + if (active != null) { + cars = cars.map { if (it.id == active) it.copy(values = now) else it } + } else if (now["car_make"] != null) { + val label = Profile("x", values = now).car?.label + val same = cars.firstOrNull { label != null && it.car?.label == label } + if (same != null) { + active = same.id + cars = cars.map { if (it.id == same.id) it.copy(values = now) else it } + } else { + val id = newId(cars.map { it.id }, random) + // A full list makes room by leaving out its oldest car (the first). + cars = (cars + Profile(id, values = now)).takeLast(MAX) + active = id + } + } + cars = cars.filter { it.id == active || it.car != null } + return Garage(cars, active) + } + + /** + * Switches to car [id]: the garage afterwards, and the changes to make to the app's settings + * (a value to save, or null to remove that setting). [garage] must be up to date ([load]). + */ + fun switchTo(garage: Garage, id: String): Pair> { + val target = garage.cars.firstOrNull { it.id == id } ?: return garage to emptyMap() + return Garage(garage.cars, id) to KEYS.associateWith { target.values[it] } + } + + /** Adds an empty car (for "Add a car") and switches to it, so the car sheet fills it in. Null when the list is full. */ + fun addCar(garage: Garage, random: java.util.Random = java.util.Random()): Pair>? { + if (!garage.canAdd) return null + val id = newId(garage.cars.map { it.id }, random) + return switchTo(Garage(garage.cars + Profile(id), garage.active), id) + } + + /** + * Removes car [id]. Removing the chosen car switches to the next one in the list (or to none), + * so the changes to the app's settings come back as for [switchTo]. + */ + fun remove(garage: Garage, id: String): Pair> { + val left = garage.cars.filter { it.id != id } + if (id != garage.active) return Garage(left, garage.active) to emptyMap() + val next = left.firstOrNull() ?: return Garage(left, null) to KEYS.associateWith { null } + return switchTo(Garage(left, garage.active), next.id) + } + + fun rename(garage: Garage, id: String, nickname: String?): Garage = + garage.copy(cars = garage.cars.map { if (it.id == id) it.copy(nickname = nickname?.let { n -> cleanNickname(n) }) else it }) + + // ---------- Backups ---------- + + /** + * The list as a backup carries it: each value checked with the backup's own rules (so the + * Bluetooth adapter, which a backup never carries, is left out), and the VIN only when the user + * chose to include it. + */ + fun forBackup(text: String?, includeVin: Boolean): String = encode(decode(text).map { p -> + p.copy(values = p.values.filterKeys { includeVin || it !in BackupFile.VIN_KEYS } + .mapNotNull { (k, v) -> BackupFile.check(k, v)?.let { k to it } }.toMap()) + }) + + /** Whether any car in the list carries a VIN. */ + fun hasVin(text: String?): Boolean = decode(text).any { p -> BackupFile.VIN_KEYS.any { it in p.values } } + + /** + * The phone's list joined with a backup's: the backup's cars, each keeping this phone's own + * adapter for the same car (a backup doesn't carry it), then the phone's cars the backup doesn't have. + */ + fun merge(phone: String?, backup: String): String { + val mine = decode(phone) + val theirs = decode(backup) + val joined = theirs.map { b -> + val same = mine.firstOrNull { it.id == b.id && it.car?.label == b.car?.label } + if (same == null) b else b.copy(values = same.values.filterKeys { !BackupFile.isBackedUp(it) } + b.values) + } + mine.filter { m -> theirs.none { it.id == m.id } } + return encode(joined.take(MAX)) + } + + /** After a restore with a list of cars: the settings a backup can't carry (the Bluetooth adapter), taken from the chosen car's entry. */ + fun localSettings(garage: Garage): Map { + val car = garage.current ?: return emptyMap() + return KEYS.filter { !BackupFile.isBackedUp(it) }.associateWith { car.values[it] } + } +} diff --git a/app/src/main/java/com/obdreader/app/session/Backups.kt b/app/src/main/java/com/obdreader/app/session/Backups.kt index 128d4895d..a1b8eef6d 100644 --- a/app/src/main/java/com/obdreader/app/session/Backups.kt +++ b/app/src/main/java/com/obdreader/app/session/Backups.kt @@ -69,6 +69,9 @@ object Backups { */ fun restore(context: Context, contents: BackupFile.Contents): Restored { val prefs = AppPrefs.of(context) + // The chosen car's settings go into its entry in the list of cars first, so joining the + // backup's list with the phone's keeps them. + CarGarage.load(prefs) val edit = prefs.edit() for (s in contents.settings) { val v = s.value @@ -83,7 +86,12 @@ object Backups { } // A different car's remembered protocol would only slow the first connection down. if (contents.has(AppPrefs.CAR_MAKE) && !contents.has(AppPrefs.LAST_PROTOCOL)) edit.remove(AppPrefs.LAST_PROTOCOL) + // A backup from before the list of cars: its car joins the phone's list (or becomes the entry + // for the same car) rather than taking the place of the car chosen on the phone. + val backupHadCars = contents.has(com.obdreader.app.obd.CarProfiles.PREF) + if (contents.has(AppPrefs.CAR_MAKE) && !backupHadCars) edit.remove(com.obdreader.app.obd.CarProfiles.ACTIVE) edit.commit() + CarGarage.afterRestore(prefs, backupHadCars) AppPrefs.applyUnits(prefs) var added = 0; var there = 0 diff --git a/app/src/main/java/com/obdreader/app/session/CarGarage.kt b/app/src/main/java/com/obdreader/app/session/CarGarage.kt new file mode 100644 index 000000000..c60e6cee9 --- /dev/null +++ b/app/src/main/java/com/obdreader/app/session/CarGarage.kt @@ -0,0 +1,68 @@ +package com.obdreader.app.session + +import android.content.SharedPreferences +import com.obdreader.app.obd.CarProfiles + +/** + * Your cars on the phone: reads and saves [CarProfiles] in the app's settings, and swaps the + * chosen car's settings in and out. Only the phone's own settings change; nothing is sent anywhere. + */ +object CarGarage { + + /** The cars, brought up to date with the settings as they are now (and saved that way). */ + fun load(prefs: SharedPreferences): CarProfiles.Garage { + val garage = CarProfiles.load(prefs.all) + save(prefs, garage) + return garage + } + + private fun save(prefs: SharedPreferences, garage: CarProfiles.Garage, changes: Map = emptyMap()) { + val edit = prefs.edit() + if (garage.cars.isEmpty()) edit.remove(CarProfiles.PREF) else edit.putString(CarProfiles.PREF, CarProfiles.encode(garage.cars)) + if (garage.active == null) edit.remove(CarProfiles.ACTIVE) else edit.putString(CarProfiles.ACTIVE, garage.active) + for ((k, v) in changes) when (v) { + null -> edit.remove(k) + is String -> edit.putString(k, v) + is Int -> edit.putInt(k, v) + } + // One write, straight away: the screen is rebuilt from these settings right after. + edit.commit() + } + + /** Makes car [id] the chosen one. */ + fun switchTo(prefs: SharedPreferences, id: String) { + val (garage, changes) = CarProfiles.switchTo(load(prefs), id) + save(prefs, garage, changes) + } + + /** Starts a new, empty car and makes it the chosen one, ready for the car sheet. False when the list is already full. */ + fun addCar(prefs: SharedPreferences): Boolean { + val (garage, changes) = CarProfiles.addCar(load(prefs)) ?: return false + save(prefs, garage, changes) + return true + } + + fun remove(prefs: SharedPreferences, id: String) { + val (garage, changes) = CarProfiles.remove(load(prefs), id) + save(prefs, garage, changes) + } + + fun rename(prefs: SharedPreferences, id: String, nickname: String?) { + save(prefs, CarProfiles.rename(load(prefs), id, nickname)) + } + + /** + * After a restore: brings the list up to date with the restored settings. When the backup had + * a list of cars, the chosen car's Bluetooth adapter (which a backup doesn't carry) comes from + * this phone's entry for it, so Connect goes to that car's own adapter. + */ + fun afterRestore(prefs: SharedPreferences, backupHadCars: Boolean) { + val restored = CarProfiles.decode(prefs.getString(CarProfiles.PREF, null)) + val active = prefs.getString(CarProfiles.ACTIVE, null) + if (backupHadCars) { + val local = CarProfiles.localSettings(CarProfiles.Garage(restored, active)) + if (local.isNotEmpty()) save(prefs, CarProfiles.Garage(restored, active), local) + } + load(prefs) + } +} diff --git a/app/src/main/res/drawable/ic_car.xml b/app/src/main/res/drawable/ic_car.xml new file mode 100644 index 000000000..af781a4e7 --- /dev/null +++ b/app/src/main/res/drawable/ic_car.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 4b4b803de..cd98c4d63 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -54,6 +54,8 @@ android:fontFamily="?attr/obdTitleFont" android:tag="@string/tag_title_font" android:text="@string/app_name" + android:ellipsize="end" + android:maxLines="1" android:includeFontPadding="false" android:textColor="?attr/obdTextPrimary" android:textSize="22sp" /> @@ -73,6 +75,39 @@ android:textColor="?attr/obdTextPrimary" android:textSize="22sp" /> + + + + + + + + + + + Disconnect first, then replay the recording. Couldn\'t replay that file. %1$s Couldn\'t open that file. + + Your cars + Your cars. Chosen: %1$s + Each car keeps its own adapter, protocol, tiles, graphs and readings. Units and styles are the same for all your cars. + Add a car + Edit cars + You have %1$d cars, the most the app keeps. Remove one to add another. + No adapter used yet + Car not chosen yet + Disconnect to switch cars? + The app is connected to %1$s. Disconnect and switch to %2$s? + The app is connected to %1$s. Disconnect and add a car? + Disconnect and switch + Switched to %1$s + Nickname + For example Dad\'s ute + Use the car\'s name + Remove + Remove %1$s? + Its settings on this phone (adapter, protocol, tiles, graphs and readings) are deleted. Its code history and your drives stay. + %1$s · %2$s diff --git a/app/src/test/java/com/obdreader/app/obd/CarProfilesTest.kt b/app/src/test/java/com/obdreader/app/obd/CarProfilesTest.kt new file mode 100644 index 000000000..1d9d480aa --- /dev/null +++ b/app/src/test/java/com/obdreader/app/obd/CarProfilesTest.kt @@ -0,0 +1,212 @@ +package com.obdreader.app.obd + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.nio.file.Files + +class CarProfilesTest { + + // The well-known sample VIN from VIN documentation, not any real car of ours. + private val vin = "1HGBH41JXMN109186" + private val random = java.util.Random(7) + + private val mazda: Map = mapOf( + "car_make" to "Mazda", "car_year" to 2006, "car_model" to "Tribute", + "protocol" to "0", "last_protocol" to "6", "user_vin" to vin, "user_vin_car" to "2006 Mazda Tribute", + "last_type" to "ble", "last_address" to "00:11:22:33:44:55", "last_name" to "Veepeak OBDCheck BLE+", + "dash_slots" to "speed,coolant", "custom_readings" to "Trans temp\u001F221E1C\u001F7E0\u001F(A*256+B)/16\u001F°C", + // Shared by every car. + "theme" to "asphalt", "units_mph" to false, + ) + + /** The app's settings after applying [changes] (null removes a setting). */ + private fun apply(all: Map, garage: CarProfiles.Garage, changes: Map): Map { + val out = all.toMutableMap() + changes.forEach { (k, v) -> if (v == null) out.remove(k) else out[k] = v } + out[CarProfiles.PREF] = CarProfiles.encode(garage.cars) + if (garage.active == null) out.remove(CarProfiles.ACTIVE) else out[CarProfiles.ACTIVE] = garage.active + return out + } + + private fun saved(all: Map, garage: CarProfiles.Garage) = apply(all, garage, emptyMap()) + + @Test fun firstTimeTheChosenCarJoinsTheList() { + val g = CarProfiles.load(mazda, random) + assertEquals(1, g.cars.size) + assertEquals("2006 Mazda Tribute", g.current?.title) + assertEquals("Veepeak OBDCheck BLE+", g.current?.adapter) + assertNull("units are shared, not kept per car", g.current?.values?.get("units_mph")) + } + + @Test fun noCarNoList() { + val g = CarProfiles.load(mapOf("theme" to "asphalt"), random) + assertTrue(g.cars.isEmpty()) + assertNull(g.active) + } + + @Test fun addSwitchAndBackKeepsEachCarsSettings() { + var all = saved(mazda, CarProfiles.load(mazda, random)) + val mazdaId = all[CarProfiles.ACTIVE] as String + + // Add a car: every per-car setting is cleared, shared ones stay. + val (added, cleared) = CarProfiles.addCar(CarProfiles.load(all, random), random)!! + all = apply(all, added, cleared) + assertNull(all["car_make"]); assertNull(all["last_address"]); assertNull(all["custom_readings"]) + assertEquals("asphalt", all["theme"]) + + // The car sheet and Connect fill in the new car. + all = all + mapOf("car_make" to "Toyota", "car_year" to 2015, "car_model" to "Hilux", + "last_type" to "wifi", "wifi_host" to "192.168.0.10", "wifi_port" to 35000, "dash_slots" to "boost,speed") + val two = CarProfiles.load(all, random) + assertEquals(2, two.cars.size) + assertEquals("192.168.0.10", two.current?.adapter) + all = saved(all, two) + + // Back to the Mazda: its own adapter, VIN and readings come back; the Toyota's are saved. + val (back, changes) = CarProfiles.switchTo(CarProfiles.load(all, random), mazdaId) + all = apply(all, back, changes) + assertEquals("Mazda", all["car_make"]); assertEquals(2006, all["car_year"]) + assertEquals("00:11:22:33:44:55", all["last_address"]); assertEquals(vin, all["user_vin"]) + assertEquals("speed,coolant", all["dash_slots"]) + assertNull("the Toyota's Wi-Fi adapter isn't the Mazda's", all["wifi_host"]) + val toyota = CarProfiles.load(all, random).cars.first { it.id != mazdaId } + assertEquals("boost,speed", toyota.values["dash_slots"]) + assertEquals(35000, toyota.values["wifi_port"]) + } + + @Test fun unfinishedAddDropsOffOnceAnotherCarIsChosen() { + var all = saved(mazda, CarProfiles.load(mazda, random)) + val mazdaId = all[CarProfiles.ACTIVE] as String + val (added, cleared) = CarProfiles.addCar(CarProfiles.load(all, random), random)!! + all = apply(all, added, cleared) + assertEquals("the empty car stays while it's the chosen one", 2, CarProfiles.load(all, random).cars.size) + val (back, changes) = CarProfiles.switchTo(CarProfiles.load(all, random), mazdaId) + all = apply(all, back, changes) + assertEquals(listOf(mazdaId), CarProfiles.load(all, random).cars.map { it.id }) + } + + @Test fun removingTheChosenCarSwitchesToTheNext() { + var all = saved(mazda, CarProfiles.load(mazda, random)) + val mazdaId = all[CarProfiles.ACTIVE] as String + val (added, cleared) = CarProfiles.addCar(CarProfiles.load(all, random), random)!! + all = apply(all, added, cleared) + mapOf("car_make" to "Volvo", "car_year" to 1997, "car_model" to "850") + all = saved(all, CarProfiles.load(all, random)) + val volvoId = all[CarProfiles.ACTIVE] as String + val (left, changes) = CarProfiles.remove(CarProfiles.load(all, random), volvoId) + all = apply(all, left, changes) + assertEquals(mazdaId, all[CarProfiles.ACTIVE]) + assertEquals("Mazda", all["car_make"]) + // And the last one: nothing chosen, every per-car setting gone. + val (none, gone) = CarProfiles.remove(CarProfiles.load(all, random), mazdaId) + all = apply(all, none, gone) + assertNull(all["car_make"]); assertNull(all[CarProfiles.ACTIVE]) + assertEquals("asphalt", all["theme"]) + } + + @Test fun listIsCapped() { + var g = CarProfiles.load(mazda, random) + var all = saved(mazda, g) + repeat(CarProfiles.MAX - 1) { i -> + val (added, cleared) = CarProfiles.addCar(CarProfiles.load(all, random), random)!! + all = apply(all, added, cleared) + mapOf("car_make" to "Ford", "car_year" to 2000 + i) + all = saved(all, CarProfiles.load(all, random)) + } + g = CarProfiles.load(all, random) + assertEquals(CarProfiles.MAX, g.cars.size) + assertFalse(g.canAdd) + assertNull(CarProfiles.addCar(g, random)) + } + + @Test fun nicknamesAreTidied() { + assertEquals("Dad's ute", CarProfiles.cleanNickname(" Dad's ute\n")) + assertEquals("Work car", CarProfiles.cleanNickname("Work car <>{}")) + assertNull(CarProfiles.cleanNickname("<>{}")) + assertEquals(CarProfiles.MAX_NICKNAME, CarProfiles.cleanNickname("x".repeat(80))!!.length) + val g = CarProfiles.rename(CarProfiles.load(mazda, random), CarProfiles.load(mazda, java.util.Random(7)).active!!, "Tribby") + assertEquals("Tribby", g.current?.title) + } + + @Test fun savedListSurvivesBadLines() { + val g = CarProfiles.load(mazda, random) + val text = CarProfiles.encode(g.cars) + "\nnot a car\nBAD|x|y\n" + val back = CarProfiles.decode(text) + assertEquals(g.cars, back) + } + + @Test fun reloadingAddsNoDuplicateForTheSameCar() { + // An older backup restored the same car while nothing was marked as chosen. + val list = CarProfiles.encode(CarProfiles.load(mazda, random).cars) + val g = CarProfiles.load(mazda + mapOf(CarProfiles.PREF to list), random) + assertEquals(1, g.cars.size) + } + + // ---------- Backups ---------- + + private fun backup(all: Map, includeVin: Boolean): BackupFile.Contents { + val out = ByteArrayOutputStream() + BackupFile.write(out, all, emptyList(), "2.5.25", 1_700_000_000_000L, includeRoutes = false, includeVin = includeVin) + return BackupFile.read(ByteArrayInputStream(out.toByteArray()), Files.createTempDirectory("cars").toFile()) + } + + private fun twoCars(): Map { + var all = saved(mazda, CarProfiles.load(mazda, random)) + val (added, cleared) = CarProfiles.addCar(CarProfiles.load(all, random), random)!! + all = apply(all, added, cleared) + mapOf("car_make" to "Toyota", "car_year" to 2015, "car_model" to "Hilux", + "last_type" to "classic", "last_address" to "66:77:88:99:AA:BB", "last_name" to "OBDLink MX+") + return saved(all, CarProfiles.load(all, random)) + } + + @Test fun backupCarriesTheCarsButNotTheirBluetoothAdapters() { + val c = backup(twoCars(), includeVin = true) + val cars = CarProfiles.decode(c.value(CarProfiles.PREF) as String) + assertEquals(2, cars.size) + assertTrue(cars.none { it.values.containsKey("last_address") || it.values.containsKey("last_name") }) + assertEquals(vin, cars.first { it.car?.make == "Mazda" }.values["user_vin"]) + assertNotNull(c.value(CarProfiles.ACTIVE)) + assertTrue(c.info.hasVin) + } + + @Test fun backupLeavesEachCarsVinOutUnlessAsked() { + val c = backup(twoCars(), includeVin = false) + val cars = CarProfiles.decode(c.value(CarProfiles.PREF) as String) + assertTrue(cars.none { it.values.containsKey("user_vin") || it.values.containsKey("user_vin_car") }) + assertFalse(c.info.hasVin) + } + + @Test fun backupChecksEachCarsValues() { + // A crafted list: a public Wi-Fi address and a custom reading that isn't a read-only request are dropped. + val bad = CarProfiles.encode(listOf(CarProfiles.Profile("cabc", "Mine", mapOf( + "car_make" to "Ford", "car_year" to 2010, "wifi_host" to "8.8.8.8", + "custom_readings" to "Clear\u001F04\u001F7E0\u001FA\u001F", + )))) + assertEquals(bad, CarProfiles.encode(CarProfiles.decode(bad))) + val checked = CarProfiles.decode(BackupFile.check(CarProfiles.PREF, bad) as String).single() + assertEquals("Ford", checked.values["car_make"]) + assertNull(checked.values["wifi_host"]) + assertNull(checked.values["custom_readings"]) + } + + @Test fun restoreKeepsThisPhonesAdapterForTheSameCar() { + val phone = twoCars() + val c = backup(phone, includeVin = false) + val merged = CarProfiles.decode(BackupFile.merge(CarProfiles.PREF, phone[CarProfiles.PREF] as String, c.value(CarProfiles.PREF) as String)) + assertEquals(2, merged.size) + assertEquals("66:77:88:99:AA:BB", merged.first { it.car?.make == "Toyota" }.values["last_address"]) + // The chosen car's Bluetooth adapter goes back into the app's settings. + val active = phone[CarProfiles.ACTIVE] as String + assertEquals("66:77:88:99:AA:BB", CarProfiles.localSettings(CarProfiles.Garage(merged, active))["last_address"]) + } + + @Test fun restoreKeepsCarsOnlyOnThisPhone() { + val other = CarProfiles.encode(listOf(CarProfiles.Profile("cother", null, mapOf("car_make" to "Volvo", "car_year" to 1997)))) + val phone = twoCars()[CarProfiles.PREF] as String + val merged = CarProfiles.decode(BackupFile.merge(CarProfiles.PREF, phone, other)) + assertEquals(3, merged.size) + } +} diff --git a/gradle.properties b/gradle.properties index 586520bf7..85d7be234 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,4 +4,4 @@ android.nonTransitiveRClass=true kotlin.code.style=official # The app version shown to users. Bump it with each release and add a CHANGELOG.md entry. -obdVersion=2.5.24 +obdVersion=2.5.25 diff --git a/preview/index.html b/preview/index.html index f28c7476c..779e0cd84 100644 --- a/preview/index.html +++ b/preview/index.html @@ -155,6 +155,22 @@ .wordmark { font-size: 22px; flex: 1; letter-spacing: -.01em; } .icon-btn { width: 40px; height: 40px; border-radius: 50%; display: grid; place-items: center; flex: none; } .icon-btn svg { width: 22px; height: 22px; fill: var(--fg-2); } +.wordmark { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* Your cars: the car button, with how many cars once there are two or more (mirrors MainCarSwitch.kt). */ +.car-switch { position: relative; } +.car-count { position: absolute; top: 3px; right: 1px; min-width: 16px; height: 16px; padding: 0 3px; box-sizing: border-box; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 10px; font-weight: 800; display: grid; place-items: center; } +.car-count[hidden] { display: none; } +.car-opt { display: flex; align-items: center; gap: 12px; width: 100%; padding: 10px; border-radius: var(--r); text-align: left; min-height: 60px; margin-bottom: 6px; } +.car-opt.on { background: var(--panel-2); } +.car-opt .tile { width: 44px; height: 44px; flex: none; display: grid; place-items: center; border-radius: var(--r); background: var(--panel-2); } +.car-opt.on .tile { background: var(--base); } +.car-opt .tile svg { width: 24px; height: 24px; fill: var(--fg-2); } +.car-opt.on .tile svg, .car-opt .tick svg { fill: var(--accent); } +.car-opt .t { flex: 1; min-width: 0; } +.car-opt .t b, .car-opt .t small { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.car-opt .t b { font-size: 16px; font-weight: 600; } +.car-opt .t small { font-size: 13px; color: var(--fg-2); margin-top: 2px; } +.car-opt .tick { width: 24px; height: 24px; flex: none; } /* ---------- Roundel ---------- */ .roundel-wrap { display: grid; place-items: center; margin-top: 8px; position: relative; } @@ -816,7 +832,7 @@
-
OBD2 Reader
+
OBD2 Reader
@@ -856,7 +872,7 @@
-
Not connected
+
Not connected