Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cad30176db | ||
|
|
33d912946e | ||
|
|
dd0d798418 | ||
|
|
58cabb214d | ||
|
|
d5440a37f2 | ||
|
|
e1202bc306 | ||
|
|
e175f5d73b | ||
|
|
8dc698a681 | ||
|
|
54772ffdac | ||
|
|
4881d80e1b | ||
|
|
dcbd41d37b |
No files matched your search
+5
-2
@@ -1,7 +1,6 @@
|
||||
# Generated Android build output
|
||||
/build/
|
||||
telemetry-service/data/
|
||||
telemetry-service/data/*.sqlite*
|
||||
|
||||
|
||||
# Local signing material
|
||||
*.keystore
|
||||
@@ -12,3 +11,7 @@ telemetry-service/data/*.sqlite*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# Private telemetry service source and runtime live outside this repository
|
||||
telemetry-service/*
|
||||
!telemetry-service/client-config.json
|
||||
__pycache__/
|
||||
+24
-2
@@ -1,4 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cloud.molberg.mgutility" android:versionCode="3" android:versionName="0.3.0">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cloud.molberg.mgutility" android:sharedUserId="android.uid.system" android:versionCode="1793740000" android:versionName="0.3.0">
|
||||
<uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28" />
|
||||
<queries>
|
||||
<intent>
|
||||
@@ -24,6 +24,11 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.microphone" android:required="false" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
@@ -38,7 +43,8 @@
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<application android:allowBackup="false" android:label="MG Utility" android:icon="@drawable/ic_mg_utility" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
|
||||
<application android:name=".MgApp" android:allowBackup="false" android:label="MG Utility" android:icon="@drawable/ic_launcher" android:roundIcon="@drawable/ic_launcher" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
|
||||
<uses-library android:name="android.car" android:required="false" />
|
||||
<activity android:name=".MainActivity" android:launchMode="singleTask" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:resizeableActivity="true" android:maxAspectRatio="3.0">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -47,6 +53,7 @@
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".ClimateActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".EnergyActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SpeedTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".ChargingActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
@@ -56,8 +63,23 @@
|
||||
<activity android:name=".SoundboardActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".DebugActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".MicRouteDiagnosticActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".MicTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".DashcamActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<service android:name=".DashcamService" android:enabled="true" android:exported="false" android:stopWithTask="false" android:foregroundServiceType="camera" />
|
||||
<receiver android:name=".DashcamOemReceiver" android:enabled="true" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="com.saicmotor.hmi.aroundview.startAVMActivity" />
|
||||
<action android:name="com.saicmotor.hmi.aroundview.ACTION_START" />
|
||||
<action android:name="com.saicmotor.hmi.aroundview.ACTION_STOP" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="cloud.molberg.mgutility.action.SAVE_DASHCAM_CLIP" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<activity android:name=".CameraTestActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".SettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".HermesSettingsActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".HermesPairActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".HermesVoiceActivity" android:taskAffinity="cloud.molberg.mgutility.hermes" android:excludeFromRecents="true" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".UpdateActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
<activity android:name=".PluginMarketplaceActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="false" android:resizeableActivity="true" android:maxAspectRatio="3.0" />
|
||||
|
||||
@@ -1,297 +1,67 @@
|
||||
# MG Utility
|
||||
|
||||
A configurable Android home-screen replacement and vehicle dashboard for SAIC-based MG cars.
|
||||
MG Utility brings live vehicle information, media, trips, charging tools, shortcuts, and custom controls into one landscape-first interface that can be selected as the vehicle's Android **Home** app.
|
||||
A landscape-first Android home-screen replacement and vehicle dashboard for Android-based MG/SAIC infotainment systems.
|
||||
|
||||
The app is designed to run across MG vehicles by detecting available services and falling back gracefully when an OEM capability is unavailable. Vehicle services, hardware, permissions, and firmware vary by model and trim. **The MG4 Luxury 2022 is the trim used for development and live validation.**
|
||||

|
||||
|
||||
> **Safety first:** MG Utility is not an MG/SAIC-approved product. Configure it only while parked, follow local law, and never use the screen or controls in a way that distracts from driving. Safety-critical systems remain excluded or read-only.
|
||||
> **Safety:** MG Utility is not approved by MG/SAIC. Configure it only while parked. Vehicle-affecting actions are capability-gated, reversible where possible, and excluded from safety-critical systems.
|
||||
|
||||

|
||||
## Features
|
||||
|
||||
*Example home screen captured on the development vehicle: 0 km/h, 346 km estimated range, 414.3 V battery voltage, 80% SOC, 8.0 kWh drive use, and media playback.*
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [What it does](#what-it-does)
|
||||
- [Feature list](#feature-list)
|
||||
- [Home dashboard and launcher](#home-dashboard-and-launcher)
|
||||
- [Vehicle data and energy](#vehicle-data-and-energy)
|
||||
- [Trips and maps](#trips-and-maps)
|
||||
- [Charging tools](#charging-tools)
|
||||
- [Driver utilities](#driver-utilities)
|
||||
- [Settings and backup](#settings-and-backup)
|
||||
- [Capability-gated vehicle settings](#capability-gated-vehicle-settings)
|
||||
- [Compatibility](#compatibility)
|
||||
- [Safety boundaries](#safety-boundaries)
|
||||
- [Install and first run](#install-and-first-run)
|
||||
- [Build from source](#build-from-source)
|
||||
- [Requirements](#requirements)
|
||||
- [Build](#build)
|
||||
- [Permissions and privacy](#permissions-and-privacy)
|
||||
- [Read-only vehicle data provider](#read-only-vehicle-data-provider)
|
||||
- [Development and testing](#development-and-testing)
|
||||
- [Plugin SDK and marketplace](#plugin-sdk-and-marketplace)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [The dashboard shows connecting or unavailable vehicle values](#the-dashboard-shows-connecting-or-unavailable-vehicle-values)
|
||||
- [Trip tracking does not start after reboot or sleep](#trip-tracking-does-not-start-after-reboot-or-sleep)
|
||||
- [Routes have no map background](#routes-have-no-map-background)
|
||||
- [The music panel is empty](#the-music-panel-is-empty)
|
||||
- [The visualizer is silent](#the-visualizer-is-silent)
|
||||
- [A vehicle setting is unavailable](#a-vehicle-setting-is-unavailable)
|
||||
- [Repository layout](#repository-layout)
|
||||
- [Status and limitations](#status-and-limitations)
|
||||
|
||||
## What it does
|
||||
|
||||
MG Utility is a local-first dashboard for Android-based MG infotainment systems. It can be used as a complete replacement for the Android home experience while leaving the OEM vehicle software in place underneath it.
|
||||
|
||||
The main screen combines:
|
||||
|
||||
- vehicle state and energy information when the SAIC vehicle service is available;
|
||||
- media playback information and album art;
|
||||
- a configurable app drawer and quick-control panel;
|
||||
- shortcuts to trips, energy, charging, settings, and other utilities;
|
||||
- live audio visualisation and custom themes.
|
||||
|
||||
The app does not require an internet connection for its core dashboard or local trip history. Network access is used for optional features such as OpenStreetMap tiles and electricity-price data.
|
||||
|
||||
## Feature list
|
||||
|
||||
### Home dashboard and launcher
|
||||
|
||||
- Landscape-first MG dashboard with speed, range, battery voltage, SOC, drive use, and charging status.
|
||||
- Android `HOME` intent support: choose MG Utility as the default Home app when the head unit offers that option.
|
||||
- Full-width music panel with notification-based media title, artist, album art, progress, and playback controls.
|
||||
- Configurable themes, palettes, fonts, home-screen options, and visualizer settings.
|
||||
- Automatic daily screen-brightness schedule with smooth fade-in/fade-out (see Settings → Appearance → Screen brightness).
|
||||
- Swipe-up app drawer populated from the user's pinned applications.
|
||||
- Swipe-down control panel with configurable quick controls, sliders, toggles, and shortcuts.
|
||||
- Quick controls include automatic brightness, Liquid Sound Balance, adaptive audio leveling, the official SAIC launcher, Software Update, and Vehicle Settings. Hold a toggle to open its settings. Existing custom layouts are preserved; add controls from **Settings → Appearance → Configure control panel**, or restore defaults to show the expanded layout.
|
||||
- Physical key remapping for supported foreground actions, with short, long, double, and repeat gestures.
|
||||
|
||||
### Vehicle data and energy
|
||||
|
||||
- Read-only integration with the SAIC vehicle service where the vehicle exposes it.
|
||||
- Vehicle speed, estimated range, battery voltage, state of charge, energy counters, regenerated energy/range, and charging status.
|
||||
- Energy dashboard with live values and connection status.
|
||||
- Graceful connecting, unavailable, and fallback states on vehicles without the expected OEM service.
|
||||
- Read-only content-provider sample for companion tools and diagnostics.
|
||||
|
||||
### Trips and maps
|
||||
|
||||
- Automatic background trip tracking after first-run setup.
|
||||
- Drive distance, duration, top speed, SOC drop, reported energy use, estimated-range drop, sample counts, and GPS point counts.
|
||||
- Regenerative-braking event detection from positive OEM counter deltas.
|
||||
- Trip history with overview, per-drive details, raw samples, route display, recovery totals, and personal bests.
|
||||
- Export selected or all drives as JSON, CSV, or styled HTML reports.
|
||||
- Touch-pannable and pinch-zoomable OpenStreetMap route view with attribution.
|
||||
- Named arrival areas with configurable radius and enabled state.
|
||||
- Arrival briefings with drive statistics and optional charging price-window recommendations.
|
||||
|
||||
### Charging tools
|
||||
|
||||
- Charging automation built from editable `IF … THEN …` blocks.
|
||||
- Conditions for SOC, electricity price, and time windows, including overnight windows.
|
||||
- Live Strømligning price data for Danish DK1/DK2 when network access is available.
|
||||
- Top-to-bottom evaluation with last matching rule winning.
|
||||
- Parked-and-connected guards before charging commands are sent.
|
||||
- Does not modify the OEM reservation schedule, target SOC, or current setting.
|
||||
|
||||
### Driver utilities
|
||||
|
||||
- 0–100 km/h tester using OEM vehicle speed when available, with GPS fallback.
|
||||
- Local top-five acceleration leaderboard; records remain on the device.
|
||||
- Soundboard for locked, booted, regeneration-best, and battery-threshold events.
|
||||
- Speed-reactive audio with configurable clip, speed range, pitch, playback rate, volume, and playback mode.
|
||||
- Adaptive audio leveling with three configurable speed/multiplier points; manual media-volume changes remain the reference level.
|
||||
- Optional live music visualizer using the Android audio FFT callback.
|
||||
- Spectrum Bars, Oscilloscope, Speed Gauge Ring, and Ferrofluid visualizer effects.
|
||||
- Ferrofluid uses the Robert Leitl WebGL2 simulation as a transparent background layer;
|
||||
Android playback FFT bass energy drives its audio response. Devices without WebGL2
|
||||
automatically use the bundled GLES shader fallback.
|
||||
- Configurable visualizer framerate, subject to the head unit's supported capture rate.
|
||||
|
||||
### Settings and backup
|
||||
|
||||
- Centralized configuration store for themes, palettes, fonts, launcher options, pinned apps, trips, charging, vehicle defaults, key mappings, audio, and map cache settings.
|
||||
- Versioned, human-readable `mg-utility-settings.json` export/import through Android's document picker.
|
||||
- Reset-to-defaults action.
|
||||
- Automatic migration from legacy per-feature preference stores on upgrade.
|
||||
- Separate JSON, CSV, and HTML drive-log exports.
|
||||
|
||||
### Capability-gated vehicle settings
|
||||
|
||||
- Vehicle settings catalog covering captured drive/energy, assistance, convenience, lighting, trim-dependent, and status rows.
|
||||
- New installations default every row to **Do not change**.
|
||||
- Validated writable profiles are enabled only when the matching capability is detected.
|
||||
- Saved startup profiles apply once per ignition session only after positive ignition, Park, and stationary-speed checks.
|
||||
- Every one-way write is followed by a getter read-back.
|
||||
- Experimental parked regeneration level 5 action with acknowledgement, previous-value capture, verification, and restoration.
|
||||
- **Vehicle dashboard** — speed, estimated range, battery voltage, state of charge, energy counters, charging status, and connection state.
|
||||
- **Home replacement** — use MG Utility as the Android Home app with a configurable app drawer and quick-control panel.
|
||||
- **Media** — now-playing metadata, album art, playback controls, progress, and notification-based media integration.
|
||||
- **Trips and maps** — automatic trip tracking, drive history, route maps, statistics, regenerative-braking events, and JSON/CSV/HTML exports.
|
||||
- **Dashcam** — loop recording from the four factory cameras (native capture from [Tommasov/MG4_Dashcam](https://github.com/Tommasov/MG4_Dashcam), GPL-3.0), a storage budget, auto-delete after N days (default 30), "keep" ranges for whole drives, clips or marked parts that are never auto-deleted, and verified offload to a home server (`dashcam-archive/`).
|
||||
- **Charging tools** — editable `IF … THEN …` automation rules for SOC, price, and time windows, with Park and connection safeguards.
|
||||
- **Audio and visualizers** — speed-reactive audio, adaptive audio leveling, soundboard events, FFT visualizers, and Ferrofluid effects.
|
||||
- **Vehicle settings** — capability-detected settings with parked/stationary checks and getter read-back after writes.
|
||||
- **Customization** — themes, palettes, fonts, brightness schedules, key remapping, pinned apps, and control-panel layouts.
|
||||
- **Backup and plugins** — versioned settings export/import plus a scoped Java 8 plugin SDK and marketplace foundation.
|
||||
- **Local-first storage** — settings, trip history, reports, and the acceleration leaderboard remain on the head unit unless explicitly exported or an optional network feature is used.
|
||||
|
||||
## Compatibility
|
||||
|
||||
MG Utility targets Android-based SAIC/MG head units and uses capability detection rather than assuming every vehicle exposes the same private OEM interfaces.
|
||||
The **MG4 Luxury 2022** is the development and validation reference. Other MG/SAIC trims and firmware versions may expose different services and capabilities. The app detects unavailable OEM services and falls back to usable local features instead of assuming compatibility.
|
||||
|
||||
| Area | Expected behaviour |
|
||||
|---|---|
|
||||
| Dashboard UI, themes, settings, local history | Available on compatible Android head units running the app. |
|
||||
| Android Home replacement | Available where the head unit permits a third-party app to be selected as the default Home app. |
|
||||
| Media panel | Uses Android media/notification access; playback information depends on the media app and permissions. |
|
||||
| Vehicle values | Requires the vehicle's SAIC service and compatible exposed data paths. Otherwise the UI reports connecting/unavailable states. |
|
||||
| Automatic trips | Vehicle-only logging can work without GPS; route and location features require location permission, a usable fix, and suitable firmware. |
|
||||
| Charging automation | Requires compatible charging data/commands, a connected vehicle, Park, and electricity-price network access for price conditions. |
|
||||
| Maps | Requires internet access for tiles; route data can remain visible without map tiles. |
|
||||
| Audio visualizer | Requires Android audio-recording permission and a supported output-visualizer/FFT path. |
|
||||
| Vehicle settings | Only validated, capability-gated profiles are writable. Unknown firmware remains read-only. |
|
||||
| Physical keys | Works only for keys Android exposes to the foreground application; OEM-consumed keys may not be observable. |
|
||||
Minimum Android version: **API 28**. Live vehicle data requires the vehicle's exposed SAIC service. Maps and electricity-price conditions require network access; core dashboard and local history do not.
|
||||
|
||||
The **MG4 Luxury 2022** is the development and validation reference, not a promise that every MG trim exposes identical services or controls. Test on the specific vehicle before relying on any optional integration.
|
||||
## Install
|
||||
|
||||
## Safety boundaries
|
||||
|
||||
MG Utility deliberately keeps the risky surface small:
|
||||
|
||||
- The dashboard and exported vehicle data provider are read-only.
|
||||
- Vehicle writes are capability-gated and limited to validated profiles.
|
||||
- Automatic vehicle-profile writes require confirmed ignition/run state, Park, and speed at or below 0.5 km/h.
|
||||
- One-way vehicle setters require getter read-back before the app reports success.
|
||||
- ADAS, ESP/traction, safety systems, and hardware-moving commands are excluded or read-only.
|
||||
- Ambient lighting is excluded where the target hardware is absent.
|
||||
- Regeneration level 5 is experimental, parked-only, acknowledgement-gated, never a preset, and never an unattended startup value.
|
||||
- The app does not replace firmware, alter the OEM launcher permanently, or claim OEM approval.
|
||||
- Configure the app and acknowledge prompts only while parked. Keep control of the vehicle at all times.
|
||||
|
||||
## Install and first run
|
||||
|
||||
1. Obtain a build of `MG-Utility.apk` from a trusted source or build it locally using the instructions below.
|
||||
2. Install it on the Android head unit using the OEM-approved installation path.
|
||||
3. Open MG Utility once after installation. Open it once again after an update if Android has force-stopped the package.
|
||||
4. Grant only the permissions needed for the features you intend to use:
|
||||
1. Obtain `MG-Utility.apk` from a trusted release or build it locally.
|
||||
2. Install it on the Android head unit using the approved installation path.
|
||||
3. Open MG Utility and grant only the permissions needed for the features you use:
|
||||
- location for GPS routes and arrival areas;
|
||||
- notification access for media information;
|
||||
- audio recording for the live music visualizer;
|
||||
- any Android settings or Bluetooth permissions requested by enabled controls.
|
||||
5. If Android asks which Home app to use, select MG Utility and choose the default/always option if desired.
|
||||
6. Configure themes, pinned apps, the app drawer, control panel, and optional automation from **Settings**.
|
||||
7. If tracking does not resume after the car sleeps, enable the head unit's **Auto-start** permission and remove MG Utility from battery/task restrictions. Some OEM firmware force-stops third-party apps and suppresses their boot broadcasts.
|
||||
- audio recording for the live visualizer.
|
||||
4. Select MG Utility as the default Home app if desired.
|
||||
5. Configure the dashboard, apps, controls, trips, charging, and optional integrations in **Settings**.
|
||||
|
||||
The app is designed to coexist with the OEM software. Selecting it as Home does not uninstall or replace the underlying MG/SAIC applications.
|
||||
## Build
|
||||
|
||||
## Build from source
|
||||
Requirements: Linux, a JDK, Android SDK build-tools 34 or newer, an Android platform SDK, and the local signing keystore.
|
||||
|
||||
### Requirements
|
||||
|
||||
- Linux development environment with a JDK and Android SDK.
|
||||
- Android SDK build-tools 34 or newer and an Android platform SDK.
|
||||
- A local signing keystore. The repository's development keystore is intentionally not part of public artifacts and is ignored by Git.
|
||||
|
||||
### Build
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
```sh
|
||||
./build.sh
|
||||
```
|
||||
|
||||
Every ordinary build is a local Dev-channel build. It uses the stable base version
|
||||
with a `.0` suffix unless a release script supplies an explicit version:
|
||||
|
||||
```bash
|
||||
./build.sh
|
||||
```
|
||||
|
||||
Dev releases use the Vault-backed wrapper, which supplies `GITEA_TOKEN` only
|
||||
through the environment and verifies the downloaded release artifact:
|
||||
|
||||
```bash
|
||||
./scripts/release-dev.sh # next Dev release, including verification
|
||||
./scripts/release-dev.sh --dry-run # authenticated version calculation only
|
||||
```
|
||||
|
||||
Never store the token in `.env`, source, command arguments, or logs. Stable
|
||||
releases require explicit intent and use `scripts/release.sh --stable` with
|
||||
credentials supplied securely through the environment.
|
||||
|
||||
Stable releases use `X.Y.Z`. Dev releases use `X.Y.Z.N`, where `N` increments
|
||||
from the latest stable release. `--stable` increments the patch component and
|
||||
publishes both `X.Y.Z` and its first `X.Y.Z.1` Dev build. Android `versionCode`
|
||||
is assigned automatically above every existing release so channel switching
|
||||
never attempts an Android downgrade. The publisher creates a Gitea Release with
|
||||
the signed `MG-Utility.apk` and a machine-readable JSON release body containing
|
||||
the channel, branch, versionCode, versionName, and SHA-256 checksum. Dev
|
||||
releases are marked pre-release; Stable releases are normal releases.
|
||||
|
||||
When the Dev channel has no newer Dev build but a newer Stable release exists,
|
||||
the app presents that stable artifact as the equivalent Dev version `X.Y.Z.0`.
|
||||
The APK is byte-for-byte the Stable artifact; `.0` is only the Dev-channel
|
||||
presentation used to make the transition explicit.
|
||||
|
||||
The app reads releases from
|
||||
`https://git.molberg.cloud/api/v1/repos/alex/mg-utility` and only accepts HTTPS
|
||||
APK assets from `git.molberg.cloud` whose package name, version code, checksum,
|
||||
and signing certificate match the installed app. Keep `.env`, `GITEA_TOKEN`, and
|
||||
all signing material out of the repository.
|
||||
|
||||
### In-app updates
|
||||
|
||||
Open **Settings → Config → Software updates**. The page displays the installed
|
||||
version and its embedded channel/branch, lets the user choose **Dev** or
|
||||
**Stable**, and provides an immediate check/download/install action. Downloads
|
||||
are stored in app-private storage until verified. Android still displays its
|
||||
required final package-install confirmation (and the one-time “install unknown
|
||||
apps” permission on Android 8+).
|
||||
|
||||
**Notify on updates** is enabled by default. When enabled, MG Utility schedules
|
||||
a network-aware check approximately every six hours and repairs the schedule
|
||||
after boot or app replacement. A short, clickable notification opens the update
|
||||
page; disabling the toggle cancels the scheduled check.
|
||||
|
||||
The update page also lists the current build, newer releases, and up to five
|
||||
previous releases for the selected channel. Selecting an older release requires
|
||||
confirmation with a warning that configuration or other app-data changes may
|
||||
make features incompatible after downgrading.
|
||||
|
||||
The script compiles the Java sources and resources without Gradle, creates a signed APK, and writes:
|
||||
The signed APK is written to:
|
||||
|
||||
```text
|
||||
build/MG-Utility.apk
|
||||
```
|
||||
|
||||
The manifest currently targets Android API 28 and declares a minimum Android API level of 28, matching the development MG4 head unit. The app may run on newer Android versions, but OEM behaviour and private vehicle APIs must still be validated per vehicle.
|
||||
For the authenticated Dev release workflow:
|
||||
|
||||
Do not commit generated `build/` output, keystores, passwords, or other signing material.
|
||||
|
||||
## Permissions and privacy
|
||||
|
||||
MG Utility is local-first:
|
||||
|
||||
- Trip history, settings, key mappings, and the acceleration leaderboard are stored on the head unit.
|
||||
- The app does not upload trip logs or leaderboard records.
|
||||
- Settings and drive reports are exported only when the user explicitly chooses a destination through Android's document picker.
|
||||
- OpenStreetMap tiles and Strømligning price data require network access and are optional.
|
||||
- Review Android permission prompts and disable features whose permissions you do not want to grant.
|
||||
- No credentials or private signing material belong in this repository.
|
||||
|
||||
## Read-only vehicle data provider
|
||||
|
||||
The exported provider exposes one typed, read-only vehicle sample for a companion process or diagnostic tool:
|
||||
|
||||
```bash
|
||||
adb shell content call \
|
||||
--uri content://cloud.molberg.mgutility.vehicle \
|
||||
--method sample
|
||||
```sh
|
||||
./scripts/release-dev.sh
|
||||
```
|
||||
|
||||
The returned bundle can contain state of charge, estimated range, vehicle speed, battery voltage, consumption since charge, regenerated energy/range since vehicle start, and charging status. The first call after process startup may report `status=connecting`; retry after the service binding completes.
|
||||
|
||||
The provider accepts shell, root, or same-app callers through the declared dump permission. It implements no write methods and sends no vehicle-control Binder transactions.
|
||||
|
||||
## Development and testing
|
||||
|
||||
The repository includes a compatibility wrapper around the shared `mg4_api28` Android emulator workflow:
|
||||
The repository includes an API 28 emulator wrapper for UI and local-feature testing:
|
||||
|
||||
```bash
|
||||
```sh
|
||||
./emulator.sh start
|
||||
./emulator.sh install
|
||||
./emulator.sh launch
|
||||
@@ -299,72 +69,15 @@ The repository includes a compatibility wrapper around the shared `mg4_api28` An
|
||||
./emulator.sh stop
|
||||
```
|
||||
|
||||
The shared emulator is API 28, landscape 1920×720, and is intended for UI, database, service-lifecycle, map, and synthetic-GPS testing. For synthetic GPS, for example:
|
||||
The emulator does not include SAIC's proprietary vehicle service, so live vehicle integration must be validated on compatible hardware.
|
||||
|
||||
```bash
|
||||
adb -s emulator-5554 emu geo fix 12.5683 55.6761
|
||||
```
|
||||
## Documentation
|
||||
|
||||
The emulator does **not** contain SAIC's proprietary `com.saicmotor.service.vehicle.VehicleService`, so live vehicle values remain unavailable there. Vehicle-service integration must be validated on compatible hardware.
|
||||
- [Plugin SDK](docs/PLUGIN_SDK.md)
|
||||
- [Settings navigation](docs/settings-navigation.md)
|
||||
- [Vehicle settings reference](docs/STARTUP_VEHICLE_SETTINGS.md)
|
||||
- [Third-party notices](THIRD_PARTY_NOTICES.md)
|
||||
|
||||
## Troubleshooting
|
||||
## Limitations
|
||||
|
||||
### The dashboard shows connecting or unavailable vehicle values
|
||||
|
||||
Confirm that the target vehicle exposes the expected SAIC service and that the app is running on the intended head unit. This is a compatibility signal, not proof that the app is broken. The UI and local features remain usable without live OEM values.
|
||||
|
||||
### Trip tracking does not start after reboot or sleep
|
||||
|
||||
Open MG Utility once after installation/update, grant the requested setup permissions, then check Auto-start and battery/task restrictions in the OEM settings. The ongoing `MG Utility trip tracking` notification is the definitive indication that the tracker is running.
|
||||
|
||||
### Routes have no map background
|
||||
|
||||
The route line can be displayed without tiles. Check internet access and allow the OpenStreetMap tile request if a background map is required. OSM attribution is displayed in the map view.
|
||||
|
||||
### The music panel is empty
|
||||
|
||||
Enable the requested notification/media access and check that a supported media application is currently playing. Some OEM media implementations do not expose complete metadata.
|
||||
|
||||
### The visualizer is silent
|
||||
|
||||
Enable audio-recording permission and confirm that the selected visualizer effect is supported by the head unit. The visualizer uses real audio FFT callbacks and intentionally becomes silent when no output is available.
|
||||
|
||||
### A vehicle setting is unavailable
|
||||
|
||||
Unknown or unsupported profiles remain read-only by design. Do not force a setting or bypass the capability gate. Verify the vehicle trim, firmware, Park state, and stationary state first.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```text
|
||||
.
|
||||
├── AndroidManifest.xml # Package, permissions, Home intent, services, provider
|
||||
├── build.sh # Gradle-free signed APK build and verification
|
||||
├── emulator.sh # Compatibility wrapper for the API 28 emulator workflow
|
||||
├── docs/ # Supporting project documentation and screenshots
|
||||
├── res/ # Android resources and drawable assets
|
||||
├── src/ # Java application sources
|
||||
├── tests/ # Test and validation material
|
||||
└── README.md # This document
|
||||
```
|
||||
|
||||
## Plugin SDK and marketplace
|
||||
|
||||
MG Utility now includes a Java 8 plugin SDK and a built-in marketplace foundation. Plugins are
|
||||
separate APKs declaring `assets/mg-plugin.json`, implementing the SDK `Plugin` lifecycle, and
|
||||
contributing dashboard tiles, settings pages, key actions, or background work through scoped host
|
||||
registries. Plugin preferences are isolated by plugin ID and repository APKs must be HTTPS downloads
|
||||
with a matching SHA-256 checksum before installation.
|
||||
|
||||
Open **Settings → Config → Plugin marketplace** to add repository index URLs. A reserved official
|
||||
repository entry is shown as “coming soon”; the remote official repository itself has not been
|
||||
created. Existing speed-reactive audio, soundboard, and key-remapping features remain built into
|
||||
the app for now. Their extraction into plugins will happen after the host contracts are validated.
|
||||
|
||||
See [docs/PLUGIN_SDK.md](docs/PLUGIN_SDK.md) for the manifest format, lifecycle guidance, capability
|
||||
allow-list, repository schema, and a minimal plugin example.
|
||||
|
||||
## Status and limitations
|
||||
|
||||
MG Utility is a vehicle-specific Android integration project intended to be adaptable across SAIC-based MG cars. Its generic UI, local storage, launcher behaviour, and fallback paths are designed for broad use; live vehicle data and vehicle settings depend on private OEM services and the specific MG trim/firmware.
|
||||
|
||||
Before distributing a build publicly, test it on the target vehicle, review the requested permissions, confirm the Home-app behaviour, and validate that all vehicle-affecting actions remain parked-only and capability-gated. The development reference remains the MG4 Luxury 2022.
|
||||
MG Utility leaves the OEM software and firmware in place. Unknown vehicle capabilities remain read-only. Test every optional integration on the target vehicle before relying on it, and never operate the app in a way that distracts from driving.
|
||||
@@ -26,3 +26,24 @@ 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.
|
||||
|
||||
## MG4 Dashcam native capture
|
||||
|
||||
`vendor/mg4-dashcam/src/` (built into `lib/arm64-v8a/libmgdashcam.so`) is the native camera
|
||||
capture, grid compositor and encoder from
|
||||
[Tommasov/MG4_Dashcam](https://github.com/Tommasov/MG4_Dashcam), a fork of
|
||||
[jamakr4/MG4-360-Camera-App](https://github.com/jamakr4/MG4-360-Camera-App). Only the JNI symbol
|
||||
prefix and library name were changed. It statically links OpenCV 4.9.0 (Apache-2.0).
|
||||
|
||||
GNU General Public License v3.0. The full licence text is in `vendor/mg4-dashcam/LICENSE`.
|
||||
Because this code is distributed inside the MG Utility APK, builds that include it are subject to
|
||||
the GPL-3.0 terms; the corresponding source is in this repository.
|
||||
@@ -13,7 +13,11 @@ TOOLS=$(find "$SDK/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail
|
||||
ANDROID_JAR=$(find "$SDK/platforms" -mindepth 2 -maxdepth 2 -name android.jar -type f | sort -V | tail -n 1)
|
||||
OUT="$ROOT/build"
|
||||
APK="$OUT/MG-Utility.apk"
|
||||
KEYSTORE="$ROOT/mg-utility.keystore"
|
||||
# Signed with the head unit's platform key (public AOSP test key, which the MG4
|
||||
# ships with). Together with android:sharedUserId="android.uid.system" this is
|
||||
# what grants access to /dev/video*. Same approach as Tommasov/MG4_Dashcam.
|
||||
PLATFORM_KEY=${PLATFORM_KEY:-"$ROOT/signing/platform.pk8"}
|
||||
PLATFORM_CERT=${PLATFORM_CERT:-"$ROOT/signing/platform.x509.pem"}
|
||||
BASE_VERSION=$(sed -n 's/.*android:versionName="\([^"]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1)
|
||||
BASE_CODE=$(sed -n 's/.*android:versionCode="\([0-9]*\)".*/\1/p' "$ROOT/AndroidManifest.xml" | head -n 1)
|
||||
BRANCH=${UPDATE_BRANCH:-$(git -C "$ROOT" branch --show-current 2>/dev/null || true)}
|
||||
@@ -32,6 +36,10 @@ case "$BUILD_VERSION_CODE" in
|
||||
esac
|
||||
[ "$BUILD_VERSION_CODE" -le 2147483647 ] || { echo "versionCode must fit Android's signed 32-bit limit" >&2; exit 2; }
|
||||
|
||||
if [ ! -f "$PLATFORM_KEY" ] || [ ! -f "$PLATFORM_CERT" ]; then
|
||||
echo "Platform signing key missing: $PLATFORM_KEY / $PLATFORM_CERT" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "$TOOLS" ] || [ -z "$ANDROID_JAR" ]; then
|
||||
echo "Android SDK build-tools and a platform are required (set ANDROID_HOME)." >&2
|
||||
exit 1
|
||||
@@ -47,6 +55,10 @@ if [ ! -f "$AAR" ] || [ ! -f "$KOTLIN_STDLIB" ]; then
|
||||
fi
|
||||
unzip -q -o "$AAR" 'classes.jar' 'jni/arm64-v8a/*.so' -d "$OUT/vendor/sherpa"
|
||||
cp "$OUT/vendor/sherpa/jni/arm64-v8a/"*.so "$OUT/lib/arm64-v8a/"
|
||||
# Dashcam capture/encoder (Tommasov/MG4_Dashcam, GPL-3.0). Rebuild with vendor/mg4-dashcam/build-native.sh.
|
||||
DASHCAM_SO="$ROOT/vendor/mg4-dashcam/prebuilt/arm64-v8a/libmgdashcam.so"
|
||||
[ -f "$DASHCAM_SO" ] || { echo "Missing $DASHCAM_SO" >&2; exit 1; }
|
||||
cp "$DASHCAM_SO" "$OUT/lib/arm64-v8a/"
|
||||
rm -rf "$OUT/vendor/sherpa/jni"
|
||||
cp -R "$ROOT/assets/sherpa-en" "$OUT/assets/"
|
||||
mkdir -p "$OUT/sherpa-classes"
|
||||
@@ -68,8 +80,8 @@ cp "$OUT/resources.apk" "$OUT/MG-Utility-unsigned.apk"
|
||||
"$TOOLS/zipalign" -f 4 "$OUT/MG-Utility-unsigned.apk" "$APK"
|
||||
rm -f "$APK.idsig"
|
||||
"$TOOLS/apksigner" sign \
|
||||
--ks "$KEYSTORE" --ks-pass pass:android --ks-key-alias androiddebugkey --key-pass pass:android \
|
||||
--key "$PLATFORM_KEY" --cert "$PLATFORM_CERT" \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--v4-signing-enabled false --min-sdk-version 23 "$APK"
|
||||
"$TOOLS/apksigner" verify -v --min-sdk-version 23 "$APK"
|
||||
"$TOOLS/apksigner" verify -v --print-certs --min-sdk-version 23 "$APK"
|
||||
echo "Built $APK"
|
||||
@@ -0,0 +1,76 @@
|
||||
# Dashcam archive server
|
||||
|
||||
Long-term storage for MG Utility dashcam clips. Single-file Python (stdlib only) service.
|
||||
|
||||
Running instance: CT112 `dashcam-archive` on pve, `http://10.0.0.148:8780` (DHCP reservation on
|
||||
the Flint), data on a 1 TiB `pvepool` volume mounted at `/srv/dashcam` (`backup=0`). Also published
|
||||
through the pve Cloudflare tunnel as `https://dashcam.molberg.cloud` for hotspot uploads; every
|
||||
request still needs the bearer token. The bearer
|
||||
token is in Vaultwarden as **MG Utility dashcam archive (CT112)** and in
|
||||
`/etc/mg-dashcam-archive.env` (0600) inside the CT.
|
||||
|
||||
## Car-side setup
|
||||
|
||||
Settings → Driving → Dashcam → Storage & offload:
|
||||
|
||||
- Server URL: `http://10.0.0.148:8780`
|
||||
- Access token: the Vault value
|
||||
- Offload finished clips automatically: ON
|
||||
|
||||
Defaults are pre-filled: home URL `http://10.0.0.148:8780`, remote URL
|
||||
`https://dashcam.molberg.cloud`. The car counts as **home** when the archive answers on the LAN
|
||||
URL (impossible over a phone hotspot). At home, offload runs automatically every two minutes.
|
||||
Away, nothing uploads until OFFLOAD NOW is pressed, which shows the size and confirms first.
|
||||
Uploads are chunked (16 MB away, 64 MB home) and resumable, so a dropped hotspot resumes. Each clip is hashed on the car, the server
|
||||
re-hashes what it received and only commits a matching file, and the car only frees the local copy
|
||||
after a fresh `GET` reports the same size and SHA-256.
|
||||
|
||||
## Web dashboard
|
||||
|
||||
`https://dashcam.molberg.cloud/` (or `http://10.0.0.148:8780/` at home) redirects to a login form.
|
||||
Sign in with the access token; "keep me signed in" gives a 30-day session cookie (HttpOnly,
|
||||
SameSite=Strict, Secure over HTTPS), otherwise 12 hours. Failed logins are rate-limited (10 per
|
||||
IP / 50 total per 15 min). The menu has "Sign out everywhere".
|
||||
|
||||
Tabs:
|
||||
- **Overview**: alerts (car offline, disk nearly full, ffmpeg missing), KPIs, storage meter,
|
||||
recorded-per-day chart with event markers, upload volume, time-of-day heatmap, weekday chart,
|
||||
latest events and recent drives.
|
||||
- **Events**: thumbnail gallery of locked events; play, download, delete (to `.trash`, 7 days).
|
||||
- **Drives**: clips grouped into drives with date filter; play a whole drive back to back with a
|
||||
real wall clock, 1-8x speed, keep the drive, a clip or a marked part, download a drive as a zip.
|
||||
- **Kept**: car and web keep ranges with the clips they protect; web ranges can be removed.
|
||||
- **Storage**: disk ring, breakdown, intake rate, days-until-full, what expires in 24 h / 7 days.
|
||||
|
||||
Drive logs: each clip can carry `<clip>.mp4.json` (uploaded by the car via
|
||||
`PUT /api/telemetry/<clip>`) with speed, battery, range, gear and GPS samples. The player shows a
|
||||
synced speed/battery/gear readout, a route map with a moving position marker and a clickable speed
|
||||
graph. Drives show distance, top speed and battery used; events show the speed and position at the
|
||||
press. Map tiles come from OpenStreetMap through the server (`/tiles/z/x/y.png`, cached 30 days in
|
||||
`/srv/dashcam/.tiles`), so the page itself never talks to a third party.
|
||||
|
||||
Parked footage: clips the car marks `"mode":"parked"` are drawn separately and can have a shorter
|
||||
server retention (`parked_retention_days`, synced from the car).
|
||||
|
||||
Thumbnails and exact durations need `ffmpeg`/`ffprobe` on the server (installed on CT112).
|
||||
Videos stream with HTTP Range support, so seeking and iOS Safari work. Web keep ranges protect the
|
||||
server copy only; they are not pushed back to the car.
|
||||
|
||||
## Retention
|
||||
|
||||
The car sends its keep ranges and auto-delete age with every offload (`PUT /api/keep`). Hourly,
|
||||
the server deletes clips older than that age **unless** they overlap a keep range, and rebuilds
|
||||
`/srv/dashcam/kept/<label>/` as hard links to the kept clips for easy browsing. Locked events in
|
||||
`events/` are never touched by retention.
|
||||
|
||||
## Deploy / update
|
||||
|
||||
```sh
|
||||
TMPD=$(ssh pve mktemp -d)
|
||||
tar czf /tmp/d.tgz server.py static && scp /tmp/d.tgz mg-dashcam-archive.service pve:$TMPD/
|
||||
ssh pve "pct push 112 $TMPD/d.tgz /tmp/d.tgz"
|
||||
ssh pve "pct exec 112 -- tar xzf /tmp/d.tgz -C /opt/mg-dashcam-archive"
|
||||
ssh pve "pct push 112 $TMPD/mg-dashcam-archive.service /etc/systemd/system/mg-dashcam-archive.service"
|
||||
ssh pve "pct exec 112 -- systemctl daemon-reload"
|
||||
ssh pve "pct exec 112 -- systemctl restart mg-dashcam-archive"
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=MG Utility dashcam archive
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
User=dashcam
|
||||
Group=dashcam
|
||||
EnvironmentFile=/etc/mg-dashcam-archive.env
|
||||
ExecStart=/usr/bin/python3 /opt/mg-dashcam-archive/server.py
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/srv/dashcam
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,148 @@
|
||||
:root {
|
||||
--bg: #090d12; --surface: #121a22; --surface2: #1a242e; --line: #26323d;
|
||||
--text: #eef3f6; --muted: #8fa1af; --cyan: #2ddaeb; --red: #ee3139; --amber: #f5ad4e;
|
||||
--green: #40cf99; --blue: #5aaee0; --violet: #a68cf0; --r: 12px;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; background: var(--bg); color: var(--text);
|
||||
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
||||
a { color: var(--cyan); text-decoration: none; }
|
||||
button, .btn, select, input { font: inherit; color: inherit; }
|
||||
button, .btn { cursor: pointer; border: 1px solid var(--line); background: var(--surface2); border-radius: 8px;
|
||||
padding: 8px 14px; display: inline-flex; align-items: center; gap: 6px; }
|
||||
button:hover, .btn:hover { border-color: var(--cyan); }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
.primary { background: var(--red); border-color: var(--red); color: #fff; font-weight: 600; }
|
||||
.primary:hover { background: #ff4a52; border-color: #ff4a52; }
|
||||
.ghost { background: transparent; }
|
||||
.small { padding: 5px 10px; font-size: 13px; }
|
||||
.wide { width: 100%; justify-content: center; padding: 12px; }
|
||||
.muted { color: var(--muted); }
|
||||
small, .small { font-size: 12px; }
|
||||
select, input[type=text], input[type=password], input[type=date], input[type=search] {
|
||||
background: var(--surface2); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; }
|
||||
input:focus, select:focus { outline: 2px solid var(--cyan); outline-offset: 0; }
|
||||
|
||||
/* login */
|
||||
.login-body { min-height: 100vh; display: grid; place-items: center; padding: 20px;
|
||||
background: radial-gradient(circle at 30% 10%, #13303a 0, transparent 50%), var(--bg); }
|
||||
.login-card { width: 100%; max-width: 400px; background: var(--surface); border: 1px solid var(--line);
|
||||
border-radius: 18px; padding: 30px; box-shadow: 0 20px 60px #0008; }
|
||||
.login-card h1 { margin: 22px 0 4px; font-size: 22px; }
|
||||
.login-card label { display: block; margin: 18px 0 6px; font-weight: 600; }
|
||||
.login-card .check { display: flex; gap: 8px; align-items: center; font-weight: 400; color: var(--muted); }
|
||||
.login-card form button.primary { margin-top: 20px; }
|
||||
.pw { display: flex; gap: 8px; } .pw input { flex: 1; min-width: 0; }
|
||||
.err { color: var(--red); min-height: 1.4em; margin: 10px 0 0; }
|
||||
|
||||
/* chrome */
|
||||
.brand { display: flex; gap: 10px; align-items: center; }
|
||||
.brand b { display: block; font-size: 16px; } .brand span { display: block; color: var(--muted); font-size: 12px; }
|
||||
.top { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 20px; padding: 12px 22px;
|
||||
background: #090d12e6; backdrop-filter: blur(8px); border-bottom: 1px solid var(--line); }
|
||||
nav { display: flex; gap: 4px; flex: 1; overflow-x: auto; }
|
||||
nav button { border: 0; background: transparent; color: var(--muted); padding: 8px 14px; border-radius: 8px; white-space: nowrap; }
|
||||
nav button.on { color: var(--text); background: var(--surface2); box-shadow: inset 0 -2px 0 var(--cyan); }
|
||||
.top-right { display: flex; align-items: center; gap: 8px; }
|
||||
.pill { padding: 4px 10px; border-radius: 99px; font-size: 12px; background: var(--surface2); border: 1px solid var(--line); white-space: nowrap; }
|
||||
.pill.ok { color: var(--green); border-color: #2b6b55; } .pill.warn { color: var(--amber); border-color: #6b5530; }
|
||||
.pill.bad { color: var(--red); border-color: #6b2b2f; }
|
||||
.menu { position: relative; }
|
||||
.menu-pop { position: absolute; right: 0; top: 40px; background: var(--surface); border: 1px solid var(--line);
|
||||
border-radius: 10px; padding: 6px; display: flex; flex-direction: column; min-width: 190px; box-shadow: 0 10px 30px #0009; }
|
||||
.menu-pop[hidden], .toast[hidden] { display: none; }
|
||||
.menu-pop button { border: 0; background: transparent; justify-content: flex-start; }
|
||||
.menu-pop button:hover { background: var(--surface2); }
|
||||
main { padding: 22px; max-width: 1500px; margin: 0 auto; }
|
||||
.tab { display: none; } .tab.on { display: block; }
|
||||
h2 { font-size: 15px; margin: 26px 0 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .08em; font-weight: 600; }
|
||||
h2:first-child { margin-top: 0; }
|
||||
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
|
||||
.spacer { flex: 1; }
|
||||
|
||||
/* cards */
|
||||
.grid { display: grid; gap: 14px; }
|
||||
.kpis { grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); }
|
||||
.two { grid-template-columns: 1fr 1fr; } .three { grid-template-columns: 2fr 1fr; }
|
||||
@media (max-width: 900px) { .two, .three { grid-template-columns: 1fr; } .top { flex-wrap: wrap; } nav { order: 3; flex-basis: 100%; } }
|
||||
.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); padding: 16px; min-width: 0; }
|
||||
.kpi .v { font-size: 26px; font-weight: 700; margin-top: 4px; } .kpi .l { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.kpi .s { color: var(--muted); font-size: 12px; margin-top: 2px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14px; }
|
||||
.alert { border-color: #6b5530; background: #1d1810; }
|
||||
|
||||
/* meters */
|
||||
.meter { height: 14px; border-radius: 99px; background: var(--surface2); overflow: hidden; display: flex; }
|
||||
.meter > i { display: block; height: 100%; }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 10px; font-size: 12px; color: var(--muted); }
|
||||
.legend span::before { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 6px; background: var(--c); vertical-align: -1px; }
|
||||
.ring-wrap { display: flex; gap: 20px; align-items: center; }
|
||||
.ring-wrap .big { font-size: 30px; font-weight: 700; }
|
||||
.c-clips { --c: var(--blue); } .c-kept { --c: var(--green); } .c-events { --c: var(--red); } .c-other { --c: #2c3741; } .c-parked { --c: #7d8b99; } .c-free { --c: var(--surface2); }
|
||||
|
||||
/* charts */
|
||||
svg.chart { width: 100%; height: auto; display: block; }
|
||||
svg.chart text { fill: var(--muted); font-size: 10px; }
|
||||
svg.chart .grid-l { stroke: var(--line); stroke-width: 1; }
|
||||
.heat { display: grid; grid-template-columns: repeat(24, 1fr); gap: 3px; }
|
||||
.heat i { aspect-ratio: 1; border-radius: 3px; background: var(--cyan); }
|
||||
.heat-l { display: grid; grid-template-columns: repeat(24, 1fr); font-size: 10px; color: var(--muted); margin-top: 4px; }
|
||||
|
||||
/* galleries */
|
||||
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 14px; }
|
||||
.tile { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; cursor: pointer; }
|
||||
.tile:hover { border-color: var(--cyan); }
|
||||
.tile .th { position: relative; aspect-ratio: 1440 / 1040; background: #141c24; }
|
||||
.tile img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.tile .badge { position: absolute; left: 8px; top: 8px; }
|
||||
.tile .dur { position: absolute; right: 8px; bottom: 8px; background: #000b; padding: 2px 7px; border-radius: 6px; font-size: 12px; }
|
||||
.tile .meta { padding: 10px 12px; } .tile .meta b { display: block; }
|
||||
.badge { padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 700; letter-spacing: .04em; }
|
||||
.b-event { background: var(--red); color: #fff; } .b-kept { background: var(--green); color: #052; }
|
||||
.b-web { background: var(--violet); color: #fff; } .b-car { background: var(--blue); color: #012; }
|
||||
.list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.drive { display: grid; grid-template-columns: 160px 1fr auto; gap: 14px; align-items: center; background: var(--surface);
|
||||
border: 1px solid var(--line); border-radius: var(--r); padding: 10px; }
|
||||
.drive img { width: 160px; aspect-ratio: 1440/1040; object-fit: cover; border-radius: 8px; cursor: pointer; background: #141c24; }
|
||||
.drive .acts { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
@media (max-width: 700px) { .drive { grid-template-columns: 100px 1fr; } .drive img { width: 100px; } .drive .acts { grid-column: 1 / -1; justify-content: flex-start; } }
|
||||
.daybar { position: sticky; top: 62px; background: var(--bg); padding: 8px 0 4px; color: var(--muted); font-weight: 600; z-index: 1; }
|
||||
.empty { padding: 40px; text-align: center; color: var(--muted); border: 1px dashed var(--line); border-radius: var(--r); }
|
||||
table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); }
|
||||
th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; }
|
||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* player */
|
||||
.modal { position: fixed; inset: 0; background: #000c; z-index: 20; display: grid; place-items: center; padding: 16px; }
|
||||
.modal[hidden] { display: none; }
|
||||
.modal-card { width: min(1200px, 100%); max-height: 100%; overflow: auto; background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 14px; }
|
||||
.modal-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
|
||||
.modal-head b { margin-right: 10px; }
|
||||
video { width: 100%; max-height: 68vh; background: #000; border-radius: 10px; display: block; }
|
||||
.pgrid { display: grid; grid-template-columns: 1fr; gap: 12px; }
|
||||
.pgrid.has-tel { grid-template-columns: minmax(0, 2.2fr) minmax(260px, 1fr); }
|
||||
@media (max-width: 900px) { .pgrid.has-tel { grid-template-columns: 1fr; } }
|
||||
.tel { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||
.tel[hidden] { display: none; }
|
||||
.readouts { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.readouts div { background: var(--surface2); border-radius: 8px; padding: 8px 10px; }
|
||||
.readouts .l { display: block; font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
|
||||
.readouts b { font-size: 20px; font-variant-numeric: tabular-nums; }
|
||||
.map { position: relative; overflow: hidden; border-radius: 10px; background: #1b232b; flex: 1; min-height: 220px; }
|
||||
.map img { position: absolute; width: 256px; height: 256px; user-select: none; -webkit-user-drag: none; filter: brightness(.8) saturate(.7); }
|
||||
.map svg { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }
|
||||
.map .attr { position: absolute; right: 4px; bottom: 2px; font-size: 10px; color: #ccc; background: #0009; padding: 0 4px; border-radius: 3px; }
|
||||
#speedchart svg { cursor: pointer; }
|
||||
.b-parked { background: #4a5966; color: #dde; }
|
||||
.stats { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--muted); margin-top: 3px; }
|
||||
.stats b { color: var(--text); font-weight: 600; }
|
||||
.bigmap { height: 420px; }
|
||||
.pbar { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.pbtns { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.clock { font: 600 20px ui-monospace, monospace; }
|
||||
.strip { display: flex; gap: 6px; overflow-x: auto; margin-top: 10px; padding-bottom: 4px; }
|
||||
.strip button { flex: 0 0 auto; font-size: 12px; padding: 6px 10px; }
|
||||
.strip button.on { border-color: var(--cyan); color: var(--cyan); }
|
||||
.strip button.k { box-shadow: inset 0 -3px 0 var(--green); }
|
||||
.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: var(--surface2); border: 1px solid var(--line);
|
||||
padding: 10px 16px; border-radius: 10px; z-index: 30; box-shadow: 0 10px 30px #000a; }
|
||||
@@ -0,0 +1,562 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var S = null; // last summary
|
||||
var player = {list: [], i: 0, markIn: null, markOut: null};
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
function $(id) { return document.getElementById(id); }
|
||||
function h(tag, attrs, kids) {
|
||||
var e = document.createElement(tag);
|
||||
if (attrs) for (var k in attrs) {
|
||||
if (k === 'class') e.className = attrs[k];
|
||||
else if (k === 'text') e.textContent = attrs[k];
|
||||
else if (k.slice(0, 2) === 'on') e.addEventListener(k.slice(2), attrs[k]);
|
||||
else if (k === 'style') e.style.cssText = attrs[k]; // CSSOM: allowed under style-src 'self'
|
||||
else e.setAttribute(k, attrs[k]);
|
||||
}
|
||||
(kids || []).forEach(function (c) { if (c != null) e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); });
|
||||
return e;
|
||||
}
|
||||
function svg(tag, attrs, kids) {
|
||||
var e = document.createElementNS('http://www.w3.org/2000/svg', tag);
|
||||
for (var k in attrs || {}) e.setAttribute(k, attrs[k]);
|
||||
(kids || []).forEach(function (c) { if (c) e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); });
|
||||
return e;
|
||||
}
|
||||
function bytes(b) {
|
||||
if (b == null) return '–';
|
||||
var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0;
|
||||
while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; }
|
||||
return (b >= 100 || i === 0 ? b.toFixed(0) : b.toFixed(1)) + ' ' + u[i];
|
||||
}
|
||||
function dur(s) {
|
||||
if (s == null) return '–';
|
||||
s = Math.round(s);
|
||||
var hh = Math.floor(s / 3600), mm = Math.floor(s % 3600 / 60), ss = s % 60;
|
||||
if (hh) return hh + 'h ' + mm + 'm';
|
||||
if (mm) return mm + 'm ' + (ss ? ss + 's' : '');
|
||||
return ss + 's';
|
||||
}
|
||||
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||||
function hms(ms) { var d = new Date(ms); return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); }
|
||||
function hm(ms) { var d = new Date(ms); return pad(d.getHours()) + ':' + pad(d.getMinutes()); }
|
||||
function day(ms) { return new Date(ms).toLocaleDateString(undefined, {weekday: 'short', day: 'numeric', month: 'short', year: 'numeric'}); }
|
||||
function dayKey(ms) { var d = new Date(ms); return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); }
|
||||
function ago(ms) {
|
||||
if (!ms) return 'never';
|
||||
var s = (Date.now() - ms) / 1000;
|
||||
if (s < 90) return 'just now';
|
||||
if (s < 5400) return Math.round(s / 60) + ' min ago';
|
||||
if (s < 172800) return Math.round(s / 3600) + ' h ago';
|
||||
return Math.round(s / 86400) + ' days ago';
|
||||
}
|
||||
function toast(t) {
|
||||
var e = $('toast'); e.textContent = t; e.hidden = false;
|
||||
clearTimeout(toast.t); toast.t = setTimeout(function () { e.hidden = true; }, 3500);
|
||||
}
|
||||
function api(method, url, body) {
|
||||
return fetch(url, {method: method, credentials: 'same-origin',
|
||||
headers: {'Content-Type': 'application/json', 'X-Requested-With': 'dashcam'},
|
||||
body: body ? JSON.stringify(body) : undefined})
|
||||
.then(function (r) {
|
||||
if (r.status === 401) { location.replace('/login'); throw new Error('signed out'); }
|
||||
return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || r.status); return b; });
|
||||
});
|
||||
}
|
||||
function card(cls, kids) { return h('div', {class: 'card ' + (cls || '')}, kids); }
|
||||
function kpi(label, value, sub) {
|
||||
return card('kpi', [h('div', {class: 'l', text: label}), h('div', {class: 'v', text: value}), sub ? h('div', {class: 's', text: sub}) : null]);
|
||||
}
|
||||
function clipUrl(n) { return '/clips/' + encodeURIComponent(n); }
|
||||
function thumbUrl(n) { return '/thumb/' + encodeURIComponent(n); }
|
||||
|
||||
// ------------------------------------------------------------------ tabs
|
||||
document.querySelectorAll('#tabs button').forEach(function (b) {
|
||||
b.onclick = function () { showTab(b.dataset.tab); };
|
||||
});
|
||||
function showTab(t) {
|
||||
document.querySelectorAll('#tabs button').forEach(function (b) { b.classList.toggle('on', b.dataset.tab === t); });
|
||||
document.querySelectorAll('.tab').forEach(function (s) { s.classList.toggle('on', s.id === t); });
|
||||
if (location.hash !== '#' + t) history.replaceState(null, '', '#' + t);
|
||||
}
|
||||
$('menubtn').onclick = function (e) { e.stopPropagation(); $('menu').hidden = !$('menu').hidden; };
|
||||
document.addEventListener('click', function () { $('menu').hidden = true; });
|
||||
$('logout').onclick = function () { api('POST', '/api/web/logout').finally(function () { location.replace('/login'); }); };
|
||||
$('logoutall').onclick = function () {
|
||||
if (confirm('Sign out every browser that is signed in to the dashboard?'))
|
||||
api('POST', '/api/web/logout-all').finally(function () { location.replace('/login'); });
|
||||
};
|
||||
$('refresh').onclick = function () { load(true); };
|
||||
|
||||
// ------------------------------------------------------------------ load
|
||||
function load(manual) {
|
||||
return fetch('/api/web/summary', {credentials: 'same-origin'}).then(function (r) {
|
||||
if (r.status === 401) { location.replace('/login'); throw new Error('signed out'); }
|
||||
return r.json();
|
||||
}).then(function (s) {
|
||||
S = s;
|
||||
render();
|
||||
if (manual) toast('Updated');
|
||||
}).catch(function (e) { if (e.message !== 'signed out') toast('Could not load: ' + e.message); });
|
||||
}
|
||||
|
||||
function render() {
|
||||
var st = S.status, seen = st.car_seen;
|
||||
var pill = $('carstate');
|
||||
var age = seen ? (Date.now() - seen) / 1000 : Infinity;
|
||||
pill.className = 'pill ' + (age < 600 ? 'ok' : age < 86400 * 3 ? 'warn' : 'bad');
|
||||
pill.textContent = seen ? 'Car seen ' + ago(seen) : 'Car never connected';
|
||||
$('sub').textContent = S.totals.clips + ' clips · ' + S.totals.events + ' events';
|
||||
renderOverview(); renderEvents(); renderDrives(); renderKept(); renderStorage();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ overview
|
||||
function storageMeter(big) {
|
||||
var d = S.disk, other = Math.max(0, d.used - d.clips - d.kept - d.events - (d.parked || 0));
|
||||
var parts = [['c-events', d.events, 'Events'], ['c-kept', d.kept, 'Kept'], ['c-clips', d.clips, 'Driving'], ['c-parked', d.parked || 0, 'Parked'], ['c-other', other, 'Other']];
|
||||
var m = h('div', {class: 'meter', style: big ? 'height:22px' : ''});
|
||||
parts.forEach(function (p) { if (p[1] > 0) m.appendChild(h('i', {class: p[0], style: 'background:var(--c);width:' + (100 * p[1] / d.total) + '%', title: p[2] + ' ' + bytes(p[1])})); });
|
||||
var lg = h('div', {class: 'legend'});
|
||||
parts.forEach(function (p) { lg.appendChild(h('span', {class: p[0], text: p[2] + ' ' + bytes(p[1])})); });
|
||||
lg.appendChild(h('span', {class: 'c-free', text: 'Free ' + bytes(d.free)}));
|
||||
return [m, lg];
|
||||
}
|
||||
|
||||
function renderOverview() {
|
||||
var el = $('overview'); el.innerHTML = '';
|
||||
var t = S.totals, f = S.forecast, d = S.disk;
|
||||
var alerts = [];
|
||||
if (S.status.car_seen && Date.now() - S.status.car_seen > 3 * 86400000) alerts.push('The car has not contacted the archive for ' + ago(S.status.car_seen).replace(' ago', '') + '.');
|
||||
if (d.free / d.total < 0.1) alerts.push('Archive disk is over 90% full.');
|
||||
if (f.days_until_full != null && f.days_until_full < 30) alerts.push('At the current rate the archive fills in about ' + Math.round(f.days_until_full) + ' days.');
|
||||
if (!S.server.ffmpeg) alerts.push('ffmpeg is not installed on the server: thumbnails and exact durations are unavailable.');
|
||||
alerts.forEach(function (a) { el.appendChild(card('alert', [h('b', {text: '⚠ '}), a])); });
|
||||
if (alerts.length) el.appendChild(h('div', {style: 'height:14px'}));
|
||||
|
||||
el.appendChild(h('div', {class: 'grid kpis'}, [
|
||||
kpi('Locked events', String(t.events), dur(t.event_s) + ' of footage'),
|
||||
kpi('Drives archived', String(t.drives), t.drives ? 'avg ' + dur(t.avg_drive_s) + ', longest ' + dur(t.longest_drive_s) : ''),
|
||||
kpi('Footage', dur(t.footage_s), t.clips + ' clips' + (t.parked_s ? ' · ' + dur(t.parked_s) + ' parked' : '')),
|
||||
kpi('Distance logged', (t.km || 0).toFixed(0) + ' km', t.top_kmh ? 'top speed ' + Math.round(t.top_kmh) + ' km/h' : (t.with_tel ? '' : 'appears once the car uploads drive logs')),
|
||||
kpi('Archive used', bytes(d.used), bytes(d.free) + ' free of ' + bytes(d.total)),
|
||||
kpi('Last upload', ago(S.status.last_upload), S.status.keep_sync ? 'keep list synced ' + ago(S.status.keep_sync) : 'keep list not synced yet'),
|
||||
kpi('Retention', S.retention_days ? S.retention_days + ' days' : 'Off', f.expiring_7d ? bytes(f.expiring_7d) + ' expires within 7 days' : 'nothing expiring this week')
|
||||
]));
|
||||
|
||||
el.appendChild(h('h2', {text: 'Storage'}));
|
||||
el.appendChild(card('', storageMeter(true)));
|
||||
|
||||
el.appendChild(h('div', {class: 'grid three', style: 'margin-top:14px'}, [
|
||||
card('', [h('h3', {text: 'Recorded per day (last 30 days)'}), barChart(S.per_day.map(function (x) { return x.rec_s / 60; }), S.per_day.map(function (x) { return x.day; }), 'min', 'var(--cyan)', S.per_day.map(function (x) { return x.events; }))]),
|
||||
card('', [h('h3', {text: 'Latest events'}), latestEvents()])
|
||||
]));
|
||||
|
||||
el.appendChild(h('div', {class: 'grid two', style: 'margin-top:14px'}, [
|
||||
card('', [h('h3', {text: 'Distance per day'}), barChart(S.per_day.map(function (x) { return x.km || 0; }), S.per_day.map(function (x) { return x.day; }), 'km', 'var(--green)'),
|
||||
h('h3', {text: 'Uploaded per day', style: 'margin-top:16px'}), barChart(S.per_day.map(function (x) { return x.bytes_up / 1073741824; }), S.per_day.map(function (x) { return x.day; }), 'GB', 'var(--blue)')]),
|
||||
card('', [h('h3', {text: 'When you drive (time of day)'}), heat(S.by_hour), h('h3', {text: 'Day of week', style: 'margin-top:16px'}), weekBars(S.by_weekday)])
|
||||
]));
|
||||
|
||||
var recent = S.drives.slice(0, 6);
|
||||
el.appendChild(h('h2', {text: 'Recent drives'}));
|
||||
el.appendChild(recent.length ? h('div', {class: 'list'}, recent.map(driveRow)) : h('div', {class: 'empty', text: 'No drives uploaded yet. Clips appear here once the car offloads at home or you press OFFLOAD NOW.'}));
|
||||
}
|
||||
|
||||
function latestEvents() {
|
||||
if (!S.events.length) return h('p', {class: 'muted', text: 'No locked events. Use “Lock dashcam event” in the car’s control panel to save 2 min before + 1 min after.'});
|
||||
return h('div', {class: 'list'}, S.events.slice(0, 4).map(function (e) {
|
||||
return h('div', {class: 'row', style: 'cursor:pointer', onclick: function () { openEvent(e); }}, [
|
||||
h('img', {src: thumbUrl(e.name), alt: '', loading: 'lazy', style: 'width:96px;border-radius:6px;aspect-ratio:1440/1040;object-fit:cover'}),
|
||||
h('div', {}, [h('b', {text: day(e.click)}), h('div', {class: 'muted small', text: 'pressed ' + hms(e.click) + ' · ' + dur(e.dur) + ' · ' + bytes(e.size)})])
|
||||
]);
|
||||
}));
|
||||
}
|
||||
|
||||
function barChart(vals, labels, unit, color, marks) {
|
||||
var W = 600, H = 170, P = 28, n = vals.length, max = Math.max.apply(null, vals.concat([0.001]));
|
||||
var nice = niceMax(max), bw = (W - P - 6) / n;
|
||||
var g = svg('svg', {viewBox: '0 0 ' + W + ' ' + H, class: 'chart', role: 'img'});
|
||||
for (var i = 0; i <= 4; i++) {
|
||||
var y = 10 + (H - 30) * i / 4;
|
||||
g.appendChild(svg('line', {x1: P, x2: W, y1: y, y2: y, class: 'grid-l'}));
|
||||
g.appendChild(svg('text', {x: P - 4, y: y + 3, 'text-anchor': 'end'}, [fmtNum(nice * (1 - i / 4))]));
|
||||
}
|
||||
vals.forEach(function (v, i) {
|
||||
var bh = (H - 30) * v / nice, x = P + 3 + i * bw;
|
||||
var r = svg('rect', {x: x + 1, y: H - 20 - bh, width: Math.max(1, bw - 2), height: Math.max(0, bh), rx: 2, fill: color});
|
||||
r.appendChild(svg('title', {}, [labels[i] + ': ' + fmtNum(v) + ' ' + unit + (marks && marks[i] ? ', ' + marks[i] + ' event(s)' : '')]));
|
||||
g.appendChild(r);
|
||||
if (marks && marks[i]) g.appendChild(svg('circle', {cx: x + bw / 2, cy: H - 24 - bh, r: 3.5, fill: 'var(--red)'}));
|
||||
if (i % 5 === 0 || i === n - 1) g.appendChild(svg('text', {x: x + bw / 2, y: H - 6, 'text-anchor': 'middle'}, [labels[i].slice(5)]));
|
||||
});
|
||||
return g;
|
||||
}
|
||||
function niceMax(m) { var p = Math.pow(10, Math.floor(Math.log10(m))), f = m / p; return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * p; }
|
||||
function fmtNum(v) { return v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(0) : v >= 1 ? v.toFixed(1) : v.toFixed(2).replace(/0+$/, '').replace(/\.$/, ''); }
|
||||
function heat(arr) {
|
||||
var max = Math.max.apply(null, arr.concat([1]));
|
||||
var g = h('div', {class: 'heat'}, arr.map(function (v, i) {
|
||||
return h('i', {style: 'opacity:' + (0.08 + 0.92 * v / max), title: pad(i) + ':00 — ' + dur(v)});
|
||||
}));
|
||||
var l = h('div', {class: 'heat-l'}, arr.map(function (_, i) { return h('span', {text: i % 3 === 0 ? pad(i) : ''}); }));
|
||||
return h('div', {}, [g, l]);
|
||||
}
|
||||
function weekBars(arr) {
|
||||
var names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], max = Math.max.apply(null, arr.concat([1]));
|
||||
return h('div', {class: 'list'}, arr.map(function (v, i) {
|
||||
return h('div', {class: 'row'}, [h('span', {class: 'muted', style: 'width:34px', text: names[i]}),
|
||||
h('div', {class: 'meter', style: 'flex:1;height:10px'}, [h('i', {style: 'background:var(--violet);width:' + (100 * v / max) + '%'})]),
|
||||
h('span', {class: 'muted small', style: 'width:60px;text-align:right', text: dur(v)})]);
|
||||
}));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ events
|
||||
function renderEvents() {
|
||||
var el = $('events'); el.innerHTML = '';
|
||||
el.appendChild(h('div', {class: 'row'}, [h('h2', {text: 'Locked events', style: 'margin:0'}), h('span', {class: 'spacer'}),
|
||||
h('span', {class: 'muted', text: 'Never deleted automatically · ' + bytes(S.disk.events)})]));
|
||||
el.appendChild(h('div', {style: 'height:12px'}));
|
||||
if (!S.events.length) { el.appendChild(h('div', {class: 'empty', text: 'No locked events yet.'})); return; }
|
||||
el.appendChild(h('div', {class: 'gallery'}, S.events.map(function (e) {
|
||||
return h('div', {class: 'tile', onclick: function () { openEvent(e); }}, [
|
||||
h('div', {class: 'th'}, [h('img', {src: thumbUrl(e.name), alt: '', loading: 'lazy'}),
|
||||
h('span', {class: 'badge b-event badge', text: 'EVENT'}), h('span', {class: 'dur', text: dur(e.dur)})]),
|
||||
h('div', {class: 'meta'}, [h('b', {text: day(e.click)}), h('span', {class: 'muted small', text: 'Pressed at ' + hms(e.click) + ' · ' + bytes(e.size)}),
|
||||
e.at ? h('div', {class: 'stats'}, [h('span', {}, [h('b', {text: Math.round(e.at.kmh || 0) + ' km/h'})]),
|
||||
e.at.soc ? h('span', {text: e.at.soc.toFixed(0) + '%'}) : null,
|
||||
typeof e.at.lat === 'number' ? h('span', {text: e.at.lat.toFixed(4) + ', ' + e.at.lon.toFixed(4)}) : null]) : null])
|
||||
]);
|
||||
})));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ drives
|
||||
var driveFilter = {from: '', to: '', keptOnly: false};
|
||||
function renderDrives() {
|
||||
var el = $('drives'); el.innerHTML = '';
|
||||
var from = h('input', {type: 'date', value: driveFilter.from}), to = h('input', {type: 'date', value: driveFilter.to});
|
||||
var kept = h('input', {type: 'checkbox'}); kept.checked = driveFilter.keptOnly;
|
||||
function apply() { driveFilter = {from: from.value, to: to.value, keptOnly: kept.checked}; renderDrives(); }
|
||||
from.onchange = to.onchange = kept.onchange = apply;
|
||||
el.appendChild(h('div', {class: 'row'}, [h('h2', {text: 'Drives', style: 'margin:0'}), h('span', {class: 'spacer'}),
|
||||
h('label', {class: 'muted small'}, ['From ']), from, h('label', {class: 'muted small'}, ['to ']), to,
|
||||
h('label', {class: 'row muted small'}, [kept, ' with kept footage only']),
|
||||
driveFilter.from || driveFilter.to || driveFilter.keptOnly ? h('button', {class: 'ghost small', text: 'Clear', onclick: function () { driveFilter = {from: '', to: '', keptOnly: false}; renderDrives(); }}) : null]));
|
||||
var list = S.drives.filter(function (d) {
|
||||
var k = dayKey(d.start);
|
||||
return (!driveFilter.from || k >= driveFilter.from) && (!driveFilter.to || k <= driveFilter.to) && (!driveFilter.keptOnly || d.kept > 0);
|
||||
});
|
||||
if (!list.length) { el.appendChild(h('div', {class: 'empty', style: 'margin-top:12px', text: S.drives.length ? 'No drives match the filter.' : 'No drives archived yet.'})); return; }
|
||||
var lastDay = null, box = h('div', {class: 'list', style: 'margin-top:12px'});
|
||||
list.forEach(function (d) {
|
||||
var k = day(d.start);
|
||||
if (k !== lastDay) { box.appendChild(h('div', {class: 'daybar', text: k})); lastDay = k; }
|
||||
box.appendChild(driveRow(d));
|
||||
});
|
||||
el.appendChild(box);
|
||||
}
|
||||
|
||||
function driveRow(d) {
|
||||
var first = d.clips[0], last = d.clips[d.clips.length - 1];
|
||||
return h('div', {class: 'drive'}, [
|
||||
h('img', {src: thumbUrl(first.name), alt: '', loading: 'lazy', onclick: function () { openDrive(d, 0); }}),
|
||||
h('div', {}, [
|
||||
h('b', {text: hm(d.start) + ' – ' + hm(d.end)}), ' ',
|
||||
d.kind === 'parked' ? h('span', {class: 'badge b-parked', text: 'PARKED'}) : null, ' ',
|
||||
d.kept ? h('span', {class: 'badge b-kept', text: d.kept === d.clips.length ? 'KEPT' : d.kept + ' KEPT'}) : null,
|
||||
h('div', {class: 'muted small', text: day(d.start) + ' · ' + dur(d.dur) + ' · ' + d.clips.length + ' clips · ' + bytes(d.size)}),
|
||||
d.tel ? h('div', {class: 'stats'}, [
|
||||
d.km ? h('span', {}, [h('b', {text: d.km.toFixed(1) + ' km'})]) : null,
|
||||
d.max_kmh ? h('span', {}, ['top ', h('b', {text: Math.round(d.max_kmh) + ' km/h'})]) : null,
|
||||
d.soc0 != null && d.soc1 != null ? h('span', {}, ['battery ', h('b', {text: d.soc0.toFixed(0) + '% → ' + d.soc1.toFixed(0) + '%'})]) : null,
|
||||
d.parked && d.kind !== 'parked' ? h('span', {text: d.parked + ' parked clip(s)'}) : null
|
||||
]) : null
|
||||
]),
|
||||
h('div', {class: 'acts'}, [
|
||||
h('button', {class: 'small', text: '▶ Play', onclick: function () { openDrive(d, 0); }}),
|
||||
h('button', {class: 'ghost small', text: 'Keep drive', onclick: function () { keepRange(d.start, d.end, 'Drive ' + day(d.start) + ' ' + hm(d.start)); }}),
|
||||
h('a', {class: 'btn ghost small', text: 'Download', href: '/api/web/drive.zip?from=' + encodeURIComponent(first.name) + '&to=' + encodeURIComponent(last.name)})
|
||||
])
|
||||
]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ kept
|
||||
function renderKept() {
|
||||
var el = $('kept'); el.innerHTML = '';
|
||||
el.appendChild(h('div', {class: 'row'}, [h('h2', {text: 'Kept ranges', style: 'margin:0'}), h('span', {class: 'spacer'}),
|
||||
h('span', {class: 'muted', text: 'Clips inside these ranges are never auto-deleted · ' + bytes(S.disk.kept)})]));
|
||||
el.appendChild(h('p', {class: 'muted small', text: 'Ranges marked CAR come from MG Utility and are managed there. WEB ranges were added here and only protect the server copy.'}));
|
||||
if (!S.keep.length) { el.appendChild(h('div', {class: 'empty', text: 'Nothing kept yet. Keep a drive, a clip, or a marked part of a clip from the player.'})); return; }
|
||||
var tb = h('tbody');
|
||||
S.keep.forEach(function (k) {
|
||||
tb.appendChild(h('tr', {}, [
|
||||
h('td', {}, [h('span', {class: 'badge ' + (k.source === 'web' ? 'b-web' : 'b-car'), text: k.source.toUpperCase()})]),
|
||||
h('td', {text: k.label}),
|
||||
h('td', {text: day(k.start) + ' ' + hms(k.start) + ' – ' + hms(k.end)}),
|
||||
h('td', {class: 'num', text: dur((k.end - k.start) / 1000)}),
|
||||
h('td', {class: 'num', text: k.clips.length + ' clips · ' + bytes(k.size)}),
|
||||
h('td', {}, [
|
||||
k.clips.length ? h('button', {class: 'ghost small', text: '▶', onclick: function () { openClips(k.clips, 0, k.label, k.start); }}) : null,
|
||||
k.source === 'web' ? h('button', {class: 'ghost small', text: 'Remove', onclick: function () {
|
||||
if (!confirm('Stop keeping “' + k.label + '”? The clips become eligible for normal retention again.')) return;
|
||||
api('DELETE', '/api/web/keep/' + k.id).then(function () { toast('Removed'); load(); }).catch(function (e) { toast(e.message); });
|
||||
}}) : null])
|
||||
]));
|
||||
});
|
||||
el.appendChild(card('', [h('table', {}, [h('thead', {}, [h('tr', {}, ['Source', 'Label', 'Range', 'Length', 'Footage', ''].map(function (x, i) { return h('th', {class: i > 2 && i < 5 ? 'num' : '', text: x}); }))]), tb])]));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ storage
|
||||
function renderStorage() {
|
||||
var el = $('storage'); el.innerHTML = '';
|
||||
var d = S.disk, f = S.forecast;
|
||||
el.appendChild(h('h2', {text: 'Archive disk'}));
|
||||
var pct = Math.round(100 * d.used / d.total);
|
||||
el.appendChild(card('', [h('div', {class: 'ring-wrap'}, [ring(pct), h('div', {}, [h('div', {class: 'big', text: bytes(d.used)}),
|
||||
h('div', {class: 'muted', text: 'used of ' + bytes(d.total) + ' · ' + bytes(d.free) + ' free'})])]),
|
||||
h('div', {style: 'height:14px'})].concat(storageMeter(true))));
|
||||
el.appendChild(h('div', {class: 'grid kpis', style: 'margin-top:14px'}, [
|
||||
kpi('Average intake', bytes(f.bytes_per_day) + '/day', 'last 14 days'),
|
||||
kpi('Disk full in', f.days_until_full == null ? '–' : f.days_until_full > 3650 ? '10+ years' : Math.round(f.days_until_full) + ' days', 'at the current rate, ignoring retention'),
|
||||
kpi('Expiring in 24 h', bytes(f.expiring_24h), S.retention_days ? S.retention_days + '-day retention' : 'retention off'),
|
||||
kpi('Expiring in 7 days', bytes(f.expiring_7d), f.next_expiry ? 'next ' + day(f.next_expiry) : ''),
|
||||
kpi('Oldest clip', S.totals.oldest ? day(S.totals.oldest) : '–', S.totals.newest ? 'newest ' + day(S.totals.newest) : ''),
|
||||
kpi('Thumbnails', bytes(d.thumbs), 'cache, safe to delete')
|
||||
]));
|
||||
el.appendChild(h('h2', {text: 'Breakdown'}));
|
||||
var rows = [['Locked events', d.events, S.totals.events + ' files', 'Never deleted automatically'],
|
||||
['Kept clips', d.kept, '', 'Inside a keep range'],
|
||||
['Driving clips', d.clips, '', S.retention_days ? 'Deleted after ' + S.retention_days + ' days' : 'Kept until retention is enabled'],
|
||||
['Parked clips', d.parked || 0, '', 'Low quality; deleted after ' + (S.parked_retention_days || S.retention_days || '–') + ' days']];
|
||||
el.appendChild(card('', [h('table', {}, [h('thead', {}, [h('tr', {}, ['Type', 'Size', 'Share of footage', 'Rule'].map(function (x, i) { return h('th', {class: i === 1 || i === 2 ? 'num' : '', text: x}); }))]),
|
||||
h('tbody', {}, rows.map(function (r) {
|
||||
var tot = d.events + d.kept + d.clips + (d.parked || 0) || 1;
|
||||
return h('tr', {}, [h('td', {text: r[0]}), h('td', {class: 'num', text: bytes(r[1])}), h('td', {class: 'num', text: Math.round(100 * r[1] / tot) + '%'}), h('td', {class: 'muted', text: r[3]})]);
|
||||
}))])]));
|
||||
}
|
||||
function ring(pct) {
|
||||
var r = 42, c = 2 * Math.PI * r, col = pct > 90 ? 'var(--red)' : pct > 75 ? 'var(--amber)' : 'var(--cyan)';
|
||||
return svg('svg', {viewBox: '0 0 100 100', width: 110, height: 110}, [
|
||||
svg('circle', {cx: 50, cy: 50, r: r, fill: 'none', stroke: 'var(--surface2)', 'stroke-width': 10}),
|
||||
svg('circle', {cx: 50, cy: 50, r: r, fill: 'none', stroke: col, 'stroke-width': 10, 'stroke-linecap': 'round',
|
||||
'stroke-dasharray': (c * pct / 100) + ' ' + c, transform: 'rotate(-90 50 50)'}),
|
||||
svg('text', {x: 50, y: 56, 'text-anchor': 'middle', fill: 'var(--text)', 'font-size': 18, 'font-weight': 700}, [pct + '%'])]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ map (OSM tiles via the server's cache)
|
||||
function lon2x(lon, z) { return (lon + 180) / 360 * 256 * Math.pow(2, z); }
|
||||
function lat2y(lat, z) { var r = lat * Math.PI / 180; return (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * 256 * Math.pow(2, z); }
|
||||
function geoPts(pts) { return pts.filter(function (p) { return typeof p.lat === 'number' && typeof p.lon === 'number' && (p.acc == null || p.acc <= 50); }); }
|
||||
|
||||
/** Draws tiles + a route into box; returns {mark(lat,lon)} to move the position marker. */
|
||||
function drawMap(box, pts) {
|
||||
box.innerHTML = '';
|
||||
var g = geoPts(pts);
|
||||
var W = box.clientWidth || 300, H = box.clientHeight || 220;
|
||||
if (!g.length) { box.appendChild(h('div', {class: 'empty', style: 'border:0', text: 'No GPS for this footage'})); return {mark: function () {}}; }
|
||||
var la = g.map(function (p) { return p.lat; }), lo = g.map(function (p) { return p.lon; });
|
||||
var minLa = Math.min.apply(null, la), maxLa = Math.max.apply(null, la), minLo = Math.min.apply(null, lo), maxLo = Math.max.apply(null, lo);
|
||||
var z = 17;
|
||||
while (z > 3 && (lon2x(maxLo, z) - lon2x(minLo, z) > W - 40 || lat2y(minLa, z) - lat2y(maxLa, z) > H - 40)) z--;
|
||||
var cx = (lon2x(minLo, z) + lon2x(maxLo, z)) / 2, cy = (lat2y(minLa, z) + lat2y(maxLa, z)) / 2;
|
||||
var ox = cx - W / 2, oy = cy - H / 2, n = Math.pow(2, z);
|
||||
for (var tx = Math.floor(ox / 256); tx <= Math.floor((ox + W) / 256); tx++) {
|
||||
for (var ty = Math.floor(oy / 256); ty <= Math.floor((oy + H) / 256); ty++) {
|
||||
if (ty < 0 || ty >= n) continue;
|
||||
var img = h('img', {src: '/tiles/' + z + '/' + ((tx % n) + n) % n + '/' + ty + '.png', alt: '', loading: 'lazy'});
|
||||
img.style.left = (tx * 256 - ox) + 'px'; img.style.top = (ty * 256 - oy) + 'px';
|
||||
box.appendChild(img);
|
||||
}
|
||||
}
|
||||
var s = svg('svg', {width: W, height: H});
|
||||
var d = g.map(function (p, i) { return (i ? 'L' : 'M') + (lon2x(p.lon, z) - ox).toFixed(1) + ' ' + (lat2y(p.lat, z) - oy).toFixed(1); }).join(' ');
|
||||
s.appendChild(svg('path', {d: d, fill: 'none', stroke: '#000', 'stroke-width': 6, 'stroke-opacity': .45, 'stroke-linejoin': 'round', 'stroke-linecap': 'round'}));
|
||||
s.appendChild(svg('path', {d: d, fill: 'none', stroke: 'var(--cyan)', 'stroke-width': 3.5, 'stroke-linejoin': 'round', 'stroke-linecap': 'round'}));
|
||||
var a = g[0], b = g[g.length - 1];
|
||||
s.appendChild(svg('circle', {cx: lon2x(a.lon, z) - ox, cy: lat2y(a.lat, z) - oy, r: 5, fill: 'var(--green)', stroke: '#000'}));
|
||||
s.appendChild(svg('circle', {cx: lon2x(b.lon, z) - ox, cy: lat2y(b.lat, z) - oy, r: 5, fill: 'var(--red)', stroke: '#000'}));
|
||||
var m = svg('circle', {r: 7, fill: '#fff', stroke: 'var(--red)', 'stroke-width': 3, cx: -50, cy: -50});
|
||||
s.appendChild(m);
|
||||
box.appendChild(s);
|
||||
box.appendChild(h('span', {class: 'attr', text: '© OpenStreetMap'}));
|
||||
return {mark: function (lat, lon) {
|
||||
if (typeof lat !== 'number') { m.setAttribute('cx', -50); return; }
|
||||
m.setAttribute('cx', lon2x(lon, z) - ox); m.setAttribute('cy', lat2y(lat, z) - oy);
|
||||
}};
|
||||
}
|
||||
|
||||
function speedChart(pts, from, to, onSeek) {
|
||||
var W = 900, H = 90, P = 26;
|
||||
var g = svg('svg', {viewBox: '0 0 ' + W + ' ' + H, class: 'chart'});
|
||||
if (!pts.length) return g;
|
||||
var max = niceMax(Math.max.apply(null, pts.map(function (p) { return p.kmh || 0; }).concat([30])));
|
||||
for (var i = 0; i <= 2; i++) {
|
||||
var y = 6 + (H - 22) * i / 2;
|
||||
g.appendChild(svg('line', {x1: P, x2: W, y1: y, y2: y, class: 'grid-l'}));
|
||||
g.appendChild(svg('text', {x: P - 4, y: y + 3, 'text-anchor': 'end'}, [String(Math.round(max * (1 - i / 2)))]));
|
||||
}
|
||||
function X(t) { return P + (W - P) * (t - from) / Math.max(1, to - from); }
|
||||
function Y(v) { return 6 + (H - 22) * (1 - v / max); }
|
||||
var d = pts.map(function (p, i) { return (i ? 'L' : 'M') + X(p.t).toFixed(1) + ' ' + Y(p.kmh || 0).toFixed(1); }).join(' ');
|
||||
g.appendChild(svg('path', {d: d + ' L' + X(pts[pts.length - 1].t) + ' ' + Y(0) + ' L' + X(pts[0].t) + ' ' + Y(0) + ' Z', fill: 'var(--cyan)', 'fill-opacity': .15}));
|
||||
g.appendChild(svg('path', {d: d, fill: 'none', stroke: 'var(--cyan)', 'stroke-width': 2}));
|
||||
g.appendChild(svg('text', {x: P, y: H - 2}, [hms(from)]));
|
||||
g.appendChild(svg('text', {x: W, y: H - 2, 'text-anchor': 'end'}, [hms(to) + ' km/h']));
|
||||
var cur = svg('line', {y1: 0, y2: H - 16, stroke: 'var(--red)', 'stroke-width': 2, x1: -10, x2: -10});
|
||||
g.appendChild(cur);
|
||||
g.addEventListener('click', function (e) {
|
||||
var r = g.getBoundingClientRect(), x = (e.clientX - r.left) / r.width * W;
|
||||
onSeek(from + (x - P) / (W - P) * (to - from));
|
||||
});
|
||||
g.cursorAt = function (t) { var x = X(t); cur.setAttribute('x1', x); cur.setAttribute('x2', x); };
|
||||
return g;
|
||||
}
|
||||
|
||||
function nearest(pts, t) {
|
||||
if (!pts.length) return null;
|
||||
var lo = 0, hi = pts.length - 1;
|
||||
while (lo < hi) { var mid = (lo + hi) >> 1; if (pts[mid].t < t) lo = mid + 1; else hi = mid; }
|
||||
var best = pts[lo];
|
||||
if (lo > 0 && Math.abs(pts[lo - 1].t - t) < Math.abs(best.t - t)) best = pts[lo - 1];
|
||||
return Math.abs(best.t - t) <= 20000 ? best : null;
|
||||
}
|
||||
// Only Park (1) is confirmed from the car's signal; other values are shown raw rather than guessed.
|
||||
function gearName(g) { return g == null ? '–' : g === 1 ? 'P' : 'not P (' + g + ')'; }
|
||||
|
||||
// ------------------------------------------------------------------ keep
|
||||
function keepRange(start, end, suggested) {
|
||||
var label = prompt('Label for this kept footage:', suggested);
|
||||
if (label === null) return;
|
||||
api('POST', '/api/web/keep', {start: Math.round(start), end: Math.round(end), label: label}).then(function () {
|
||||
toast('Kept — excluded from retention on the server'); load();
|
||||
}).catch(function (e) { toast('Could not keep: ' + e.message); });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ player
|
||||
var v = $('video');
|
||||
function openEvent(e) {
|
||||
var before = e.dur ? Math.max(0, e.dur - 60) * 1000 : 120000; // events are N s before + 60 s after the press
|
||||
player = {list: [{name: e.name, start: e.click - before, event: true, dur: e.dur}], i: 0, markIn: null, markOut: null, title: 'Event ' + day(e.click), event: e};
|
||||
show();
|
||||
}
|
||||
function openDrive(d, i) {
|
||||
player = {list: d.clips.map(function (c) { return {name: c.name, start: c.start, dur: c.dur, kept: c.kept}; }), i: i, markIn: null, markOut: null,
|
||||
title: 'Drive ' + day(d.start) + ' ' + hm(d.start) + '–' + hm(d.end)};
|
||||
show();
|
||||
}
|
||||
function openClips(names, i, title) {
|
||||
var all = {};
|
||||
S.drives.forEach(function (d) { d.clips.forEach(function (c) { all[c.name] = c; }); });
|
||||
player = {list: names.map(function (n) { var c = all[n] || {}; return {name: n, start: c.start, dur: c.dur, kept: c.kept}; }), i: i, markIn: null, markOut: null, title: title};
|
||||
show();
|
||||
}
|
||||
function cur() { return player.list[player.i]; }
|
||||
function loadTelemetry() {
|
||||
var first = player.list[0], last = player.list[player.list.length - 1];
|
||||
if (first.start == null) return;
|
||||
var from = first.start, to = (last.start || first.start) + (last.dur || 60) * 1000;
|
||||
player.tel = []; player.telFrom = from; player.telTo = to;
|
||||
$('tel').hidden = true; $('speedchart').innerHTML = '';
|
||||
document.querySelector('.pgrid').classList.remove('has-tel');
|
||||
fetch('/api/web/telemetry?from=' + from + '&to=' + to, {credentials: 'same-origin'}).then(function (r) { return r.json(); }).then(function (b) {
|
||||
var pts = b.points || [];
|
||||
player.tel = pts;
|
||||
if (!pts.length) return;
|
||||
$('tel').hidden = false;
|
||||
document.querySelector('.pgrid').classList.add('has-tel');
|
||||
player.map = drawMap($('map'), pts);
|
||||
player.chart = speedChart(pts, from, to, seekWall);
|
||||
$('speedchart').appendChild(player.chart);
|
||||
updateTel();
|
||||
}).catch(function () {});
|
||||
}
|
||||
function seekWall(t) {
|
||||
for (var i = 0; i < player.list.length; i++) {
|
||||
var c = player.list[i], end = c.start + (c.dur || 60) * 1000;
|
||||
if (t >= c.start && t < end) {
|
||||
var at = (t - c.start) / 1000;
|
||||
if (i === player.i) v.currentTime = at; else load_(i, at);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
function updateTel() {
|
||||
if (!player.tel || !player.tel.length) return;
|
||||
var w = wall(); if (w == null) return;
|
||||
var p = nearest(player.tel, w);
|
||||
$('rSpeed').textContent = p ? Math.round(p.kmh || 0) + ' km/h' : '–';
|
||||
$('rSoc').textContent = p && p.soc ? p.soc.toFixed(1) + ' %' : '–';
|
||||
$('rGear').textContent = p ? gearName(p.gear) : '–';
|
||||
$('rRange').textContent = p && p.range ? p.range + ' km' : '–';
|
||||
$('rPos').textContent = p && typeof p.lat === 'number' ? p.lat.toFixed(5) + ', ' + p.lon.toFixed(5) + (p.acc != null ? ' ±' + p.acc + ' m' : '') : 'No GPS fix at this moment';
|
||||
if (player.map) player.map.mark(p && p.lat, p && p.lon);
|
||||
if (player.chart) player.chart.cursorAt(w);
|
||||
}
|
||||
|
||||
function show() {
|
||||
$('player').hidden = false;
|
||||
$('ptitle').textContent = player.title;
|
||||
loadTelemetry();
|
||||
var isEvent = !!player.event;
|
||||
$('pmarkin').hidden = $('pmarkout').hidden = $('pkeep').hidden = isEvent;
|
||||
$('pprev').hidden = $('pnext').hidden = player.list.length < 2;
|
||||
var strip = $('pstrip'); strip.innerHTML = '';
|
||||
if (player.list.length > 1) player.list.forEach(function (c, i) {
|
||||
strip.appendChild(h('button', {class: (i === player.i ? 'on ' : '') + (c.kept ? 'k' : ''), text: hm(c.start), onclick: function () { load_(i, 0); }}));
|
||||
});
|
||||
if (isEvent) {
|
||||
var del = h('button', {class: 'ghost small', text: 'Delete event…', onclick: function () {
|
||||
if (!confirm('Delete this event from the server? It goes to the trash for 7 days, and the car keeps its own copy.')) return;
|
||||
api('POST', '/api/web/events/' + encodeURIComponent(player.event.name) + '/delete').then(function () { toast('Event moved to trash'); close(); load(); })
|
||||
.catch(function (e) { toast(e.message); });
|
||||
}});
|
||||
strip.appendChild(del);
|
||||
}
|
||||
load_(player.i, 0);
|
||||
}
|
||||
function load_(i, at) {
|
||||
player.i = i;
|
||||
var c = cur();
|
||||
v.src = clipUrl(c.name);
|
||||
v.playbackRate = parseFloat($('prate').value);
|
||||
v.onloadedmetadata = function () { if (at) v.currentTime = at; v.playbackRate = parseFloat($('prate').value); v.play().catch(function () {}); };
|
||||
$('pdl').href = clipUrl(c.name) + '?dl=1';
|
||||
$('psub').textContent = c.name;
|
||||
document.querySelectorAll('#pstrip button').forEach(function (b, j) { b.classList.toggle('on', j === i); });
|
||||
marks();
|
||||
}
|
||||
function wall() { var c = cur(); return c.start != null ? c.start + v.currentTime * 1000 : null; }
|
||||
v.ontimeupdate = function () { var w = wall(); $('pclock').textContent = w ? hms(w) : '--:--:--'; updateTel(); };
|
||||
v.onended = function () { if (player.i < player.list.length - 1) load_(player.i + 1, 0); };
|
||||
$('pprev').onclick = function () { if (player.i > 0) load_(player.i - 1, 0); };
|
||||
$('pnext').onclick = function () { if (player.i < player.list.length - 1) load_(player.i + 1, 0); };
|
||||
$('prate').onchange = function () { v.playbackRate = parseFloat(this.value); };
|
||||
$('pmarkin').onclick = function () { player.markIn = wall(); marks(); };
|
||||
$('pmarkout').onclick = function () { player.markOut = wall(); marks(); };
|
||||
$('pkeep').onclick = function () {
|
||||
var a = player.markIn, b = player.markOut, c = cur();
|
||||
if (a != null && b != null && b > a) return keepRange(a, b, 'Clip ' + hms(a));
|
||||
keepRange(c.start, c.start + (c.dur || 60) * 1000, 'Clip ' + day(c.start) + ' ' + hms(c.start));
|
||||
};
|
||||
function marks() {
|
||||
var a = player.markIn, b = player.markOut;
|
||||
$('pmarks').textContent = a || b ? 'Marked: ' + (a ? hms(a) : '…') + ' → ' + (b ? hms(b) : '…') + (a && b && b > a ? ' (' + dur((b - a) / 1000) + ') — “Keep…” keeps this part' : '')
|
||||
: 'Keep… saves the whole clip, or mark a start and end to keep just a part.';
|
||||
}
|
||||
function close() { v.pause(); v.removeAttribute('src'); v.load(); $('player').hidden = true; }
|
||||
$('pclose').onclick = close;
|
||||
$('player').onclick = function (e) { if (e.target === $('player')) close(); };
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if ($('player').hidden || /INPUT|SELECT/.test(e.target.tagName)) return;
|
||||
if (e.key === 'Escape') close();
|
||||
else if (e.key === ' ') { e.preventDefault(); v.paused ? v.play() : v.pause(); }
|
||||
else if (e.key === 'ArrowRight') v.currentTime += 5;
|
||||
else if (e.key === 'ArrowLeft') v.currentTime -= 5;
|
||||
else if (e.key === 'n') $('pnext').click();
|
||||
else if (e.key === 'p') $('pprev').click();
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ boot
|
||||
showTab((location.hash || '#overview').slice(1).replace(/[^a-z]/g, '') || 'overview');
|
||||
load();
|
||||
setInterval(function () { if ($('player').hidden && !document.hidden) load(); }, 60000);
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#101820"/><rect x="10" y="20" width="32" height="24" rx="5" fill="none" stroke="#2ddaeb" stroke-width="4"/><path d="M42 28l12-7v22l-12-7z" fill="#2ddaeb"/><circle cx="18" cy="27" r="3" fill="#ee3139"/></svg>
|
||||
|
After Width: | Height: | Size: 311 B |
@@ -0,0 +1,82 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>MG Dashcam</title>
|
||||
<link rel="icon" href="/static/icon.svg">
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<div class="brand"><img src="/static/icon.svg" alt="" width="32" height="32"><div><b>MG Dashcam</b><span id="sub">Archive</span></div></div>
|
||||
<nav id="tabs">
|
||||
<button data-tab="overview" class="on">Overview</button>
|
||||
<button data-tab="events">Events</button>
|
||||
<button data-tab="drives">Drives</button>
|
||||
<button data-tab="kept">Kept</button>
|
||||
<button data-tab="storage">Storage</button>
|
||||
</nav>
|
||||
<div class="top-right">
|
||||
<span id="carstate" class="pill">…</span>
|
||||
<button id="refresh" class="ghost small" title="Refresh">↻</button>
|
||||
<div class="menu">
|
||||
<button id="menubtn" class="ghost small">⋯</button>
|
||||
<div id="menu" class="menu-pop" hidden>
|
||||
<button id="logout">Sign out</button>
|
||||
<button id="logoutall">Sign out everywhere</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="app">
|
||||
<section id="overview" class="tab on"></section>
|
||||
<section id="events" class="tab"></section>
|
||||
<section id="drives" class="tab"></section>
|
||||
<section id="kept" class="tab"></section>
|
||||
<section id="storage" class="tab"></section>
|
||||
</main>
|
||||
|
||||
<div id="player" class="modal" hidden>
|
||||
<div class="modal-card">
|
||||
<div class="modal-head">
|
||||
<div><b id="ptitle"></b><span id="psub" class="muted"></span></div>
|
||||
<button id="pclose" class="ghost small" aria-label="Close">✕</button>
|
||||
</div>
|
||||
<div class="pgrid">
|
||||
<video id="video" controls playsinline preload="metadata"></video>
|
||||
<div id="tel" class="tel" hidden>
|
||||
<div class="readouts">
|
||||
<div><span class="l">Speed</span><b id="rSpeed">–</b></div>
|
||||
<div><span class="l">Battery</span><b id="rSoc">–</b></div>
|
||||
<div><span class="l">Gear</span><b id="rGear">–</b></div>
|
||||
<div><span class="l">Range</span><b id="rRange">–</b></div>
|
||||
</div>
|
||||
<div id="map" class="map"></div>
|
||||
<p id="rPos" class="muted small"></p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="speedchart"></div>
|
||||
<div class="pbar">
|
||||
<span id="pclock" class="clock">--:--:--</span>
|
||||
<div class="pbtns">
|
||||
<button id="pprev" class="ghost small">⏮ Prev</button>
|
||||
<button id="pnext" class="ghost small">Next ⏭</button>
|
||||
<select id="prate"><option value="1">1×</option><option value="2">2×</option><option value="4">4×</option><option value="8">8×</option></select>
|
||||
<button id="pmarkin" class="ghost small">Mark start</button>
|
||||
<button id="pmarkout" class="ghost small">Mark end</button>
|
||||
<button id="pkeep" class="primary small">Keep…</button>
|
||||
<a id="pdl" class="btn ghost small" href="#">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
<p id="pmarks" class="muted small"></p>
|
||||
<div id="pstrip" class="strip"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Sign in · MG Dashcam</title>
|
||||
<link rel="icon" href="/static/icon.svg">
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
</head>
|
||||
<body class="login-body">
|
||||
<main class="login-card">
|
||||
<div class="brand"><img src="/static/icon.svg" alt="" width="40" height="40"><div><b>MG Dashcam</b><span>Archive</span></div></div>
|
||||
<h1>Sign in</h1>
|
||||
<p class="muted">Use the archive access token (Vault: “MG Utility dashcam archive (CT112)”).</p>
|
||||
<form id="login" autocomplete="on">
|
||||
<input type="text" name="username" value="dashcam" autocomplete="username" hidden>
|
||||
<label for="token">Access token</label>
|
||||
<div class="pw">
|
||||
<input id="token" name="password" type="password" autocomplete="current-password" required autofocus spellcheck="false">
|
||||
<button type="button" id="show" class="ghost small" aria-label="Show token">Show</button>
|
||||
</div>
|
||||
<label class="check"><input id="remember" type="checkbox" checked> Keep me signed in for 30 days</label>
|
||||
<button type="submit" class="primary wide" id="go">Sign in</button>
|
||||
<p id="err" class="err" role="alert"></p>
|
||||
</form>
|
||||
</main>
|
||||
<script src="/static/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,26 @@
|
||||
(function () {
|
||||
var f = document.getElementById('login'), t = document.getElementById('token'),
|
||||
err = document.getElementById('err'), go = document.getElementById('go');
|
||||
document.getElementById('show').onclick = function () {
|
||||
t.type = t.type === 'password' ? 'text' : 'password';
|
||||
this.textContent = t.type === 'password' ? 'Show' : 'Hide';
|
||||
};
|
||||
f.onsubmit = function (e) {
|
||||
e.preventDefault();
|
||||
err.textContent = '';
|
||||
go.disabled = true; go.textContent = 'Signing in…';
|
||||
fetch('/api/web/login', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'}, credentials: 'same-origin',
|
||||
body: JSON.stringify({token: t.value.trim(), remember: document.getElementById('remember').checked})
|
||||
}).then(function (r) {
|
||||
return r.json().catch(function () { return {}; }).then(function (b) { return {ok: r.ok, b: b}; });
|
||||
}).then(function (res) {
|
||||
if (res.ok) { location.replace('/'); return; }
|
||||
err.textContent = res.b.error || 'Sign-in failed';
|
||||
go.disabled = false; go.textContent = 'Sign in'; t.select();
|
||||
}).catch(function () {
|
||||
err.textContent = 'Could not reach the server';
|
||||
go.disabled = false; go.textContent = 'Sign in';
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 347"><rect width="480" height="347" fill="#141c24"/><path d="M200 140h60v44h-60zM260 152l22-12v44l-22-12z" fill="#31404d"/></svg>
|
||||
|
After Width: | Height: | Size: 187 B |
+37
-17
@@ -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
|
||||
|
||||
@@ -88,7 +88,6 @@ System
|
||||
Run setup wizard → SetupWizardActivity (review mode)
|
||||
Diagnostics
|
||||
Debug console → DebugActivity
|
||||
Upload diagnostics → consent dialog; upload only after confirmation
|
||||
Keys and launcher
|
||||
Key remapping → KeyRemappingActivity
|
||||
Official SAIC launcher → OEM home activity; generic home intent fallback
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,15 @@
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<size android:width="64dp" android:height="64dp" />
|
||||
<gradient android:angle="315"
|
||||
android:startColor="#203443"
|
||||
android:centerColor="#111E2B"
|
||||
android:endColor="#080E17" />
|
||||
<corners android:radius="16dp" />
|
||||
</shape>
|
||||
</item>
|
||||
<item android:drawable="@drawable/ic_mg_utility"
|
||||
android:left="6dp" android:top="6dp"
|
||||
android:right="6dp" android:bottom="6dp" />
|
||||
</layer-list>
|
||||
@@ -0,0 +1,7 @@
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<gradient android:angle="315"
|
||||
android:startColor="#203443"
|
||||
android:centerColor="#111E2B"
|
||||
android:endColor="#080E17" />
|
||||
</shape>
|
||||
@@ -0,0 +1,3 @@
|
||||
<inset xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:drawable="@drawable/ic_mg_utility"
|
||||
android:inset="20.37037%" />
|
||||
@@ -1,9 +1,32 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp"
|
||||
android:height="48dp"
|
||||
android:viewportWidth="48"
|
||||
android:viewportHeight="48">
|
||||
<path android:fillColor="#10252B" android:pathData="M4,6C4,3.8 5.8,2 8,2H40C42.2,2 44,3.8 44,6V42C44,44.2 42.2,46 40,46H8C5.8,46 4,44.2 4,42Z"/>
|
||||
<path android:fillColor="#00D8A5" android:pathData="M15,12H33C34.1,12 35,12.9 35,14V34C35,35.1 34.1,36 33,36H15C13.9,36 13,35.1 13,34V14C13,12.9 13.9,12 15,12M35,19H39V29H35Z"/>
|
||||
<path android:fillColor="#10252B" android:pathData="M26,15L18,26H24L22,33L30,22H24Z"/>
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="64dp"
|
||||
android:height="64dp"
|
||||
android:viewportWidth="64"
|
||||
android:viewportHeight="64">
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:strokeWidth="4.5"
|
||||
android:strokeLineCap="round"
|
||||
android:pathData="M14.32,49.68A25,25 0,1 1,49.68 49.68">
|
||||
<aapt:attr name="android:strokeColor">
|
||||
<gradient android:type="linear"
|
||||
android:startX="10" android:startY="10"
|
||||
android:endX="53" android:endY="51">
|
||||
<item android:offset="0" android:color="#46CFFF" />
|
||||
<item android:offset="0.5" android:color="#00D4D6" />
|
||||
<item android:offset="1" android:color="#48EDB5" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:pathData="M36.9,15.5C37.6,14.7 38.8,15.4 38.5,16.4L35.1,28H43.4C44.5,28 45,29.2 44.3,30L27.1,49.5C26.4,50.3 25.2,49.6 25.5,48.6L28.9,37H20.6C19.5,37 19,35.8 19.7,35Z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient android:type="linear"
|
||||
android:startX="27" android:startY="16"
|
||||
android:endX="37" android:endY="50"
|
||||
android:startColor="#FFFFFF"
|
||||
android:endColor="#CDE8F2" />
|
||||
</aapt:attr>
|
||||
</path>
|
||||
</vector>
|
||||
@@ -0,0 +1,4 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M5.35,5.64c-0.9,-0.64 -1.12,-1.88 -0.49,-2.79c0.63,-0.9 1.88,-1.12 2.79,-0.49c0.9,0.64 1.12,1.88 0.49,2.79c-0.64,0.9 -1.88,1.12 -2.79,0.49zM16,19L8.93,19c-1.48,0 -2.74,-1.08 -2.96,-2.54L4,7L2,7l1.99,9.76C4.37,19.2 6.47,21 8.94,21L16,21v-2zM16.23,15h-4.88l-1.03,-4.1c1.58,0.89 3.28,1.54 5.15,1.22L15.47,10c-1.63,0.31 -3.44,-0.27 -4.69,-1.25L9.14,7.48c-0.23,-0.18 -0.49,-0.3 -0.76,-0.38c-0.32,-0.09 -0.66,-0.12 -0.99,-0.06h-0.02c-1.23,0.22 -2.05,1.39 -1.84,2.61l1.35,5.92C7.16,16.98 8.39,18 9.83,18h6.85l3.82,3l1.5,-1.5l-5.77,-4.5z"/>
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M17,3.5c0,0.8 0.5,1.2 0.8,1.6c0.3,0.4 0.7,0.9 0.7,1.9c0,1 -0.5,1.6 -0.9,2l-0.7,-0.7c0.3,-0.3 0.6,-0.7 0.6,-1.3c0,-0.6 -0.2,-0.9 -0.5,-1.3C16.6,5.3 16,4.6 16,3.5c0,-1 0.5,-1.6 0.9,-2l0.7,0.7C17.3,2.5 17,2.9 17,3.5zM20.5,3.5c0,0.8 0.5,1.2 0.8,1.6c0.3,0.4 0.7,0.9 0.7,1.9c0,1 -0.5,1.6 -0.9,2l-0.7,-0.7c0.3,-0.3 0.6,-0.7 0.6,-1.3c0,-0.6 -0.2,-0.9 -0.5,-1.3C20.1,5.3 19.5,4.6 19.5,3.5c0,-1 0.5,-1.6 0.9,-2l0.7,0.7C20.8,2.5 20.5,2.9 20.5,3.5z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,3 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M17 10.5V7c0-0.55-0.45-1-1-1H4c-0.55 0-1 0.45-1 1v10c0 0.55 0.45 1 1 1h12c0.55 0 1-0.45 1-1v-3.5l4 4v-11l-4 4z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,4 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M12,4C7.58,4 4,7.58 4,12s3.58,8 8,8s8,-3.58 8,-8S16.42,4 12,4zM12,6c2.61,0 4.83,1.67 5.65,4L6.35,10C7.17,7.67 9.39,6 12,6zM6,12.5l3.5,0.6c0.9,0.15 1.5,0.95 1.5,1.85v2.83C8.32,17.32 6.27,15.17 6,12.5zM13,17.78v-2.83c0,-0.9 0.6,-1.7 1.5,-1.85L18,12.5c-0.27,2.67 -2.32,4.82 -5,5.28zM12,13.5c-0.83,0 -1.5,-0.67 -1.5,-1.5s0.67,-1.5 1.5,-1.5s1.5,0.67 1.5,1.5S12.83,13.5 12,13.5z"/>
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M8.5,0.8c0,0.6 0.4,0.9 0.6,1.2c0.25,0.3 0.5,0.65 0.5,1.3h-0.9c0,-0.35 -0.15,-0.55 -0.35,-0.8C8.1,2.2 7.6,1.7 7.6,0.8zM12.45,0.8c0,0.6 0.4,0.9 0.6,1.2c0.25,0.3 0.5,0.65 0.5,1.3h-0.9c0,-0.35 -0.15,-0.55 -0.35,-0.8c-0.25,-0.3 -0.75,-0.8 -0.75,-1.7zM16.4,0.8c0,0.6 0.4,0.9 0.6,1.2c0.25,0.3 0.5,0.65 0.5,1.3h-0.9c0,-0.35 -0.15,-0.55 -0.35,-0.8c-0.25,-0.3 -0.75,-0.8 -0.75,-1.7z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,16 @@
|
||||
# Platform signing key
|
||||
|
||||
MG Utility declares `android:sharedUserId="android.uid.system"` so it can open
|
||||
the head unit's `/dev/video*` camera nodes. Android only honours that if the APK
|
||||
is signed with the device's platform key. The MG4 ships with the **public AOSP
|
||||
test platform key**, so these files are not secret:
|
||||
|
||||
- `platform.pk8` / `platform.x509.pem` — from
|
||||
`android.googlesource.com/platform/build/+/refs/heads/main/target/product/security/`
|
||||
(identical to the ones in Tommasov/MG4_Dashcam `tools/`).
|
||||
- cert SHA-256: `C8:A2:E9:BC:CF:59:7C:2F:B6:DC:66:BE:E2:93:FC:13:F2:FC:47:EC:77:BC:6B:2B:0D:52:C1:1F:51:19:2A:B8`
|
||||
|
||||
`build.sh` signs with these (override with `PLATFORM_KEY` / `PLATFORM_CERT`).
|
||||
|
||||
Switching from the old `mg-utility.keystore` signature (and adding a shared
|
||||
user ID) is not an in-place upgrade: uninstall the old build once, then install.
|
||||
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEqDCCA5CgAwIBAgIJALOZgIbQVs/6MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYD
|
||||
VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4g
|
||||
VmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UE
|
||||
AxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAe
|
||||
Fw0wODA0MTUyMjQwNTBaFw0zNTA5MDEyMjQwNTBaMIGUMQswCQYDVQQGEwJVUzET
|
||||
MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4G
|
||||
A1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9p
|
||||
ZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZI
|
||||
hvcNAQEBBQADggENADCCAQgCggEBAJx4BZKsDV04HN6qZezIpgBuNkgMbXIHsSAR
|
||||
vlCGOqvitV0Amt9xRtbyICKAx81Ne9smJDuKgGwms0sTdSOkkmgiSQTcAUk+fArP
|
||||
GgXIdPabA3tgMJ2QdNJCgOFrrSqHNDYZUer3KkgtCbIEsYdeEqyYwap3PWgAuer9
|
||||
5W1Yvtjo2hb5o2AJnDeoNKbf7be2tEoEngeiafzPLFSW8s821k35CjuNjzSjuqtM
|
||||
9TNxqydxmzulh1StDFP8FOHbRdUeI0+76TybpO35zlQmE1DsU1YHv2mi/0qgfbX3
|
||||
6iANCabBtJ4hQC+J7RGQiTqrWpGA8VLoL4WkV1PPX8GQccXuyCcCAQOjgfwwgfkw
|
||||
HQYDVR0OBBYEFE/koLPdnLop9x1yh8Tnw48ghsKZMIHJBgNVHSMEgcEwgb6AFE/k
|
||||
oLPdnLop9x1yh8Tnw48ghsKZoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UE
|
||||
CBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMH
|
||||
QW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAG
|
||||
CSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJALOZgIbQVs/6MAwGA1Ud
|
||||
EwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBAFclUbjZOh9z3g9tRp+G2tZwFAAp
|
||||
PIigzXzXeLc9r8wZf6t25iEuVsHHYc/EL9cz3lLFCuCIFM78CjtaGkNGBU2Cnx2C
|
||||
tCsgSL+ItdFJKe+F9g7dEtctVWV+IuPoXQTIMdYT0Zk4u4mCJH+jISVroS0dao+S
|
||||
6h2xw3Mxe6DAN/DRr/ZFrvIkl5+6bnoUvAJccbmBOM7z3fwFlhfPJIRc97QNY4L3
|
||||
J17XOElatuWTG5QhdlxJG3L7aOCA29tYwgKdNHyLMozkPvaosVUz7fvpib1qSN1L
|
||||
IC7alMarjdW4OZID2q4u1EYjLk/pvZYTlMYwDlE448/Shebk5INTjLixs1c=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -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));
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
/** Pure microphone-level math shared by the mic test screen and its unit test. */
|
||||
final class AudioLevel {
|
||||
static final double SILENT_PEAK = 0.002;
|
||||
static final double QUIET_PEAK = 0.02;
|
||||
|
||||
private AudioLevel() { }
|
||||
|
||||
/** Root-mean-square of 16-bit PCM, normalised to 0..1. */
|
||||
static double rms(short[] pcm, int count) {
|
||||
if (count <= 0) return 0;
|
||||
double sum = 0;
|
||||
for (int i = 0; i < count; i++) sum += (double) pcm[i] * pcm[i];
|
||||
return Math.sqrt(sum / count) / 32768.0;
|
||||
}
|
||||
|
||||
/** Largest absolute sample, normalised to 0..1. */
|
||||
static double peak(short[] pcm, int count) {
|
||||
int peak = 0;
|
||||
for (int i = 0; i < count; i++) peak = Math.max(peak, Math.abs((int) pcm[i]));
|
||||
return peak / 32768.0;
|
||||
}
|
||||
|
||||
static double dbfs(double linear) {
|
||||
return linear <= 0.00001 ? -100.0 : 20.0 * Math.log10(linear);
|
||||
}
|
||||
|
||||
static String verdict(double peak) {
|
||||
if (peak < SILENT_PEAK) return "SILENT - no signal reaching the app";
|
||||
if (peak < QUIET_PEAK) return "VERY QUIET - signal present but faint";
|
||||
return "OK - microphone signal detected";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Pure (Android-free) codec for the automatic settings backup. Every SharedPreferences
|
||||
* file is stored with typed values so a restore reproduces Boolean/Int/Long/Float/String/
|
||||
* StringSet entries exactly.
|
||||
*/
|
||||
final class BackupCodec {
|
||||
static final int SCHEMA = 1;
|
||||
static final String TYPE = "mg-utility-settings-backup";
|
||||
|
||||
private BackupCodec() { }
|
||||
|
||||
/** files: prefsFileName -> (key -> value). */
|
||||
static String encode(Map<String, ? extends Map<String, ?>> files, long createdAt, String appVersion)
|
||||
throws JSONException {
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", SCHEMA);
|
||||
root.put("type", TYPE);
|
||||
root.put("created_at", createdAt);
|
||||
root.put("app_version", appVersion == null ? "" : appVersion);
|
||||
root.put("fingerprint", fingerprint(files));
|
||||
JSONObject out = new JSONObject();
|
||||
for (Map.Entry<String, ? extends Map<String, ?>> file : new TreeMap<String, Map<String, ?>>(files).entrySet()) {
|
||||
JSONObject entries = new JSONObject();
|
||||
for (Map.Entry<String, ?> e : file.getValue().entrySet()) {
|
||||
JSONObject typed = typed(e.getValue());
|
||||
if (typed != null) entries.put(e.getKey(), typed);
|
||||
}
|
||||
out.put(file.getKey(), entries);
|
||||
}
|
||||
root.put("files", out);
|
||||
return root.toString(1);
|
||||
}
|
||||
|
||||
static Map<String, Map<String, Object>> decode(String json) throws JSONException {
|
||||
JSONObject root = new JSONObject(json);
|
||||
if (root.optInt("schema", -1) != SCHEMA || !TYPE.equals(root.optString("type")))
|
||||
throw new IllegalArgumentException("Not an MG Utility settings backup");
|
||||
JSONObject files = root.getJSONObject("files");
|
||||
Map<String, Map<String, Object>> result = new LinkedHashMap<String, Map<String, Object>>();
|
||||
Iterator<String> names = files.keys();
|
||||
while (names.hasNext()) {
|
||||
String name = names.next();
|
||||
JSONObject entries = files.getJSONObject(name);
|
||||
Map<String, Object> values = new LinkedHashMap<String, Object>();
|
||||
Iterator<String> keys = entries.keys();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
JSONObject typed = entries.getJSONObject(key);
|
||||
Object value = untyped(typed);
|
||||
if (value != null) values.put(key, value);
|
||||
}
|
||||
result.put(name, values);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static long createdAt(String json) {
|
||||
try { return new JSONObject(json).optLong("created_at", 0L); } catch (Exception e) { return 0L; }
|
||||
}
|
||||
|
||||
static int countKeys(Map<String, ? extends Map<String, ?>> files) {
|
||||
int count = 0;
|
||||
for (Map<String, ?> values : files.values()) count += values.size();
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Order-independent SHA-256 over file names, keys, types and values. */
|
||||
static String fingerprint(Map<String, ? extends Map<String, ?>> files) {
|
||||
StringBuilder canonical = new StringBuilder();
|
||||
for (Map.Entry<String, ? extends Map<String, ?>> file : new TreeMap<String, Map<String, ?>>(files).entrySet()) {
|
||||
canonical.append('[').append(file.getKey()).append("]\n");
|
||||
for (Map.Entry<String, ?> e : new TreeMap<String, Object>(file.getValue()).entrySet()) {
|
||||
JSONObject typed = typed(e.getValue());
|
||||
if (typed == null) continue;
|
||||
canonical.append(e.getKey()).append('=').append(typed.optString("t")).append(':')
|
||||
.append(typed.opt("v") instanceof JSONArray ? canonicalArray((JSONArray) typed.opt("v"))
|
||||
: String.valueOf(typed.opt("v"))).append('\n');
|
||||
}
|
||||
}
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes("UTF-8"));
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte b : digest) hex.append(String.format("%02x", b & 0xff));
|
||||
return hex.toString();
|
||||
} catch (Exception e) {
|
||||
return Integer.toHexString(canonical.toString().hashCode());
|
||||
}
|
||||
}
|
||||
|
||||
private static String canonicalArray(JSONArray array) {
|
||||
TreeSet<String> sorted = new TreeSet<String>();
|
||||
for (int i = 0; i < array.length(); i++) sorted.add(array.optString(i));
|
||||
return sorted.toString();
|
||||
}
|
||||
|
||||
private static JSONObject typed(Object value) {
|
||||
try {
|
||||
JSONObject o = new JSONObject();
|
||||
if (value instanceof Boolean) { o.put("t", "b"); o.put("v", ((Boolean) value).booleanValue()); }
|
||||
else if (value instanceof Integer) { o.put("t", "i"); o.put("v", ((Integer) value).intValue()); }
|
||||
else if (value instanceof Long) { o.put("t", "l"); o.put("v", ((Long) value).longValue()); }
|
||||
else if (value instanceof Float) { o.put("t", "f"); o.put("v", Float.toString(((Float) value).floatValue())); }
|
||||
else if (value instanceof String) { o.put("t", "s"); o.put("v", (String) value); }
|
||||
else if (value instanceof Set) {
|
||||
JSONArray array = new JSONArray();
|
||||
for (Object item : new TreeSet<Object>((Set<?>) value)) array.put(String.valueOf(item));
|
||||
o.put("t", "ss"); o.put("v", array);
|
||||
} else return null;
|
||||
return o;
|
||||
} catch (JSONException e) { return null; }
|
||||
}
|
||||
|
||||
private static Object untyped(JSONObject typed) throws JSONException {
|
||||
String t = typed.getString("t");
|
||||
if ("b".equals(t)) return Boolean.valueOf(typed.getBoolean("v"));
|
||||
if ("i".equals(t)) return Integer.valueOf(typed.getInt("v"));
|
||||
if ("l".equals(t)) return Long.valueOf(typed.getLong("v"));
|
||||
if ("f".equals(t)) return Float.valueOf(Float.parseFloat(typed.getString("v")));
|
||||
if ("s".equals(t)) return typed.getString("v");
|
||||
if ("ss".equals(t)) {
|
||||
JSONArray array = typed.getJSONArray("v");
|
||||
ArrayList<String> items = new ArrayList<String>();
|
||||
for (int i = 0; i < array.length(); i++) items.add(array.getString(i));
|
||||
return new TreeSet<String>(items);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Automatic settings + trip-report backup to shared storage (/sdcard/MG-Utility/backup).
|
||||
* Files there are not owned by the app, so they survive uninstall/reinstall on Android 9.
|
||||
*
|
||||
* Safety rule: a backup is never written by an install until that install has either
|
||||
* restored from the backup or confirmed that none exists. That stops a fresh, empty
|
||||
* install from overwriting the good backup before it had a chance to be restored.
|
||||
*/
|
||||
final class BackupManager {
|
||||
private static final String TAG = "MGBackup";
|
||||
static final String DIR_NAME = "MG-Utility/backup";
|
||||
static final String SETTINGS_FILE = "settings.json";
|
||||
static final String TRIPS_FILE = "mg_trips.db";
|
||||
private static final String TRIPS_PREV = "mg_trips.db.prev";
|
||||
private static final String STATE = "mg_backup_state";
|
||||
private static final String K_READY = "ready";
|
||||
private static final String K_LAST_OK = "last_ok";
|
||||
private static final String K_LAST_MSG = "last_msg";
|
||||
private static final String K_FP = "settings_fp";
|
||||
private static final String K_DB_SIG = "db_sig";
|
||||
private static final String K_SNAP_AT = "snapshot_at";
|
||||
private static final String K_PREV_AT = "db_prev_at";
|
||||
private static final long PERIOD_MIN = 15;
|
||||
private static final long SNAPSHOT_GAP_MS = 60L * 60L * 1000L;
|
||||
private static final long DB_PREV_GAP_MS = 24L * 60L * 60L * 1000L;
|
||||
private static final int MAX_SNAPSHOTS = 10;
|
||||
private static final Set<String> EXCLUDED = new HashSet<String>(Arrays.asList(
|
||||
STATE, "hermes_agent", "remote_diagnostics", "WebViewChromiumPrefs"));
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static ScheduledExecutorService executor;
|
||||
|
||||
private BackupManager() { }
|
||||
|
||||
/** Called once from Application.onCreate. Restores synchronously, then schedules backups. */
|
||||
static void start(Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
try { restoreIfFresh(app); } catch (Throwable error) { Log.w(TAG, "startup restore failed", error); }
|
||||
synchronized (LOCK) {
|
||||
if (executor != null) return;
|
||||
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
|
||||
@Override public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(r, "mg-backup"); t.setDaemon(true); return t;
|
||||
}
|
||||
});
|
||||
executor.scheduleWithFixedDelay(new Runnable() {
|
||||
@Override public void run() { backupNow(app); }
|
||||
}, 1, PERIOD_MIN, TimeUnit.MINUTES);
|
||||
}
|
||||
}
|
||||
|
||||
/** Debounced-by-fingerprint background backup request. */
|
||||
static void requestBackup(final Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
ScheduledExecutorService ex;
|
||||
synchronized (LOCK) { ex = executor; }
|
||||
if (ex == null) return;
|
||||
ex.execute(new Runnable() { @Override public void run() { backupNow(app); } });
|
||||
}
|
||||
|
||||
static boolean hasStorageAccess(Context context) {
|
||||
if (Build.VERSION.SDK_INT >= 23 && context.checkSelfPermission(
|
||||
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) return false;
|
||||
File dir = backupDir();
|
||||
if (dir == null) return false;
|
||||
return dir.isDirectory() ? dir.canWrite() : dir.mkdirs() || dir.isDirectory();
|
||||
}
|
||||
|
||||
static File backupDir() {
|
||||
try {
|
||||
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return null;
|
||||
return new File(Environment.getExternalStorageDirectory(), DIR_NAME);
|
||||
} catch (Throwable t) { return null; }
|
||||
}
|
||||
|
||||
/** True when a restorable settings backup exists on disk. */
|
||||
static boolean hasBackup() {
|
||||
File dir = backupDir();
|
||||
return dir != null && new File(dir, SETTINGS_FILE).isFile();
|
||||
}
|
||||
|
||||
static String status(Context context) {
|
||||
SharedPreferences s = state(context);
|
||||
File dir = backupDir();
|
||||
String where = dir == null ? "storage unavailable" : dir.getAbsolutePath();
|
||||
long ok = s.getLong(K_LAST_OK, 0L);
|
||||
String when = ok == 0L ? "no backup yet" : "last " + new SimpleDateFormat("d MMM HH:mm", Locale.US).format(new Date(ok));
|
||||
return when + " • " + where;
|
||||
}
|
||||
|
||||
static String lastMessage(Context context) { return state(context).getString(K_LAST_MSG, ""); }
|
||||
|
||||
// ---- backup ----------------------------------------------------------------------
|
||||
|
||||
/** Returns a short human-readable result; never throws. */
|
||||
static String backupNow(Context context) {
|
||||
synchronized (LOCK) {
|
||||
Context app = context.getApplicationContext();
|
||||
SharedPreferences state = state(app);
|
||||
try {
|
||||
if (!hasStorageAccess(app)) return remember(state, "Waiting for storage permission", false);
|
||||
if (!state.getBoolean(K_READY, false)) {
|
||||
if (hasBackup()) {
|
||||
// A backup exists that this install has not restored yet: do it now, never overwrite.
|
||||
String r = restoreSettingsAndTrips(app);
|
||||
state.edit().putBoolean(K_READY, true).commit();
|
||||
return remember(state, r, true);
|
||||
}
|
||||
state.edit().putBoolean(K_READY, true).commit();
|
||||
}
|
||||
File dir = backupDir();
|
||||
StringBuilder msg = new StringBuilder();
|
||||
msg.append(backupSettings(app, dir, state));
|
||||
msg.append("; ").append(backupTrips(app, dir, state));
|
||||
return remember(state, msg.toString(), true);
|
||||
} catch (Throwable error) {
|
||||
Log.w(TAG, "backup failed", error);
|
||||
return remember(state, "Backup failed: " + error.getClass().getSimpleName() + " " + error.getMessage(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String backupSettings(Context app, File dir, SharedPreferences state) throws Exception {
|
||||
Map<String, Map<String, ?>> files = snapshotPrefs(app);
|
||||
String fp = BackupCodec.fingerprint(files);
|
||||
File current = new File(dir, SETTINGS_FILE);
|
||||
if (fp.equals(state.getString(K_FP, "")) && current.isFile()) return "settings unchanged";
|
||||
long now = System.currentTimeMillis();
|
||||
String json = BackupCodec.encode(files, now, UpdateManager.installedVersion(app));
|
||||
writeAtomically(current, json.getBytes("UTF-8"));
|
||||
if (now - state.getLong(K_SNAP_AT, 0L) >= SNAPSHOT_GAP_MS) {
|
||||
String stamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(new Date(now));
|
||||
writeAtomically(new File(dir, "settings-" + stamp + ".json"), json.getBytes("UTF-8"));
|
||||
pruneSnapshots(dir);
|
||||
state.edit().putLong(K_SNAP_AT, now).apply();
|
||||
}
|
||||
state.edit().putString(K_FP, fp).apply();
|
||||
return "settings saved (" + BackupCodec.countKeys(files) + " keys)";
|
||||
}
|
||||
|
||||
private static void pruneSnapshots(File dir) {
|
||||
File[] all = dir.listFiles();
|
||||
if (all == null) return;
|
||||
List<String> names = new ArrayList<String>();
|
||||
for (File f : all) if (f.getName().startsWith("settings-") && f.getName().endsWith(".json")) names.add(f.getName());
|
||||
Collections.sort(names);
|
||||
for (int i = 0; i < names.size() - MAX_SNAPSHOTS; i++) new File(dir, names.get(i)).delete();
|
||||
}
|
||||
|
||||
private static String backupTrips(Context app, File dir, SharedPreferences state) throws Exception {
|
||||
File db = app.getDatabasePath("mg_trips.db");
|
||||
if (!db.isFile()) return "no trips yet";
|
||||
SQLiteDatabase source = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
|
||||
File temp = new File(app.getCacheDir(), "trips-backup.tmp");
|
||||
try {
|
||||
String sig = signature(source);
|
||||
File target = new File(dir, TRIPS_FILE);
|
||||
if (sig.equals(state.getString(K_DB_SIG, "")) && target.isFile()) return "trips unchanged";
|
||||
if (sig.startsWith("0|")) return "no trips yet"; // never replace a backup with an empty database
|
||||
deleteDbFiles(temp);
|
||||
snapshotDatabase(source, temp);
|
||||
long now = System.currentTimeMillis();
|
||||
File prev = new File(dir, TRIPS_PREV);
|
||||
if (target.isFile() && now - state.getLong(K_PREV_AT, 0L) >= DB_PREV_GAP_MS) {
|
||||
copyFile(target, new File(dir, TRIPS_PREV + ".tmp"));
|
||||
prev.delete();
|
||||
new File(dir, TRIPS_PREV + ".tmp").renameTo(prev);
|
||||
state.edit().putLong(K_PREV_AT, now).apply();
|
||||
}
|
||||
File staged = new File(dir, TRIPS_FILE + ".tmp");
|
||||
copyFile(temp, staged);
|
||||
target.delete();
|
||||
if (!staged.renameTo(target)) throw new IOException("rename failed");
|
||||
state.edit().putString(K_DB_SIG, sig).apply();
|
||||
return "trips saved (" + sig.substring(0, sig.indexOf('|')) + ")";
|
||||
} finally {
|
||||
source.close();
|
||||
deleteDbFiles(temp);
|
||||
}
|
||||
}
|
||||
|
||||
private static String signature(SQLiteDatabase db) {
|
||||
Cursor c = db.rawQuery("SELECT (SELECT COUNT(*) FROM trips), (SELECT COALESCE(MAX(end_time),0) FROM trips),"
|
||||
+ " (SELECT COALESCE(MAX(id),0) FROM trip_samples), (SELECT COALESCE(MAX(id),0) FROM trip_points),"
|
||||
+ " (SELECT COALESCE(MAX(id),0) FROM regen_events)", null);
|
||||
try {
|
||||
c.moveToFirst();
|
||||
return c.getLong(0) + "|" + c.getLong(1) + "|" + c.getLong(2) + "|" + c.getLong(3) + "|" + c.getLong(4);
|
||||
} finally { c.close(); }
|
||||
}
|
||||
|
||||
/** Consistent point-in-time copy via ATTACH; works while the trip service keeps writing. */
|
||||
private static void snapshotDatabase(SQLiteDatabase source, File temp) {
|
||||
List<String> schema = new ArrayList<String>();
|
||||
List<String> tables = new ArrayList<String>();
|
||||
Cursor c = source.rawQuery("SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL"
|
||||
+ " AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%' ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END", null);
|
||||
try {
|
||||
while (c.moveToNext()) {
|
||||
String type = c.getString(0), name = c.getString(1), sql = c.getString(2);
|
||||
if ("table".equals(type)) {
|
||||
tables.add(name);
|
||||
schema.add(sql.replaceFirst("(?i)CREATE\\s+TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?\"?" + java.util.regex.Pattern.quote(name) + "\"?",
|
||||
"CREATE TABLE bk.\"" + name + "\""));
|
||||
} else if ("index".equals(type)) {
|
||||
schema.add(sql.replaceFirst("(?i)CREATE\\s+(UNIQUE\\s+)?INDEX\\s+(IF\\s+NOT\\s+EXISTS\\s+)?\"?" + java.util.regex.Pattern.quote(name) + "\"?",
|
||||
"CREATE $1INDEX bk.\"" + name + "\""));
|
||||
}
|
||||
}
|
||||
} finally { c.close(); }
|
||||
int version = source.getVersion();
|
||||
source.execSQL("ATTACH DATABASE '" + temp.getPath().replace("'", "''") + "' AS bk");
|
||||
try {
|
||||
for (String sql : schema) source.execSQL(sql);
|
||||
source.beginTransaction();
|
||||
try {
|
||||
for (String table : tables) source.execSQL("INSERT INTO bk.\"" + table + "\" SELECT * FROM main.\"" + table + "\"");
|
||||
source.setTransactionSuccessful();
|
||||
} finally { source.endTransaction(); }
|
||||
source.execSQL("PRAGMA bk.user_version = " + version);
|
||||
} finally {
|
||||
source.execSQL("DETACH DATABASE bk");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- restore ---------------------------------------------------------------------
|
||||
|
||||
/** Restore on first run of an install when a backup is available. */
|
||||
static boolean restoreIfFresh(Context context) {
|
||||
Context app = context.getApplicationContext();
|
||||
SharedPreferences state = state(app);
|
||||
if (state.getBoolean(K_READY, false)) return false;
|
||||
if (!hasStorageAccess(app)) return false;
|
||||
synchronized (LOCK) {
|
||||
if (!hasBackup()) { state.edit().putBoolean(K_READY, true).commit(); return false; }
|
||||
String result = restoreSettingsAndTrips(app);
|
||||
state.edit().putBoolean(K_READY, true).commit();
|
||||
remember(state, result, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Explicit user-requested restore of the latest backup. Returns a result message. */
|
||||
static String restoreLatest(Context context) {
|
||||
synchronized (LOCK) {
|
||||
Context app = context.getApplicationContext();
|
||||
if (!hasStorageAccess(app)) return "Storage permission is required";
|
||||
if (!hasBackup()) return "No backup found in " + backupDir();
|
||||
String result = restoreSettingsAndTrips(app);
|
||||
SharedPreferences state = state(app);
|
||||
state.edit().putBoolean(K_READY, true).commit();
|
||||
return remember(state, result, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static String restoreSettingsAndTrips(Context app) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
File dir = backupDir();
|
||||
try {
|
||||
byte[] bytes = readAll(new File(dir, SETTINGS_FILE));
|
||||
Map<String, Map<String, Object>> files = BackupCodec.decode(new String(bytes, "UTF-8"));
|
||||
int applied = 0;
|
||||
for (Map.Entry<String, Map<String, Object>> file : files.entrySet()) {
|
||||
if (EXCLUDED.contains(file.getKey())) continue;
|
||||
SharedPreferences.Editor editor = app.getSharedPreferences(file.getKey(), Context.MODE_PRIVATE).edit();
|
||||
for (Map.Entry<String, Object> e : file.getValue().entrySet()) {
|
||||
Object v = e.getValue();
|
||||
if (v instanceof Boolean) editor.putBoolean(e.getKey(), (Boolean) v);
|
||||
else if (v instanceof Integer) editor.putInt(e.getKey(), (Integer) v);
|
||||
else if (v instanceof Long) editor.putLong(e.getKey(), (Long) v);
|
||||
else if (v instanceof Float) editor.putFloat(e.getKey(), (Float) v);
|
||||
else if (v instanceof String) editor.putString(e.getKey(), (String) v);
|
||||
else if (v instanceof Set) {
|
||||
Set<String> set = new HashSet<String>(); for (Object item : (Set<?>) v) set.add(String.valueOf(item));
|
||||
editor.putStringSet(e.getKey(), set);
|
||||
} else continue;
|
||||
applied++;
|
||||
}
|
||||
editor.commit();
|
||||
}
|
||||
out.append("restored ").append(applied).append(" settings");
|
||||
} catch (Throwable error) {
|
||||
Log.w(TAG, "settings restore failed", error);
|
||||
out.append("settings restore failed: ").append(error.getClass().getSimpleName());
|
||||
}
|
||||
try { out.append("; ").append(restoreTrips(app, dir)); }
|
||||
catch (Throwable error) { Log.w(TAG, "trip restore failed", error); out.append("; trips restore failed: ").append(error.getClass().getSimpleName()); }
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String restoreTrips(Context app, File dir) throws Exception {
|
||||
File backup = new File(dir, TRIPS_FILE);
|
||||
if (!backup.isFile()) return "no trip backup";
|
||||
SQLiteDatabase check = SQLiteDatabase.openDatabase(backup.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||
long backupTrips;
|
||||
try {
|
||||
Cursor c = check.rawQuery("SELECT COUNT(*) FROM trips", null);
|
||||
try { c.moveToFirst(); backupTrips = c.getLong(0); } finally { c.close(); }
|
||||
if (check.getVersion() > 4) return "trip backup is from a newer app version; skipped";
|
||||
} finally { check.close(); }
|
||||
File db = app.getDatabasePath("mg_trips.db");
|
||||
if (db.isFile()) {
|
||||
SQLiteDatabase existing = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||
long localTrips;
|
||||
try {
|
||||
Cursor c = existing.rawQuery("SELECT COUNT(*) FROM trips", null);
|
||||
try { c.moveToFirst(); localTrips = c.getLong(0); } finally { c.close(); }
|
||||
} finally { existing.close(); }
|
||||
if (localTrips >= backupTrips && localTrips > 0) return "kept " + localTrips + " existing trips";
|
||||
// Keep whatever was there so a restore is itself reversible.
|
||||
copyFile(db, new File(db.getParentFile(), "mg_trips.db.before-restore"));
|
||||
}
|
||||
db.getParentFile().mkdirs();
|
||||
deleteDbFiles(db);
|
||||
copyFile(backup, db);
|
||||
return "restored " + backupTrips + " trips";
|
||||
}
|
||||
|
||||
/** Relaunch the home activity in a fresh process so every cache re-reads restored data. */
|
||||
static void restartApp(final Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
android.content.Intent launch = new android.content.Intent(app, MainActivity.class)
|
||||
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
|
||||
android.app.PendingIntent pi = android.app.PendingIntent.getActivity(app, 7421, launch,
|
||||
android.app.PendingIntent.FLAG_CANCEL_CURRENT);
|
||||
((android.app.AlarmManager) app.getSystemService(Context.ALARM_SERVICE))
|
||||
.set(android.app.AlarmManager.RTC, System.currentTimeMillis() + 600L, pi);
|
||||
} catch (Throwable ignored) { }
|
||||
android.os.Process.killProcess(android.os.Process.myPid());
|
||||
}
|
||||
}, 1800L);
|
||||
}
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------------
|
||||
|
||||
private static Map<String, Map<String, ?>> snapshotPrefs(Context app) {
|
||||
Map<String, Map<String, ?>> files = new LinkedHashMap<String, Map<String, ?>>();
|
||||
File prefsDir = new File(app.getApplicationInfo().dataDir, "shared_prefs");
|
||||
File[] list = prefsDir.listFiles();
|
||||
if (list == null) return files;
|
||||
for (File f : list) {
|
||||
String n = f.getName();
|
||||
if (!n.endsWith(".xml")) continue;
|
||||
String name = n.substring(0, n.length() - 4);
|
||||
if (EXCLUDED.contains(name) || name.startsWith("WebView") || name.startsWith("com.google")) continue;
|
||||
Map<String, ?> all = app.getSharedPreferences(name, Context.MODE_PRIVATE).getAll();
|
||||
if (!all.isEmpty()) files.put(name, new LinkedHashMap<String, Object>(all));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private static SharedPreferences state(Context context) {
|
||||
return context.getApplicationContext().getSharedPreferences(STATE, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static String remember(SharedPreferences state, String message, boolean ok) {
|
||||
SharedPreferences.Editor e = state.edit().putString(K_LAST_MSG, message);
|
||||
if (ok) e.putLong(K_LAST_OK, System.currentTimeMillis());
|
||||
e.apply();
|
||||
return message;
|
||||
}
|
||||
|
||||
private static void writeAtomically(File target, byte[] bytes) throws IOException {
|
||||
File parent = target.getParentFile();
|
||||
if (!parent.isDirectory() && !parent.mkdirs()) throw new IOException("cannot create " + parent);
|
||||
File tmp = new File(parent, target.getName() + ".tmp");
|
||||
FileOutputStream out = new FileOutputStream(tmp);
|
||||
try { out.write(bytes); out.getFD().sync(); } finally { out.close(); }
|
||||
target.delete();
|
||||
if (!tmp.renameTo(target)) throw new IOException("rename failed for " + target);
|
||||
}
|
||||
|
||||
private static byte[] readAll(File file) throws IOException {
|
||||
InputStream in = new FileInputStream(file);
|
||||
try {
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
byte[] buf = new byte[8192]; int n;
|
||||
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
|
||||
return out.toByteArray();
|
||||
} finally { in.close(); }
|
||||
}
|
||||
|
||||
private static void copyFile(File from, File to) throws IOException {
|
||||
InputStream in = new FileInputStream(from);
|
||||
try {
|
||||
OutputStream out = new FileOutputStream(to);
|
||||
try {
|
||||
byte[] buf = new byte[65536]; int n;
|
||||
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
|
||||
out.flush();
|
||||
if (out instanceof FileOutputStream) ((FileOutputStream) out).getFD().sync();
|
||||
} finally { out.close(); }
|
||||
} finally { in.close(); }
|
||||
}
|
||||
|
||||
private static void deleteDbFiles(File db) {
|
||||
db.delete();
|
||||
new File(db.getPath() + "-wal").delete();
|
||||
new File(db.getPath() + "-shm").delete();
|
||||
new File(db.getPath() + "-journal").delete();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -64,6 +73,8 @@ public final class BootReceiver extends BroadcastReceiver {
|
||||
|
||||
TripTrackingService.start(context);
|
||||
TripTrackingService.scheduleWatchdog(context);
|
||||
// Dashcam survives boot, unlock and app updates like the trip tracker.
|
||||
try { DashcamService.startIfEnabled(context); } catch (Throwable ignored) { }
|
||||
launchDashboard(context, action);
|
||||
// There is no public MG lock broadcast on all firmware versions. The
|
||||
// head unit's screen-off and power-disconnected broadcasts are the
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.SurfaceTexture;
|
||||
import android.hardware.Camera;
|
||||
import android.hardware.camera2.CameraManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Gravity;
|
||||
import android.view.TextureView;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Settings → System → Camera test: lists every camera path the head unit exposes and previews the chosen one. */
|
||||
public final class CameraTestActivity extends AnimatedActivity implements TextureView.SurfaceTextureListener {
|
||||
private static final int REQUEST_CAMERA = 5102;
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private TextureView preview;
|
||||
private TextView status;
|
||||
private TextView info;
|
||||
private Button cameraButton;
|
||||
private Button previewButton;
|
||||
private Camera camera;
|
||||
private SurfaceTexture surface;
|
||||
private int legacyCount;
|
||||
private int selected;
|
||||
private boolean previewing;
|
||||
private long frames;
|
||||
private long startedAt;
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
UiTheme.applyFontScale(this);
|
||||
setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
|
||||
try { legacyCount = Camera.getNumberOfCameras(); } catch (Throwable t) { legacyCount = 0; }
|
||||
setContentView(buildUi());
|
||||
updateCameraLabel();
|
||||
info.setText(describeHardware());
|
||||
if (!hasPermission() && Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_CAMERA);
|
||||
}
|
||||
|
||||
private View buildUi() {
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(28, 18, 28, 18);
|
||||
root.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
LinearLayout header = new LinearLayout(this);
|
||||
header.setGravity(Gravity.CENTER_VERTICAL);
|
||||
header.addView(UiTheme.title(this, "CAMERA TEST", 28), new LinearLayout.LayoutParams(0, 56, 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);
|
||||
LinearLayout left = new LinearLayout(this);
|
||||
left.setOrientation(LinearLayout.VERTICAL);
|
||||
cameraButton = UiTheme.button(this, "", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { cycleCamera(); }
|
||||
}, false);
|
||||
previewButton = UiTheme.button(this, "START PREVIEW", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { if (previewing) stopPreview("Stopped"); else startPreview(); }
|
||||
}, true);
|
||||
Button rescan = UiTheme.button(this, "RESCAN", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
try { legacyCount = Camera.getNumberOfCameras(); } catch (Throwable t) { legacyCount = 0; }
|
||||
updateCameraLabel(); info.setText(describeHardware());
|
||||
}
|
||||
}, false);
|
||||
left.addView(cameraButton, new LinearLayout.LayoutParams(-1, 52));
|
||||
left.addView(previewButton, new LinearLayout.LayoutParams(-1, 52));
|
||||
left.addView(rescan, new LinearLayout.LayoutParams(-1, 52));
|
||||
status = UiTheme.text(this, "Idle", 14, UiTheme.TEXT, android.graphics.Typeface.BOLD);
|
||||
left.addView(status, new LinearLayout.LayoutParams(-1, 70));
|
||||
info = UiTheme.text(this, "", 12, UiTheme.MUTED, android.graphics.Typeface.NORMAL);
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.addView(info);
|
||||
left.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
body.addView(left, new LinearLayout.LayoutParams(0, -1, 4));
|
||||
|
||||
FrameLayout frame = new FrameLayout(this);
|
||||
frame.setBackground(UiTheme.surface(UiTheme.SURFACE, 8));
|
||||
preview = new TextureView(this);
|
||||
preview.setSurfaceTextureListener(this);
|
||||
frame.addView(preview, new FrameLayout.LayoutParams(-1, -1));
|
||||
LinearLayout.LayoutParams fp = new LinearLayout.LayoutParams(0, -1, 6);
|
||||
fp.setMargins(14, 8, 0, 8);
|
||||
body.addView(frame, fp);
|
||||
root.addView(body, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
return root;
|
||||
}
|
||||
|
||||
private boolean hasPermission() {
|
||||
return Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
|
||||
super.onRequestPermissionsResult(code, permissions, results);
|
||||
if (code == REQUEST_CAMERA) {
|
||||
boolean granted = results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED;
|
||||
status.setText(granted ? "Camera permission granted" : "Camera permission DENIED");
|
||||
status.setTextColor(granted ? UiTheme.TEXT : UiTheme.WARNING);
|
||||
info.setText(describeHardware());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCameraLabel() {
|
||||
cameraButton.setText(legacyCount == 0 ? "NO CAMERAS FOUND" : "CAMERA " + selected + " OF " + legacyCount);
|
||||
}
|
||||
|
||||
private void cycleCamera() {
|
||||
if (legacyCount == 0) return;
|
||||
boolean was = previewing;
|
||||
if (was) stopPreview("Switching");
|
||||
selected = (selected + 1) % legacyCount;
|
||||
updateCameraLabel();
|
||||
if (was) startPreview();
|
||||
}
|
||||
|
||||
private String describeHardware() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Permission: ").append(hasPermission() ? "granted" : "NOT granted").append('\n');
|
||||
sb.append("Camera API (legacy): ").append(legacyCount).append(" camera(s)\n");
|
||||
for (int i = 0; i < legacyCount; i++) {
|
||||
try {
|
||||
Camera.CameraInfo ci = new Camera.CameraInfo();
|
||||
Camera.getCameraInfo(i, ci);
|
||||
sb.append(" #").append(i).append(ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ? " front" : " back")
|
||||
.append(", orientation ").append(ci.orientation).append("°\n");
|
||||
} catch (Throwable t) { sb.append(" #").append(i).append(" info error: ").append(t.getMessage()).append('\n'); }
|
||||
}
|
||||
try {
|
||||
CameraManager cm = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
|
||||
String[] ids = cm.getCameraIdList();
|
||||
sb.append("Camera2 API: ").append(ids.length).append(" id(s) ").append(Arrays.toString(ids)).append('\n');
|
||||
} catch (Throwable t) { sb.append("Camera2 API: ").append(t.getClass().getSimpleName()).append(" ").append(t.getMessage()).append('\n'); }
|
||||
File[] nodes = new File("/dev").listFiles();
|
||||
int video = 0;
|
||||
StringBuilder raw = new StringBuilder();
|
||||
if (nodes != null) {
|
||||
Arrays.sort(nodes);
|
||||
for (File f : nodes) {
|
||||
if (!f.getName().startsWith("video")) continue;
|
||||
video++;
|
||||
boolean readable = f.canRead();
|
||||
String openResult = "not tried";
|
||||
if (readable) {
|
||||
try { new FileInputStream(f).close(); openResult = "open OK"; }
|
||||
catch (Throwable t) { openResult = "open failed: " + t.getMessage(); }
|
||||
}
|
||||
raw.append(" ").append(f.getPath()).append(" read=").append(readable).append(" write=").append(f.canWrite())
|
||||
.append(" ").append(openResult).append('\n');
|
||||
}
|
||||
}
|
||||
sb.append("Raw V4L2 nodes (/dev/video*): ").append(video == 0 ? "none visible to this app" : video).append('\n').append(raw);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void startPreview() {
|
||||
if (previewing) return;
|
||||
if (legacyCount == 0) { setStatus("No camera reported by Android. See raw nodes list below.", true); return; }
|
||||
if (!hasPermission()) {
|
||||
setStatus("Camera permission not granted", true);
|
||||
if (Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_CAMERA);
|
||||
return;
|
||||
}
|
||||
if (surface == null) { setStatus("Preview surface not ready yet, try again", true); return; }
|
||||
try {
|
||||
camera = Camera.open(selected);
|
||||
Camera.Parameters params = camera.getParameters();
|
||||
Camera.Size size = params.getPreviewSize();
|
||||
camera.setPreviewTexture(surface);
|
||||
frames = 0; startedAt = System.currentTimeMillis();
|
||||
camera.setErrorCallback(new Camera.ErrorCallback() {
|
||||
@Override public void onError(int error, Camera cam) { stopPreview("Camera error " + error); }
|
||||
});
|
||||
camera.setPreviewCallback(new Camera.PreviewCallback() {
|
||||
@Override public void onPreviewFrame(byte[] data, Camera cam) { frames++; }
|
||||
});
|
||||
camera.startPreview();
|
||||
previewing = true;
|
||||
previewButton.setText("STOP PREVIEW");
|
||||
setStatus(String.format(Locale.US, "Opened camera %d %dx%d", selected, size.width, size.height), false);
|
||||
ui.postDelayed(fpsTick, 1000);
|
||||
} catch (Throwable error) {
|
||||
releaseCamera();
|
||||
setStatus("OPEN FAILED: " + error.getClass().getSimpleName() + " " + error.getMessage(), true);
|
||||
}
|
||||
}
|
||||
|
||||
private final Runnable fpsTick = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (!previewing) return;
|
||||
double seconds = Math.max(0.001, (System.currentTimeMillis() - startedAt) / 1000.0);
|
||||
boolean live = frames > 0;
|
||||
setStatus(String.format(Locale.US, "Camera %d streaming: %d frames, %.1f fps", selected, frames, frames / seconds), !live && seconds > 3);
|
||||
if (!live && seconds > 3) status.setText("Opened but NO FRAMES received after " + (int) seconds + "s");
|
||||
ui.postDelayed(this, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
private void stopPreview(String message) {
|
||||
previewing = false;
|
||||
ui.removeCallbacks(fpsTick);
|
||||
releaseCamera();
|
||||
previewButton.setText("START PREVIEW");
|
||||
setStatus(message, false);
|
||||
}
|
||||
|
||||
private void releaseCamera() {
|
||||
if (camera == null) return;
|
||||
try { camera.setPreviewCallback(null); camera.stopPreview(); } catch (Throwable ignored) { }
|
||||
try { camera.release(); } catch (Throwable ignored) { }
|
||||
camera = null;
|
||||
}
|
||||
|
||||
private void setStatus(String text, boolean warn) {
|
||||
status.setText(text);
|
||||
status.setTextColor(warn ? UiTheme.WARNING : UiTheme.TEXT);
|
||||
}
|
||||
|
||||
@Override public void onSurfaceTextureAvailable(SurfaceTexture s, int w, int h) { surface = s; }
|
||||
@Override public void onSurfaceTextureSizeChanged(SurfaceTexture s, int w, int h) { }
|
||||
@Override public boolean onSurfaceTextureDestroyed(SurfaceTexture s) { stopPreview("Stopped"); surface = null; return true; }
|
||||
@Override public void onSurfaceTextureUpdated(SurfaceTexture s) { }
|
||||
|
||||
@Override protected void onPause() {
|
||||
if (previewing) stopPreview("Stopped (screen left)");
|
||||
super.onPause();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 "--";
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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 = 3;
|
||||
|
||||
public enum Kind { SLIDER, TOGGLE, SHORTCUT }
|
||||
|
||||
@@ -47,18 +47,32 @@ 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"),
|
||||
new Control("energy", "Energy dashboard", "energy", Kind.SHORTCUT, "MG Utility"),
|
||||
new Control("charging", "Charging automation", "charging", Kind.SHORTCUT, "MG Utility"),
|
||||
new Control("settings", "Settings", "settings", Kind.SHORTCUT, "MG Utility")
|
||||
new Control("settings", "Settings", "settings", Kind.SHORTCUT, "MG Utility"),
|
||||
new Control("dashcam_event", "Lock dashcam event", "videocam", Kind.SHORTCUT, "Dashcam")
|
||||
));
|
||||
|
||||
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",
|
||||
"dashcam_event", "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" },
|
||||
{ "dashcam_event" }
|
||||
};
|
||||
|
||||
public static List<Control> all() { return ALL; }
|
||||
@@ -91,7 +105,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();
|
||||
|
||||
@@ -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<Runnable> liveRenders = new ArrayList<Runnable>();
|
||||
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<Runnable>(liveRenders)) {
|
||||
try { r.run(); } catch (Exception ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
private View buildTiles() {
|
||||
LinearLayout container = new LinearLayout(activity);
|
||||
container.setOrientation(LinearLayout.HORIZONTAL);
|
||||
container.setGravity(Gravity.TOP);
|
||||
List<String> order = ControlPanelCatalog.loadOrder(activity);
|
||||
ArrayList<String> sliderIds = new ArrayList<String>();
|
||||
ArrayList<ControlPanelCatalog.Control> toggles = new ArrayList<ControlPanelCatalog.Control>();
|
||||
@@ -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<ControlPanelCatalog.Control> 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 {
|
||||
@@ -1064,6 +1364,11 @@ final class ControlPanelOverlay extends FrameLayout {
|
||||
}
|
||||
|
||||
private void launchShortcut(String id) {
|
||||
if ("dashcam_event".equals(id)) {
|
||||
// Stays open on purpose: the toast confirms it, and the driver can keep using the panel.
|
||||
DashcamService.saveMoment(activity);
|
||||
return;
|
||||
}
|
||||
if ("saic_launcher".equals(id)) {
|
||||
Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
|
||||
.setClassName("com.saicmotor.hmi.launcher", "com.saicmotor.hmi.launcher.ui.MainActivity")
|
||||
@@ -1082,6 +1387,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);
|
||||
|
||||
@@ -0,0 +1,739 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Typeface;
|
||||
import android.media.MediaPlayer;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.text.InputType;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
import android.widget.VideoView;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Settings → Driving → Dashcam. Three tabs: status + quick actions, recordings (drives, clips,
|
||||
* playback, keep ranges), and storage/offload settings.
|
||||
*/
|
||||
public final class DashcamActivity extends AnimatedActivity {
|
||||
private static final int REQUEST_STORAGE = 6101;
|
||||
private static final long DRIVE_GAP_MS = 3L * 60L * 1000L;
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private LinearLayout tabs;
|
||||
private LinearLayout content;
|
||||
private int tab;
|
||||
|
||||
// Player state
|
||||
private VideoView player;
|
||||
private SeekBar scrub;
|
||||
private TextView playerLabel;
|
||||
private DashcamPolicy.Clip playing;
|
||||
private long markIn = -1L, markOut = -1L;
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
DashcamStore.init(this);
|
||||
UiTheme.applyFontScale(this);
|
||||
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, "DASHCAM", 30), new LinearLayout.LayoutParams(0, 62, 1));
|
||||
header.addView(UiTheme.backButton(this, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { finish(); }
|
||||
}), new LinearLayout.LayoutParams(120, 52));
|
||||
root.addView(header);
|
||||
tabs = new LinearLayout(this);
|
||||
root.addView(tabs, new LinearLayout.LayoutParams(-1, 56));
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
content = new LinearLayout(this);
|
||||
content.setOrientation(LinearLayout.VERTICAL);
|
||||
content.setPadding(0, 12, 0, 0);
|
||||
scroll.addView(content);
|
||||
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
setContentView(root);
|
||||
if (!hasStorage() && Build.VERSION.SDK_INT >= 23) {
|
||||
requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, REQUEST_STORAGE);
|
||||
}
|
||||
show(0);
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
ui.postDelayed(refresher, 2000L);
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
ui.removeCallbacks(refresher);
|
||||
stopPlayer();
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private final Runnable refresher = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (tab == 0) show(0);
|
||||
ui.postDelayed(this, 3000L);
|
||||
}
|
||||
};
|
||||
|
||||
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, results);
|
||||
show(tab);
|
||||
}
|
||||
|
||||
private boolean hasStorage() {
|
||||
return Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private void show(int index) {
|
||||
if (index != tab) stopPlayer();
|
||||
tab = index;
|
||||
String[] names = { "Status", "Recordings", "Storage & offload" };
|
||||
tabs.removeAllViews();
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
final int target = i;
|
||||
TextView t = UiTheme.text(this, names[i], 15, i == index ? UiTheme.TEXT : UiTheme.MUTED, Typeface.NORMAL);
|
||||
t.setGravity(Gravity.CENTER);
|
||||
t.setBackground(i == index ? UiTheme.outline(UiTheme.CYAN, 2, 4) : UiTheme.surface(UiTheme.SURFACE, 4));
|
||||
t.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { show(target); } });
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, 50, 1);
|
||||
if (i > 0) p.setMargins(6, 0, 0, 0);
|
||||
tabs.addView(t, p);
|
||||
}
|
||||
if (index == 1 && player != null && playing != null) return; // keep player alive while refreshing
|
||||
content.removeAllViews();
|
||||
if (!hasStorage()) {
|
||||
content.addView(note("MG Utility needs storage access to keep recordings in " + DashcamStore.DIR_NAME + ", where they survive an app reinstall."));
|
||||
content.addView(button("GRANT STORAGE ACCESS", true, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, REQUEST_STORAGE); }
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (index == 0) statusTab();
|
||||
else if (index == 1) recordingsTab();
|
||||
else settingsTab();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
|
||||
private void statusTab() {
|
||||
boolean on = DashcamStore.enabled(this);
|
||||
List<DashcamPolicy.Clip> clips = DashcamStore.listClips();
|
||||
List<DashcamPolicy.Range> keep = DashcamStore.keepRanges();
|
||||
long used = DashcamPolicy.totalBytes(clips);
|
||||
long kept = DashcamPolicy.protectedBytes(clips, keep);
|
||||
long cap = DashcamStore.capGb(this) * 1024L * 1024L * 1024L;
|
||||
section("Recorder");
|
||||
content.addView(row("Dashcam", on ? DashcamService.describe() : "Off", null));
|
||||
if (!DashcamNative.available()) content.addView(row("Camera library", "Not loaded: " + DashcamNative.loadError(), null));
|
||||
String err = DashcamService.lastError();
|
||||
if (err != null && !err.isEmpty()) content.addView(row("Last problem", err, null));
|
||||
LinearLayout actions = new LinearLayout(this);
|
||||
actions.addView(button(on ? "TURN OFF" : "TURN ON", !on, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { setEnabled(!DashcamStore.enabled(DashcamActivity.this)); }
|
||||
}), weight());
|
||||
actions.addView(button("LOCK EVENT", true, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { DashcamService.saveMoment(DashcamActivity.this); show(0); }
|
||||
}), weight());
|
||||
content.addView(actions, new LinearLayout.LayoutParams(-1, 60));
|
||||
section("Storage");
|
||||
content.addView(row("Used on device", DashcamPolicy.formatBytes(used) + " of " + DashcamStore.capGb(this) + " GB budget", null));
|
||||
int waiting = DashcamEvents.pending().size();
|
||||
content.addView(row("Locked events", DashcamEvents.list().size() + " saved (" + DashcamPolicy.formatBytes(DashcamEvents.totalBytes()) + ")"
|
||||
+ (waiting > 0 ? ", " + waiting + " finishing" : ""), null));
|
||||
if (!DashcamEvents.lastError().isEmpty()) content.addView(row("Last event problem", DashcamEvents.lastError(), null));
|
||||
content.addView(row("Kept (never auto-deleted)", DashcamPolicy.formatBytes(kept) + " in " + DashcamStore.keeps().size() + " saved range(s)", null));
|
||||
content.addView(row("Auto-delete after", DashcamStore.retentionLabel(DashcamStore.retentionDays(this)), null));
|
||||
content.addView(row("Budget holds about", DashcamPolicy.minutesForBudget(cap, DashcamStore.bitrateBps(this)) / 60 + " h of driving", null));
|
||||
File recRoot = DashcamStore.recordingRoot(this);
|
||||
content.addView(row("Recording to", recRoot == null ? "Waiting for " + DashcamStore.customDir()
|
||||
: recRoot.getAbsolutePath() + (DashcamStore.usingFallback(this) ? " (USB missing - using head unit)" : ""), null));
|
||||
long free = DashcamStore.volumeFreeBytes(this);
|
||||
if (free >= 0) content.addView(row(recRoot != null && !DashcamStore.isInternal(recRoot) ? "Free on USB (approx.)" : "Free on head unit", DashcamPolicy.formatBytes(free), null));
|
||||
long parkedBytes = 0L;
|
||||
for (DashcamPolicy.Clip c : clips) if (c.lowPriority) parkedBytes += c.sizeBytes;
|
||||
content.addView(row("Parked footage (deleted first)", DashcamPolicy.formatBytes(parkedBytes), null));
|
||||
DashcamTelemetry.Point tp = DashcamTelemetry.latest();
|
||||
content.addView(row("Drive log", tp == null ? "No vehicle data yet" : String.format(Locale.US, "%.0f km/h • %.0f%% • %s%s",
|
||||
tp.kmh, tp.soc, tp.gear == DashcamTelemetry.GEAR_PARK ? "Park" : "gear " + tp.gear, tp.fix ? " • GPS" : " • no GPS"), null));
|
||||
if (kept > cap * 8 / 10) content.addView(note("Saved clips use most of the budget. Offload them to the server, or raise the budget, or new recording will have little room."));
|
||||
section("Offload to server");
|
||||
DashcamUploader.Route route = DashcamUploader.cachedRoute();
|
||||
content.addView(row("Network", route == null ? "Checking..." : route.label, null));
|
||||
if (route == null || DashcamUploader.cachedRouteAgeMs() > 30000L) refreshRoute();
|
||||
content.addView(row("Automatic offload", DashcamStore.uploadEnabled(this) ? "On (home network only)" : "Off", null));
|
||||
content.addView(row("Waiting to offload", DashcamPolicy.formatBytes(DashcamUploader.pendingBytes(DashcamService.activeClipName())), null));
|
||||
content.addView(row("Last run", DashcamUploader.lastRunMs() == 0 ? DashcamUploader.lastResult()
|
||||
: DashcamStore.timeLabel(DashcamUploader.lastRunMs()) + " - " + DashcamUploader.lastResult(), null));
|
||||
content.addView(button("OFFLOAD NOW", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { offloadNow(); }
|
||||
}), new LinearLayout.LayoutParams(-1, 56));
|
||||
}
|
||||
|
||||
private void setEnabled(boolean on) {
|
||||
DashcamStore.prefs(this).edit().putBoolean(DashcamStore.KEY_ENABLED, on).apply();
|
||||
if (on) DashcamService.startIfEnabled(this); else DashcamService.stop(this);
|
||||
ui.postDelayed(new Runnable() { @Override public void run() { show(tab); } }, 600L);
|
||||
}
|
||||
|
||||
private boolean routeRefreshing;
|
||||
|
||||
private void refreshRoute() {
|
||||
if (routeRefreshing) return;
|
||||
routeRefreshing = true;
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
DashcamUploader.route(DashcamActivity.this);
|
||||
runOnUiThread(new Runnable() { @Override public void run() { routeRefreshing = false; if (tab == 0) show(0); } });
|
||||
}
|
||||
}, "mg-dashcam-route").start();
|
||||
}
|
||||
|
||||
/** Away from home this goes over the phone's data, so say how much first. */
|
||||
private void offloadNow() {
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final DashcamUploader.Route route = DashcamUploader.route(DashcamActivity.this);
|
||||
final long pending = DashcamUploader.pendingBytes(DashcamService.activeClipName());
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
if (route.home) { startOffload(); return; }
|
||||
if (route.base.isEmpty()) {
|
||||
Toast.makeText(DashcamActivity.this, "Archive not reachable and no remote URL set", Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
UiTheme.dialog(DashcamActivity.this, "OFFLOAD OVER HOTSPOT?",
|
||||
"The car is not on the home network. About " + DashcamPolicy.formatBytes(pending)
|
||||
+ " will be uploaded over the internet (your phone's mobile data). Uploads resume where they stopped if the connection drops.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("UPLOAD", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) { startOffload(); }
|
||||
}).show();
|
||||
} });
|
||||
}
|
||||
}, "mg-dashcam-route").start();
|
||||
}
|
||||
|
||||
private void startOffload() {
|
||||
Toast.makeText(this, "Offloading...", Toast.LENGTH_SHORT).show();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final String r = DashcamUploader.runManual(DashcamActivity.this, DashcamService.activeClipName());
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
Toast.makeText(DashcamActivity.this, r, Toast.LENGTH_LONG).show(); show(tab); } });
|
||||
}
|
||||
}, "mg-dashcam-offload").start();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ recordings
|
||||
|
||||
private void recordingsTab() {
|
||||
List<DashcamPolicy.Clip> clips = DashcamStore.listClips();
|
||||
final List<DashcamStore.Keep> keeps = DashcamStore.keeps();
|
||||
List<DashcamPolicy.Range> ranges = DashcamStore.keepRanges();
|
||||
List<File> events = DashcamEvents.list();
|
||||
List<DashcamEvents.Pending> waiting = DashcamEvents.pending();
|
||||
if (!events.isEmpty() || !waiting.isEmpty()) {
|
||||
section("Locked events (never auto-deleted, uploaded first)");
|
||||
java.util.Set<String> up = DashcamStore.uploaded();
|
||||
for (DashcamEvents.Pending w : waiting) {
|
||||
content.addView(row("Event " + DashcamStore.timeLabel(w.clickMs), "finishing - recording the minute after", null));
|
||||
}
|
||||
for (final File ev : events) {
|
||||
long click = DashcamEvents.eventClickMs(ev.getName());
|
||||
String detail = DashcamPolicy.formatBytes(ev.length()) + (up.contains(ev.getName()) ? " • on server" : " • waiting to upload");
|
||||
content.addView(row("Event " + DashcamStore.dayLabel(click) + " " + DashcamStore.timeLabel(click), detail, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { openEvent(ev); }
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (!keeps.isEmpty()) {
|
||||
section("Kept ranges");
|
||||
for (final DashcamStore.Keep k : keeps) {
|
||||
String when = DashcamStore.dayLabel(k.startMs) + " " + DashcamStore.timeLabel(k.startMs) + " - " + DashcamStore.timeLabel(k.endMs);
|
||||
content.addView(row(k.label.isEmpty() ? "Kept range" : k.label, when, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
UiTheme.dialog(DashcamActivity.this, "REMOVE KEEP?",
|
||||
"The footage stays on the device and on the server, but becomes eligible for automatic deletion again.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) { DashcamStore.removeKeep(k.id); show(1); }
|
||||
}).show();
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (clips.isEmpty()) {
|
||||
section("Drives");
|
||||
content.addView(note("No recordings on the device yet."));
|
||||
return;
|
||||
}
|
||||
List<List<DashcamPolicy.Clip>> drives = DashcamPolicy.sessions(clips, DRIVE_GAP_MS);
|
||||
java.util.Set<String> uploaded = DashcamStore.uploaded();
|
||||
section("Drives (newest first)");
|
||||
for (int i = drives.size() - 1; i >= 0; i--) {
|
||||
final List<DashcamPolicy.Clip> drive = drives.get(i);
|
||||
DashcamPolicy.Clip first = drive.get(0), last = drive.get(drive.size() - 1);
|
||||
long minutes = Math.max(1L, (last.endMs - first.startMs) / 60000L);
|
||||
TextView head = UiTheme.label(this, (DashcamStore.dayLabel(first.startMs) + " " + DashcamStore.timeLabel(first.startMs)
|
||||
+ " - " + DashcamStore.timeLabel(last.endMs) + " • " + minutes + " min • "
|
||||
+ DashcamPolicy.formatBytes(DashcamPolicy.totalBytes(drive))).toUpperCase(Locale.US));
|
||||
head.setPadding(14, 14, 0, 4);
|
||||
content.addView(head);
|
||||
LinearLayout driveActions = new LinearLayout(this);
|
||||
driveActions.addView(button("KEEP WHOLE DRIVE", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
DashcamPolicy.Clip a = drive.get(0), b = drive.get(drive.size() - 1);
|
||||
askLabel("KEEP DRIVE", "Drive " + DashcamStore.dayLabel(a.startMs) + " " + DashcamStore.timeLabel(a.startMs), a.startMs, b.endMs);
|
||||
}
|
||||
}), weight());
|
||||
content.addView(driveActions, new LinearLayout.LayoutParams(-1, 52));
|
||||
for (int j = drive.size() - 1; j >= 0; j--) {
|
||||
final DashcamPolicy.Clip c = drive.get(j);
|
||||
boolean kept = DashcamPolicy.isProtected(c, ranges);
|
||||
boolean live = c.name.equals(DashcamService.activeClipName());
|
||||
String detail = DashcamPolicy.formatBytes(c.sizeBytes)
|
||||
+ (live ? " • recording" : "")
|
||||
+ (kept ? " • KEPT" : "")
|
||||
+ (uploaded.contains(c.name) ? " • on server" : "");
|
||||
content.addView(row(DashcamStore.timeLabel(c.startMs), detail, live ? null : new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { openPlayer(c); }
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void openEvent(final File ev) {
|
||||
stopPlayer();
|
||||
content.removeAllViews();
|
||||
section(ev.getName());
|
||||
FrameLayout frame = new FrameLayout(this);
|
||||
frame.setBackgroundColor(0xff000000);
|
||||
final VideoView v = new VideoView(this);
|
||||
player = v;
|
||||
frame.addView(v, new FrameLayout.LayoutParams(-1, -1, Gravity.CENTER));
|
||||
content.addView(frame, new LinearLayout.LayoutParams(-1, 420));
|
||||
LinearLayout controls = new LinearLayout(this);
|
||||
controls.addView(button("PLAY / PAUSE", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View x) { if (v.isPlaying()) v.pause(); else v.start(); }
|
||||
}), weight());
|
||||
controls.addView(button("DELETE EVENT", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View x) {
|
||||
UiTheme.dialog(DashcamActivity.this, "DELETE EVENT?",
|
||||
"Removes this event from the car. A copy already uploaded stays on the server.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) { stopPlayer(); DashcamEvents.delete(ev); show(1); }
|
||||
}).show();
|
||||
}
|
||||
}), weight());
|
||||
controls.addView(button("CLOSE", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View x) { stopPlayer(); show(1); }
|
||||
}), weight());
|
||||
content.addView(controls, new LinearLayout.LayoutParams(-1, 56));
|
||||
v.setVideoURI(Uri.fromFile(ev));
|
||||
v.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { v.start(); } });
|
||||
}
|
||||
|
||||
private void openPlayer(final DashcamPolicy.Clip clip) {
|
||||
stopPlayer();
|
||||
playing = clip;
|
||||
markIn = -1L; markOut = -1L;
|
||||
content.removeAllViews();
|
||||
section("Clip " + DashcamStore.dayLabel(clip.startMs) + " " + DashcamStore.timeLabel(clip.startMs));
|
||||
FrameLayout frame = new FrameLayout(this);
|
||||
frame.setBackgroundColor(0xff000000);
|
||||
player = new VideoView(this);
|
||||
frame.addView(player, new FrameLayout.LayoutParams(-1, -1, Gravity.CENTER));
|
||||
content.addView(frame, new LinearLayout.LayoutParams(-1, 380));
|
||||
scrub = new SeekBar(this);
|
||||
UiTheme.tintSeekBar(scrub);
|
||||
content.addView(scrub, new LinearLayout.LayoutParams(-1, 48));
|
||||
playerLabel = UiTheme.text(this, "", 13, UiTheme.MUTED, Typeface.NORMAL);
|
||||
playerLabel.setPadding(14, 0, 0, 6);
|
||||
content.addView(playerLabel);
|
||||
LinearLayout controls = new LinearLayout(this);
|
||||
controls.addView(button("PLAY / PAUSE", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { if (player.isPlaying()) player.pause(); else player.start(); }
|
||||
}), weight());
|
||||
controls.addView(button("MARK START", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { markIn = player.getCurrentPosition(); updatePlayerLabel(); }
|
||||
}), weight());
|
||||
controls.addView(button("MARK END", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { markOut = player.getCurrentPosition(); updatePlayerLabel(); }
|
||||
}), weight());
|
||||
content.addView(controls, new LinearLayout.LayoutParams(-1, 56));
|
||||
LinearLayout keepRow = new LinearLayout(this);
|
||||
keepRow.addView(button("KEEP MARKED PART", true, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
if (markIn < 0 || markOut < 0 || markOut <= markIn) {
|
||||
Toast.makeText(DashcamActivity.this, "Mark a start and an end first", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
askLabel("KEEP PART", "Clip " + DashcamStore.timeLabel(clip.startMs + markIn), clip.startMs + markIn, clip.startMs + markOut);
|
||||
}
|
||||
}), weight());
|
||||
keepRow.addView(button("KEEP WHOLE CLIP", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { askLabel("KEEP CLIP", "Clip " + DashcamStore.timeLabel(clip.startMs), clip.startMs, clip.endMs); }
|
||||
}), weight());
|
||||
keepRow.addView(button("CLOSE", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { stopPlayer(); show(1); }
|
||||
}), weight());
|
||||
content.addView(keepRow, new LinearLayout.LayoutParams(-1, 56));
|
||||
content.addView(note("Tip: a kept part protects every clip file it touches, so a few seconds may be kept on either side."));
|
||||
|
||||
File f = DashcamStore.clipFile(clip.name);
|
||||
player.setVideoURI(Uri.fromFile(f));
|
||||
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
|
||||
@Override public void onPrepared(MediaPlayer mp) {
|
||||
scrub.setMax(Math.max(1, player.getDuration()));
|
||||
player.start();
|
||||
ui.post(progress);
|
||||
}
|
||||
});
|
||||
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
|
||||
@Override public boolean onError(MediaPlayer mp, int what, int extra) {
|
||||
playerLabel.setText("This clip cannot be played (" + what + "/" + extra + ")");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
scrub.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar s, int p, boolean fromUser) { if (fromUser && player != null) player.seekTo(p); }
|
||||
@Override public void onStartTrackingTouch(SeekBar s) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar s) { }
|
||||
});
|
||||
}
|
||||
|
||||
private final Runnable progress = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (player == null) return;
|
||||
scrub.setProgress(player.getCurrentPosition());
|
||||
updatePlayerLabel();
|
||||
ui.postDelayed(this, 300L);
|
||||
}
|
||||
};
|
||||
|
||||
private void updatePlayerLabel() {
|
||||
if (player == null || playing == null || playerLabel == null) return;
|
||||
String text = DashcamStore.timeLabel(playing.startMs + player.getCurrentPosition());
|
||||
if (markIn >= 0) text += " start " + DashcamStore.timeLabel(playing.startMs + markIn);
|
||||
if (markOut >= 0) text += " end " + DashcamStore.timeLabel(playing.startMs + markOut);
|
||||
playerLabel.setText(text);
|
||||
}
|
||||
|
||||
private void stopPlayer() {
|
||||
ui.removeCallbacks(progress);
|
||||
if (player != null) { try { player.stopPlayback(); } catch (Throwable ignored) { } }
|
||||
player = null;
|
||||
playing = null;
|
||||
}
|
||||
|
||||
private void askLabel(String title, String suggestion, final long start, final long end) {
|
||||
final EditText input = new EditText(this);
|
||||
input.setText(suggestion);
|
||||
input.setTextColor(UiTheme.TEXT);
|
||||
input.setInputType(InputType.TYPE_CLASS_TEXT);
|
||||
UiTheme.dialog(this).setTitle(title).setView(input)
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("KEEP", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) {
|
||||
DashcamStore.addKeep(start, end, input.getText().toString().trim());
|
||||
Toast.makeText(DashcamActivity.this, "Kept - excluded from auto-delete", Toast.LENGTH_SHORT).show();
|
||||
if (DashcamStore.uploadEnabled(DashcamActivity.this)) DashcamService.uploadNow(DashcamActivity.this);
|
||||
stopPlayer();
|
||||
show(1);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ settings
|
||||
|
||||
private void settingsTab() {
|
||||
final SharedPreferences p = DashcamStore.prefs(this);
|
||||
section("Recording folder");
|
||||
String dir = DashcamStore.customDir();
|
||||
content.addView(row("Save recordings to", dir.isEmpty() ? "Head unit (" + DashcamStore.DIR_NAME + ")" : dir, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { pickFolder(); }
|
||||
}));
|
||||
if (!dir.isEmpty()) {
|
||||
content.addView(row("Folder status", DashcamStore.customUsable() ? "Writable" : "Not writable / not plugged in", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { DashcamStore.init(DashcamActivity.this); show(tab); }
|
||||
}));
|
||||
content.addView(toggle("If the USB is missing, record to the head unit", DashcamStore.KEY_FALLBACK_INTERNAL, true));
|
||||
}
|
||||
content.addView(note("Pick a folder on a USB stick to use it as extra storage. Clips and locked events are written there; "
|
||||
+ "the keep list stays on the head unit. Footage already recorded elsewhere is still listed, uploaded and cleaned up. "
|
||||
+ "Use a stick formatted FAT32 or exFAT, ideally a high-endurance one: dashcams wear cheap sticks out."));
|
||||
section("On-device storage");
|
||||
content.addView(row("Storage budget", DashcamStore.capGb(this) + " GB", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose("STORAGE BUDGET", gbLabels(), DashcamStore.CAP_CHOICES_GB, DashcamStore.KEY_CAP_GB);
|
||||
}
|
||||
}));
|
||||
content.addView(row("Auto-delete recordings after", DashcamStore.retentionLabel(DashcamStore.retentionDays(this)), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
String[] labels = new String[DashcamStore.RETENTION_CHOICES_DAYS.length];
|
||||
for (int i = 0; i < labels.length; i++) labels[i] = DashcamStore.retentionLabel(DashcamStore.RETENTION_CHOICES_DAYS[i]);
|
||||
choose("AUTO-DELETE AFTER", labels, DashcamStore.RETENTION_CHOICES_DAYS, DashcamStore.KEY_RETENTION_DAYS);
|
||||
}
|
||||
}));
|
||||
content.addView(note("Locked events are separate files in the events folder and are never deleted automatically. "
|
||||
+ "When the budget is full, parked footage goes first, then the oldest driving footage. Kept ranges are never removed "
|
||||
+ "automatically. On the head unit at least " + DashcamPolicy.formatBytes(DashcamStore.VOLUME_RESERVE_BYTES)
|
||||
+ " is always left free; on a USB stick the budget is capped at the stick's size."));
|
||||
section("Recording");
|
||||
content.addView(row("Clip length", DashcamStore.segmentSec(this) + " s", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose("CLIP LENGTH", new String[] { "30 s", "60 s", "120 s", "180 s" }, new int[] { 30, 60, 120, 180 }, DashcamStore.KEY_SEGMENT_SEC);
|
||||
}
|
||||
}));
|
||||
content.addView(row("Driving quality", (DashcamStore.bitrateBps(this) / 1000) + " kbit/s (" + DashcamStore.perHour(DashcamStore.bitrateBps(this)) + ")", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
int[] kbps = { 3000, 4500, 6000, 9000, 14000 };
|
||||
String[] names = { "Saver", "Balanced", "Standard", "High", "Max" };
|
||||
String[] labels = new String[kbps.length];
|
||||
for (int i = 0; i < kbps.length; i++) labels[i] = names[i] + " " + (kbps[i] / 1000f) + " Mbit/s (" + DashcamStore.perHour(kbps[i] * 1000) + ")";
|
||||
choose("DRIVING QUALITY", labels, kbps, DashcamStore.KEY_BITRATE_KBPS);
|
||||
}
|
||||
}));
|
||||
content.addView(row("Parked quality", DashcamStore.parkedModeLabel(DashcamStore.parkedMode(this)), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
int[] modes = { DashcamStore.PARKED_LOW, DashcamStore.PARKED_MEDIUM, DashcamStore.PARKED_FULL, DashcamStore.PARKED_OFF };
|
||||
String[] labels = new String[modes.length];
|
||||
for (int i = 0; i < modes.length; i++) {
|
||||
int m = modes[i];
|
||||
labels[i] = DashcamStore.parkedModeLabel(m) + (m == DashcamStore.PARKED_OFF ? "" : " (" + DashcamStore.perHour(DashcamStore.bitrateFor(DashcamActivity.this, true, m)) + ")");
|
||||
}
|
||||
choose("PARKED QUALITY", labels, modes, DashcamStore.KEY_PARKED_MODE);
|
||||
}
|
||||
}));
|
||||
content.addView(row("Delete parked footage after", DashcamStore.retentionLabel(DashcamStore.parkedRetentionDays(this)).replace("Never (budget only)", "Same as driving"), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose("DELETE PARKED FOOTAGE AFTER", new String[] { "1 day", "3 days", "7 days", "14 days", "Same as driving" },
|
||||
new int[] { 1, 3, 7, 14, 0 }, DashcamStore.KEY_PARKED_RETENTION_DAYS);
|
||||
}
|
||||
}));
|
||||
content.addView(note("Parked = gear in P and standing still. Parked clips are smaller and are the first to go when space runs out, "
|
||||
+ "before any driving footage. Moving off switches back to driving quality within about 2 seconds."));
|
||||
content.addView(row("Lock event: before the press", DashcamService.fmtDur(DashcamStore.saveBeforeSec(this)), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose("EVENT: BEFORE THE PRESS", new String[] { "30 s", "1 min", "2 min", "3 min", "5 min" },
|
||||
new int[] { 30, 60, 120, 180, 300 }, DashcamStore.KEY_SAVE_BEFORE_SEC);
|
||||
}
|
||||
}));
|
||||
content.addView(row("Lock event: after the press", DashcamService.fmtDur(DashcamStore.saveAfterSec(this)), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose("EVENT: AFTER THE PRESS", new String[] { "30 s", "1 min", "2 min", "3 min" },
|
||||
new int[] { 30, 60, 120, 180 }, DashcamStore.KEY_SAVE_AFTER_SEC);
|
||||
}
|
||||
}));
|
||||
content.addView(toggle("Speed in footer", DashcamStore.KEY_SHOW_SPEED, true));
|
||||
content.addView(toggle("Hand cameras to the 360 view", DashcamStore.KEY_OEM_HANDOFF, true));
|
||||
content.addView(row("Footer text", DashcamStore.signature(this), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { editText("FOOTER TEXT", DashcamStore.KEY_SIGNATURE, DashcamStore.signature(DashcamActivity.this), false); }
|
||||
}));
|
||||
section("Offload to server");
|
||||
content.addView(toggle("Offload automatically on home network", DashcamStore.KEY_UPLOAD_ENABLED, false));
|
||||
content.addView(toggle("Free device space after a verified upload", DashcamStore.KEY_UPLOAD_DELETE_LOCAL, true));
|
||||
content.addView(row("Home (LAN) URL", DashcamStore.serverUrl(this).isEmpty() ? "Not set" : DashcamStore.serverUrl(this), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { editText("HOME (LAN) URL", DashcamStore.KEY_SERVER_URL, DashcamStore.serverUrl(DashcamActivity.this), false); }
|
||||
}));
|
||||
content.addView(row("Remote URL (hotspot)", DashcamStore.remoteUrl(this).isEmpty() ? "Not set" : DashcamStore.remoteUrl(this), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { editText("REMOTE URL", DashcamStore.KEY_REMOTE_URL, DashcamStore.remoteUrl(DashcamActivity.this), false); }
|
||||
}));
|
||||
content.addView(row("Access token", DashcamStore.serverToken(this).isEmpty() ? "Not set" : "Set (" + DashcamStore.serverToken(this).length() + " chars)", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { editText("ACCESS TOKEN", DashcamStore.KEY_SERVER_TOKEN, DashcamStore.serverToken(DashcamActivity.this), true); }
|
||||
}));
|
||||
content.addView(button("TEST CONNECTION", false, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final String r = DashcamUploader.test(DashcamActivity.this);
|
||||
runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(DashcamActivity.this, r, Toast.LENGTH_LONG).show(); } });
|
||||
} }, "mg-dashcam-test").start();
|
||||
}
|
||||
}), new LinearLayout.LayoutParams(-1, 56));
|
||||
content.addView(note("Home is detected by reaching the archive on its LAN address, which is impossible over a phone hotspot. "
|
||||
+ "At home, uploads run automatically every two minutes. Elsewhere, nothing is uploaded until you press OFFLOAD NOW on the Status tab. "
|
||||
+ "A clip is only removed from the car after the server reports the same size and SHA-256. "
|
||||
+ "The server applies the same auto-delete age, and never deletes kept ranges."));
|
||||
}
|
||||
|
||||
/** Lists head-unit storage and every mounted USB volume; also allows a typed path. */
|
||||
private void pickFolder() {
|
||||
final List<DashcamStore.Volume> vols = DashcamStore.volumes();
|
||||
String[] labels = new String[vols.size() + 1];
|
||||
for (int i = 0; i < vols.size(); i++) {
|
||||
DashcamStore.Volume v = vols.get(i);
|
||||
labels[i] = v.label + (v.total > 0 ? " • " + DashcamPolicy.formatBytes(v.total) : "") + "\n" + v.suggested.getAbsolutePath();
|
||||
}
|
||||
labels[vols.size()] = "Type a folder path...";
|
||||
UiTheme.dialog(this).setTitle("SAVE RECORDINGS TO").setItems(labels, new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int which) {
|
||||
if (which == vols.size()) {
|
||||
typeFolder();
|
||||
return;
|
||||
}
|
||||
DashcamStore.Volume v = vols.get(which);
|
||||
applyFolder(which == 0 ? "" : v.suggested.getAbsolutePath());
|
||||
}
|
||||
}).setNegativeButton("CANCEL", null).show();
|
||||
}
|
||||
|
||||
private void typeFolder() {
|
||||
final EditText input = new EditText(this);
|
||||
input.setText(DashcamStore.customDir().isEmpty() ? "/mnt/media_rw/" : DashcamStore.customDir());
|
||||
input.setTextColor(UiTheme.TEXT);
|
||||
input.setSingleLine(true);
|
||||
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
|
||||
UiTheme.dialog(this).setTitle("FOLDER PATH").setView(input)
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("USE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) { applyFolder(input.getText().toString().trim()); }
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void applyFolder(final String path) {
|
||||
if (path.isEmpty()) {
|
||||
DashcamStore.setCustomDir(this, "");
|
||||
Toast.makeText(this, "Recording to the head unit", Toast.LENGTH_SHORT).show();
|
||||
DashcamService.restartRecording(this);
|
||||
show(tab);
|
||||
return;
|
||||
}
|
||||
Toast.makeText(this, "Testing " + path + " ...", Toast.LENGTH_SHORT).show();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final boolean ok = DashcamStore.writable(new File(path));
|
||||
final long total = DashcamStore.volumeTotalBytes(new File(path));
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
if (!ok) {
|
||||
UiTheme.dialog(DashcamActivity.this, "CAN'T WRITE THERE",
|
||||
"MG Utility could not create and write a test file in " + path + ". Check the USB stick is plugged in "
|
||||
+ "and not read-only. Try the \"(direct)\" entry for the stick if the /storage one fails.")
|
||||
.setPositiveButton("OK", null).show();
|
||||
return;
|
||||
}
|
||||
DashcamStore.setCustomDir(DashcamActivity.this, path);
|
||||
long totalGb = total / (1024L * 1024L * 1024L);
|
||||
String msg = "Recordings now go to " + path + ".";
|
||||
if (totalGb > DashcamStore.capGb(DashcamActivity.this) * 2L) {
|
||||
msg += " The storage budget is " + DashcamStore.capGb(DashcamActivity.this) + " GB but the stick holds "
|
||||
+ DashcamPolicy.formatBytes(total) + ". Raise the budget under On-device storage to use it.";
|
||||
}
|
||||
UiTheme.dialog(DashcamActivity.this, "FOLDER SET", msg).setPositiveButton("OK", null).show();
|
||||
DashcamService.restartRecording(DashcamActivity.this);
|
||||
show(tab);
|
||||
} });
|
||||
}
|
||||
}, "mg-dashcam-folder").start();
|
||||
}
|
||||
|
||||
private String[] gbLabels() {
|
||||
String[] out = new String[DashcamStore.CAP_CHOICES_GB.length];
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
long bytes = DashcamStore.CAP_CHOICES_GB[i] * 1024L * 1024L * 1024L;
|
||||
out[i] = DashcamStore.CAP_CHOICES_GB[i] + " GB (~" + DashcamPolicy.minutesForBudget(bytes, DashcamStore.bitrateBps(this)) / 60 + " h driving)";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private void choose(String title, String[] labels, final int[] values, final String key) {
|
||||
UiTheme.dialog(this).setTitle(title).setItems(labels, new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int which) {
|
||||
DashcamStore.prefs(DashcamActivity.this).edit().putInt(key, values[which]).apply();
|
||||
show(tab);
|
||||
}
|
||||
}).setNegativeButton("CANCEL", null).show();
|
||||
}
|
||||
|
||||
private void editText(String title, final String key, String current, boolean secret) {
|
||||
final EditText input = new EditText(this);
|
||||
input.setText(current);
|
||||
input.setTextColor(UiTheme.TEXT);
|
||||
input.setSingleLine(true);
|
||||
input.setInputType(secret ? InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
|
||||
: InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
|
||||
UiTheme.dialog(this).setTitle(title).setView(input)
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface d, int w) {
|
||||
DashcamStore.prefs(DashcamActivity.this).edit().putString(key, input.getText().toString().trim()).apply();
|
||||
show(tab);
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ small views
|
||||
|
||||
private void section(String title) {
|
||||
TextView t = UiTheme.label(this, title.toUpperCase(Locale.US));
|
||||
t.setPadding(10, 12, 0, 6);
|
||||
content.addView(t);
|
||||
}
|
||||
|
||||
private TextView note(String text) {
|
||||
TextView t = UiTheme.text(this, text, 12, UiTheme.MUTED, Typeface.NORMAL);
|
||||
t.setPadding(14, 6, 14, 10);
|
||||
return t;
|
||||
}
|
||||
|
||||
private View row(String label, String value, View.OnClickListener listener) {
|
||||
LinearLayout item = new LinearLayout(this);
|
||||
item.setGravity(Gravity.CENTER_VERTICAL);
|
||||
item.setPadding(18, 0, 18, 0);
|
||||
item.setBackground(UiTheme.surface(UiTheme.SURFACE, 5));
|
||||
if (listener != null) item.setOnClickListener(listener);
|
||||
TextView name = UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL);
|
||||
name.setGravity(Gravity.CENTER_VERTICAL);
|
||||
item.addView(name, new LinearLayout.LayoutParams(0, 64, 1));
|
||||
TextView detail = UiTheme.text(this, value, 13, UiTheme.MUTED, Typeface.NORMAL);
|
||||
detail.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
|
||||
item.addView(detail, new LinearLayout.LayoutParams(0, 64, 1.4f));
|
||||
TextView arrow = UiTheme.text(this, listener == null ? "" : "›", 25, UiTheme.CYAN, Typeface.NORMAL);
|
||||
arrow.setGravity(Gravity.CENTER);
|
||||
item.addView(arrow, new LinearLayout.LayoutParams(32, 64));
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 64);
|
||||
p.setMargins(0, 0, 0, 2);
|
||||
item.setLayoutParams(p);
|
||||
return item;
|
||||
}
|
||||
|
||||
private View toggle(String label, final String key, final boolean def) {
|
||||
final boolean on = DashcamStore.prefs(this).getBoolean(key, def);
|
||||
return row(label, on ? "ON" : "OFF", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
DashcamStore.prefs(DashcamActivity.this).edit().putBoolean(key, !on).apply();
|
||||
show(tab);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Button button(String label, boolean primary, View.OnClickListener l) {
|
||||
return UiTheme.button(this, label, l, primary);
|
||||
}
|
||||
|
||||
private LinearLayout.LayoutParams weight() {
|
||||
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, 52, 1);
|
||||
p.setMargins(0, 4, 6, 4);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaExtractor;
|
||||
import android.media.MediaFormat;
|
||||
import android.media.MediaMuxer;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* "Something happened" events: a separate MP4 covering N seconds before and M seconds after the
|
||||
* press (default 2 min + 1 min), stitched from the loop segments.
|
||||
*
|
||||
* <p>Event files live in {@code MG-Utility/dashcam/events}, are never deleted automatically on the
|
||||
* car or the server, and upload before ordinary clips. While an event waits for its "after" part,
|
||||
* its source segments are protected by a keep range, so nothing can be lost if the build fails;
|
||||
* the keep range is released only after the event file has been written and verified.
|
||||
*/
|
||||
final class DashcamEvents {
|
||||
private static final String TAG = "MGDashcamEvent";
|
||||
static final String PREFIX = "EVENT_";
|
||||
private static final Object LOCK = new Object();
|
||||
private static volatile Thread worker;
|
||||
private static volatile String lastError = "";
|
||||
|
||||
private DashcamEvents() { }
|
||||
|
||||
static String lastError() { return lastError; }
|
||||
|
||||
static File eventsDir() {
|
||||
File d = new File(DashcamStore.rootDir(), "events");
|
||||
if (!d.isDirectory()) d.mkdirs();
|
||||
return d;
|
||||
}
|
||||
|
||||
private static File pendingFile() { return new File(eventsDir(), "pending.json"); }
|
||||
|
||||
static String eventName(long clickMs) {
|
||||
return PREFIX + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date(clickMs)) + ".mp4";
|
||||
}
|
||||
|
||||
static boolean isEventName(String name) {
|
||||
return name != null && name.startsWith(PREFIX) && DashcamPolicy.clipStart(name.substring(PREFIX.length())) >= 0;
|
||||
}
|
||||
|
||||
static long eventClickMs(String name) {
|
||||
return isEventName(name) ? DashcamPolicy.clipStart(name.substring(PREFIX.length())) : -1L;
|
||||
}
|
||||
|
||||
static final class Pending {
|
||||
final String name;
|
||||
final long clickMs, startMs, endMs;
|
||||
final String keepId;
|
||||
Pending(String name, long clickMs, long startMs, long endMs, String keepId) {
|
||||
this.name = name; this.clickMs = clickMs; this.startMs = startMs; this.endMs = endMs; this.keepId = keepId;
|
||||
}
|
||||
}
|
||||
|
||||
/** Finished event files from every storage folder, newest first. */
|
||||
static List<File> list() {
|
||||
List<File> out = new ArrayList<File>();
|
||||
java.util.Set<String> seen = new java.util.HashSet<String>();
|
||||
for (File root : DashcamStore.allRoots()) {
|
||||
File[] files = new File(root, "events").listFiles();
|
||||
if (files != null) for (File f : files) if (f.isFile() && isEventName(f.getName()) && seen.add(f.getName())) out.add(f);
|
||||
}
|
||||
java.util.Collections.sort(out, new Comparator<File>() {
|
||||
@Override public int compare(File a, File b) { return b.getName().compareTo(a.getName()); }
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
static File find(String name) {
|
||||
for (File root : DashcamStore.allRoots()) {
|
||||
File f = new File(new File(root, "events"), name);
|
||||
if (f.isFile()) return f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static long totalBytes() {
|
||||
long t = 0L;
|
||||
for (File f : list()) t += f.length();
|
||||
return t;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ request
|
||||
|
||||
/** The control-panel / key / notification button. Returns the event file name. */
|
||||
static String request(Context context) {
|
||||
long now = System.currentTimeMillis();
|
||||
long start = now - DashcamStore.saveBeforeSec(context) * 1000L;
|
||||
long end = now + DashcamStore.saveAfterSec(context) * 1000L;
|
||||
String name = eventName(now);
|
||||
synchronized (LOCK) {
|
||||
DashcamStore.Keep keep = DashcamStore.addKeep(start, end,
|
||||
"Event " + DashcamStore.dayLabel(now) + " " + DashcamStore.timeLabel(now) + " (building)");
|
||||
List<Pending> all = pending();
|
||||
all.add(new Pending(name, now, start, end, keep.id));
|
||||
writePending(all);
|
||||
}
|
||||
kick(context);
|
||||
return name;
|
||||
}
|
||||
|
||||
static List<Pending> pending() {
|
||||
synchronized (LOCK) {
|
||||
List<Pending> out = new ArrayList<Pending>();
|
||||
File f = pendingFile();
|
||||
if (!f.isFile()) return out;
|
||||
try {
|
||||
JSONArray a = new JSONArray(DashcamStore.readText(f));
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
JSONObject o = a.getJSONObject(i);
|
||||
out.add(new Pending(o.getString("name"), o.getLong("click"), o.getLong("start"),
|
||||
o.getLong("end"), o.optString("keep")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "pending list unreadable", e);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
private static void writePending(List<Pending> all) {
|
||||
try {
|
||||
JSONArray a = new JSONArray();
|
||||
for (Pending p : all) {
|
||||
JSONObject o = new JSONObject();
|
||||
o.put("name", p.name); o.put("click", p.clickMs); o.put("start", p.startMs);
|
||||
o.put("end", p.endMs); o.put("keep", p.keepId);
|
||||
a.put(o);
|
||||
}
|
||||
DashcamStore.writeTextAtomic(pendingFile(), a.toString(2));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "pending list not written", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void removePending(String name) {
|
||||
synchronized (LOCK) {
|
||||
List<Pending> next = new ArrayList<Pending>();
|
||||
for (Pending p : pending()) if (!p.name.equals(name)) next.add(p);
|
||||
writePending(next);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ worker
|
||||
|
||||
/** Starts the builder if anything is waiting. Safe to call often (app start, service start). */
|
||||
static void kick(final Context context) {
|
||||
if (context == null) return;
|
||||
final Context app = context.getApplicationContext();
|
||||
synchronized (DashcamEvents.class) {
|
||||
Thread w = worker;
|
||||
if (w != null && w.isAlive()) return;
|
||||
if (pending().isEmpty()) return;
|
||||
w = new Thread(new Runnable() { @Override public void run() { work(app); } }, "mg-dashcam-event");
|
||||
worker = w;
|
||||
w.start();
|
||||
}
|
||||
}
|
||||
|
||||
private static void work(Context context) {
|
||||
try {
|
||||
while (true) {
|
||||
List<Pending> all = pending();
|
||||
if (all.isEmpty()) break;
|
||||
boolean built = false;
|
||||
for (Pending p : all) {
|
||||
if (ready(p)) { build(context, p); built = true; }
|
||||
}
|
||||
if (built && DashcamStore.uploadEnabled(context)) {
|
||||
// Events go first; at home this pushes the new event straight to the server.
|
||||
DashcamUploader.runAuto(context, DashcamService.activeClipName());
|
||||
}
|
||||
try { Thread.sleep(5000L); } catch (InterruptedException e) { break; }
|
||||
}
|
||||
} finally {
|
||||
worker = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The after-part has been recorded and closed, or we have waited long enough to give up on it. */
|
||||
private static boolean ready(Pending p) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now < p.endMs + 3000L) return false;
|
||||
if (now > p.endMs + 10L * 60L * 1000L) return true;
|
||||
String active = DashcamService.activeClipName();
|
||||
if (active == null) return true;
|
||||
long activeStart = DashcamPolicy.clipStart(active);
|
||||
return activeStart < 0 || activeStart > p.endMs;
|
||||
}
|
||||
|
||||
private static void build(Context context, Pending p) {
|
||||
List<DashcamPolicy.Clip> sources = DashcamPolicy.clipsInRange(DashcamStore.listClips(),
|
||||
new DashcamPolicy.Range(p.startMs, p.endMs));
|
||||
String active = DashcamService.activeClipName();
|
||||
List<DashcamPolicy.Clip> usable = new ArrayList<DashcamPolicy.Clip>();
|
||||
for (DashcamPolicy.Clip c : sources) if (!c.name.equals(active)) usable.add(c);
|
||||
if (usable.isEmpty()) {
|
||||
removePending(p.name);
|
||||
DashcamStore.removeKeep(p.keepId);
|
||||
fail(context, "Event " + DashcamStore.timeLabel(p.clickMs) + ": no dashcam footage around that moment");
|
||||
return;
|
||||
}
|
||||
File dir = DashcamStore.eventsWriteDir();
|
||||
File out = new File(dir, p.name);
|
||||
File tmp = new File(dir, p.name + ".part");
|
||||
try {
|
||||
stitch(usable, p.startMs, p.endMs, tmp);
|
||||
if (!tmp.isFile() || tmp.length() < 64 * 1024) throw new IOException("event file came out empty");
|
||||
if (!tmp.renameTo(out)) throw new IOException("rename failed");
|
||||
writeEventTelemetry(usable, p, out);
|
||||
removePending(p.name);
|
||||
// The stitched file now holds the footage; the source segments may age out normally.
|
||||
DashcamStore.removeKeep(p.keepId);
|
||||
lastError = "";
|
||||
toast(context, "Dashcam event saved: " + p.name + " (" + DashcamPolicy.formatBytes(out.length()) + ")");
|
||||
Log.i(TAG, "built " + p.name + " from " + usable.size() + " segment(s)");
|
||||
} catch (Throwable t) {
|
||||
tmp.delete();
|
||||
removePending(p.name);
|
||||
// Keep range stays: the footage is still protected even though the stitch failed.
|
||||
Log.w(TAG, "event build failed", t);
|
||||
fail(context, "Event " + DashcamStore.timeLabel(p.clickMs) + " could not be stitched ("
|
||||
+ t.getClass().getSimpleName() + "). The footage is kept as a range instead.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void fail(Context context, String message) {
|
||||
lastError = message;
|
||||
toast(context, message);
|
||||
}
|
||||
|
||||
private static void toast(final Context context, final String text) {
|
||||
new Handler(Looper.getMainLooper()).post(new Runnable() {
|
||||
@Override public void run() {
|
||||
try { Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (Throwable ignored) { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ stitching
|
||||
|
||||
/**
|
||||
* Copies the H.264 samples covering [startMs, endMs] from consecutive segments into one MP4,
|
||||
* without re-encoding. Cuts land on keyframes (the encoder emits one every second), and each
|
||||
* segment's timestamps continue where the previous one ended.
|
||||
*/
|
||||
static void stitch(List<DashcamPolicy.Clip> clips, long startMs, long endMs, File out) throws IOException {
|
||||
List<DashcamPolicy.Clip> sorted = new ArrayList<DashcamPolicy.Clip>(clips);
|
||||
java.util.Collections.sort(sorted, new Comparator<DashcamPolicy.Clip>() {
|
||||
@Override public int compare(DashcamPolicy.Clip a, DashcamPolicy.Clip b) {
|
||||
return a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0;
|
||||
}
|
||||
});
|
||||
out.delete();
|
||||
MediaMuxer muxer = null;
|
||||
int track = -1;
|
||||
long base = 0L, maxPts = -1L, frameUs = 40000L;
|
||||
int samples = 0;
|
||||
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
|
||||
ByteBuffer buf = ByteBuffer.allocate(4 * 1024 * 1024);
|
||||
try {
|
||||
for (DashcamPolicy.Clip clip : sorted) {
|
||||
MediaExtractor ex = new MediaExtractor();
|
||||
try {
|
||||
ex.setDataSource(DashcamStore.clipFile(clip.name).getAbsolutePath());
|
||||
int idx = -1;
|
||||
MediaFormat format = null;
|
||||
for (int i = 0; i < ex.getTrackCount(); i++) {
|
||||
MediaFormat f = ex.getTrackFormat(i);
|
||||
String mime = f.getString(MediaFormat.KEY_MIME);
|
||||
if (mime != null && mime.startsWith("video/")) { idx = i; format = f; break; }
|
||||
}
|
||||
if (idx < 0) continue;
|
||||
ex.selectTrack(idx);
|
||||
if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
|
||||
int max = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
|
||||
if (max > buf.capacity()) buf = ByteBuffer.allocate(max);
|
||||
}
|
||||
if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) {
|
||||
try { frameUs = 1000000L / Math.max(1, format.getInteger(MediaFormat.KEY_FRAME_RATE)); }
|
||||
catch (Throwable ignored) { }
|
||||
}
|
||||
if (muxer == null) {
|
||||
muxer = new MediaMuxer(out.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
|
||||
track = muxer.addTrack(format);
|
||||
muxer.start();
|
||||
}
|
||||
long fromUs = Math.max(0L, startMs - clip.startMs) * 1000L;
|
||||
long toUs = (endMs - clip.startMs) * 1000L;
|
||||
if (fromUs > 0) ex.seekTo(fromUs, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
|
||||
long first = -1L;
|
||||
while (true) {
|
||||
buf.clear();
|
||||
int n = ex.readSampleData(buf, 0);
|
||||
if (n < 0) break;
|
||||
long t = ex.getSampleTime();
|
||||
if (t > toUs) break;
|
||||
boolean sync = (ex.getSampleFlags() & MediaExtractor.SAMPLE_FLAG_SYNC) != 0;
|
||||
if (first < 0) {
|
||||
if (!sync) { ex.advance(); continue; }
|
||||
first = t;
|
||||
}
|
||||
long pts = base + (t - first);
|
||||
info.set(0, n, pts, sync ? MediaCodec.BUFFER_FLAG_KEY_FRAME : 0);
|
||||
muxer.writeSampleData(track, buf, info);
|
||||
if (pts > maxPts) maxPts = pts;
|
||||
samples++;
|
||||
ex.advance();
|
||||
}
|
||||
if (maxPts >= 0) base = maxPts + frameUs;
|
||||
} finally {
|
||||
ex.release();
|
||||
}
|
||||
}
|
||||
if (muxer == null || samples == 0) throw new IOException("no video samples in range");
|
||||
muxer.stop();
|
||||
} finally {
|
||||
if (muxer != null) { try { muxer.release(); } catch (Throwable ignored) { } }
|
||||
}
|
||||
}
|
||||
|
||||
/** The drive log for the event window, merged from the source clips' sidecars. */
|
||||
private static void writeEventTelemetry(List<DashcamPolicy.Clip> sources, Pending p, File event) {
|
||||
try {
|
||||
JSONArray pts = new JSONArray();
|
||||
long last = -1L;
|
||||
for (DashcamPolicy.Clip c : sources) {
|
||||
File side = DashcamTelemetry.sidecar(DashcamStore.clipFile(c.name));
|
||||
if (!side.isFile()) continue;
|
||||
JSONArray a = new JSONObject(DashcamStore.readText(side)).optJSONArray("points");
|
||||
if (a == null) continue;
|
||||
for (int i = 0; i < a.length(); i++) {
|
||||
JSONObject o = a.optJSONObject(i);
|
||||
if (o == null) continue;
|
||||
long t = o.optLong("t", -1L);
|
||||
if (t < p.startMs || t > p.endMs || t <= last) continue;
|
||||
pts.put(o);
|
||||
last = t;
|
||||
}
|
||||
}
|
||||
if (pts.length() == 0) return;
|
||||
JSONObject o = new JSONObject();
|
||||
o.put("schema", 1);
|
||||
o.put("clip", event.getName());
|
||||
o.put("event", true);
|
||||
o.put("click", p.clickMs);
|
||||
o.put("start", p.startMs);
|
||||
o.put("end", p.endMs);
|
||||
o.put("mode", "event");
|
||||
o.put("points", pts);
|
||||
DashcamStore.writeTextAtomic(DashcamTelemetry.sidecar(event), o.toString());
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "event telemetry not written", t);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean delete(File f) {
|
||||
if (f == null || !isEventName(f.getName())) return false;
|
||||
DashcamTelemetry.sidecar(f).delete();
|
||||
return f.delete();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static String debug(List<DashcamPolicy.Clip> c) { return Arrays.toString(c.toArray()); }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
/**
|
||||
* JNI bridge to libmgdashcam.so, the four-camera V4L2 capture + grid compositor + H.264 encoder
|
||||
* from Tommasov/MG4_Dashcam (GPL-3.0). Source and build script: vendor/mg4-dashcam/.
|
||||
*
|
||||
* <p>Opening /dev/video* needs the system uid, which MG Utility already has through its platform
|
||||
* signature and android:sharedUserId="android.uid.system".
|
||||
*/
|
||||
final class DashcamNative {
|
||||
private static volatile Boolean loaded;
|
||||
private static volatile String loadError = "";
|
||||
|
||||
private DashcamNative() { }
|
||||
|
||||
static boolean available() {
|
||||
Boolean current = loaded;
|
||||
if (current != null) return current;
|
||||
synchronized (DashcamNative.class) {
|
||||
if (loaded != null) return loaded;
|
||||
try {
|
||||
System.loadLibrary("mgdashcam");
|
||||
loaded = Boolean.TRUE;
|
||||
} catch (Throwable t) {
|
||||
loadError = t.getClass().getSimpleName() + ": " + t.getMessage();
|
||||
loaded = Boolean.FALSE;
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
}
|
||||
|
||||
static String loadError() { return loadError; }
|
||||
|
||||
/** Camera bit order understood by the native compositor. */
|
||||
static final int CAMERA_FRONT = 1;
|
||||
static final int CAMERA_RIGHT = 1 << 1;
|
||||
static final int CAMERA_LEFT = 1 << 2;
|
||||
static final int CAMERA_REAR = 1 << 3;
|
||||
static final int CAMERA_ALL = CAMERA_FRONT | CAMERA_RIGHT | CAMERA_LEFT | CAMERA_REAR;
|
||||
|
||||
/** Each camera cell, in pixels. Four cells plus a footer give a 1440x1040 clip. */
|
||||
static final int CELL_WIDTH = 720;
|
||||
static final int CELL_HEIGHT = 480;
|
||||
|
||||
static native String probeAll(int maxIndex);
|
||||
static native String describeCameraFormats();
|
||||
static native boolean syncFilesystem(String path);
|
||||
|
||||
static native boolean startCombinedMp4Record(String outputPath, int cellWidth, int cellHeight,
|
||||
int fps, int bitrate, String signature, boolean showSpeed, int cameraMask);
|
||||
|
||||
/**
|
||||
* @param keepCamerasWarm true only when another clip starts immediately.
|
||||
* @param urgent true when the factory 360 view is waiting for the devices.
|
||||
*/
|
||||
static native boolean stopCombinedMp4Record(boolean keepCamerasWarm, boolean urgent);
|
||||
static native void releaseCombinedCameras();
|
||||
static native boolean awaitPendingFlushes(int timeoutMs);
|
||||
static native void updateCombinedRecordingSpeed(int speedKmh);
|
||||
|
||||
static native boolean attachCombinedPreview(android.view.Surface surface, int cellWidth,
|
||||
int cellHeight, int fps, String signature, boolean showSpeed, int cameraMask);
|
||||
static native boolean detachCombinedPreview();
|
||||
static native int previewCanvasWidth(int cellWidth, int cellHeight);
|
||||
static native int previewCanvasHeight(int cellWidth, int cellHeight);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/**
|
||||
* Factory 360-camera start/stop broadcasts (sent by some SAIC firmware), plus an explicit
|
||||
* "save dashcam clip" action for automations. The foreground-task watch in DashcamService is the
|
||||
* reliable path for the 360 hand-off; this only makes it faster where the broadcast exists.
|
||||
*/
|
||||
public final class DashcamOemReceiver extends BroadcastReceiver {
|
||||
static final String ACTION_SAVE_CLIP = "cloud.molberg.mgutility.action.SAVE_DASHCAM_CLIP";
|
||||
|
||||
@Override public void onReceive(Context context, Intent intent) {
|
||||
String a = intent == null ? null : intent.getAction();
|
||||
if (a == null) return;
|
||||
if (ACTION_SAVE_CLIP.equals(a)) {
|
||||
DashcamService.saveMoment(context);
|
||||
} else if (a.endsWith("startAVMActivity") || a.endsWith("ACTION_START")) {
|
||||
DashcamService.onOemBroadcast(context, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Pure dashcam storage rules, kept free of Android types so they can be unit-tested on the JVM.
|
||||
*
|
||||
* <p>A clip is one recorded segment file. A tag is a time range the driver asked to keep; every
|
||||
* clip overlapping a tag is protected and is never removed by age or by the storage budget.
|
||||
*/
|
||||
final class DashcamPolicy {
|
||||
private DashcamPolicy() { }
|
||||
|
||||
static final long DAY_MS = 24L * 60L * 60L * 1000L;
|
||||
static final String CLIP_SUFFIX = ".mp4";
|
||||
private static final String NAME_PATTERN = "yyyyMMdd_HHmmss";
|
||||
|
||||
static final class Clip {
|
||||
final String name;
|
||||
final long startMs;
|
||||
final long endMs;
|
||||
final long sizeBytes;
|
||||
/** Recorded while parked: lower quality, deleted before driving footage. */
|
||||
final boolean lowPriority;
|
||||
|
||||
Clip(String name, long startMs, long endMs, long sizeBytes) {
|
||||
this(name, startMs, endMs, sizeBytes, false);
|
||||
}
|
||||
|
||||
Clip(String name, long startMs, long endMs, long sizeBytes, boolean lowPriority) {
|
||||
this.name = name;
|
||||
this.startMs = startMs;
|
||||
this.endMs = Math.max(startMs, endMs);
|
||||
this.sizeBytes = Math.max(0L, sizeBytes);
|
||||
this.lowPriority = lowPriority;
|
||||
}
|
||||
}
|
||||
|
||||
static final class Range {
|
||||
final long startMs;
|
||||
final long endMs;
|
||||
|
||||
Range(long startMs, long endMs) {
|
||||
this.startMs = Math.min(startMs, endMs);
|
||||
this.endMs = Math.max(startMs, endMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** File name for a clip that starts at the given wall-clock time (local time zone). */
|
||||
static String clipName(long startMs) {
|
||||
return new SimpleDateFormat(NAME_PATTERN, Locale.US).format(new Date(startMs)) + CLIP_SUFFIX;
|
||||
}
|
||||
|
||||
/** Start time encoded in a clip name, or -1 if the name is not one of ours. */
|
||||
static long clipStart(String name) {
|
||||
if (name == null || !name.endsWith(CLIP_SUFFIX)) return -1L;
|
||||
String stem = name.substring(0, name.length() - CLIP_SUFFIX.length());
|
||||
if (stem.length() != NAME_PATTERN.length()) return -1L;
|
||||
SimpleDateFormat format = new SimpleDateFormat(NAME_PATTERN, Locale.US);
|
||||
format.setLenient(false);
|
||||
try {
|
||||
return format.parse(stem).getTime();
|
||||
} catch (ParseException e) {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean overlaps(long aStart, long aEnd, long bStart, long bEnd) {
|
||||
return aStart <= bEnd && bStart <= aEnd;
|
||||
}
|
||||
|
||||
static boolean isProtected(Clip clip, List<Range> tags) {
|
||||
if (tags == null) return false;
|
||||
for (Range r : tags) {
|
||||
if (overlaps(clip.startMs, clip.endMs, r.startMs, r.endMs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static long totalBytes(List<Clip> clips) {
|
||||
long total = 0L;
|
||||
for (Clip c : clips) total += c.sizeBytes;
|
||||
return total;
|
||||
}
|
||||
|
||||
static long protectedBytes(List<Clip> clips, List<Range> tags) {
|
||||
long total = 0L;
|
||||
for (Clip c : clips) if (isProtected(c, tags)) total += c.sizeBytes;
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clips that should be deleted now, oldest first.
|
||||
*
|
||||
* <ol>
|
||||
* <li>Unprotected clips older than {@code retentionDays} (0 disables age-based deletion).
|
||||
* Parked (low-priority) clips age out after {@code parkedRetentionDays} if that is
|
||||
* shorter.</li>
|
||||
* <li>Then, to fit the budget, the oldest unprotected <b>parked</b> clips go first, and only
|
||||
* when none are left the oldest unprotected driving clips, until the remaining total plus
|
||||
* {@code headroomBytes} (room for the next segment) fits inside {@code capBytes}.</li>
|
||||
* </ol>
|
||||
* Protected clips and the clip currently being written ({@code activeName}) are never chosen.
|
||||
* If protected footage alone exceeds the cap the result simply stops short; the caller reports
|
||||
* that rather than deleting something the driver asked to keep.
|
||||
*/
|
||||
static List<Clip> selectForDeletion(List<Clip> clips, List<Range> tags, long nowMs,
|
||||
long capBytes, int retentionDays, long headroomBytes,
|
||||
String activeName) {
|
||||
return selectForDeletion(clips, tags, nowMs, capBytes, retentionDays, 0, headroomBytes, activeName);
|
||||
}
|
||||
|
||||
static List<Clip> selectForDeletion(List<Clip> clips, List<Range> tags, long nowMs,
|
||||
long capBytes, int retentionDays, int parkedRetentionDays,
|
||||
long headroomBytes, String activeName) {
|
||||
List<Clip> sorted = new ArrayList<Clip>(clips);
|
||||
Collections.sort(sorted, new Comparator<Clip>() {
|
||||
@Override public int compare(Clip a, Clip b) {
|
||||
return a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : a.name.compareTo(b.name);
|
||||
}
|
||||
});
|
||||
List<Clip> delete = new ArrayList<Clip>();
|
||||
long remaining = totalBytes(sorted);
|
||||
long maxAge = retentionDays > 0 ? retentionDays * DAY_MS : Long.MAX_VALUE;
|
||||
long parkedAge = parkedRetentionDays > 0 ? Math.min(maxAge, parkedRetentionDays * DAY_MS) : maxAge;
|
||||
for (Clip c : sorted) {
|
||||
if (isActive(c, activeName) || isProtected(c, tags)) continue;
|
||||
if (nowMs - c.endMs > (c.lowPriority ? parkedAge : maxAge)) {
|
||||
delete.add(c);
|
||||
remaining -= c.sizeBytes;
|
||||
}
|
||||
}
|
||||
if (capBytes > 0) {
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
boolean wantLow = pass == 0;
|
||||
for (Clip c : sorted) {
|
||||
if (remaining + Math.max(0L, headroomBytes) <= capBytes) break;
|
||||
if (c.lowPriority != wantLow) continue;
|
||||
if (delete.contains(c) || isActive(c, activeName) || isProtected(c, tags)) continue;
|
||||
delete.add(c);
|
||||
remaining -= c.sizeBytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
return delete;
|
||||
}
|
||||
|
||||
private static boolean isActive(Clip c, String activeName) {
|
||||
return activeName != null && activeName.equals(c.name);
|
||||
}
|
||||
|
||||
/** Bytes one segment takes at the given bitrate, with 5% container overhead. */
|
||||
static long segmentBytes(int bitrateBps, int segmentSeconds) {
|
||||
long raw = (long) Math.max(0, bitrateBps) / 8L * Math.max(1, segmentSeconds);
|
||||
return raw + raw / 20L;
|
||||
}
|
||||
|
||||
/** Roughly how many minutes of driving fit inside the budget at a bitrate. */
|
||||
static long minutesForBudget(long capBytes, int bitrateBps) {
|
||||
long perMinute = segmentBytes(bitrateBps, 60);
|
||||
return perMinute <= 0 ? 0 : capBytes / perMinute;
|
||||
}
|
||||
|
||||
/** Clip names that belong to a tag range (used for uploads and listing). */
|
||||
static List<Clip> clipsInRange(List<Clip> clips, Range range) {
|
||||
List<Clip> out = new ArrayList<Clip>();
|
||||
for (Clip c : clips) if (overlaps(c.startMs, c.endMs, range.startMs, range.endMs)) out.add(c);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups clips into drives: consecutive clips whose gap is at most {@code maxGapMs}.
|
||||
* Input in any order; output oldest drive first, each drive oldest clip first.
|
||||
*/
|
||||
static List<List<Clip>> sessions(List<Clip> clips, long maxGapMs) {
|
||||
List<Clip> sorted = new ArrayList<Clip>(clips);
|
||||
Collections.sort(sorted, new Comparator<Clip>() {
|
||||
@Override public int compare(Clip a, Clip b) { return a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0; }
|
||||
});
|
||||
List<List<Clip>> out = new ArrayList<List<Clip>>();
|
||||
List<Clip> current = null;
|
||||
long lastEnd = Long.MIN_VALUE;
|
||||
for (Clip c : sorted) {
|
||||
if (current == null || c.startMs - lastEnd > maxGapMs) {
|
||||
current = new ArrayList<Clip>();
|
||||
out.add(current);
|
||||
}
|
||||
current.add(c);
|
||||
lastEnd = Math.max(lastEnd, c.endMs);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String formatBytes(long bytes) {
|
||||
if (bytes >= 1024L * 1024L * 1024L) return String.format(Locale.US, "%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
|
||||
if (bytes >= 1024L * 1024L) return String.format(Locale.US, "%.0f MB", bytes / (1024.0 * 1024.0));
|
||||
return String.format(Locale.US, "%d KB", Math.max(0L, bytes / 1024L));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Loop-recording dashcam: four factory cameras composed into one clip per segment, written to
|
||||
* {@code MG-Utility/dashcam/clips}. After every segment the storage policy runs (age + budget,
|
||||
* never touching kept ranges) and, when enabled, finished clips are offloaded to the archive
|
||||
* server.
|
||||
*
|
||||
* <p>The capture/encode path is the native library from Tommasov/MG4_Dashcam; the camera hand-off
|
||||
* to the factory 360 view follows the same approach (watch the foreground task, free the devices
|
||||
* fast, wait a little longer after a failed visit so the second press works).
|
||||
*/
|
||||
public final class DashcamService extends Service {
|
||||
private static final String TAG = "MGDashcam";
|
||||
static final String ACTION_START = "cloud.molberg.mgutility.dashcam.START";
|
||||
static final String ACTION_STOP = "cloud.molberg.mgutility.dashcam.STOP";
|
||||
static final String ACTION_SAVE = "cloud.molberg.mgutility.dashcam.SAVE";
|
||||
static final String ACTION_UPLOAD_NOW = "cloud.molberg.mgutility.dashcam.UPLOAD_NOW";
|
||||
static final String ACTION_STATUS = "cloud.molberg.mgutility.dashcam.STATUS";
|
||||
|
||||
private static final String CHANNEL_ID = "mg_dashcam";
|
||||
private static final int NOTIFICATION_ID = 4711;
|
||||
private static final String OEM_AVM_PACKAGE = "com.saicmotor.hmi.aroundview";
|
||||
private static final long OEM_POLL_MS = 120L;
|
||||
private static final long OEM_FAILED_VISIT_MS = 1500L;
|
||||
private static final long OEM_RESUME_DELAY_MS = 2000L;
|
||||
private static final long OEM_RETRY_GRACE_MS = 8000L;
|
||||
private static final int PARKED_KMH = 3;
|
||||
private static final long UPLOAD_PERIOD_MS = 2L * 60L * 1000L;
|
||||
|
||||
/** Latest vehicle speed, fed by the trip tracker; used for the footer and parked checks. */
|
||||
static volatile float lastSpeedKph = -1f;
|
||||
static volatile long lastSpeedAtMs = 0L;
|
||||
static volatile boolean activeClipParked = false;
|
||||
static volatile String lastClipMode = "";
|
||||
|
||||
private static volatile String status = "Off";
|
||||
private static volatile String lastError = "";
|
||||
private static volatile String activeClipName;
|
||||
private static volatile long lastClipCompletedMs;
|
||||
private static volatile boolean running;
|
||||
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final Object lock = new Object();
|
||||
private volatile Thread worker;
|
||||
private volatile boolean stopRequested;
|
||||
private volatile boolean segmentStopRequested;
|
||||
private volatile boolean oemPause;
|
||||
private volatile boolean screenPause;
|
||||
private long oemSinceMs;
|
||||
private long oemGoneMs;
|
||||
private ScheduledExecutorService oemWatch;
|
||||
private ExecutorService housekeeping;
|
||||
private BroadcastReceiver screenReceiver;
|
||||
|
||||
// ------------------------------------------------------------------ public entry points
|
||||
|
||||
static void startIfEnabled(Context context) {
|
||||
if (context == null || !DashcamStore.enabled(context)) return;
|
||||
send(context, ACTION_START);
|
||||
}
|
||||
|
||||
static void stop(Context context) { send(context, ACTION_STOP); }
|
||||
|
||||
/** Keeps the last N seconds and the next M seconds of footage. Safe to call any time. */
|
||||
static void saveMoment(Context context) {
|
||||
if (context == null) return;
|
||||
String msg;
|
||||
if (!DashcamStore.enabled(context)) {
|
||||
msg = "Dashcam is off - nothing is being recorded";
|
||||
} else {
|
||||
DashcamEvents.request(context);
|
||||
int before = DashcamStore.saveBeforeSec(context), after = DashcamStore.saveAfterSec(context);
|
||||
msg = "Event locked: " + fmtDur(before) + " before + " + fmtDur(after) + " after. Saving when recording catches up.";
|
||||
}
|
||||
try { Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_LONG).show(); }
|
||||
catch (Throwable ignored) { }
|
||||
if (running) send(context, ACTION_STATUS);
|
||||
}
|
||||
|
||||
static String fmtDur(int sec) { return sec % 60 == 0 ? (sec / 60) + " min" : sec + " s"; }
|
||||
|
||||
static void uploadNow(Context context) { send(context, ACTION_UPLOAD_NOW); }
|
||||
|
||||
private static void send(Context context, String action) {
|
||||
Intent intent = new Intent(context, DashcamService.class).setAction(action);
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent);
|
||||
else context.startService(intent);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "service start deferred", t);
|
||||
try { context.startService(intent); } catch (Throwable ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isRunning() { return running; }
|
||||
static String status() { return status; }
|
||||
static String lastError() { return lastError; }
|
||||
static String activeClipName() { return activeClipName; }
|
||||
static long lastClipCompletedMs() { return lastClipCompletedMs; }
|
||||
|
||||
// ------------------------------------------------------------------ lifecycle
|
||||
|
||||
@Override public IBinder onBind(Intent intent) { return null; }
|
||||
|
||||
@Override public void onCreate() {
|
||||
super.onCreate();
|
||||
running = true;
|
||||
housekeeping = Executors.newSingleThreadExecutor();
|
||||
createChannel();
|
||||
startForeground(NOTIFICATION_ID, notification("Dashcam starting"));
|
||||
registerScreenReceiver();
|
||||
main.postDelayed(uploadTick, 15000L);
|
||||
DashcamEvents.kick(this);
|
||||
}
|
||||
|
||||
@Override public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
String action = intent == null ? ACTION_START : intent.getAction();
|
||||
startForeground(NOTIFICATION_ID, notification(statusLine()));
|
||||
if (ACTION_STOP.equals(action)) {
|
||||
shutdown("Off");
|
||||
stopForegroundCompat();
|
||||
stopSelf();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
if (ACTION_SAVE.equals(action)) {
|
||||
saveMoment(this);
|
||||
} else if (ACTION_UPLOAD_NOW.equals(action)) {
|
||||
scheduleUpload(true);
|
||||
}
|
||||
if (!DashcamStore.enabled(this)) {
|
||||
if (worker == null) {
|
||||
if (ACTION_UPLOAD_NOW.equals(action)) return START_NOT_STICKY;
|
||||
publish("Off", "");
|
||||
stopForegroundCompat();
|
||||
stopSelf();
|
||||
}
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
ensureWorker();
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override public void onDestroy() {
|
||||
shutdown("Off");
|
||||
main.removeCallbacks(uploadTick);
|
||||
if (screenReceiver != null) { try { unregisterReceiver(screenReceiver); } catch (Throwable ignored) { } }
|
||||
if (housekeeping != null) housekeeping.shutdown();
|
||||
running = false;
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private void ensureWorker() {
|
||||
if (worker != null && worker.isAlive()) return;
|
||||
if (!DashcamNative.available()) {
|
||||
publish("Error", "Camera library failed to load: " + DashcamNative.loadError());
|
||||
return;
|
||||
}
|
||||
stopRequested = false;
|
||||
segmentStopRequested = false;
|
||||
startOemWatch();
|
||||
Thread t = new Thread(new Runnable() {
|
||||
@Override public void run() { loop(); }
|
||||
}, "mg-dashcam");
|
||||
worker = t;
|
||||
t.start();
|
||||
}
|
||||
|
||||
private void shutdown(String finalStatus) {
|
||||
stopRequested = true;
|
||||
segmentStopRequested = true;
|
||||
synchronized (lock) { lock.notifyAll(); }
|
||||
Thread t = worker;
|
||||
if (t != null) {
|
||||
t.interrupt();
|
||||
try { t.join(6000L); } catch (InterruptedException ignored) { }
|
||||
}
|
||||
worker = null;
|
||||
stopOemWatch();
|
||||
if (DashcamNative.available()) {
|
||||
try {
|
||||
DashcamNative.stopCombinedMp4Record(false, false);
|
||||
DashcamNative.releaseCombinedCameras();
|
||||
DashcamNative.awaitPendingFlushes(5000);
|
||||
} catch (Throwable ignored) { }
|
||||
}
|
||||
activeClipName = null;
|
||||
publish(finalStatus, "");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ recording loop
|
||||
|
||||
private void loop() {
|
||||
try {
|
||||
loopBody();
|
||||
} catch (Throwable t) {
|
||||
Log.e(TAG, "recording loop died", t);
|
||||
publish("Error", "Recording loop stopped: " + t.getClass().getSimpleName());
|
||||
try { DashcamNative.stopCombinedMp4Record(false, false); DashcamNative.releaseCombinedCameras(); }
|
||||
catch (Throwable ignored) { }
|
||||
} finally {
|
||||
worker = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void loopBody() {
|
||||
DashcamStore.init(this);
|
||||
int failures = 0;
|
||||
while (!stopRequested && DashcamStore.enabled(this)) {
|
||||
if (!waitWhilePaused()) break;
|
||||
File root = DashcamStore.recordingRoot(this);
|
||||
if (root == null) {
|
||||
publish("Waiting for storage", "Recording folder " + DashcamStore.customDir() + " is not writable (USB unplugged?)");
|
||||
sleepQuietly(10000L);
|
||||
DashcamStore.init(this);
|
||||
continue;
|
||||
}
|
||||
File dir = DashcamStore.clipsDirIn(root);
|
||||
if (!dir.isDirectory() || !dir.canWrite()) {
|
||||
publish("Error", "Cannot write to " + dir.getAbsolutePath() + " (storage permission?)");
|
||||
sleepQuietly(10000L);
|
||||
continue;
|
||||
}
|
||||
boolean parked = DashcamTelemetry.parked();
|
||||
if (parked && DashcamStore.parkedMode(this) == DashcamStore.PARKED_OFF) {
|
||||
publish("Paused (parked)", "Parked recording is off in settings");
|
||||
try { DashcamNative.releaseCombinedCameras(); } catch (Throwable ignored) { }
|
||||
while (!stopRequested && DashcamStore.enabled(this) && DashcamTelemetry.parked()
|
||||
&& DashcamStore.parkedMode(this) == DashcamStore.PARKED_OFF) {
|
||||
sleepQuietly(1000L);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
int bitrate = DashcamStore.bitrateFor(this, parked);
|
||||
enforcePolicy(DashcamPolicy.segmentBytes(bitrate, DashcamStore.segmentSec(this)));
|
||||
long startWall = System.currentTimeMillis();
|
||||
String name = DashcamPolicy.clipName(startWall);
|
||||
File out = new File(dir, name);
|
||||
DashcamTelemetry.clipStarted(name, startWall, parked);
|
||||
boolean ok = recordSegment(out, DashcamStore.segmentSec(this) * 1000L, parked, bitrate);
|
||||
if (ok) {
|
||||
String mode = DashcamTelemetry.clipFinished(out, System.currentTimeMillis(), bitrate);
|
||||
lastClipMode = mode;
|
||||
} else {
|
||||
DashcamTelemetry.clipFinished(out, System.currentTimeMillis(), bitrate);
|
||||
DashcamTelemetry.sidecar(out).delete();
|
||||
}
|
||||
if (!ok) {
|
||||
if (oemPause || screenPause || stopRequested) continue;
|
||||
failures++;
|
||||
if (failures >= 5) {
|
||||
publish("Error", "Cameras did not start (5 attempts). Retrying in 30 s");
|
||||
sleepQuietly(30000L);
|
||||
failures = 0;
|
||||
} else {
|
||||
sleepQuietly(2000L);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
failures = 0;
|
||||
lastClipCompletedMs = System.currentTimeMillis();
|
||||
housekeeping.execute(new Runnable() {
|
||||
@Override public void run() { enforcePolicy(0L); }
|
||||
});
|
||||
}
|
||||
try { DashcamNative.releaseCombinedCameras(); } catch (Throwable ignored) { }
|
||||
activeClipName = null;
|
||||
if (!stopRequested) publish("Off", "");
|
||||
}
|
||||
|
||||
private boolean recordSegment(File out, long durationMs, boolean parked, int bitrate) {
|
||||
boolean showSpeed = DashcamStore.showSpeed(this);
|
||||
boolean started = DashcamNative.startCombinedMp4Record(out.getAbsolutePath(),
|
||||
DashcamNative.CELL_WIDTH, DashcamNative.CELL_HEIGHT, DashcamStore.fpsFor(this, parked),
|
||||
bitrate, DashcamStore.signature(this), showSpeed, DashcamNative.CAMERA_ALL);
|
||||
if (!started) {
|
||||
discard(out);
|
||||
publish("Error", "Camera start failed");
|
||||
return false;
|
||||
}
|
||||
activeClipName = out.getName();
|
||||
activeClipParked = parked;
|
||||
publish(parked ? "Recording (parked, low quality)" : "Recording", "");
|
||||
long start = SystemClock.elapsedRealtime();
|
||||
long modeChangedAt = 0L;
|
||||
boolean modeSwitch = false;
|
||||
while (!stopRequested && !segmentStopRequested && SystemClock.elapsedRealtime() - start < durationMs) {
|
||||
if (showSpeed) {
|
||||
try { DashcamNative.updateCombinedRecordingSpeed(Math.round(currentSpeed())); } catch (Throwable ignored) { }
|
||||
}
|
||||
// Driving away from a parked clip switches to full quality quickly (2 s); settling
|
||||
// into Park waits 20 s so a short stop at a light is not re-encoded.
|
||||
boolean nowParked = DashcamTelemetry.parked() && DashcamStore.parkedMode(this) != DashcamStore.PARKED_FULL;
|
||||
boolean wasParked = parked && DashcamStore.parkedMode(this) != DashcamStore.PARKED_FULL;
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (nowParked != wasParked && now - start > 3000L) {
|
||||
if (modeChangedAt == 0L) modeChangedAt = now;
|
||||
if (now - modeChangedAt >= (wasParked ? 2000L : 20000L)) { modeSwitch = true; break; }
|
||||
} else {
|
||||
modeChangedAt = 0L;
|
||||
}
|
||||
try { Thread.sleep(250L); } catch (InterruptedException ignored) { }
|
||||
}
|
||||
if (modeSwitch) Log.i(TAG, "rotating clip: " + (parked ? "driving" : "parked"));
|
||||
boolean rotating = !stopRequested && !segmentStopRequested && !oemPause && !screenPause;
|
||||
boolean urgent = oemPause;
|
||||
boolean stopped = DashcamNative.stopCombinedMp4Record(rotating, urgent);
|
||||
activeClipName = null;
|
||||
if (!stopped) {
|
||||
discard(out);
|
||||
publish("Error", "Clip did not finalise");
|
||||
return false;
|
||||
}
|
||||
if (!out.isFile() || out.length() < 64 * 1024) {
|
||||
discard(out);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void discard(File f) {
|
||||
try { if (f != null && f.exists()) f.delete(); } catch (Throwable ignored) { }
|
||||
}
|
||||
|
||||
private boolean waitWhilePaused() {
|
||||
boolean announced = false;
|
||||
while (!stopRequested && DashcamStore.enabled(this) && (oemPause || screenPause)) {
|
||||
segmentStopRequested = true;
|
||||
if (!announced) {
|
||||
try { DashcamNative.releaseCombinedCameras(); } catch (Throwable ignored) { }
|
||||
publish(oemPause ? "Paused for 360 camera" : "Paused (screen off)", "");
|
||||
announced = true;
|
||||
}
|
||||
synchronized (lock) {
|
||||
try { lock.wait(500L); } catch (InterruptedException ignored) { }
|
||||
}
|
||||
}
|
||||
segmentStopRequested = false;
|
||||
return !stopRequested && DashcamStore.enabled(this);
|
||||
}
|
||||
|
||||
private void sleepQuietly(long ms) {
|
||||
long until = SystemClock.elapsedRealtime() + ms;
|
||||
while (!stopRequested && SystemClock.elapsedRealtime() < until) {
|
||||
synchronized (lock) {
|
||||
try { lock.wait(Math.min(500L, Math.max(1L, until - SystemClock.elapsedRealtime()))); }
|
||||
catch (InterruptedException ignored) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ storage policy
|
||||
|
||||
/** Deletes what the age and budget rules allow. {@code headroom} reserves room for the next clip. */
|
||||
private void enforcePolicy(long headroom) {
|
||||
try {
|
||||
List<DashcamPolicy.Clip> clips = DashcamStore.listClips();
|
||||
List<DashcamPolicy.Range> keep = DashcamStore.keepRanges();
|
||||
long total = DashcamPolicy.totalBytes(clips);
|
||||
long cap = DashcamStore.effectiveCapBytes(this, total);
|
||||
List<DashcamPolicy.Clip> doomed = DashcamPolicy.selectForDeletion(clips, keep,
|
||||
System.currentTimeMillis(), cap, DashcamStore.retentionDays(this),
|
||||
DashcamStore.parkedRetentionDays(this), headroom, activeClipName);
|
||||
for (DashcamPolicy.Clip c : doomed) DashcamStore.deleteClip(c.name);
|
||||
if (!doomed.isEmpty()) {
|
||||
File root = DashcamStore.recordingRoot(this);
|
||||
if (root != null) {
|
||||
try { DashcamNative.syncFilesystem(root.getAbsolutePath()); } catch (Throwable ignored) { }
|
||||
}
|
||||
Log.i(TAG, "storage policy removed " + doomed.size() + " clip(s)");
|
||||
}
|
||||
long protectedBytes = DashcamPolicy.protectedBytes(clips, keep);
|
||||
if (cap > 0 && protectedBytes + headroom > cap) {
|
||||
lastError = "Saved clips fill the storage budget. Offload them or raise the budget.";
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "storage policy failed", t);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ uploads
|
||||
|
||||
private final Runnable uploadTick = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (housekeeping != null && !housekeeping.isShutdown()) {
|
||||
housekeeping.execute(new Runnable() { @Override public void run() { enforcePolicy(0L); } });
|
||||
}
|
||||
scheduleUpload(false);
|
||||
main.postDelayed(this, UPLOAD_PERIOD_MS);
|
||||
}
|
||||
};
|
||||
|
||||
private void scheduleUpload(final boolean manual) {
|
||||
if (!manual && !DashcamStore.uploadEnabled(this)) return;
|
||||
if (housekeeping == null || housekeeping.isShutdown()) return;
|
||||
housekeeping.execute(new Runnable() {
|
||||
@Override public void run() {
|
||||
String result = manual ? DashcamUploader.runManual(DashcamService.this, activeClipName)
|
||||
: DashcamUploader.runAuto(DashcamService.this, activeClipName);
|
||||
if (manual) toast(result);
|
||||
refreshNotification();
|
||||
// A one-off offload with the recorder switched off should not leave a service behind.
|
||||
if (!DashcamStore.enabled(DashcamService.this) && worker == null) {
|
||||
main.post(new Runnable() { @Override public void run() { stopForegroundCompat(); stopSelf(); } });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ factory 360 hand-off
|
||||
|
||||
private void startOemWatch() {
|
||||
stopOemWatch();
|
||||
oemWatch = Executors.newSingleThreadScheduledExecutor();
|
||||
oemWatch.scheduleWithFixedDelay(new Runnable() {
|
||||
@Override public void run() { pollOem(); }
|
||||
}, OEM_POLL_MS, OEM_POLL_MS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void stopOemWatch() {
|
||||
ScheduledExecutorService w = oemWatch;
|
||||
oemWatch = null;
|
||||
if (w != null) w.shutdownNow();
|
||||
}
|
||||
|
||||
private void pollOem() {
|
||||
try {
|
||||
if (!DashcamStore.oemHandoff(this)) {
|
||||
if (oemPause) { oemPause = false; wake(); }
|
||||
return;
|
||||
}
|
||||
boolean front = oemInForeground();
|
||||
long now = System.currentTimeMillis();
|
||||
if (front) {
|
||||
oemGoneMs = 0L;
|
||||
if (oemSinceMs == 0L) oemSinceMs = now;
|
||||
if (!oemPause) {
|
||||
oemPause = true;
|
||||
segmentStopRequested = true;
|
||||
Thread w = worker;
|
||||
if (w != null) w.interrupt();
|
||||
wake();
|
||||
}
|
||||
} else if (oemPause) {
|
||||
if (oemGoneMs == 0L) oemGoneMs = now;
|
||||
long visit = Math.max(0L, oemGoneMs - oemSinceMs);
|
||||
long hold = visit < OEM_FAILED_VISIT_MS ? OEM_RETRY_GRACE_MS : OEM_RESUME_DELAY_MS;
|
||||
if (now - oemGoneMs >= hold) {
|
||||
oemPause = false;
|
||||
oemSinceMs = 0L;
|
||||
oemGoneMs = 0L;
|
||||
wake();
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "oem watch", t);
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes the current clip so the next one picks up new settings (folder, quality). */
|
||||
static void restartRecording(Context context) {
|
||||
DashcamService s = instanceRef;
|
||||
if (s == null) return;
|
||||
s.segmentStopRequested = true;
|
||||
s.wake();
|
||||
}
|
||||
|
||||
/** Fast path for the factory app's own start/stop broadcasts (some firmware sends them). */
|
||||
static void onOemBroadcast(Context context, boolean starting) {
|
||||
DashcamService s = instanceRef;
|
||||
if (s == null || !DashcamStore.oemHandoff(context)) return;
|
||||
if (starting && currentSpeed() <= 20f) {
|
||||
s.oemSinceMs = System.currentTimeMillis();
|
||||
s.oemGoneMs = 0L;
|
||||
s.oemPause = true;
|
||||
s.segmentStopRequested = true;
|
||||
Thread w = s.worker;
|
||||
if (w != null) w.interrupt();
|
||||
s.wake();
|
||||
}
|
||||
}
|
||||
|
||||
private static volatile DashcamService instanceRef;
|
||||
{ instanceRef = this; }
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private boolean oemInForeground() {
|
||||
try {
|
||||
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
|
||||
if (am == null) return false;
|
||||
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
|
||||
if (tasks == null || tasks.isEmpty() || tasks.get(0).topActivity == null) return false;
|
||||
return OEM_AVM_PACKAGE.equals(tasks.get(0).topActivity.getPackageName());
|
||||
} catch (Throwable t) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void wake() { synchronized (lock) { lock.notifyAll(); } }
|
||||
|
||||
// ------------------------------------------------------------------ screen off while parked
|
||||
|
||||
private void registerScreenReceiver() {
|
||||
screenReceiver = new BroadcastReceiver() {
|
||||
@Override public void onReceive(Context context, Intent intent) {
|
||||
String a = intent == null ? null : intent.getAction();
|
||||
if (Intent.ACTION_SCREEN_OFF.equals(a)) {
|
||||
if (currentSpeed() <= PARKED_KMH) {
|
||||
screenPause = true;
|
||||
segmentStopRequested = true;
|
||||
wake();
|
||||
}
|
||||
} else if (Intent.ACTION_SCREEN_ON.equals(a)) {
|
||||
if (screenPause) { screenPause = false; wake(); }
|
||||
}
|
||||
}
|
||||
};
|
||||
IntentFilter f = new IntentFilter();
|
||||
f.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
f.addAction(Intent.ACTION_SCREEN_ON);
|
||||
registerReceiver(screenReceiver, f);
|
||||
}
|
||||
|
||||
static float currentSpeed() {
|
||||
float s = lastSpeedKph;
|
||||
if (s >= 0f && System.currentTimeMillis() - lastSpeedAtMs < 15000L) return s;
|
||||
try {
|
||||
Class<?> sp = Class.forName("android.os.SystemProperties");
|
||||
String v = (String) sp.getMethod("get", String.class, String.class).invoke(null, "arcsoft.avm.mCurCarSpeed", "");
|
||||
if (v != null && !v.isEmpty()) return Math.max(0f, Float.parseFloat(v));
|
||||
} catch (Throwable ignored) { }
|
||||
return 0f;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status + notification
|
||||
|
||||
private void publish(String newStatus, String error) {
|
||||
status = newStatus;
|
||||
if (error != null) lastError = error;
|
||||
refreshNotification();
|
||||
}
|
||||
|
||||
private static String statusLine() {
|
||||
String s = status;
|
||||
if (lastError != null && !lastError.isEmpty() && "Error".equals(s)) s += ": " + lastError;
|
||||
return s;
|
||||
}
|
||||
|
||||
private void refreshNotification() {
|
||||
main.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||
if (nm != null) nm.notify(NOTIFICATION_ID, notification(statusLine()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Notification notification(String text) {
|
||||
Notification.Builder b = Build.VERSION.SDK_INT >= 26
|
||||
? new Notification.Builder(this, CHANNEL_ID) : new Notification.Builder(this);
|
||||
Intent open = new Intent(this, DashcamActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
PendingIntent openPi = PendingIntent.getActivity(this, 1, open, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
Intent save = new Intent(this, DashcamService.class).setAction(ACTION_SAVE);
|
||||
PendingIntent savePi = PendingIntent.getService(this, 2, save, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
return b.setContentTitle("MG Utility dashcam")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(android.R.drawable.presence_video_online)
|
||||
.setOngoing(true)
|
||||
.setContentIntent(openPi)
|
||||
.addAction(new Notification.Action.Builder(null, "LOCK EVENT", savePi).build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private void createChannel() {
|
||||
if (Build.VERSION.SDK_INT < 26) return;
|
||||
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||
if (nm != null) nm.createNotificationChannel(new NotificationChannel(CHANNEL_ID, "Dashcam", NotificationManager.IMPORTANCE_LOW));
|
||||
}
|
||||
|
||||
private void stopForegroundCompat() {
|
||||
try { stopForeground(true); } catch (Throwable ignored) { }
|
||||
}
|
||||
|
||||
private void toast(final String text) {
|
||||
main.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
try { Toast.makeText(DashcamService.this, text, Toast.LENGTH_LONG).show(); } catch (Throwable ignored) { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static String describe() {
|
||||
StringBuilder sb = new StringBuilder(statusLine());
|
||||
String active = activeClipName;
|
||||
if (active != null) sb.append(" • ").append(active);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
static String summary(Context c) {
|
||||
List<DashcamPolicy.Clip> clips = DashcamStore.listClips();
|
||||
long used = DashcamPolicy.totalBytes(clips);
|
||||
return String.format(Locale.US, "%s • %s of %d GB", running ? status : (DashcamStore.enabled(c) ? "Starting" : "Off"),
|
||||
DashcamPolicy.formatBytes(used), DashcamStore.capGb(c));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Environment;
|
||||
import android.os.StatFs;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Dashcam settings, clip listing and the "keep" list.
|
||||
*
|
||||
* <p>Clips and the keep list live in shared storage under {@code MG-Utility/dashcam} so that an
|
||||
* uninstall or app-data wipe cannot take saved footage with it.
|
||||
*/
|
||||
final class DashcamStore {
|
||||
private DashcamStore() { }
|
||||
|
||||
static final String PREFS = "dashcam";
|
||||
static final String KEY_ENABLED = "enabled";
|
||||
static final String KEY_CAP_GB = "storage_cap_gb";
|
||||
static final String KEY_RETENTION_DAYS = "retention_days";
|
||||
static final String KEY_SEGMENT_SEC = "segment_sec";
|
||||
static final String KEY_BITRATE_KBPS = "bitrate_kbps";
|
||||
static final String KEY_FPS = "fps";
|
||||
static final String KEY_SHOW_SPEED = "show_speed";
|
||||
static final String KEY_SIGNATURE = "signature";
|
||||
static final String KEY_OEM_HANDOFF = "oem_handoff";
|
||||
static final String KEY_UPLOAD_ENABLED = "upload_enabled";
|
||||
static final String KEY_UPLOAD_DELETE_LOCAL = "upload_delete_local";
|
||||
static final String KEY_SERVER_URL = "server_url";
|
||||
static final String KEY_SERVER_TOKEN = "server_token";
|
||||
static final String KEY_REMOTE_URL = "remote_url";
|
||||
static final String DEFAULT_SERVER_URL = "http://10.0.0.148:8780";
|
||||
static final String DEFAULT_REMOTE_URL = "https://dashcam.molberg.cloud";
|
||||
static final String KEY_STORAGE_DIR = "storage_dir";
|
||||
static final String KEY_KNOWN_DIRS = "known_storage_dirs";
|
||||
static final String KEY_FALLBACK_INTERNAL = "fallback_internal";
|
||||
static final String KEY_PARKED_MODE = "parked_mode";
|
||||
static final String KEY_PARKED_RETENTION_DAYS = "parked_retention_days";
|
||||
static final String KEY_SAVE_BEFORE_SEC = "event_before_sec";
|
||||
static final String KEY_SAVE_AFTER_SEC = "event_after_sec";
|
||||
|
||||
static final int DEFAULT_CAP_GB = 8;
|
||||
static final int DEFAULT_RETENTION_DAYS = 30;
|
||||
static final int DEFAULT_SEGMENT_SEC = 60;
|
||||
static final int DEFAULT_BITRATE_KBPS = 6000;
|
||||
/** Parked recording: 0 = don't record, 1 = low, 2 = medium, 3 = same as driving. */
|
||||
static final int PARKED_OFF = 0, PARKED_LOW = 1, PARKED_MEDIUM = 2, PARKED_FULL = 3;
|
||||
static final int DEFAULT_PARKED_MODE = PARKED_LOW;
|
||||
static final int DEFAULT_PARKED_RETENTION_DAYS = 7;
|
||||
static final int DEFAULT_FPS = 25;
|
||||
static final int DEFAULT_SAVE_BEFORE_SEC = 120;
|
||||
static final int DEFAULT_SAVE_AFTER_SEC = 60;
|
||||
static final int[] CAP_CHOICES_GB = { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };
|
||||
static final int[] RETENTION_CHOICES_DAYS = { 3, 7, 14, 30, 60, 90, 180, 365, 0 };
|
||||
/** Space left on the volume for the head unit itself, whatever the budget says. */
|
||||
static final long VOLUME_RESERVE_BYTES = 2L * 1024L * 1024L * 1024L;
|
||||
|
||||
static final String DIR_NAME = "MG-Utility/dashcam";
|
||||
|
||||
static SharedPreferences prefs(Context c) { return c.getSharedPreferences(PREFS, Context.MODE_PRIVATE); }
|
||||
|
||||
static boolean enabled(Context c) { return prefs(c).getBoolean(KEY_ENABLED, false); }
|
||||
static int capGb(Context c) { return prefs(c).getInt(KEY_CAP_GB, DEFAULT_CAP_GB); }
|
||||
static int retentionDays(Context c) { return prefs(c).getInt(KEY_RETENTION_DAYS, DEFAULT_RETENTION_DAYS); }
|
||||
static int segmentSec(Context c) { return clamp(prefs(c).getInt(KEY_SEGMENT_SEC, DEFAULT_SEGMENT_SEC), 15, 300); }
|
||||
static int bitrateBps(Context c) { return clamp(prefs(c).getInt(KEY_BITRATE_KBPS, DEFAULT_BITRATE_KBPS), 1000, 30000) * 1000; }
|
||||
static int fps(Context c) { return clamp(prefs(c).getInt(KEY_FPS, DEFAULT_FPS), 5, 30); }
|
||||
static boolean showSpeed(Context c) { return prefs(c).getBoolean(KEY_SHOW_SPEED, true); }
|
||||
static String signature(Context c) { return prefs(c).getString(KEY_SIGNATURE, "MG Utility"); }
|
||||
static boolean oemHandoff(Context c) { return prefs(c).getBoolean(KEY_OEM_HANDOFF, true); }
|
||||
static boolean uploadEnabled(Context c) { return prefs(c).getBoolean(KEY_UPLOAD_ENABLED, false); }
|
||||
static boolean deleteAfterUpload(Context c) { return prefs(c).getBoolean(KEY_UPLOAD_DELETE_LOCAL, true); }
|
||||
static String serverUrl(Context c) { return prefs(c).getString(KEY_SERVER_URL, DEFAULT_SERVER_URL).trim(); }
|
||||
static String remoteUrl(Context c) { return prefs(c).getString(KEY_REMOTE_URL, DEFAULT_REMOTE_URL).trim(); }
|
||||
static String serverToken(Context c) { return prefs(c).getString(KEY_SERVER_TOKEN, "").trim(); }
|
||||
static int parkedMode(Context c) { return clamp(prefs(c).getInt(KEY_PARKED_MODE, DEFAULT_PARKED_MODE), 0, 3); }
|
||||
static int parkedRetentionDays(Context c) { return prefs(c).getInt(KEY_PARKED_RETENTION_DAYS, DEFAULT_PARKED_RETENTION_DAYS); }
|
||||
static boolean fallbackInternal(Context c) { return prefs(c).getBoolean(KEY_FALLBACK_INTERNAL, true); }
|
||||
|
||||
/** Bitrate and frame rate for the current mode. */
|
||||
static int bitrateFor(Context c, boolean parked) {
|
||||
return bitrateFor(c, parked, parkedMode(c));
|
||||
}
|
||||
|
||||
static int bitrateFor(Context c, boolean parked, int mode) {
|
||||
if (!parked) return bitrateBps(c);
|
||||
switch (mode) {
|
||||
case PARKED_LOW: return 1500 * 1000;
|
||||
case PARKED_MEDIUM: return 3000 * 1000;
|
||||
default: return bitrateBps(c);
|
||||
}
|
||||
}
|
||||
|
||||
static int fpsFor(Context c, boolean parked) {
|
||||
if (!parked) return fps(c);
|
||||
switch (parkedMode(c)) {
|
||||
case PARKED_LOW: return 10;
|
||||
case PARKED_MEDIUM: return 15;
|
||||
default: return fps(c);
|
||||
}
|
||||
}
|
||||
|
||||
static String parkedModeLabel(int mode) {
|
||||
switch (mode) {
|
||||
case PARKED_OFF: return "Don't record while parked";
|
||||
case PARKED_LOW: return "Low (1.5 Mbit/s, 10 fps)";
|
||||
case PARKED_MEDIUM: return "Medium (3 Mbit/s, 15 fps)";
|
||||
default: return "Same as driving";
|
||||
}
|
||||
}
|
||||
|
||||
/** Rough storage per hour at a bitrate. */
|
||||
static String perHour(int bitrateBps) { return DashcamPolicy.formatBytes(DashcamPolicy.segmentBytes(bitrateBps, 3600)) + "/hour"; }
|
||||
|
||||
static int saveBeforeSec(Context c) { return clamp(prefs(c).getInt(KEY_SAVE_BEFORE_SEC, DEFAULT_SAVE_BEFORE_SEC), 10, 600); }
|
||||
static int saveAfterSec(Context c) { return clamp(prefs(c).getInt(KEY_SAVE_AFTER_SEC, DEFAULT_SAVE_AFTER_SEC), 0, 300); }
|
||||
|
||||
private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
static String retentionLabel(int days) { return days <= 0 ? "Never (budget only)" : days + " days"; }
|
||||
|
||||
// ---------------------------------------------------------------- directories
|
||||
|
||||
/** Overridable for on-device tests that run outside an app process. */
|
||||
static volatile File rootOverride;
|
||||
/** The recording folder chosen by the driver ("" = internal). Loaded by {@link #init}. */
|
||||
private static volatile String customDir = "";
|
||||
private static volatile boolean customUsable = true;
|
||||
private static volatile java.util.Set<String> knownDirs = new java.util.HashSet<String>();
|
||||
|
||||
/** Loads the folder settings; call before the first listing (app start, service start, screens). */
|
||||
static void init(Context c) {
|
||||
SharedPreferences p = prefs(c);
|
||||
customDir = p.getString(KEY_STORAGE_DIR, "").trim();
|
||||
java.util.Set<String> known = new java.util.HashSet<String>(p.getStringSet(KEY_KNOWN_DIRS, new java.util.HashSet<String>()));
|
||||
if (!customDir.isEmpty()) known.add(customDir);
|
||||
knownDirs = known;
|
||||
customUsable = customDir.isEmpty() || writable(new File(customDir));
|
||||
}
|
||||
|
||||
/** Small control files (keep list, upload ledger, pending events) always stay internal. */
|
||||
static File rootDir() {
|
||||
File o = rootOverride;
|
||||
return o != null ? o : new File(Environment.getExternalStorageDirectory(), DIR_NAME);
|
||||
}
|
||||
|
||||
static String customDir() { return customDir; }
|
||||
static boolean customUsable() { return customUsable; }
|
||||
|
||||
/**
|
||||
* Where new footage goes: the chosen folder when it is writable, otherwise internal storage
|
||||
* (or null when the driver asked not to fall back).
|
||||
*/
|
||||
static File recordingRoot(Context c) {
|
||||
if (rootOverride != null || customDir.isEmpty()) return rootDir();
|
||||
File d = new File(customDir);
|
||||
customUsable = writable(d);
|
||||
if (customUsable) return d;
|
||||
return fallbackInternal(c) ? rootDir() : null;
|
||||
}
|
||||
|
||||
static boolean usingFallback(Context c) { return !customDir.isEmpty() && !customUsable; }
|
||||
|
||||
/** Every folder that may hold footage: internal, the current choice, and earlier choices. */
|
||||
static List<File> allRoots() {
|
||||
List<File> out = new ArrayList<File>();
|
||||
out.add(rootDir());
|
||||
for (String s : knownDirs) {
|
||||
File f = new File(s);
|
||||
if (!out.contains(f) && f.isDirectory()) out.add(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static void setCustomDir(Context c, String path) {
|
||||
String clean = path == null ? "" : path.trim();
|
||||
while (clean.length() > 1 && clean.endsWith("/")) clean = clean.substring(0, clean.length() - 1);
|
||||
SharedPreferences p = prefs(c);
|
||||
java.util.Set<String> known = new java.util.HashSet<String>(p.getStringSet(KEY_KNOWN_DIRS, new java.util.HashSet<String>()));
|
||||
if (!clean.isEmpty()) known.add(clean);
|
||||
p.edit().putString(KEY_STORAGE_DIR, clean).putStringSet(KEY_KNOWN_DIRS, known).apply();
|
||||
init(c);
|
||||
}
|
||||
|
||||
/** Real write test: create, write, sync, read back, delete. */
|
||||
static boolean writable(File dir) {
|
||||
try {
|
||||
if (!dir.isDirectory() && !dir.mkdirs()) return false;
|
||||
File probe = new File(dir, ".mgu-write-test");
|
||||
FileOutputStream out = new FileOutputStream(probe);
|
||||
try { out.write(new byte[] { 'o', 'k' }); out.getFD().sync(); } finally { out.close(); }
|
||||
boolean ok = probe.length() == 2;
|
||||
probe.delete();
|
||||
return ok;
|
||||
} catch (Throwable t) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static File clipsDir() { return clipsDirIn(rootDir()); }
|
||||
|
||||
static File clipsDirIn(File root) {
|
||||
File dir = new File(root, "clips");
|
||||
if (!dir.isDirectory()) dir.mkdirs();
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Bytes on the recording volume that are not ours (set by the folder check; 0 = unknown). */
|
||||
static volatile long otherBytesHint = 0L;
|
||||
|
||||
static boolean isInternal(File dir) {
|
||||
String p = dir.getAbsolutePath();
|
||||
return p.startsWith("/storage/emulated") || p.startsWith("/sdcard") || p.startsWith("/data")
|
||||
|| p.startsWith(Environment.getExternalStorageDirectory().getAbsolutePath());
|
||||
}
|
||||
|
||||
/** Space kept free on the volume: more on the head unit's own storage than on a USB stick. */
|
||||
static long reserveFor(File dir) {
|
||||
return isInternal(dir) ? VOLUME_RESERVE_BYTES : 512L * 1024L * 1024L;
|
||||
}
|
||||
|
||||
/** Where a locked event is written: next to the clips, so a USB stick takes the bulk. */
|
||||
static File eventsWriteDir() {
|
||||
File root = rootOverride != null ? rootDir() : (customDir.isEmpty() || !customUsable ? rootDir() : new File(customDir));
|
||||
File d = new File(root, "events");
|
||||
if (!d.isDirectory()) d.mkdirs();
|
||||
return d;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- storage candidates
|
||||
|
||||
static final class Volume {
|
||||
final String label;
|
||||
final File suggested;
|
||||
final long total, free;
|
||||
final boolean removable;
|
||||
Volume(String label, File suggested, long total, long free, boolean removable) {
|
||||
this.label = label; this.suggested = suggested; this.total = total; this.free = free; this.removable = removable;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounted volumes a recording folder could go on: the head unit's own storage, plus every
|
||||
* removable volume under /storage, and its raw mount under /mnt/media_rw (MG Utility runs as
|
||||
* the system user, which can write there even when the /storage view is read-only).
|
||||
*/
|
||||
static List<Volume> volumes() {
|
||||
List<Volume> out = new ArrayList<Volume>();
|
||||
File internal = Environment.getExternalStorageDirectory();
|
||||
out.add(new Volume("Head unit storage", new File(internal, DIR_NAME), volumeTotalBytes(internal), freeOf(internal), false));
|
||||
java.util.Set<String> seen = new java.util.HashSet<String>();
|
||||
File[] raw = new File("/mnt/media_rw").listFiles();
|
||||
if (raw != null) for (File v : raw) {
|
||||
if (!v.isDirectory()) continue;
|
||||
seen.add(v.getName());
|
||||
out.add(new Volume("USB " + v.getName() + " (direct)", new File(v, DIR_NAME), volumeTotalBytes(v), freeOf(v), true));
|
||||
}
|
||||
File[] st = new File("/storage").listFiles();
|
||||
if (st != null) for (File v : st) {
|
||||
String n = v.getName();
|
||||
if (!v.isDirectory() || "emulated".equals(n) || "self".equals(n)) continue;
|
||||
out.add(new Volume("USB " + n + (seen.contains(n) ? " (/storage view)" : ""), new File(v, DIR_NAME), volumeTotalBytes(v), freeOf(v), true));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static long freeOf(File dir) {
|
||||
try { return new StatFs(dir.getAbsolutePath()).getAvailableBytes(); }
|
||||
catch (Throwable t) { return -1L; }
|
||||
}
|
||||
|
||||
static File keepFile() { return new File(rootDir(), "keep.json"); }
|
||||
static File uploadedFile() { return new File(rootDir(), "uploaded.txt"); }
|
||||
|
||||
/** Budget actually usable: the chosen cap, but never eating the recording volume's reserve. */
|
||||
static long effectiveCapBytes(Context c, long currentClipBytes) {
|
||||
long cap = capGb(c) * 1024L * 1024L * 1024L;
|
||||
File root = recordingRoot(c);
|
||||
if (root == null) return cap;
|
||||
try {
|
||||
StatFs fs = new StatFs(root.getAbsolutePath());
|
||||
if (!isInternal(root)) {
|
||||
// On this head unit a USB stick's free-space figure drifts towards zero while
|
||||
// the stick is in use and only resets on remount (measured by the upstream
|
||||
// MG4_Dashcam project over five weeks). Trusting it would delete footage to make
|
||||
// room that was never missing, so a USB budget is bounded by the stick's size.
|
||||
long total = fs.getTotalBytes();
|
||||
return total > 0 ? Math.min(cap, Math.max(0L, total - reserveFor(root) - otherBytesHint)) : cap;
|
||||
}
|
||||
long free = fs.getAvailableBytes();
|
||||
long possible = currentClipBytes + Math.max(0L, free - reserveFor(root));
|
||||
return Math.min(cap, possible);
|
||||
} catch (Throwable t) {
|
||||
return cap;
|
||||
}
|
||||
}
|
||||
|
||||
static long volumeFreeBytes(Context c) {
|
||||
File root = recordingRoot(c);
|
||||
if (root == null) return -1L;
|
||||
try { return new StatFs(root.getAbsolutePath()).getAvailableBytes(); }
|
||||
catch (Throwable t) { return -1L; }
|
||||
}
|
||||
|
||||
static long volumeTotalBytes(File dir) {
|
||||
try { return new StatFs(dir.getAbsolutePath()).getTotalBytes(); }
|
||||
catch (Throwable t) { return -1L; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- clips
|
||||
|
||||
private static final java.util.concurrent.ConcurrentHashMap<String, Boolean> PARKED_CACHE =
|
||||
new java.util.concurrent.ConcurrentHashMap<String, Boolean>();
|
||||
|
||||
static List<DashcamPolicy.Clip> listClips() {
|
||||
List<DashcamPolicy.Clip> out = new ArrayList<DashcamPolicy.Clip>();
|
||||
java.util.Set<String> seen = new java.util.HashSet<String>();
|
||||
for (File root : allRoots()) {
|
||||
File[] files = new File(root, "clips").listFiles();
|
||||
if (files == null) continue;
|
||||
for (File f : files) {
|
||||
if (!f.isFile() || !seen.add(f.getName())) continue;
|
||||
long start = DashcamPolicy.clipStart(f.getName());
|
||||
if (start < 0) continue;
|
||||
long end = Math.max(start, f.lastModified());
|
||||
// A clip that has not been closed for hours cannot be longer than ten minutes.
|
||||
if (end - start > 10L * 60L * 1000L) end = start + 10L * 60L * 1000L;
|
||||
Boolean parked = PARKED_CACHE.get(f.getAbsolutePath());
|
||||
if (parked == null) {
|
||||
File side = DashcamTelemetry.sidecar(f);
|
||||
if (side.isFile()) {
|
||||
parked = "parked".equals(DashcamTelemetry.mode(f));
|
||||
PARKED_CACHE.put(f.getAbsolutePath(), parked);
|
||||
} else {
|
||||
parked = Boolean.FALSE; // not cached: the sidecar may still be on its way
|
||||
}
|
||||
}
|
||||
out.add(new DashcamPolicy.Clip(f.getName(), start, end, f.length(), parked));
|
||||
}
|
||||
}
|
||||
Collections.sort(out, new java.util.Comparator<DashcamPolicy.Clip>() {
|
||||
@Override public int compare(DashcamPolicy.Clip a, DashcamPolicy.Clip b) {
|
||||
return a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0;
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Finds a clip in whichever folder holds it (new clips: the current recording folder). */
|
||||
static File clipFile(String name) {
|
||||
for (File root : allRoots()) {
|
||||
File f = new File(new File(root, "clips"), name);
|
||||
if (f.exists()) return f;
|
||||
}
|
||||
return new File(clipsDir(), name);
|
||||
}
|
||||
|
||||
/** Deletes a clip and its telemetry sidecar. */
|
||||
static boolean deleteClip(String name) {
|
||||
File f = clipFile(name);
|
||||
PARKED_CACHE.remove(f.getAbsolutePath());
|
||||
DashcamTelemetry.sidecar(f).delete();
|
||||
return f.delete();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- keep list
|
||||
|
||||
static final class Keep {
|
||||
final String id;
|
||||
final long startMs;
|
||||
final long endMs;
|
||||
final String label;
|
||||
final long createdMs;
|
||||
|
||||
Keep(String id, long startMs, long endMs, String label, long createdMs) {
|
||||
this.id = id;
|
||||
this.startMs = Math.min(startMs, endMs);
|
||||
this.endMs = Math.max(startMs, endMs);
|
||||
this.label = label == null ? "" : label;
|
||||
this.createdMs = createdMs;
|
||||
}
|
||||
|
||||
DashcamPolicy.Range range() { return new DashcamPolicy.Range(startMs, endMs); }
|
||||
}
|
||||
|
||||
private static final Object KEEP_LOCK = new Object();
|
||||
|
||||
static List<Keep> keeps() {
|
||||
synchronized (KEEP_LOCK) {
|
||||
List<Keep> out = new ArrayList<Keep>();
|
||||
File f = keepFile();
|
||||
if (!f.isFile()) return out;
|
||||
try {
|
||||
JSONArray arr = new JSONObject(readText(f)).optJSONArray("keep");
|
||||
if (arr == null) return out;
|
||||
for (int i = 0; i < arr.length(); i++) {
|
||||
JSONObject o = arr.getJSONObject(i);
|
||||
out.add(new Keep(o.optString("id"), o.optLong("start"), o.optLong("end"),
|
||||
o.optString("label"), o.optLong("created")));
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
static List<DashcamPolicy.Range> keepRanges() {
|
||||
List<DashcamPolicy.Range> out = new ArrayList<DashcamPolicy.Range>();
|
||||
for (Keep k : keeps()) out.add(k.range());
|
||||
return out;
|
||||
}
|
||||
|
||||
static Keep addKeep(long startMs, long endMs, String label) {
|
||||
synchronized (KEEP_LOCK) {
|
||||
List<Keep> all = keeps();
|
||||
Keep k = new Keep(UUID.randomUUID().toString().substring(0, 8), startMs, endMs,
|
||||
label, System.currentTimeMillis());
|
||||
all.add(k);
|
||||
writeKeeps(all);
|
||||
return k;
|
||||
}
|
||||
}
|
||||
|
||||
static void removeKeep(String id) {
|
||||
synchronized (KEEP_LOCK) {
|
||||
List<Keep> all = keeps();
|
||||
List<Keep> next = new ArrayList<Keep>();
|
||||
for (Keep k : all) if (!k.id.equals(id)) next.add(k);
|
||||
writeKeeps(next);
|
||||
}
|
||||
}
|
||||
|
||||
static JSONArray keepsJson(List<Keep> keeps) {
|
||||
JSONArray arr = new JSONArray();
|
||||
try {
|
||||
for (Keep k : keeps) {
|
||||
JSONObject o = new JSONObject();
|
||||
o.put("id", k.id); o.put("start", k.startMs); o.put("end", k.endMs);
|
||||
o.put("label", k.label); o.put("created", k.createdMs);
|
||||
arr.put(o);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return arr;
|
||||
}
|
||||
|
||||
private static void writeKeeps(List<Keep> keeps) {
|
||||
try {
|
||||
JSONObject root = new JSONObject();
|
||||
root.put("schema", 1);
|
||||
root.put("keep", keepsJson(keeps));
|
||||
writeTextAtomic(keepFile(), root.toString(2));
|
||||
} catch (Exception ignored) { }
|
||||
}
|
||||
|
||||
static boolean isKept(DashcamPolicy.Clip clip, List<DashcamPolicy.Range> ranges) {
|
||||
return DashcamPolicy.isProtected(clip, ranges);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- upload ledger
|
||||
|
||||
private static final Object UPLOAD_LOCK = new Object();
|
||||
|
||||
static Set<String> uploaded() {
|
||||
synchronized (UPLOAD_LOCK) {
|
||||
Set<String> out = new HashSet<String>();
|
||||
File f = uploadedFile();
|
||||
if (!f.isFile()) return out;
|
||||
try {
|
||||
for (String line : readText(f).split("\n")) {
|
||||
String s = line.trim();
|
||||
if (!s.isEmpty()) out.add(s);
|
||||
}
|
||||
} catch (IOException ignored) { }
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
static void markUploaded(String name) {
|
||||
synchronized (UPLOAD_LOCK) {
|
||||
try {
|
||||
File f = uploadedFile();
|
||||
f.getParentFile().mkdirs();
|
||||
OutputStream out = new FileOutputStream(f, true);
|
||||
out.write((name + "\n").getBytes("UTF-8"));
|
||||
out.close();
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops ledger lines for clips that no longer exist locally, so the file stays small. */
|
||||
static void compactUploaded() {
|
||||
synchronized (UPLOAD_LOCK) {
|
||||
Set<String> all = uploaded();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String n : all) {
|
||||
boolean exists;
|
||||
if (DashcamEvents.isEventName(n)) exists = DashcamEvents.find(n) != null;
|
||||
else if (n.endsWith(".json")) {
|
||||
String base = n.substring(0, n.length() - 5);
|
||||
File owner = DashcamEvents.isEventName(base) ? DashcamEvents.find(base) : clipFile(base);
|
||||
exists = owner != null && DashcamTelemetry.sidecar(owner).exists();
|
||||
}
|
||||
else exists = clipFile(n).exists();
|
||||
if (exists) sb.append(n).append('\n');
|
||||
}
|
||||
try { writeTextAtomic(uploadedFile(), sb.toString()); } catch (IOException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- io helpers
|
||||
|
||||
static String readText(File f) throws IOException {
|
||||
InputStream in = new FileInputStream(f);
|
||||
try {
|
||||
byte[] buf = new byte[(int) Math.min(f.length(), 4L * 1024L * 1024L)];
|
||||
int off = 0, n;
|
||||
while (off < buf.length && (n = in.read(buf, off, buf.length - off)) > 0) off += n;
|
||||
return new String(buf, 0, off, "UTF-8");
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
}
|
||||
|
||||
static void writeTextAtomic(File f, String text) throws IOException {
|
||||
f.getParentFile().mkdirs();
|
||||
File tmp = new File(f.getParentFile(), f.getName() + ".tmp");
|
||||
FileOutputStream out = new FileOutputStream(tmp);
|
||||
try {
|
||||
out.write(text.getBytes("UTF-8"));
|
||||
out.getFD().sync();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
if (!tmp.renameTo(f)) {
|
||||
f.delete();
|
||||
if (!tmp.renameTo(f)) throw new IOException("rename failed for " + f);
|
||||
}
|
||||
}
|
||||
|
||||
static String timeLabel(long ms) {
|
||||
return new java.text.SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new java.util.Date(ms));
|
||||
}
|
||||
|
||||
static String dayLabel(long ms) {
|
||||
return new java.text.SimpleDateFormat("EEE d MMM", Locale.getDefault()).format(new java.util.Date(ms));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.location.Location;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Drive-log data that belongs to each dashcam clip.
|
||||
*
|
||||
* <p>The trip tracker already reads the vehicle every few seconds; it pushes each reading here.
|
||||
* While a clip is recording, readings are buffered and written next to the clip as
|
||||
* {@code <clip>.json} when it closes, so an archived clip carries its own speed, GPS track,
|
||||
* battery and gear log. The latest reading also decides whether the car is parked, which picks
|
||||
* the low-quality "parked" recording mode.
|
||||
*/
|
||||
final class DashcamTelemetry {
|
||||
private DashcamTelemetry() { }
|
||||
|
||||
/** SAIC CAR_GEAR_PARK_RANGE. */
|
||||
static final int GEAR_PARK = 1;
|
||||
private static final int MAX_POINTS = 2000;
|
||||
|
||||
static final class Point {
|
||||
final long t;
|
||||
final float kmh, soc, volts;
|
||||
final int range, gear;
|
||||
final double lat, lon;
|
||||
final float acc, heading, gpsKmh;
|
||||
final boolean fix;
|
||||
|
||||
Point(long t, float kmh, float soc, int range, float volts, int gear, Location l) {
|
||||
this.t = t; this.kmh = kmh; this.soc = soc; this.range = range; this.volts = volts; this.gear = gear;
|
||||
fix = l != null;
|
||||
lat = fix ? l.getLatitude() : 0; lon = fix ? l.getLongitude() : 0;
|
||||
acc = fix && l.hasAccuracy() ? l.getAccuracy() : -1f;
|
||||
heading = fix && l.hasBearing() ? l.getBearing() : -1f;
|
||||
gpsKmh = fix && l.hasSpeed() ? l.getSpeed() * 3.6f : -1f;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static volatile Point latest;
|
||||
private static volatile Location latestFix;
|
||||
private static String activeClip;
|
||||
private static long activeStart;
|
||||
private static JSONArray buffer = new JSONArray();
|
||||
private static float maxKmh;
|
||||
private static boolean sawMotion;
|
||||
|
||||
// ------------------------------------------------------------------ feed (trip tracker)
|
||||
|
||||
static void feed(long t, float kmh, float soc, int range, float volts, int gear, Location fix) {
|
||||
Location l = fix != null ? fix : freshFix(t);
|
||||
Point p = new Point(t, kmh, soc, range, volts, gear, l);
|
||||
latest = p;
|
||||
DashcamService.lastSpeedKph = kmh;
|
||||
DashcamService.lastSpeedAtMs = t;
|
||||
synchronized (LOCK) {
|
||||
if (activeClip == null || buffer.length() >= MAX_POINTS) return;
|
||||
buffer.put(toJson(p));
|
||||
if (kmh > maxKmh) maxKmh = kmh;
|
||||
if (kmh >= 3f) sawMotion = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void feedLocation(Location l) { if (l != null) latestFix = new Location(l); }
|
||||
|
||||
private static Location freshFix(long now) {
|
||||
Location l = latestFix;
|
||||
return l != null && Math.abs(now - l.getTime()) < 30000L ? l : null;
|
||||
}
|
||||
|
||||
static Point latest() { return latest; }
|
||||
|
||||
/**
|
||||
* Parked = the last reading is fresh, in Park, and stationary. If the vehicle service has not
|
||||
* reported for 30 s we do not know, and record at driving quality to be safe.
|
||||
*/
|
||||
static boolean parked() {
|
||||
Point p = latest;
|
||||
long now = System.currentTimeMillis();
|
||||
if (p == null || now - p.t > 30000L) return false;
|
||||
// The trip tracker's fast speed poll (up to 5 Hz) sees a drive-away before the next full sample.
|
||||
if (now - DashcamService.lastSpeedAtMs < 5000L && DashcamService.lastSpeedKph >= 3f) return false;
|
||||
return p.gear == GEAR_PARK && p.kmh < 2f;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ per-clip log
|
||||
|
||||
static void clipStarted(String name, long startMs, boolean parkedMode) {
|
||||
synchronized (LOCK) {
|
||||
activeClip = name;
|
||||
activeStart = startMs;
|
||||
buffer = new JSONArray();
|
||||
maxKmh = 0f;
|
||||
sawMotion = false;
|
||||
Point p = latest;
|
||||
if (p != null && System.currentTimeMillis() - p.t < 30000L) buffer.put(toJson(p));
|
||||
}
|
||||
parkedAtStart = parkedMode;
|
||||
}
|
||||
|
||||
private static volatile boolean parkedAtStart;
|
||||
|
||||
/** Writes {@code <clip>.json} beside the clip. Returns the mode label written. */
|
||||
static String clipFinished(File clip, long endMs, int bitrateBps) {
|
||||
JSONArray pts;
|
||||
float max;
|
||||
boolean moved;
|
||||
long start;
|
||||
synchronized (LOCK) {
|
||||
pts = buffer;
|
||||
max = maxKmh;
|
||||
moved = sawMotion;
|
||||
start = activeStart;
|
||||
activeClip = null;
|
||||
buffer = new JSONArray();
|
||||
}
|
||||
String mode = parkedAtStart && !moved ? "parked" : "driving";
|
||||
try {
|
||||
JSONObject o = new JSONObject();
|
||||
o.put("schema", 1);
|
||||
o.put("clip", clip.getName());
|
||||
o.put("start", start);
|
||||
o.put("end", endMs);
|
||||
o.put("mode", mode);
|
||||
o.put("bitrate", bitrateBps);
|
||||
o.put("max_kmh", Math.round(max * 10f) / 10.0);
|
||||
o.put("points", pts);
|
||||
DashcamStore.writeTextAtomic(sidecar(clip), o.toString());
|
||||
} catch (Exception ignored) { }
|
||||
return mode;
|
||||
}
|
||||
|
||||
static File sidecar(File clip) { return new File(clip.getParentFile(), clip.getName() + ".json"); }
|
||||
|
||||
/** "parked" or "driving"; clips without a sidecar count as driving (never demoted by accident). */
|
||||
static String mode(File clip) {
|
||||
File s = sidecar(clip);
|
||||
if (!s.isFile()) return "driving";
|
||||
try {
|
||||
String text = DashcamStore.readText(s);
|
||||
return text.contains("\"mode\":\"parked\"") ? "parked" : "driving";
|
||||
} catch (Exception e) {
|
||||
return "driving";
|
||||
}
|
||||
}
|
||||
|
||||
private static JSONObject toJson(Point p) {
|
||||
JSONObject o = new JSONObject();
|
||||
try {
|
||||
o.put("t", p.t);
|
||||
o.put("kmh", Math.round(p.kmh * 10f) / 10.0);
|
||||
o.put("soc", Math.round(p.soc * 10f) / 10.0);
|
||||
o.put("range", p.range);
|
||||
if (p.volts > 0) o.put("v", Math.round(p.volts * 10f) / 10.0);
|
||||
o.put("gear", p.gear);
|
||||
if (p.fix) {
|
||||
o.put("lat", Math.round(p.lat * 1e6) / 1e6);
|
||||
o.put("lon", Math.round(p.lon * 1e6) / 1e6);
|
||||
if (p.acc >= 0) o.put("acc", Math.round(p.acc));
|
||||
if (p.heading >= 0) o.put("hdg", Math.round(p.heading));
|
||||
if (p.gpsKmh >= 0) o.put("gkmh", Math.round(p.gpsKmh * 10f) / 10.0);
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return o;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Offloads finished clips to the dashcam archive server (CT on pve) and keeps the server's copy
|
||||
* of the keep list in sync.
|
||||
*
|
||||
* <p>Protocol (bearer token on every request):
|
||||
* <ul>
|
||||
* <li>{@code GET /api/health}</li>
|
||||
* <li>{@code GET /api/clips/<name>} → {@code {"size":..,"sha256":..}} or 404</li>
|
||||
* <li>{@code PUT /api/clips/<name>} with {@code X-Content-SHA256}; the server hashes what it
|
||||
* received and only commits a matching file</li>
|
||||
* <li>{@code PUT /api/keep} → {@code {"retention_days":..,"keep":[...]}}</li>
|
||||
* </ul>
|
||||
* A local clip is only removed after a fresh GET returns the same size and SHA-256.
|
||||
*/
|
||||
final class DashcamUploader {
|
||||
private static final String TAG = "MGDashcamUpload";
|
||||
private static final Object RUN_LOCK = new Object();
|
||||
private static volatile String lastResult = "Never run";
|
||||
private static volatile long lastRunMs;
|
||||
|
||||
private DashcamUploader() { }
|
||||
|
||||
static String lastResult() { return lastResult; }
|
||||
static long lastRunMs() { return lastRunMs; }
|
||||
|
||||
/** Where an offload goes from the current network. */
|
||||
static final class Route {
|
||||
final String base;
|
||||
final boolean home;
|
||||
final String label;
|
||||
Route(String base, boolean home, String label) { this.base = base; this.home = home; this.label = label; }
|
||||
}
|
||||
|
||||
private static volatile Route lastRoute;
|
||||
private static volatile long lastRouteMs;
|
||||
|
||||
static Route cachedRoute() { return lastRoute; }
|
||||
static long cachedRouteAgeMs() { return System.currentTimeMillis() - lastRouteMs; }
|
||||
|
||||
/**
|
||||
* Home = the archive answers on its LAN address. That cannot happen over a phone hotspot or
|
||||
* mobile data, so it needs no Wi-Fi name setup and cannot be fooled by a hotspot that happens
|
||||
* to look like Wi-Fi to Android. Away = use the public URL (Cloudflare), manual offload only.
|
||||
*/
|
||||
static Route route(Context context) {
|
||||
String lan = normalise(DashcamStore.serverUrl(context));
|
||||
String remote = normalise(DashcamStore.remoteUrl(context));
|
||||
String ssid = wifiName(context);
|
||||
Route r;
|
||||
if (!lan.isEmpty() && lanReachable(lan)) {
|
||||
r = new Route(lan, true, "Home network" + (ssid.isEmpty() ? "" : " (" + ssid + ")"));
|
||||
} else if (!remote.isEmpty()) {
|
||||
r = new Route(remote, false, "Away" + (ssid.isEmpty() ? "" : " (" + ssid + ")") + " - manual offload via internet");
|
||||
} else {
|
||||
r = new Route("", false, "Away - no remote URL set");
|
||||
}
|
||||
lastRoute = r;
|
||||
lastRouteMs = System.currentTimeMillis();
|
||||
return r;
|
||||
}
|
||||
|
||||
private static boolean lanReachable(String base) {
|
||||
HttpURLConnection c = null;
|
||||
try {
|
||||
c = (HttpURLConnection) new URL(base + "/api/health").openConnection();
|
||||
c.setConnectTimeout(1500);
|
||||
c.setReadTimeout(2000);
|
||||
int code = c.getResponseCode();
|
||||
return code == 200 || code == 401;
|
||||
} catch (Throwable t) {
|
||||
return false;
|
||||
} finally {
|
||||
if (c != null) c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
static String wifiName(Context context) {
|
||||
try {
|
||||
android.net.wifi.WifiManager wm = (android.net.wifi.WifiManager) context.getApplicationContext()
|
||||
.getSystemService(Context.WIFI_SERVICE);
|
||||
if (wm == null || !wm.isWifiEnabled()) return "";
|
||||
String s = wm.getConnectionInfo() == null ? null : wm.getConnectionInfo().getSSID();
|
||||
if (s == null || s.contains("unknown ssid")) return "";
|
||||
return s.replace("\"", "");
|
||||
} catch (Throwable t) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Automatic pass: only on the home network. */
|
||||
static String runAuto(Context context, String activeName) { return run(context, activeName, false); }
|
||||
|
||||
/** Driver pressed OFFLOAD NOW: any network, over the internet if away. */
|
||||
static String runManual(Context context, String activeName) { return run(context, activeName, true); }
|
||||
|
||||
static String run(Context context, String activeName, boolean manual) {
|
||||
synchronized (RUN_LOCK) {
|
||||
String result;
|
||||
try {
|
||||
result = runLocked(context, activeName, manual);
|
||||
} catch (Throwable t) {
|
||||
result = "Offload failed: " + t.getClass().getSimpleName() + (t.getMessage() == null ? "" : " " + t.getMessage());
|
||||
Log.w(TAG, result, t);
|
||||
}
|
||||
lastResult = result;
|
||||
lastRunMs = System.currentTimeMillis();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static String runLocked(Context context, String activeName, boolean manual) throws Exception {
|
||||
String token = DashcamStore.serverToken(context);
|
||||
if (token.isEmpty()) return "Archive token not set";
|
||||
Route route = route(context);
|
||||
if (!manual && !route.home) return "Not on home network - waiting (use OFFLOAD NOW to upload over the hotspot)";
|
||||
if (route.base.isEmpty()) return "No route to the archive (set the remote URL)";
|
||||
String base = route.base;
|
||||
int chunk = route.home ? 64 * 1024 * 1024 : 16 * 1024 * 1024;
|
||||
health(base, token);
|
||||
syncKeep(context, base, token);
|
||||
|
||||
Set<String> done = DashcamStore.uploaded();
|
||||
// Locked events first: they are what matters if the trip to the server is cut short.
|
||||
int events = 0;
|
||||
for (File ev : DashcamEvents.list()) {
|
||||
if (done.contains(ev.getName())) continue;
|
||||
String sha = sha256(ev);
|
||||
Remote remote = stat(base, token, ev.getName());
|
||||
if (remote == null || remote.size != ev.length() || !sha.equals(remote.sha256)) {
|
||||
putResumable(base, token, ev, sha, chunk);
|
||||
events++;
|
||||
}
|
||||
Remote check = stat(base, token, ev.getName());
|
||||
if (check == null || check.size != ev.length() || !sha.equals(check.sha256)) {
|
||||
throw new IOException("server copy of " + ev.getName() + " does not match after upload");
|
||||
}
|
||||
DashcamStore.markUploaded(ev.getName());
|
||||
File evSide = DashcamTelemetry.sidecar(ev);
|
||||
if (evSide.isFile() && !done.contains(evSide.getName())) {
|
||||
putTelemetry(base, token, ev.getName(), evSide);
|
||||
DashcamStore.markUploaded(evSide.getName());
|
||||
}
|
||||
}
|
||||
|
||||
List<DashcamPolicy.Clip> clips = DashcamStore.listClips();
|
||||
List<DashcamPolicy.Range> keep = DashcamStore.keepRanges();
|
||||
boolean deleteLocal = DashcamStore.deleteAfterUpload(context);
|
||||
int uploaded = 0, freed = 0, skipped = 0;
|
||||
for (DashcamPolicy.Clip c : clips) {
|
||||
if (c.name.equals(activeName)) continue;
|
||||
File f = DashcamStore.clipFile(c.name);
|
||||
if (!f.isFile()) continue;
|
||||
// A clip still being finalised has a fresh mtime; leave it for the next pass.
|
||||
if (System.currentTimeMillis() - f.lastModified() < 15000L) { skipped++; continue; }
|
||||
boolean already = done.contains(c.name);
|
||||
String sha = null;
|
||||
if (!already) {
|
||||
sha = sha256(f);
|
||||
Remote remote = stat(base, token, c.name);
|
||||
if (remote == null || remote.size != f.length() || !sha.equals(remote.sha256)) {
|
||||
putResumable(base, token, f, sha, chunk);
|
||||
uploaded++;
|
||||
}
|
||||
Remote check = stat(base, token, c.name);
|
||||
if (check == null || check.size != f.length() || !sha.equals(check.sha256)) {
|
||||
throw new IOException("server copy of " + c.name + " does not match after upload");
|
||||
}
|
||||
DashcamStore.markUploaded(c.name);
|
||||
}
|
||||
File side = DashcamTelemetry.sidecar(f);
|
||||
if (side.isFile() && !done.contains(side.getName())) {
|
||||
putTelemetry(base, token, c.name, side);
|
||||
DashcamStore.markUploaded(side.getName());
|
||||
}
|
||||
if (deleteLocal && !DashcamPolicy.isProtected(c, keep)) {
|
||||
if (sha == null) sha = sha256(f);
|
||||
Remote check = stat(base, token, c.name);
|
||||
if (check != null && check.size == f.length() && sha.equals(check.sha256)) {
|
||||
// Only drop the drive log once the archive has it too.
|
||||
if (!side.isFile() || DashcamStore.uploaded().contains(side.getName())) {
|
||||
if (DashcamStore.deleteClip(c.name)) freed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (freed > 0) DashcamStore.compactUploaded();
|
||||
return String.format(Locale.US, "Offloaded %s%d clip(s) via %s, freed %d on device%s",
|
||||
events > 0 ? events + " event(s) + " : "", uploaded,
|
||||
route.home ? "home network" : "internet", freed, skipped > 0 ? ", " + skipped + " still closing" : "");
|
||||
}
|
||||
|
||||
/** Bytes still waiting to go to the archive (excluding the clip being recorded). */
|
||||
static long pendingBytes(String activeName) {
|
||||
java.util.Set<String> done = DashcamStore.uploaded();
|
||||
long total = 0L;
|
||||
for (File ev : DashcamEvents.list()) if (!done.contains(ev.getName())) total += ev.length();
|
||||
for (DashcamPolicy.Clip c : DashcamStore.listClips()) {
|
||||
if (!c.name.equals(activeName) && !done.contains(c.name)) total += c.sizeBytes;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static String test(Context context) {
|
||||
try {
|
||||
String base = normalise(DashcamStore.serverUrl(context));
|
||||
String token = DashcamStore.serverToken(context);
|
||||
if (token.isEmpty()) return "Enter the access token first";
|
||||
Route route = route(context);
|
||||
base = route.base;
|
||||
if (base.isEmpty()) return "Archive not reachable on the LAN and no remote URL set";
|
||||
JSONObject h = health(base, token);
|
||||
long free = h.optLong("free_bytes", -1L);
|
||||
return "Connected via " + (route.home ? "home network" : "internet") + (free >= 0 ? " - " + DashcamPolicy.formatBytes(free) + " free on server" : "")
|
||||
+ ", " + h.optInt("clips", 0) + " clips archived";
|
||||
} catch (Throwable t) {
|
||||
return "Connection failed: " + t.getClass().getSimpleName() + (t.getMessage() == null ? "" : " " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ requests
|
||||
|
||||
private static final class Remote {
|
||||
long size;
|
||||
String sha256;
|
||||
}
|
||||
|
||||
private static JSONObject health(String base, String token) throws IOException {
|
||||
HttpURLConnection c = open(base + "/api/health", "GET", token);
|
||||
try {
|
||||
int code = c.getResponseCode();
|
||||
if (code == 401 || code == 403) throw new IOException("token rejected");
|
||||
if (code != 200) throw new IOException("health HTTP " + code);
|
||||
return new JSONObject(read(c.getInputStream()));
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("bad health response");
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static Remote stat(String base, String token, String name) throws IOException {
|
||||
HttpURLConnection c = open(base + "/api/clips/" + name, "GET", token);
|
||||
try {
|
||||
int code = c.getResponseCode();
|
||||
if (code == 404) return null;
|
||||
if (code != 200) throw new IOException("stat HTTP " + code);
|
||||
JSONObject o = new JSONObject(read(c.getInputStream()));
|
||||
Remote r = new Remote();
|
||||
r.size = o.optLong("size", -1L);
|
||||
r.sha256 = o.optString("sha256", "");
|
||||
return r;
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("bad stat response");
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/** Chunked, resumable upload: survives a hotspot dropping out and fits Cloudflare's body limit. */
|
||||
private static void putResumable(String base, String token, File f, String sha, int chunk) throws IOException {
|
||||
String url = base + "/api/upload/" + f.getName();
|
||||
long length = f.length();
|
||||
long offset = uploadOffset(url, token);
|
||||
if (offset > length) { discardPartial(url, token); offset = 0L; }
|
||||
java.io.RandomAccessFile raf = new java.io.RandomAccessFile(f, "r");
|
||||
try {
|
||||
byte[] buf = new byte[256 * 1024];
|
||||
int conflicts = 0;
|
||||
while (offset < length) {
|
||||
int n = (int) Math.min(chunk, length - offset);
|
||||
HttpURLConnection c = open(url + "?offset=" + offset, "PUT", token);
|
||||
c.setDoOutput(true);
|
||||
c.setFixedLengthStreamingMode(n);
|
||||
c.setRequestProperty("Content-Type", "application/octet-stream");
|
||||
c.setReadTimeout(120000);
|
||||
try {
|
||||
raf.seek(offset);
|
||||
OutputStream out = c.getOutputStream();
|
||||
int left = n;
|
||||
while (left > 0) {
|
||||
int r = raf.read(buf, 0, Math.min(buf.length, left));
|
||||
if (r <= 0) throw new IOException("short read on " + f.getName());
|
||||
out.write(buf, 0, r);
|
||||
left -= r;
|
||||
}
|
||||
out.close();
|
||||
int code = c.getResponseCode();
|
||||
if (code == 409) {
|
||||
if (++conflicts > 3) throw new IOException("upload offset keeps moving for " + f.getName());
|
||||
offset = uploadOffset(url, token);
|
||||
continue;
|
||||
}
|
||||
if (code != 200) throw new IOException("chunk HTTP " + code + " for " + f.getName());
|
||||
offset = new JSONObject(read(c.getInputStream())).optLong("offset", offset + n);
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("bad chunk response");
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
raf.close();
|
||||
}
|
||||
HttpURLConnection c = open(url + "/commit", "POST", token);
|
||||
c.setDoOutput(true);
|
||||
c.setFixedLengthStreamingMode(0);
|
||||
c.setRequestProperty("X-Content-SHA256", sha);
|
||||
c.setRequestProperty("X-Content-Length-Total", Long.toString(length));
|
||||
c.setReadTimeout(120000);
|
||||
try {
|
||||
c.getOutputStream().close();
|
||||
int code = c.getResponseCode();
|
||||
if (code != 200 && code != 201) throw new IOException("commit HTTP " + code + " for " + f.getName());
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static long uploadOffset(String url, String token) throws IOException {
|
||||
HttpURLConnection c = open(url, "GET", token);
|
||||
try {
|
||||
int code = c.getResponseCode();
|
||||
if (code != 200) throw new IOException("upload status HTTP " + code);
|
||||
return new JSONObject(read(c.getInputStream())).optLong("offset", 0L);
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("bad upload status");
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static void discardPartial(String url, String token) throws IOException {
|
||||
HttpURLConnection c = open(url, "DELETE", token);
|
||||
try { c.getResponseCode(); } finally { c.disconnect(); }
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static void put(String base, String token, File f, String sha) throws IOException {
|
||||
HttpURLConnection c = open(base + "/api/clips/" + f.getName(), "PUT", token);
|
||||
c.setDoOutput(true);
|
||||
c.setFixedLengthStreamingMode(f.length());
|
||||
c.setRequestProperty("Content-Type", "video/mp4");
|
||||
c.setRequestProperty("X-Content-SHA256", sha);
|
||||
c.setReadTimeout(120000);
|
||||
InputStream in = new FileInputStream(f);
|
||||
try {
|
||||
OutputStream out = c.getOutputStream();
|
||||
byte[] buf = new byte[256 * 1024];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
|
||||
out.close();
|
||||
int code = c.getResponseCode();
|
||||
if (code != 200 && code != 201) throw new IOException("upload HTTP " + code + " for " + f.getName());
|
||||
} finally {
|
||||
in.close();
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static void syncKeep(Context context, String base, String token) throws IOException {
|
||||
JSONObject body = new JSONObject();
|
||||
try {
|
||||
body.put("retention_days", DashcamStore.retentionDays(context));
|
||||
body.put("parked_retention_days", DashcamStore.parkedRetentionDays(context));
|
||||
body.put("keep", DashcamStore.keepsJson(DashcamStore.keeps()));
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("keep json");
|
||||
}
|
||||
byte[] bytes = body.toString().getBytes("UTF-8");
|
||||
HttpURLConnection c = open(base + "/api/keep", "PUT", token);
|
||||
c.setDoOutput(true);
|
||||
c.setFixedLengthStreamingMode(bytes.length);
|
||||
c.setRequestProperty("Content-Type", "application/json");
|
||||
try {
|
||||
OutputStream out = c.getOutputStream();
|
||||
out.write(bytes);
|
||||
out.close();
|
||||
int code = c.getResponseCode();
|
||||
if (code != 200) throw new IOException("keep sync HTTP " + code);
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/** Uploads a clip's drive log ({@code <clip>.json}); small, so one request. */
|
||||
private static void putTelemetry(String base, String token, String clipName, File side) throws IOException {
|
||||
byte[] bytes = DashcamStore.readText(side).getBytes("UTF-8");
|
||||
if (bytes.length > 4 * 1024 * 1024) return;
|
||||
HttpURLConnection c = open(base + "/api/telemetry/" + clipName, "PUT", token);
|
||||
c.setDoOutput(true);
|
||||
c.setFixedLengthStreamingMode(bytes.length);
|
||||
c.setRequestProperty("Content-Type", "application/json");
|
||||
try {
|
||||
OutputStream out = c.getOutputStream();
|
||||
out.write(bytes);
|
||||
out.close();
|
||||
int code = c.getResponseCode();
|
||||
if (code != 200 && code != 201) throw new IOException("telemetry upload HTTP " + code);
|
||||
} finally {
|
||||
c.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpURLConnection open(String url, String method, String token) throws IOException {
|
||||
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
|
||||
c.setRequestMethod(method);
|
||||
c.setConnectTimeout(8000);
|
||||
c.setReadTimeout(30000);
|
||||
c.setRequestProperty("Authorization", "Bearer " + token);
|
||||
return c;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
|
||||
static String normalise(String url) {
|
||||
String s = url == null ? "" : url.trim();
|
||||
while (s.endsWith("/")) s = s.substring(0, s.length() - 1);
|
||||
if (!s.isEmpty() && !s.startsWith("http://") && !s.startsWith("https://")) s = "http://" + s;
|
||||
return s;
|
||||
}
|
||||
|
||||
private static boolean isMetered(Context context) {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
return cm != null && cm.isActiveNetworkMetered();
|
||||
} catch (Throwable t) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static String sha256(File f) throws Exception {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
InputStream in = new FileInputStream(f);
|
||||
try {
|
||||
byte[] buf = new byte[256 * 1024];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) md.update(buf, 0, n);
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : md.digest()) sb.append(String.format(Locale.US, "%02x", b & 0xff));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(InputStream in) throws IOException {
|
||||
try {
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
byte[] buf = new byte[8192];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0 && out.size() < 1024 * 1024) out.write(buf, 0, n);
|
||||
return out.toString("UTF-8");
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@ public final class DiagnosticsClient {
|
||||
} }, "mg-startup-analytics").start();
|
||||
}
|
||||
|
||||
private static String getAppVersion(Context context) {
|
||||
static String getAppVersion(Context context) {
|
||||
try { String value = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; return value == null ? "unknown" : value; }
|
||||
catch (Exception ignored) { return "unknown"; }
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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<float[]> queue =
|
||||
new java.util.concurrent.LinkedBlockingQueue<float[]>(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); }}); }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String>(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);
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -7,6 +7,8 @@ final class IconPack {
|
||||
static String forLabel(String value) {
|
||||
if (value == null) return "help";
|
||||
String s = value.toLowerCase(java.util.Locale.ROOT);
|
||||
if (s.contains("backup") || s.contains("back up") || s.contains("restore")) return "storage";
|
||||
if (s.contains("camera")) return "videocam";
|
||||
if (s.contains("update") || s.contains("version")) return "system_update";
|
||||
if (s.contains("plugin")) return "extension";
|
||||
if (s.contains("export")) return "file_upload";
|
||||
|
||||
@@ -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";
|
||||
@@ -42,6 +46,7 @@ final class KeyRemappingManager {
|
||||
static final String ACTION_SOUND_BEST = "SOUND_BEST";
|
||||
static final String ACTION_SOUND_BATTERY = "SOUND_BATTERY";
|
||||
static final String ACTION_HERMES = "HERMES_VOICE";
|
||||
static final String ACTION_DASHCAM_SAVE = "DASHCAM_SAVE";
|
||||
static final String ACTION_USER_INTENT = "USER_INTENT";
|
||||
|
||||
static final class Action {
|
||||
@@ -57,6 +62,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"),
|
||||
@@ -67,6 +76,7 @@ final class KeyRemappingManager {
|
||||
new Action(ACTION_SOUND_BEST, "Play personal-best sound", "Saved soundboard event"),
|
||||
new Action(ACTION_SOUND_BATTERY, "Play battery threshold sound", "Saved soundboard event"),
|
||||
new Action(ACTION_HERMES, "Hermes voice assistant", "Hold a mapped key to dictate a prompt"),
|
||||
new Action(ACTION_DASHCAM_SAVE, "Lock dashcam event", "Save 2 min before + 1 min after as its own file"),
|
||||
new Action(ACTION_USER_INTENT, "Open user-defined intent", "Explicit Android intent URI")
|
||||
};
|
||||
|
||||
@@ -270,6 +280,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 +302,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);
|
||||
@@ -290,6 +315,7 @@ final class KeyRemappingManager {
|
||||
else if (ACTION_SOUND_BEST.equals(action)) { SoundboardManager.play(context, SoundboardManager.EVENT_PERSONAL_BEST_REGEN); return; }
|
||||
else if (ACTION_SOUND_BATTERY.equals(action)) { SoundboardManager.play(context, SoundboardManager.EVENT_BATTERY_THRESHOLD); return; }
|
||||
else if (ACTION_HERMES.equals(action)) { HermesVoiceActivity.begin(context); return; }
|
||||
else if (ACTION_DASHCAM_SAVE.equals(action)) { DashcamService.saveMoment(context); return; }
|
||||
else if (ACTION_USER_INTENT.equals(action)) {
|
||||
try { intent = Intent.parseUri(mapping.intentUri, Intent.URI_INTENT_SCHEME); }
|
||||
catch (Exception error) { Toast.makeText(context, "Invalid user intent URI", Toast.LENGTH_SHORT).show(); return; }
|
||||
|
||||
@@ -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();
|
||||
@@ -213,11 +213,7 @@ public class MainActivity extends AnimatedActivity {
|
||||
final Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
|
||||
@Override public void uncaughtException(Thread thread, Throwable error) {
|
||||
StringWriter trace = new StringWriter();
|
||||
error.printStackTrace(new PrintWriter(trace));
|
||||
prefs.edit().putString("crash_type", error.getClass().getName())
|
||||
.putString("crash_message", error.getMessage() == null ? "" : error.getMessage())
|
||||
.putString("crash_stack", trace.toString().substring(0, Math.min(trace.toString().length(), 12000))).commit();
|
||||
DiagnosticsClient.queueCrash(getApplicationContext(), error);
|
||||
if (previous != null) previous.uncaughtException(thread, error);
|
||||
}
|
||||
});
|
||||
@@ -765,6 +761,7 @@ public class MainActivity extends AnimatedActivity {
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
BackupManager.requestBackup(this);
|
||||
if (dashboardGauges != null) dashboardGauges.stopVisualizer();
|
||||
MusicPlayerManager.setListener(null);
|
||||
if (campingModeController != null) campingModeController.onActivityPaused();
|
||||
@@ -775,8 +772,19 @@ public class MainActivity extends AnimatedActivity {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
if (controlPanel != null) controlPanel.onPermissionResult(requestCode);
|
||||
if (requestCode == AUDIO_REQUEST) {
|
||||
if (BackupManager.hasStorageAccess(this)) {
|
||||
// A fresh install gets its permission only now: restore the surviving backup, then restart.
|
||||
if (BackupManager.restoreIfFresh(this)) {
|
||||
Toast.makeText(this, "Restored settings and trips from backup - restarting", Toast.LENGTH_LONG).show();
|
||||
BackupManager.restartApp(this);
|
||||
return;
|
||||
}
|
||||
BackupManager.requestBackup(this);
|
||||
}
|
||||
boolean granted = false;
|
||||
for (int result : grantResults) if (result == android.content.pm.PackageManager.PERMISSION_GRANTED) granted = true;
|
||||
for (String permission : permissions) if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
|
||||
granted = checkSelfPermission(permission) == android.content.pm.PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
if (dashboardGauges != null) dashboardGauges.setVisualizerEnabled(granted &&
|
||||
getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean("home_visualizer_enabled", true));
|
||||
if (!granted) Toast.makeText(this, "Live music visualizer needs microphone/audio permission", Toast.LENGTH_LONG).show();
|
||||
@@ -1114,16 +1122,24 @@ public class MainActivity extends AnimatedActivity {
|
||||
homeRow.setPadding(UiTheme.dp(this, 12), UiTheme.dp(this, 12),
|
||||
UiTheme.dp(this, 12), UiTheme.dp(this, 12));
|
||||
dashboardGauges = new DashboardGauges(this);
|
||||
ferrofluidShader = new FerrofluidLayer(this);
|
||||
// The app runs as android.uid.system (platform-signed, for /dev/video*
|
||||
// access). Android refuses WebView in privileged processes and throws
|
||||
// UnsupportedOperationException, so fall back to the native renderer.
|
||||
try {
|
||||
ferrofluidShader = new FerrofluidLayer(this);
|
||||
} catch (Throwable webViewUnavailable) {
|
||||
android.util.Log.w("MGUtility", "WebView unavailable; using native ferrofluid", webViewUnavailable);
|
||||
ferrofluidShader = null;
|
||||
}
|
||||
ferrofluidFallback = new FerrofluidShaderView(this);
|
||||
FrameLayout gaugeLayer = new FrameLayout(this);
|
||||
gaugeLayer.setBackground(UiTheme.surface(UiTheme.SURFACE, 12));
|
||||
gaugeLayer.addView(ferrofluidShader, new FrameLayout.LayoutParams(-1, -1));
|
||||
if (ferrofluidShader != null) gaugeLayer.addView(ferrofluidShader, new FrameLayout.LayoutParams(-1, -1));
|
||||
gaugeLayer.addView(ferrofluidFallback, new FrameLayout.LayoutParams(-1, -1));
|
||||
// The GPU surface is deliberately the background; the Canvas gauge is
|
||||
// drawn above it so arcs, values, labels, and touch handling remain clear.
|
||||
gaugeLayer.addView(dashboardGauges, new FrameLayout.LayoutParams(-1, -1));
|
||||
dashboardGauges.setFerrofluidShader(ferrofluidShader);
|
||||
if (ferrofluidShader != null) dashboardGauges.setFerrofluidShader(ferrofluidShader);
|
||||
dashboardGauges.setFerrofluidFallback(ferrofluidFallback);
|
||||
musicPanel = new MusicPlayerPanel(this);
|
||||
LinearLayout.LayoutParams musicParams = new LinearLayout.LayoutParams(0, -1, 1f);
|
||||
@@ -1164,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());
|
||||
@@ -1274,10 +1293,18 @@ public class MainActivity extends AnimatedActivity {
|
||||
}
|
||||
|
||||
private void requestAudioAccess() {
|
||||
if (Build.VERSION.SDK_INT < 23 || !getSharedPreferences(UI_PREFS, MODE_PRIVATE)
|
||||
.getBoolean("home_visualizer_enabled", true)) return;
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED) return;
|
||||
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST);
|
||||
if (Build.VERSION.SDK_INT < 23) return;
|
||||
java.util.ArrayList<String> needed = new java.util.ArrayList<String>();
|
||||
if (getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean("home_visualizer_enabled", true)
|
||||
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) != android.content.pm.PackageManager.PERMISSION_GRANTED)
|
||||
needed.add(Manifest.permission.RECORD_AUDIO);
|
||||
// Backups live on shared storage so they outlive an uninstall.
|
||||
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
needed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
|
||||
needed.add(Manifest.permission.READ_EXTERNAL_STORAGE);
|
||||
}
|
||||
if (needed.isEmpty()) return;
|
||||
requestPermissions(needed.toArray(new String[0]), AUDIO_REQUEST);
|
||||
}
|
||||
|
||||
private void openComponent(String pkg, String cls) {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
/** Application entry point: restores a surviving backup (if any) before any component reads settings. */
|
||||
public final class MgApp extends Application {
|
||||
@Override public void onCreate() {
|
||||
super.onCreate();
|
||||
BackupManager.start(this);
|
||||
try { DashcamEvents.kick(this); } catch (Throwable ignored) { }
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
@@ -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(); }
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioFormat;
|
||||
import android.media.AudioManager;
|
||||
import android.media.AudioRecord;
|
||||
import android.media.AudioTrack;
|
||||
import android.media.MediaRecorder;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** Settings → System → Microphone test: live level meter per audio source plus record-and-playback. */
|
||||
public final class MicTestActivity extends AnimatedActivity {
|
||||
private static final int REQUEST_AUDIO = 5101;
|
||||
private static final int RATE = 16000;
|
||||
private static final int[] SOURCES = {
|
||||
MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.VOICE_RECOGNITION,
|
||||
MediaRecorder.AudioSource.VOICE_COMMUNICATION, MediaRecorder.AudioSource.CAMCORDER,
|
||||
MediaRecorder.AudioSource.DEFAULT };
|
||||
private static final String[] NAMES = { "MIC", "VOICE_RECOGNITION", "VOICE_COMMUNICATION", "CAMCORDER", "DEFAULT" };
|
||||
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private int sourceIndex;
|
||||
private volatile boolean metering;
|
||||
private volatile boolean busy;
|
||||
private Thread worker;
|
||||
private MicScopeView scope;
|
||||
private TextView readout;
|
||||
private TextView verdict;
|
||||
private TextView devices;
|
||||
private Button sourceButton;
|
||||
private Button meterButton;
|
||||
private Button loopButton;
|
||||
|
||||
@Override public void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
UiTheme.applyFontScale(this);
|
||||
setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
|
||||
setContentView(buildUi());
|
||||
refreshDevices();
|
||||
ensurePermission();
|
||||
}
|
||||
|
||||
private View buildUi() {
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(28, 18, 28, 18);
|
||||
root.setBackgroundColor(UiTheme.BACKGROUND);
|
||||
LinearLayout header = new LinearLayout(this);
|
||||
header.setGravity(Gravity.CENTER_VERTICAL);
|
||||
header.addView(UiTheme.title(this, "MICROPHONE TEST", 28), new LinearLayout.LayoutParams(0, 56, 1));
|
||||
header.addView(UiTheme.backButton(this, new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { finish(); }
|
||||
}), new LinearLayout.LayoutParams(120, 52));
|
||||
root.addView(header);
|
||||
root.addView(UiTheme.text(this, "Speak or tap near the microphone. The meter should move; pick another source if it stays silent.",
|
||||
13, UiTheme.MUTED, android.graphics.Typeface.NORMAL), new LinearLayout.LayoutParams(-1, 38));
|
||||
|
||||
LinearLayout buttons = new LinearLayout(this);
|
||||
sourceButton = UiTheme.button(this, "", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { cycleSource(); }
|
||||
}, false);
|
||||
meterButton = UiTheme.button(this, "START LIVE METER", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { toggleMeter(); }
|
||||
}, true);
|
||||
loopButton = UiTheme.button(this, "RECORD 4s + PLAY BACK", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { recordAndPlay(); }
|
||||
}, false);
|
||||
LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(0, 52, 1);
|
||||
bp.setMargins(0, 0, 10, 0);
|
||||
buttons.addView(sourceButton, bp);
|
||||
buttons.addView(meterButton, new LinearLayout.LayoutParams(bp));
|
||||
buttons.addView(loopButton, new LinearLayout.LayoutParams(0, 52, 1));
|
||||
root.addView(buttons, new LinearLayout.LayoutParams(-1, 56));
|
||||
updateSourceLabel();
|
||||
|
||||
scope = new MicScopeView(this);
|
||||
root.addView(scope, new LinearLayout.LayoutParams(-1, 110));
|
||||
readout = UiTheme.text(this, "Level: —", 16, UiTheme.TEXT, android.graphics.Typeface.NORMAL);
|
||||
root.addView(readout, new LinearLayout.LayoutParams(-1, 34));
|
||||
verdict = UiTheme.text(this, "Not started", 18, UiTheme.MUTED, android.graphics.Typeface.BOLD);
|
||||
root.addView(verdict, new LinearLayout.LayoutParams(-1, 40));
|
||||
devices = UiTheme.text(this, "", 13, UiTheme.MUTED, android.graphics.Typeface.NORMAL);
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.addView(devices);
|
||||
root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1));
|
||||
return root;
|
||||
}
|
||||
|
||||
private void ensurePermission() {
|
||||
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, REQUEST_AUDIO);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
|
||||
super.onRequestPermissionsResult(code, permissions, results);
|
||||
if (code == REQUEST_AUDIO) {
|
||||
boolean granted = results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED;
|
||||
verdict.setText(granted ? "Microphone permission granted" : "Microphone permission DENIED");
|
||||
verdict.setTextColor(granted ? UiTheme.MUTED : UiTheme.WARNING);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasPermission() {
|
||||
return Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private void cycleSource() {
|
||||
if (metering || busy) return;
|
||||
sourceIndex = (sourceIndex + 1) % SOURCES.length;
|
||||
updateSourceLabel();
|
||||
}
|
||||
|
||||
private void updateSourceLabel() { sourceButton.setText("SOURCE: " + NAMES[sourceIndex]); }
|
||||
|
||||
private void refreshDevices() {
|
||||
StringBuilder sb = new StringBuilder("INPUT DEVICES\n");
|
||||
if (Build.VERSION.SDK_INT >= 23) {
|
||||
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
|
||||
AudioDeviceInfo[] inputs = am.getDevices(AudioManager.GET_DEVICES_INPUTS);
|
||||
if (inputs.length == 0) sb.append(" (none reported by Android)\n");
|
||||
for (AudioDeviceInfo d : inputs) {
|
||||
sb.append(" • ").append(typeName(d.getType())).append(" ").append(d.getProductName()).append('\n');
|
||||
}
|
||||
} else sb.append(" (device listing needs Android 6+)\n");
|
||||
sb.append("\nPCM format: ").append(RATE).append(" Hz mono 16-bit");
|
||||
devices.setText(sb.toString());
|
||||
}
|
||||
|
||||
private static String typeName(int type) {
|
||||
switch (type) {
|
||||
case 15: return "BUILTIN_MIC";
|
||||
case 3: return "WIRED_HEADSET";
|
||||
case 4: return "WIRED_HEADPHONES";
|
||||
case 7: return "BLUETOOTH_SCO";
|
||||
case 11: return "USB_DEVICE";
|
||||
case 12: return "USB_ACCESSORY";
|
||||
case 18: return "TELEPHONY";
|
||||
case 25: return "REMOTE_SUBMIX";
|
||||
default: return "TYPE_" + type;
|
||||
}
|
||||
}
|
||||
|
||||
private void toggleMeter() {
|
||||
if (metering) { stopMeter(); return; }
|
||||
if (busy) return;
|
||||
if (!hasPermission()) { ensurePermission(); return; }
|
||||
metering = true;
|
||||
meterButton.setText("STOP METER");
|
||||
loopButton.setEnabled(false);
|
||||
final int source = SOURCES[sourceIndex];
|
||||
worker = new Thread(new Runnable() { @Override public void run() { meterLoop(source); } }, "mic-test-meter");
|
||||
worker.start();
|
||||
}
|
||||
|
||||
private void stopMeter() {
|
||||
metering = false;
|
||||
meterButton.setText("START LIVE METER");
|
||||
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; }
|
||||
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;
|
||||
int zeroReads = 0;
|
||||
while (metering) {
|
||||
int count = record.read(buffer, 0, buffer.length);
|
||||
if (count <= 0) { if (++zeroReads > 20) { fail("No audio frames returned (read=" + count + ")"); return; } continue; }
|
||||
zeroReads = 0;
|
||||
frames += count;
|
||||
final double rms = AudioLevel.rms(buffer, count);
|
||||
final double peak = AudioLevel.peak(buffer, count);
|
||||
sessionPeak = Math.max(sessionPeak, peak);
|
||||
final double best = sessionPeak;
|
||||
final long total = frames;
|
||||
ui.post(new Runnable() { @Override public void run() { showLevel(rms, peak, best, total); } });
|
||||
}
|
||||
} catch (Throwable error) {
|
||||
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(); } });
|
||||
}
|
||||
}
|
||||
|
||||
private void showLevel(double rms, double peak, double sessionPeak, long frames) {
|
||||
scope.setLevel((float) Math.min(1.0, rms * 8.0));
|
||||
readout.setText(String.format(Locale.US, "RMS %.1f dBFS peak %.1f dBFS session peak %.1f dBFS %.1f s captured",
|
||||
AudioLevel.dbfs(rms), AudioLevel.dbfs(peak), AudioLevel.dbfs(sessionPeak), frames / (double) RATE));
|
||||
String text = AudioLevel.verdict(sessionPeak);
|
||||
verdict.setText(text);
|
||||
verdict.setTextColor(text.startsWith("OK") ? UiTheme.CYAN_BRIGHT : UiTheme.WARNING);
|
||||
}
|
||||
|
||||
private void fail(final String message) {
|
||||
ui.post(new Runnable() {
|
||||
@Override public void run() {
|
||||
verdict.setText("ERROR: " + message);
|
||||
verdict.setTextColor(UiTheme.WARNING);
|
||||
stopMeter();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void recordAndPlay() {
|
||||
if (metering || busy) return;
|
||||
if (!hasPermission()) { ensurePermission(); return; }
|
||||
busy = true;
|
||||
loopButton.setEnabled(false); meterButton.setEnabled(false);
|
||||
verdict.setText("Recording 4 seconds… speak now");
|
||||
verdict.setTextColor(UiTheme.CYAN_BRIGHT);
|
||||
final int source = SOURCES[sourceIndex];
|
||||
new Thread(new Runnable() {
|
||||
@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];
|
||||
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) {
|
||||
int n = record.read(pcm, filled, Math.min(1600, pcm.length - filled));
|
||||
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);
|
||||
result[0] = String.format(Locale.US, "%s (peak %.1f dBFS, RMS %.1f dBFS)", AudioLevel.verdict(peak), AudioLevel.dbfs(peak), AudioLevel.dbfs(rms));
|
||||
ui.post(new Runnable() { @Override public void run() { verdict.setText("Playing back… " + String.format(Locale.US, "peak %.1f dBFS", AudioLevel.dbfs(peak))); } });
|
||||
track = new AudioTrack(AudioManager.STREAM_MUSIC, RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
|
||||
filled * 2, AudioTrack.MODE_STATIC);
|
||||
track.write(pcm, 0, filled);
|
||||
track.play();
|
||||
Thread.sleep(filled * 1000L / RATE + 400L);
|
||||
} catch (Throwable error) {
|
||||
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() {
|
||||
@Override public void run() {
|
||||
busy = false;
|
||||
verdict.setText(result[0]);
|
||||
verdict.setTextColor(result[0].startsWith("OK") ? UiTheme.CYAN_BRIGHT : UiTheme.WARNING);
|
||||
loopButton.setEnabled(true); meterButton.setEnabled(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "mic-test-loopback").start();
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
metering = false;
|
||||
super.onPause();
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,27 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
rebuildCategory();
|
||||
}
|
||||
|
||||
private void requestStorage() {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 23) requestPermissions(new String[] {
|
||||
android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE }, 5103);
|
||||
}
|
||||
|
||||
@Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) {
|
||||
super.onRequestPermissionsResult(code, permissions, results);
|
||||
if (code == 5103) {
|
||||
if (BackupManager.hasStorageAccess(this)) {
|
||||
Toast.makeText(this, "Storage granted - backing up", Toast.LENGTH_SHORT).show();
|
||||
BackupManager.requestBackup(this);
|
||||
} else Toast.makeText(this, "Storage permission denied - backups paused", Toast.LENGTH_LONG).show();
|
||||
rebuildCategory();
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
BackupManager.requestBackup(this);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private void rebuildCategory() { showCategory(selectedCategory); }
|
||||
|
||||
@Override protected void onSaveInstanceState(android.os.Bundle outState) {
|
||||
@@ -182,6 +203,39 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
private void system() {
|
||||
section("System", "Updates, extensions, diagnostics, and settings maintenance");
|
||||
systemTools();
|
||||
subsection("Hardware tests", "Check that the head unit's microphone and cameras reach the app");
|
||||
content.addView(row("◉", "Microphone test", "Live level meter, source selection and playback", open(MicTestActivity.class)));
|
||||
content.addView(row("▣", "Camera test", "List cameras, raw video nodes and live preview", open(CameraTestActivity.class)));
|
||||
subsection("Automatic backup", "Settings and trip reports are copied to " + BackupManager.DIR_NAME + " on internal storage and survive uninstall");
|
||||
content.addView(row("↻", "Back up now", BackupManager.status(this), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
if (!BackupManager.hasStorageAccess(SettingsActivity.this)) { requestStorage(); return; }
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final String result = BackupManager.backupNow(SettingsActivity.this);
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
Toast.makeText(SettingsActivity.this, result, Toast.LENGTH_LONG).show(); rebuildCategory(); } });
|
||||
} }, "mg-backup-now").start();
|
||||
}
|
||||
}));
|
||||
content.addView(row("⇩", "Restore from backup", BackupManager.hasBackup() ? "Replace current settings and trips with the saved backup" : "No backup found yet", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
if (!BackupManager.hasStorageAccess(SettingsActivity.this)) { requestStorage(); return; }
|
||||
if (!BackupManager.hasBackup()) { Toast.makeText(SettingsActivity.this, "No backup found", Toast.LENGTH_LONG).show(); return; }
|
||||
UiTheme.dialog(SettingsActivity.this).setTitle("RESTORE BACKUP?")
|
||||
.setMessage("Settings are replaced with the saved backup. Trip reports are restored if the backup has more trips than this device. The app restarts afterwards.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("RESTORE", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final String result = BackupManager.restoreLatest(SettingsActivity.this);
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
Toast.makeText(SettingsActivity.this, result + " - restarting", Toast.LENGTH_LONG).show();
|
||||
BackupManager.restartApp(SettingsActivity.this); } });
|
||||
} }, "mg-backup-restore").start();
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
}));
|
||||
subsection("Software updates", "Choose the Gitea release channel and install updates inside MG Utility");
|
||||
content.addView(row("↥", "Software updates",
|
||||
UpdateManager.installedVersion(this) + " • " +
|
||||
@@ -307,6 +361,8 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
subsection("Trip tracking", "Choose how drive samples are collected and reviewed");
|
||||
content.addView(row("T", "Trip reports", "View saved drives", open(TripsActivity.class)));
|
||||
content.addView(row("A", "Arrival areas", "Configure geofences and price-window briefings", open(ArrivalGeofenceActivity.class)));
|
||||
subsection("Dashcam", "Loop recording from the four factory cameras, saved clips and server offload");
|
||||
content.addView(row("▣", "Dashcam", DashcamService.summary(this), open(DashcamActivity.class)));
|
||||
content.addView(row("S", "Drive log sample interval", sampleIntervalLabel(), new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { chooseSampleInterval(); }
|
||||
}));
|
||||
@@ -328,29 +384,6 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
}));
|
||||
}
|
||||
|
||||
private void confirmDiagnosticsUpload() {
|
||||
UiTheme.dialog(this).setTitle("UPLOAD DIAGNOSTICS?")
|
||||
.setMessage("This sends the diagnostic snapshot and filtered app-owned warnings/errors to help troubleshoot compatibility. It excludes unrestricted system logcat and VIN. Upload is only sent after you choose UPLOAD.")
|
||||
.setNegativeButton("CANCEL", null)
|
||||
.setPositiveButton("UPLOAD", new DialogInterface.OnClickListener() {
|
||||
@Override public void onClick(DialogInterface dialog, int which) {
|
||||
final android.app.ProgressDialog progress = new android.app.ProgressDialog(SettingsActivity.this);
|
||||
progress.setMessage("Preparing diagnostics…"); progress.setCancelable(false); progress.show();
|
||||
new Thread(new Runnable() { @Override public void run() {
|
||||
final org.json.JSONObject report = VehicleDiagnosticsCollector.collect(SettingsActivity.this);
|
||||
DiagnosticsClient.uploadDiagnostics(SettingsActivity.this, report, new DiagnosticsClient.Callback() {
|
||||
@Override public void complete(final String message) {
|
||||
runOnUiThread(new Runnable() { @Override public void run() {
|
||||
if (!isFinishing()) progress.dismiss();
|
||||
Toast.makeText(SettingsActivity.this, message, Toast.LENGTH_LONG).show();
|
||||
}});
|
||||
}
|
||||
});
|
||||
}}).start();
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
|
||||
private void audio() {
|
||||
section("Audio", "Playback, sound field, and assistant controls");
|
||||
subsection("Sound and volume", "Configure event sounds and speed-aware playback");
|
||||
@@ -418,11 +451,25 @@ public final class SettingsActivity extends AnimatedActivity {
|
||||
startActivity(intent);
|
||||
}
|
||||
}));
|
||||
subsection("Diagnostics", "Troubleshooting and voluntary diagnostic uploads");
|
||||
content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class)));
|
||||
content.addView(row("↑", "Upload diagnostics", "Review data and voluntarily upload detailed logs", new View.OnClickListener() {
|
||||
@Override public void onClick(View v) { confirmDiagnosticsUpload(); }
|
||||
subsection("Diagnostics", "Usage sharing and troubleshooting");
|
||||
content.addView(toggleRow("↑", "Share usage data with developer",
|
||||
"Send device/car compatibility details once, then app crashes and errors. No VIN or live vehicle data.",
|
||||
"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)));
|
||||
|
||||
|
||||
@@ -172,6 +172,7 @@ public final class TripTrackingService extends Service {
|
||||
@Override public void onLocationChanged(Location location) {
|
||||
if (location == null) return;
|
||||
latestLocation = new Location(location);
|
||||
try { DashcamTelemetry.feedLocation(location); } catch (Throwable ignored) { }
|
||||
getSharedPreferences("trip_tracker", MODE_PRIVATE).edit()
|
||||
.putBoolean("gps_ready", true)
|
||||
.putLong("last_fix", System.currentTimeMillis())
|
||||
@@ -448,6 +449,8 @@ public final class TripTrackingService extends Service {
|
||||
return;
|
||||
}
|
||||
float validSpeed = validSpeed(speed);
|
||||
DashcamService.lastSpeedKph = validSpeed / EnergyActivity.VehicleGateway.DISPLAY_SPEED_FACTOR;
|
||||
DashcamService.lastSpeedAtMs = System.currentTimeMillis();
|
||||
if (reactiveAudio) SpeedAudioManager.updateSpeed(this, validSpeed);
|
||||
if (liquidBalance) {
|
||||
if (Float.isNaN(speed) || Float.isInfinite(speed) || speed < 0f || speed > 300f) {
|
||||
@@ -525,6 +528,8 @@ public final class TripTrackingService extends Service {
|
||||
SoundboardManager.play(this, SoundboardManager.EVENT_BATTERY_THRESHOLD);
|
||||
}
|
||||
final float speed = validSpeed(sample.speed);
|
||||
DashcamService.lastSpeedKph = speed / EnergyActivity.VehicleGateway.DISPLAY_SPEED_FACTOR;
|
||||
DashcamService.lastSpeedAtMs = now;
|
||||
final boolean moving = speed >= MOVING_SPEED_KPH;
|
||||
final long elapsed = lastSampleAt == 0 ? 0 : Math.min(maxDistanceIntervalMs(),
|
||||
Math.max(0, now - lastSampleAt));
|
||||
@@ -545,6 +550,11 @@ public final class TripTrackingService extends Service {
|
||||
|
||||
int gear = readGearSafely();
|
||||
boolean parked = speed <= PARKED_SPEED_KPH && gear == PARK_GEAR_VALUE;
|
||||
try {
|
||||
Location fix = usableLocation();
|
||||
DashcamTelemetry.feed(now, speed / EnergyActivity.VehicleGateway.DISPLAY_SPEED_FACTOR, sample.soc, sample.range,
|
||||
sample.volts, gear, fix);
|
||||
} catch (Throwable ignored) { }
|
||||
if (parked) { if (parkedSince == 0) parkedSince = now; }
|
||||
else parkedSince = 0;
|
||||
|
||||
@@ -573,6 +583,7 @@ public final class TripTrackingService extends Service {
|
||||
Location arrivalLocation = usableLocation();
|
||||
database.finishTrip(finishedTripId, parkedSince + PARKED_GRACE_MS, sample);
|
||||
publishArrivalBriefing(finishedTripId, arrivalLocation);
|
||||
BackupManager.requestBackup(this);
|
||||
activeTripId = TripDatabase.NO_TRIP;
|
||||
lastDistanceLocation = null;
|
||||
lastStoredLocation = null;
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class UsageDataPolicy {
|
||||
private static final Pattern LOG_LINE = Pattern.compile("^\\s*(\\d+\\.\\d+)\\s+(\\d+)\\s+\\d+\\s+([WEF])\\s+([^:]+):\\s?(.*)$");
|
||||
|
||||
private UsageDataPolicy() { }
|
||||
|
||||
public static String redact(String value, int limit) {
|
||||
if (value == null) return "";
|
||||
String safe = value.replaceAll("(?i)bearer\\s+[^\\s,;\"]+", "Bearer [REDACTED]");
|
||||
safe = safe.replaceAll("(?i)((?:authorization|access[_-]?token|refresh[_-]?token|token|password|secret|api[_-]?key|vin|serial(?:number)?|imei|imsi|android[_ ]?id|mac(?: address)?)[\"']?\\s*[:=]\\s*)(?:\"[^\"]*\"|'[^']*'|[^\\s,;]+)", "$1[REDACTED]");
|
||||
safe = safe.replaceAll("(?i)https?://[^\\s]+", "[REDACTED_URL]");
|
||||
safe = safe.replaceAll("(?i)(?:[0-9a-f]{2}:){5}[0-9a-f]{2}", "[REDACTED_MAC]");
|
||||
safe = safe.replaceAll("(?<![A-Za-z0-9])[A-HJ-NPR-Z0-9]{17}(?![A-Za-z0-9])", "[REDACTED_VIN_OR_SERIAL]");
|
||||
return safe.substring(0, Math.min(safe.length(), limit));
|
||||
}
|
||||
|
||||
public static String warning(String line, int pid, double after) {
|
||||
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("MGDiagnostics") || tag.equals("MGUsageReporter")) return "";
|
||||
return redact(line, 1500);
|
||||
}
|
||||
|
||||
public static double timestamp(String line) {
|
||||
Matcher match = LOG_LINE.matcher(line);
|
||||
return match.matches() ? Double.parseDouble(match.group(1)) : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class UsageDataReporter {
|
||||
private static final ScheduledExecutorService WORKER = Executors.newSingleThreadScheduledExecutor();
|
||||
private static boolean started;
|
||||
private static volatile HttpURLConnection activeConnection;
|
||||
static final Object CONSENT_LOCK = new Object();
|
||||
|
||||
private UsageDataReporter() { }
|
||||
|
||||
private static SharedPreferences preferences(Context context) {
|
||||
return context.getSharedPreferences("remote_diagnostics", Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
public static boolean isEnabled(Context context) {
|
||||
return preferences(context).getBoolean("share_usage_data", true);
|
||||
}
|
||||
|
||||
public static synchronized void start(Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
if (!started) {
|
||||
started = true;
|
||||
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); } });
|
||||
}
|
||||
|
||||
public static void preferenceChanged(Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
if (!isEnabled(app)) {
|
||||
synchronized (CONSENT_LOCK) {
|
||||
preferences(app).edit().remove("pending_crash").remove("pending_usage_errors")
|
||||
.remove("crash_type").remove("crash_message").remove("crash_stack")
|
||||
.putString("usage_log_cursor", String.valueOf(System.currentTimeMillis() / 1000.0)).apply();
|
||||
}
|
||||
HttpURLConnection connection = activeConnection;
|
||||
if (connection != null) connection.disconnect();
|
||||
} else {
|
||||
preferences(app).edit().putString("usage_log_cursor", String.valueOf(System.currentTimeMillis() / 1000.0)).apply();
|
||||
DiagnosticsClient.refreshConfig(app);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean allowed(Context context) {
|
||||
return isEnabled(context) && preferences(context).getBoolean("telemetry_enabled", false);
|
||||
}
|
||||
|
||||
private static JSONObject identity(Context context) throws Exception {
|
||||
JSONObject payload = new JSONObject();
|
||||
payload.put("vehicleId", DiagnosticsClient.getVehicleId(context));
|
||||
payload.put("appVersion", DiagnosticsClient.getAppVersion(context));
|
||||
return payload;
|
||||
}
|
||||
|
||||
private static JSONObject registration(Context context) throws Exception {
|
||||
JSONObject payload = identity(context);
|
||||
payload.put("platform", "android-" + Build.VERSION.SDK_INT);
|
||||
payload.put("manufacturer", Build.MANUFACTURER);
|
||||
payload.put("carModel", Build.MODEL);
|
||||
payload.put("carBuild", Build.FINGERPRINT);
|
||||
payload.put("appProfile", VehicleSettingsProfile.UNKNOWN_READ_ONLY);
|
||||
JSONObject details = new JSONObject();
|
||||
details.put("schema", 1);
|
||||
details.put("modelSource", "android_build_model_not_verified_vehicle_trim");
|
||||
details.put("brand", Build.BRAND);
|
||||
details.put("device", Build.DEVICE);
|
||||
details.put("product", Build.PRODUCT);
|
||||
details.put("board", Build.BOARD);
|
||||
details.put("hardware", Build.HARDWARE);
|
||||
details.put("androidRelease", Build.VERSION.RELEASE);
|
||||
details.put("buildDisplay", Build.DISPLAY);
|
||||
details.put("buildType", Build.TYPE);
|
||||
details.put("supportedAbis", new JSONArray(Build.SUPPORTED_ABIS));
|
||||
DisplayMetrics metrics = new DisplayMetrics();
|
||||
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
|
||||
manager.getDefaultDisplay().getRealMetrics(metrics);
|
||||
details.put("screenWidthPx", metrics.widthPixels);
|
||||
details.put("screenHeightPx", metrics.heightPixels);
|
||||
details.put("densityDpi", metrics.densityDpi);
|
||||
details.put("screenDensity", metrics.density);
|
||||
details.put("availableProcessors", Runtime.getRuntime().availableProcessors());
|
||||
android.app.ActivityManager.MemoryInfo memory = new android.app.ActivityManager.MemoryInfo();
|
||||
((android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(memory);
|
||||
details.put("totalMemoryBytes", memory.totalMem);
|
||||
JSONObject snapshot = VehicleDiagnosticsCollector.collect(context);
|
||||
JSONObject compatibility = new JSONObject();
|
||||
for (String key : new String[]{"vehicleService", "vehicleServiceOperations", "systemSettingsServices", "vehicleSettingsCatalog", "appControlCatalog"}) {
|
||||
if (snapshot.has(key)) compatibility.put(key, snapshot.get(key));
|
||||
}
|
||||
details.put("compatibility", compatibility);
|
||||
payload.put("details", details);
|
||||
return payload;
|
||||
}
|
||||
|
||||
private static volatile String outcome = "";
|
||||
|
||||
private static void upload(Context context) {
|
||||
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://")) { outcome = "Server address not loaded yet"; return; }
|
||||
String base = endpoint.endsWith("/") ? endpoint : endpoint + "/";
|
||||
try {
|
||||
if (!prefs.getString("usage_registration_endpoint", "").equals(base)) {
|
||||
if (!post(context, base + "v1/install", registration(context))) return;
|
||||
prefs.edit().putString("usage_registration_endpoint", base).apply();
|
||||
}
|
||||
if (!allowed(context)) return;
|
||||
String pending = prefs.getString("pending_crash", "");
|
||||
if (!pending.isEmpty()) {
|
||||
JSONObject old = new JSONObject(pending);
|
||||
JSONObject crash = identity(context);
|
||||
crash.put("reportId", old.optString("reportId", UUID.randomUUID().toString()));
|
||||
crash.put("appVersion", old.optString("appVersion", DiagnosticsClient.getAppVersion(context)));
|
||||
crash.put("exceptionType", UsageDataPolicy.redact(old.optString("exceptionType"), 160));
|
||||
crash.put("message", UsageDataPolicy.redact(old.optString("message"), 2000));
|
||||
crash.put("stack", UsageDataPolicy.redact(old.optString("stack"), 12000));
|
||||
synchronized (CONSENT_LOCK) {
|
||||
if (!allowed(context) || !prefs.getString("pending_crash", "").equals(pending)) return;
|
||||
pending = crash.toString();
|
||||
prefs.edit().putString("pending_crash", pending).apply();
|
||||
}
|
||||
if (!post(context, base + "v1/crashes", crash)) return;
|
||||
synchronized (CONSENT_LOCK) {
|
||||
if (prefs.getString("pending_crash", "").equals(pending)) prefs.edit().remove("pending_crash").apply();
|
||||
}
|
||||
}
|
||||
if (!allowed(context)) return;
|
||||
String errors = prefs.getString("pending_usage_errors", "");
|
||||
if (errors.isEmpty()) {
|
||||
JSONObject batch = collectErrors(context);
|
||||
if (batch == null) { outcome = "Nothing new to send"; return; }
|
||||
if (!allowed(context)) return;
|
||||
errors = batch.toString();
|
||||
synchronized (CONSENT_LOCK) {
|
||||
if (!allowed(context)) return;
|
||||
prefs.edit().putString("pending_usage_errors", errors).apply();
|
||||
}
|
||||
}
|
||||
JSONObject batch = new JSONObject(errors);
|
||||
if (post(context, base + "v1/errors", batch)) {
|
||||
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)).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", "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()))) {
|
||||
String line;
|
||||
double latest = cursor;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String warning = UsageDataPolicy.warning(line, android.os.Process.myPid(), cursor);
|
||||
if (warning.isEmpty()) continue;
|
||||
if (lines.length() + warning.length() > 14000) break;
|
||||
lines.append(warning).append('\n');
|
||||
latest = Math.max(latest, UsageDataPolicy.timestamp(line));
|
||||
}
|
||||
if (lines.length() == 0) return null;
|
||||
JSONObject payload = identity(context);
|
||||
payload.put("reportId", UUID.randomUUID().toString());
|
||||
payload.put("details", lines.toString());
|
||||
payload.put("cursor", String.valueOf(latest));
|
||||
return payload;
|
||||
} finally { timeout.cancel(); process.destroy(); }
|
||||
}
|
||||
|
||||
private static boolean post(Context context, String url, JSONObject payload) throws Exception {
|
||||
if (!allowed(context)) return false;
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
activeConnection = connection;
|
||||
try {
|
||||
connection.setConnectTimeout(8000);
|
||||
connection.setReadTimeout(8000);
|
||||
connection.setInstanceFollowRedirects(false);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setDoOutput(true);
|
||||
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
|
||||
if (!allowed(context)) return false;
|
||||
try (OutputStream output = connection.getOutputStream()) { output.write(payload.toString().getBytes(StandardCharsets.UTF_8)); }
|
||||
int status = connection.getResponseCode();
|
||||
if (status == 404) preferences(context).edit().remove("usage_registration_endpoint").apply();
|
||||
if (status != 202) return false;
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
char[] response = new char[2048];
|
||||
StringBuilder text = new StringBuilder();
|
||||
int count;
|
||||
while ((count = reader.read(response)) != -1) {
|
||||
text.append(response, 0, count);
|
||||
if (text.length() > 4096) return false;
|
||||
}
|
||||
return new JSONObject(text.toString()).optBoolean("accepted", false);
|
||||
}
|
||||
} finally { activeConnection = null; connection.disconnect(); }
|
||||
}
|
||||
}
|
||||
@@ -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 < 2<sup>len</sup>.
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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:
|
||||
* <ul>
|
||||
* <li><p>Decrease the error correction level if it was greater than {@code Ecc.LOW}.</p></li>
|
||||
* <li><p>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}.)</p></li>
|
||||
* <li><p>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()}.)</p></li>
|
||||
* <li><p>Change the text or binary data to be shorter.</p></li>
|
||||
* <li><p>Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).</p></li>
|
||||
* <li><p>Propagate the error upward to the caller/user.</p></li>
|
||||
* </ul>
|
||||
* @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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.
|
||||
* <p>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.</p>
|
||||
* <p>Ways to create a QR Code object:</p>
|
||||
* <ul>
|
||||
* <li><p>High level: Take the payload data and call {@link QrCode#encodeText(CharSequence,Ecc)}
|
||||
* or {@link QrCode#encodeBinary(byte[],Ecc)}.</p></li>
|
||||
* <li><p>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)}</p></li>
|
||||
* <li><p>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}.</p></li>
|
||||
* </ul>
|
||||
* <p>(Note that all ways require supplying the desired error correction level.)</p>
|
||||
* @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<QrSegment> 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.
|
||||
* <p>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)}.</p>
|
||||
* @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<QrSegment> 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).
|
||||
* <p>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)}.</p>
|
||||
* @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<QrSegment> 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).
|
||||
* <p>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.
|
||||
* <p>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.</p>
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.
|
||||
* <p>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.</p>
|
||||
* <p>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.</p>
|
||||
*/
|
||||
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.
|
||||
* <p>Any text string can be converted to UTF-8 bytes ({@code
|
||||
* s.getBytes(StandardCharsets.UTF_8)}) and encoded as a byte mode segment.</p>
|
||||
* @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<QrSegment> makeSegments(CharSequence text) {
|
||||
Objects.requireNonNull(text);
|
||||
|
||||
// Select the most efficient segment encoding automatically
|
||||
List<QrSegment> 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, 10<sup>6</sup>)
|
||||
*/
|
||||
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<QrSegment> 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];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
# MG Utility diagnostics service
|
||||
|
||||
The service listens on `0.0.0.0:7013`; the configured public origin is
|
||||
`https://analytics.molberg.cloud/`.
|
||||
|
||||
## Routes
|
||||
|
||||
- `GET /health` — health check.
|
||||
- `GET /v1/config` — public client config (`enabled`, `uploadUrl`, announcement,
|
||||
changelog). `uploadUrl` is an HTTPS base URL; the app appends `v1/events`.
|
||||
- `POST /v1/install` — automatic minimal install/build/car-model fingerprint on startup; no logs or live vehicle data.
|
||||
- `POST /v1/crashes` — bounded automatic crash summary from a previous unclean app exit.
|
||||
- `POST /v1/events` — detailed diagnostic uploads only after the user explicitly taps upload; controlled by the config's `enabled` field.
|
||||
- `GET /admin/` — existing authenticated support dashboard for voluntary reports and remote client controls.
|
||||
- `GET /admin/analytics` — separate authenticated compatibility dashboard with SQLite-backed install fingerprints, crash reports, voluntary diagnostics, and copy-to-clipboard summaries.
|
||||
|
||||
The admin password is stored in Vaultwarden as **MG Utility Analytics
|
||||
Dashboard** (`login.password`). `run-server.sh` loads it at process start; it is
|
||||
never written into the repository or runtime data directory. Admin event and
|
||||
config APIs require the dashboard's signed session cookie. Sessions expire in
|
||||
12 hours and are invalidated by process restart. The public dashboard is HTTPS
|
||||
only in normal deployment; the cookie is Secure/HttpOnly/SameSite=Lax.
|
||||
The dashboard is designed phone-first: bottom-sheet report details, 44px
|
||||
minimum touch targets, sticky top bar, horizontally scrollable tabs, and safe-area
|
||||
padding for notched devices.
|
||||
|
||||
## App config discovery
|
||||
|
||||
The APK contains only the stable public Gitea contents-API URL for
|
||||
`alex/mg-utility`'s `telemetry-service/client-config.json`. That bootstrap file
|
||||
contains `configUrl`; the app fetches live settings from that HTTPS API on
|
||||
startup. The live API response supplies the upload endpoint. The upload URL is
|
||||
not compiled into the APK. The Gitea bootstrap file must be published before
|
||||
clients can discover this service.
|
||||
|
||||
## Data and privacy
|
||||
|
||||
Detailed diagnostic uploads happen only after the user taps **UPLOAD DIAGNOSTICS**, with a disclosure beside that button. Those uploads include the app diagnostic snapshot and filtered app-owned warning/error lines, but never unrestricted system logcat or optional “ALL PROPS”. Separately, startup sends an install-scoped random ID and bounded car/build fingerprint, and an unclean exit queues a crash summary for delivery on next launch. Automatic records never include detailed logs, VIN, Android ID, MAC, or live vehicle values. Dashboard data is stored in `data/analytics.sqlite` (directory mode 0700, database mode 0600), with a 20,000-event retention cap. Request IP addresses are not stored. The app profile is a compatibility catalog, not a VIN-verified trim.
|
||||
|
||||
## Local verification
|
||||
|
||||
```sh
|
||||
npm test
|
||||
curl -fsS http://127.0.0.1:7013/health
|
||||
curl -fsS https://analytics.molberg.cloud/v1/config
|
||||
```
|
||||
|
||||
Run under PM2 via `run-server.sh`, not `server.js` directly, so the dashboard
|
||||
password is fetched from Vault at process launch. Runtime data stays under the
|
||||
ignored `data/` directory.
|
||||
@@ -1,132 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="theme-color" content="#0b1115"><meta name="robots" content="noindex,nofollow">
|
||||
<title>MG Fielddesk · Analytics</title>
|
||||
<style>
|
||||
:root{color-scheme:dark;--bg:#0b1115;--panel:#111a20;--panel2:#162229;--line:#26383e;--text:#edf5f2;--muted:#93a7a7;--teal:#59e0c0;--amber:#ffc570;--red:#ff7c79;--radius:18px;--safe-bottom:env(safe-area-inset-bottom,0px)}
|
||||
*{box-sizing:border-box}html{min-height:100%;background:var(--bg)}body{margin:0;background:radial-gradient(1000px 600px at 100% -10%,#153b3a 0,transparent 60%),var(--bg);color:var(--text);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
|
||||
button,input,textarea,select{font:inherit;color:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
|
||||
.hidden{display:none!important}.shell{max-width:1120px;margin:auto;padding:0 20px 50px}.topbar{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:14px;padding:12px 20px;background:#0b1115ed;border-bottom:1px solid #203238;backdrop-filter:blur(16px);margin:0 -20px}
|
||||
.brandmark{width:38px;height:38px;border-radius:12px;display:grid;place-items:center;background:#173e39;color:var(--teal);font-weight:900;letter-spacing:-1px}.brand{font-weight:760;letter-spacing:-.3px}.brand small{display:block;color:var(--muted);font-size:11px;font-weight:550;letter-spacing:.12em;text-transform:uppercase}.topright{margin-left:auto;display:flex;gap:10px;align-items:center}.live{font-size:12px;color:var(--teal);display:flex;align-items:center;gap:7px}.dot{width:7px;height:7px;border-radius:50%;background:currentColor;box-shadow:0 0 10px currentColor}.iconbtn,.btn{border:1px solid var(--line);background:var(--panel2);border-radius:12px;padding:10px 14px;min-height:42px}.iconbtn{padding:9px 11px}.btn.primary{background:var(--teal);border-color:var(--teal);color:#06221d;font-weight:750}.btn.danger{color:#ffaaa3;border-color:#663936;background:#261918}.btn.small{padding:7px 10px;min-height:34px;font-size:13px}.panelhead>.btn.small{white-space:nowrap;flex-shrink:0}.nav{display:flex;gap:6px;overflow:auto;padding:14px 0 6px;scrollbar-width:none}.nav::-webkit-scrollbar{display:none}.nav button{white-space:nowrap;border:0;background:transparent;color:var(--muted);border-radius:10px;padding:10px 13px;min-height:44px}.nav button.active{background:#193b38;color:var(--teal);font-weight:700}
|
||||
.view{display:none}.view.active{display:block}.hero{display:flex;justify-content:space-between;align-items:flex-end;gap:20px;padding:22px 0 18px}.eyebrow{color:var(--teal);font-size:11px;font-weight:800;letter-spacing:.16em;text-transform:uppercase}.hero h1{font-size:clamp(26px,5vw,38px);letter-spacing:-1.2px;line-height:1.1;margin:8px 0}.hero p{margin:0;color:var(--muted);max-width:580px}.date{color:var(--muted);font-size:13px;white-space:nowrap}
|
||||
.grid{display:grid;gap:14px}.stats{grid-template-columns:repeat(4,minmax(0,1fr));margin:10px 0 22px}.stat,.panel{border:1px solid var(--line);background:linear-gradient(145deg,#132027,#10171c);border-radius:var(--radius);padding:18px}.stat label{display:block;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.09em}.stat strong{display:block;font-size:29px;letter-spacing:-.7px;margin-top:8px}.stat .hint{font-size:12px;color:var(--muted);margin-top:3px}.panel{margin-bottom:16px}.panelhead{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.panelhead h2{font-size:17px;margin:0;letter-spacing:-.2px}.subtle{color:var(--muted);font-size:13px}.split{display:grid;grid-template-columns:1.2fr .8fr;gap:15px}.productchips{display:flex;flex-wrap:wrap;gap:8px}.chip{border:1px solid var(--line);border-radius:999px;background:#162329;padding:8px 11px;color:#d9e6e2;font-size:13px}.chip b{color:var(--teal);margin-left:6px}
|
||||
.toolbar{display:grid;grid-template-columns:minmax(180px,1fr) minmax(130px,.55fr) minmax(130px,.55fr) auto;gap:9px;margin-bottom:12px}.field{width:100%;min-height:44px;border:1px solid var(--line);background:#0d1519;border-radius:12px;padding:10px 12px}.field::placeholder{color:#6f8586}.report-list{display:grid;gap:10px}.report{border:1px solid var(--line);background:#10191e;border-radius:15px;padding:14px;cursor:pointer;transition:border-color .15s,transform .15s}.report:hover{border-color:#4c8881;transform:translateY(-1px)}.reporttop{display:flex;gap:10px;align-items:center}.badge{font-size:11px;letter-spacing:.04em;text-transform:uppercase;font-weight:760;color:#9cebd8;background:#163833;border:1px solid #245448;padding:4px 8px;border-radius:999px;max-width:45%;overflow:hidden;text-overflow:ellipsis}.reporttime{margin-left:auto;color:var(--muted);font-size:12px}.report h3{font-size:15px;margin:9px 0 4px;overflow-wrap:anywhere}.reportmeta{display:flex;gap:10px;flex-wrap:wrap;color:var(--muted);font-size:12px}.reportpreview{color:#c0d0cb;font-size:13px;margin-top:8px;white-space:pre-wrap;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}.empty{padding:38px 12px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:15px}.loadmore{width:100%;margin-top:10px}
|
||||
.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.toggleline{display:flex;gap:12px;align-items:center;padding:14px;background:#0d1519;border:1px solid var(--line);border-radius:14px}.toggleline input{appearance:none;width:48px;height:28px;background:#38464a;border-radius:20px;position:relative;flex:0 0 auto;transition:.2s}.toggleline input:before{content:"";position:absolute;width:22px;height:22px;top:3px;left:3px;border-radius:50%;background:#e9f2ed;transition:.2s}.toggleline input:checked{background:#188d74}.toggleline input:checked:before{left:23px}.togglecopy strong{display:block}.togglecopy span{font-size:12px;color:var(--muted)}.help{font-size:12px;color:var(--muted);margin:8px 2px}.formrow{margin:14px 0}.formrow label{display:block;color:#b9c9c4;font-size:13px;margin:0 0 7px}.actions{display:flex;gap:9px;align-items:center;flex-wrap:wrap}.status{font-size:12px;color:var(--teal);min-height:18px}.notice{border-left:3px solid var(--amber);padding:10px 12px;background:#261f15;border-radius:0 10px 10px 0;color:#e9d5b5;font-size:13px;margin-top:12px}
|
||||
.changelog{display:grid;gap:10px}.changeitem{border:1px solid var(--line);padding:12px;border-radius:14px;background:#0d1519}.changehead{display:grid;grid-template-columns:110px 1fr auto;gap:8px;align-items:center}.changeitem textarea{margin-top:8px;min-height:75px;resize:vertical}.dangerlink{border:0;background:transparent;color:var(--red);font-size:13px;padding:8px;min-width:44px;min-height:44px;border-radius:10px}
|
||||
.overlay{position:fixed;inset:0;z-index:20;background:#0009;display:none;align-items:center;justify-content:center;padding:18px}.overlay.open{display:flex}.sheet{width:min(720px,100%);max-height:min(85vh,900px);overflow:auto;background:#111a20;border:1px solid #345057;border-radius:22px;padding:20px;box-shadow:0 30px 90px #000a}.sheethead{display:flex;gap:10px;align-items:flex-start}.sheethead h2{font-size:20px;margin:3px 0 4px;overflow-wrap:anywhere}.sheethead .iconbtn{margin-left:auto}.sheetmeta{color:var(--muted);font-size:13px}.details{white-space:pre-wrap;overflow-wrap:anywhere;background:#091014;border:1px solid var(--line);border-radius:13px;padding:14px;font:12px/1.55 ui-monospace,SFMono-Regular,monospace;max-height:45vh;overflow:auto;margin:16px 0}.toast{position:fixed;z-index:30;bottom:calc(18px + var(--safe-bottom));left:50%;transform:translateX(-50%);padding:11px 16px;border:1px solid #32665c;border-radius:999px;background:#132723;color:#dffff6;box-shadow:0 8px 30px #0008;display:none;max-width:calc(100vw - 32px);text-align:center}.toast.show{display:block}
|
||||
#login{max-width:440px;margin:10vh auto;padding:24px}.logininput{font-size:17px;min-height:52px}.loginbtn{width:100%;margin-top:12px;min-height:50px}.foot{color:#6f8586;font-size:11px;padding:14px 2px;text-align:center}
|
||||
@media(max-width:760px){.shell{padding:0 14px calc(30px + var(--safe-bottom))}.topbar{margin:0 -14px;padding:10px 14px}.brand small{font-size:10px}.live span:last-child{display:none}.hero{display:block;padding-top:18px}.hero h1{font-size:29px}.date{display:block;margin-top:8px}.stats{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.stat{padding:14px;border-radius:15px}.stat strong{font-size:25px}.stat label{font-size:10px}.split,.settings-grid{grid-template-columns:1fr}.toolbar{grid-template-columns:1fr 1fr}.toolbar .search{grid-column:1/-1}.toolbar button{width:100%}.panel{padding:14px;border-radius:16px}.panelhead{align-items:flex-start}.report{padding:13px}.reporttime{font-size:11px}.changehead{grid-template-columns:1fr auto}.changehead .version{grid-column:1}.changehead .title{grid-column:1/-1;grid-row:2}.changehead .remove{grid-column:2;grid-row:1}.overlay{align-items:flex-end;padding:0}.sheet{width:100%;max-height:90dvh;border-radius:22px 22px 0 0;padding:20px 16px calc(18px + var(--safe-bottom));border-bottom:0}.details{max-height:42dvh}.actions .btn{flex:1}#saveAnnouncement{flex:2}#clearAnnouncement{flex:1}.topright .iconbtn{min-width:43px}.btn.small{min-height:44px}.nav{margin:0 -14px;padding:10px 14px 4px}.brandmark{width:35px;height:35px}}
|
||||
@media(max-width:370px){.topbar{gap:9px}.brand{font-size:14px}.stats{gap:7px}.stat{padding:11px}.toolbar{grid-template-columns:1fr}.toolbar .search{grid-column:auto}}
|
||||
@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition:none!important}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="topbar">
|
||||
<div class="brandmark">MG</div><div class="brand">Fielddesk<small>Telemetry & support</small></div>
|
||||
<div class="topright"><div class="live"><i class="dot"></i><span id="liveLabel">Connecting</span></div><button id="logout" class="iconbtn hidden" aria-label="Log out" title="Log out">↗</button></div>
|
||||
</header>
|
||||
<section id="login" class="panel hidden">
|
||||
<div class="eyebrow">Restricted console</div><h1 style="margin:8px 0">Welcome back</h1><p class="subtle">Sign in to manage diagnostics and client settings.</p>
|
||||
<form id="loginForm"><div class="formrow"><label for="pw">Admin password</label><input class="field logininput" id="pw" type="password" autocomplete="current-password" required></div><button class="btn primary loginbtn" type="submit">Sign in securely</button><p id="loginMsg" class="status"></p></form>
|
||||
</section>
|
||||
<div id="app" class="hidden">
|
||||
<nav class="nav" aria-label="Dashboard sections">
|
||||
<button class="active" data-view="overview">Overview</button><button data-view="reports">Reports</button><button data-view="fleet">Fleet & crashes</button><button data-view="controls">Client controls</button>
|
||||
</nav>
|
||||
<section id="view-overview" class="view active">
|
||||
<div class="hero"><div><div class="eyebrow">Support operations</div><h1>Fleet pulse</h1><p>Keep an eye on user-submitted diagnostics and manage what clients receive.</p></div><div class="date" id="updatedAt">—</div></div>
|
||||
<div class="grid stats">
|
||||
<article class="stat"><label>Reports retained</label><strong id="statTotal">—</strong><div class="hint">Most recent 20,000</div></article>
|
||||
<article class="stat"><label>Last 24 hours</label><strong id="statDay">—</strong><div class="hint">New support uploads</div></article>
|
||||
<article class="stat"><label>App builds seen</label><strong id="statBuilds">—</strong><div class="hint">Distinct versions</div></article>
|
||||
<article class="stat"><label>Products</label><strong id="statProducts">—</strong><div class="hint">SAIC apps reporting in</div></article>
|
||||
<article class="stat"><label>Vehicles identified</label><strong id="statVehicles">—</strong><div class="hint">Random app-install IDs</div></article>
|
||||
</div>
|
||||
<div class="split">
|
||||
<section class="panel"><div class="panelhead"><div><h2>Recent reports</h2><div class="subtle">Latest user-submitted diagnostics</div></div><button class="btn small" data-goto="reports">View all →</button></div><div id="recentList" class="report-list"></div></section>
|
||||
<section class="panel"><div class="panelhead"><div><h2>Products in view</h2><div class="subtle">Auto-discovered from uploads</div></div></div><div id="productList" class="productchips"></div><div class="notice">Uploads are user-triggered. Review device/build details as potentially sensitive.</div></section>
|
||||
</div>
|
||||
</section>
|
||||
<section id="view-reports" class="view">
|
||||
<div class="hero"><div><div class="eyebrow">Triage queue</div><h1>Support reports</h1><p>Search recent submissions, narrow by product/category, then open a report for full diagnostic details.</p></div></div>
|
||||
<section class="panel">
|
||||
<div class="toolbar">
|
||||
<input id="search" class="field search" type="search" placeholder="Search messages and details…" aria-label="Search reports">
|
||||
<select id="filterProduct" class="field" aria-label="Filter by product"><option value="">All products</option></select>
|
||||
<select id="filterCategory" class="field" aria-label="Filter by category"><option value="">All categories</option></select>
|
||||
<select id="filterVehicle" class="field" aria-label="Filter by vehicle instance"><option value="">All vehicles</option></select>
|
||||
<button id="refresh" class="btn">Refresh</button>
|
||||
</div>
|
||||
<div class="panelhead"><span id="reportCount" class="subtle">Loading…</span><button id="export" class="btn small">Export JSON ↓</button></div>
|
||||
<div id="reportList" class="report-list"></div><button id="loadMore" class="btn loadmore hidden">Load older reports</button>
|
||||
</section>
|
||||
</section>
|
||||
<section id="view-fleet" class="view">
|
||||
<div class="hero"><div><div class="eyebrow">Automatic compatibility telemetry</div><h1>Fleet & crashes</h1><p>Install-level counts and minimal startup car/build fingerprints, plus crash reports captured when the app restarts after an unclean exit.</p></div></div>
|
||||
<div class="grid stats"><article class="stat"><label>Known installs</label><strong id="fleetInstalls">—</strong></article><article class="stat"><label>Crash reports</label><strong id="fleetCrashes">—</strong></article></div>
|
||||
<section class="panel"><div class="panelhead"><h2>Install fingerprints</h2><button id="copyFleet" class="btn small">Copy fleet summary</button></div><pre id="fleetList" class="details"></pre></section>
|
||||
<section class="panel"><div class="panelhead"><h2>Crash reports</h2><button id="copyCrashes" class="btn small">Copy crash summary</button></div><div id="crashList" class="report-list"></div></section>
|
||||
</section>
|
||||
<section id="view-controls" class="view">
|
||||
<div class="hero"><div><div class="eyebrow">Remote operations</div><h1>Client controls</h1><p>Changes here are served by the live config API; app clients refresh this config on launch.</p></div></div>
|
||||
<section class="panel">
|
||||
<div class="panelhead"><div><h2>Diagnostics intake</h2><div class="subtle">Route explicit user uploads to the selected HTTPS endpoint.</div></div><span id="intakeBadge" class="badge">—</span></div>
|
||||
<div class="settings-grid">
|
||||
<div><label class="toggleline"><input id="telemetryEnabled" type="checkbox"><span class="togglecopy"><strong>Automatic compatibility telemetry</strong><span>Controls startup fingerprints and crash summaries; logs remain user-triggered.</span></span></label><label class="toggleline" style="margin-top:9px"><input id="enabled" type="checkbox"><span class="togglecopy"><strong>Accept detailed uploads</strong><span>Users can voluntarily submit diagnostics after explicit confirmation.</span></span></label><p class="help">Automatic telemetry and detailed voluntary reports have separate switches.</p></div>
|
||||
<div class="formrow" style="margin:0"><label for="uploadUrl">Upload endpoint base URL</label><input id="uploadUrl" class="field" type="url" inputmode="url" placeholder="https://host.example/" autocomplete="url"><p class="help">HTTPS required. The client appends <code>v1/events</code>.</p></div>
|
||||
</div>
|
||||
<div class="actions"><button id="saveConfig" class="btn primary">Save intake settings</button><span id="cfgStatus" class="status" role="status"></span></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<div class="panelhead"><div><h2>Announcement banner</h2><div class="subtle">Shown in the app while this text is published.</div></div><span id="annCount" class="subtle">0 / 2,000</span></div>
|
||||
<textarea id="announcement" class="field" rows="3" maxlength="2000" placeholder="Share a short service notice or release message…" style="resize:vertical"></textarea>
|
||||
<div class="actions" style="margin-top:10px"><button id="saveAnnouncement" class="btn primary">Publish announcement</button><button id="clearAnnouncement" class="btn">Clear</button><span id="annStatus" class="status" role="status"></span></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<div class="panelhead"><div><h2>Release notes</h2><div class="subtle">Versioned notices returned in remote config.</div></div><button id="addChangelog" class="btn small">+ Add note</button></div>
|
||||
<div id="changelogList" class="changelog"></div>
|
||||
<div class="actions" style="margin-top:12px"><button id="saveChangelog" class="btn primary">Save release notes</button><span id="changeStatus" class="status" role="status"></span></div>
|
||||
</section>
|
||||
<p class="foot">Bootstrap discovery remains controlled by the public Gitea config. These settings change the live API config only.</p>
|
||||
</section>
|
||||
</div>
|
||||
<footer class="foot">MG FIELD DESK · private operator console · no user IPs stored</footer>
|
||||
</div>
|
||||
<div id="detailOverlay" class="overlay" role="dialog" aria-modal="true" aria-labelledby="detailTitle"><div class="sheet"><div class="sheethead"><div><div class="eyebrow" id="detailCategory">Report</div><h2 id="detailTitle"></h2><div id="detailMeta" class="sheetmeta"></div></div><button id="closeDetail" class="iconbtn" aria-label="Close report">✕</button></div><pre id="detailText" class="details"></pre><div class="actions"><button id="copyDetail" class="btn">Copy details</button><button id="deleteDetail" class="btn danger">Delete report</button></div></div></div>
|
||||
<div id="toast" class="toast" role="status"></div>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id);let timer=null,events=[],offset=0,limit=50,selected=null,config={},metrics={},fleet={installs:[],crashes:[]};
|
||||
const api=async(path,opts={})=>{const r=await fetch(path,{credentials:'same-origin',...opts});return{status:r.status,body:await r.json().catch(()=>({}))}};
|
||||
const esc=(node,value)=>{node.textContent=value==null?'':String(value);return node};
|
||||
const fmtDate=value=>{try{return new Intl.DateTimeFormat(undefined,{month:'short',day:'numeric',hour:'numeric',minute:'2-digit'}).format(new Date(value))}catch(_){return value||''}};
|
||||
function toast(message){esc($('toast'),message);$('toast').classList.add('show');setTimeout(()=>$('toast').classList.remove('show'),2400)}
|
||||
function setView(name){document.querySelectorAll('.view').forEach(v=>v.classList.toggle('active',v.id==='view-'+name));document.querySelectorAll('.nav button').forEach(b=>b.classList.toggle('active',b.dataset.view===name));history.replaceState(null,'','#'+name);window.scrollTo({top:0,behavior:'smooth'});if(name==='reports')loadEvents(true);if(name==='fleet')loadFleet();if(name==='controls')loadConfig()}
|
||||
async function check(){const c=await api('/admin/api/session');if(c.body.authorized){$('login').classList.add('hidden');$('app').classList.remove('hidden');$('logout').classList.remove('hidden');$('liveLabel').textContent='Live service';loadEvents(true);loadConfig();const route=location.hash.slice(1);if(['overview','reports','fleet','controls'].includes(route))setView(route);if(!timer)timer=setInterval(()=>{if($('view-overview').classList.contains('active'))loadEvents(true);if($('view-fleet').classList.contains('active'))loadFleet()},30000)}else{$('app').classList.add('hidden');$('login').classList.remove('hidden');$('logout').classList.add('hidden');$('liveLabel').textContent='Sign in'}}
|
||||
async function loadFleet(){const r=await api('/admin/api/analytics');if(r.status!==200)return;fleet=r.body;$('fleetInstalls').textContent=String(r.body.stats?.activeInstalls||0);$('fleetCrashes').textContent=String(r.body.stats?.crashReports||0);$('fleetList').textContent=JSON.stringify(r.body.installs||[],null,2);const list=$('crashList');list.textContent='';(r.body.crashes||[]).forEach(c=>{const row=document.createElement('article');row.className='report';const title=document.createElement('h3');esc(title,(c.exceptionType||'Crash')+': '+(c.message||''));const meta=document.createElement('div');meta.className='reportmeta';esc(meta,[c.carModel,c.appProfile,c.appVersion,c.platform,fmtDate(c.receivedAt)].filter(Boolean).join(' · '));const pre=document.createElement('div');pre.className='reportpreview';esc(pre,c.stack||'');row.append(title,meta,pre);row.onclick=()=>{const pack=JSON.stringify(c,null,2);$('detailCategory').textContent='Crash report';$('detailTitle').textContent=c.exceptionType||'Crash';$('detailMeta').textContent=[c.carModel,c.appProfile,c.appVersion,fmtDate(c.receivedAt)].filter(Boolean).join(' · ');$('detailText').textContent=pack;$('detailOverlay').classList.add('open');document.body.style.overflow='hidden'};list.append(row)});if(!list.childNodes.length){const empty=document.createElement('div');empty.className='empty';esc(empty,'No crash reports received.');list.append(empty)}}
|
||||
function makeReport(e){const card=document.createElement('article');card.className='report';card.tabIndex=0;card.setAttribute('role','button');card.setAttribute('aria-label','Open report '+(e.message||e.category));const top=document.createElement('div');top.className='reporttop';const badge=document.createElement('span');badge.className='badge';esc(badge,e.category||'report');const time=document.createElement('span');time.className='reporttime';esc(time,fmtDate(e.receivedAt));top.append(badge,time);const title=document.createElement('h3');esc(title,e.message||'Diagnostic details attached');const meta=document.createElement('div');meta.className='reportmeta';const vehicle=e.vehicleId?' · instance '+e.vehicleId.slice(0,8)+(e.appProfile?' · app profile '+e.appProfile:''):'';esc(meta,(e.product||'MG Utility')+' · '+(e.appVersion||'version unknown')+' · '+(e.platform||'platform unknown')+vehicle);card.append(top,title,meta);if(e.details){const pre=document.createElement('div');pre.className='reportpreview';esc(pre,e.details);card.append(pre)}card.onclick=()=>openDetail(e);card.onkeydown=ev=>{if(ev.key==='Enter'||ev.key===' '){ev.preventDefault();openDetail(e)}};return card}
|
||||
function fillSelect(select,items,label){const current=select.value;select.textContent='';const all=document.createElement('option');all.value='';all.textContent=label;select.append(all);for(const value of items){const o=document.createElement('option');o.value=value;o.textContent=value;select.append(o)}select.value=items.includes(current)?current:''}
|
||||
function copyText(value,label){navigator.clipboard.writeText(value).then(()=>toast(label+' copied')).catch(()=>toast('Clipboard unavailable'))}
|
||||
async function loadEvents(reset=true,render=true){if(reset)offset=0;const q=new URLSearchParams({limit:String(limit),offset:String(offset)});if($('filterProduct').value)q.set('product',$('filterProduct').value);if($('filterCategory').value)q.set('category',$('filterCategory').value);if($('filterVehicle').value)q.set('vehicleId',$('filterVehicle').value);const r=await api('/admin/api/events?'+q);if(r.status!==200){if(r.status===401)check();return}const batch=r.body.events||[];if(reset)events=batch;else events=events.concat(batch);metrics=r.body.stats||{};$('updatedAt').textContent='Updated '+fmtDate(new Date().toISOString());$('reportCount').textContent=(r.body.total||0)+' matching · showing '+events.length;$('loadMore').classList.toggle('hidden',!r.body.hasMore);fillSelect($('filterProduct'),(r.body.products||[]).map(x=>x.name),'All products');fillSelect($('filterCategory'),r.body.categories||[],'All categories');fillSelect($('filterVehicle'),(r.body.vehicles||[]).map(v=>v.id),'All vehicles');if(render)renderEvents()}
|
||||
function renderEvents(){const term=$('search').value.trim().toLowerCase();const visible=events.filter(e=>!term||[e.message,e.details,e.category,e.product,e.appVersion,e.vehicleId,e.appProfile].some(v=>String(v||'').toLowerCase().includes(term)));const list=$('reportList');list.textContent='';if(!visible.length){const empty=document.createElement('div');empty.className='empty';esc(empty,events.length?'No matching reports. Try a shorter search.':'No user uploads yet. Reports appear after a user submits diagnostics in the app.');list.append(empty)}else visible.forEach(e=>list.append(makeReport(e)));const recent=$('recentList');recent.textContent='';if(events.length)events.slice(0,4).forEach(e=>recent.append(makeReport(e)));else{const empty=document.createElement('div');empty.className='empty';esc(empty,'No reports received yet.');recent.append(empty)}$('statTotal').textContent=String(metrics.total||0);$('statDay').textContent=String(metrics.last24h||0);$('statBuilds').textContent=String(metrics.builds||0);$('statProducts').textContent=String(metrics.products||0);$('statVehicles').textContent=String(metrics.vehicles||0);const chips=$('productList');chips.textContent='';if((metrics.productList||[]).length)metrics.productList.forEach(item=>{const c=document.createElement('button');c.className='chip';esc(c,item.name);const b=document.createElement('b');esc(b,item.count);c.append(b);c.onclick=()=>{$('filterProduct').value=item.name;setView('reports')};chips.append(c)});else{const s=document.createElement('span');s.className='subtle';esc(s,'No product data yet');chips.append(s)}}
|
||||
function openDetail(e){selected=e;$('detailCategory').textContent=e.category||'Report';$('detailTitle').textContent=e.message||'Diagnostic details';$('detailMeta').textContent=[e.product||'MG Utility',e.appVersion||'unknown version',e.platform||'unknown platform',e.appProfile?'app profile '+e.appProfile:'',e.vehicleId?'instance '+e.vehicleId:'',fmtDate(e.receivedAt)].filter(Boolean).join(' · ');$('detailText').textContent=JSON.stringify({vehicleId:e.vehicleId||null,appProfile:e.appProfile||null,details:e.details,appVersion:e.appVersion,platform:e.platform,product:e.product,category:e.category,id:e.id,receivedAt:e.receivedAt},null,2);$('detailOverlay').classList.add('open');document.body.style.overflow='hidden'}
|
||||
function closeDetail(){$('detailOverlay').classList.remove('open');document.body.style.overflow='';selected=null}
|
||||
function ensureEmptyNotes(){const list=$('changelogList');if(!list.querySelector('.changeitem')&&!list.querySelector('.empty')){const empty=document.createElement('div');empty.className='empty';esc(empty,'No release notes yet. Add a versioned note to announce what changed.');list.append(empty)}}
|
||||
function changelogItem(item={}){const box=document.createElement('article');box.className='changeitem';const head=document.createElement('div');head.className='changehead';const version=document.createElement('input');version.className='field version';version.placeholder='Version';version.value=item.version||'';const title=document.createElement('input');title.className='field title';title.placeholder='Release title';title.value=item.title||'';const remove=document.createElement('button');remove.className='dangerlink remove';remove.type='button';remove.textContent='Remove';remove.onclick=()=>{box.remove();ensureEmptyNotes()};const notes=document.createElement('textarea');notes.className='field';notes.placeholder='Short release notes (plain text)';notes.value=item.notes||item.body||'';head.append(version,title,remove);box.append(head,notes);return box}
|
||||
async function loadConfig(){const r=await api('/admin/api/config');if(r.status!==200)return;config=r.body;$('enabled').checked=!!config.enabled;$('telemetryEnabled').checked=config.telemetryEnabled!==false;$('uploadUrl').value=config.uploadUrl||'';$('announcement').value=config.announcement?config.announcement.text||'':'';$('annCount').textContent=$('announcement').value.length+' / 2,000';$('intakeBadge').textContent=config.enabled?'Detailed uploads enabled':'Detailed uploads paused';$('intakeBadge').style.color=config.enabled?'var(--teal)':'var(--amber)';const list=$('changelogList');list.textContent='';(config.changelog||[]).forEach(item=>list.append(changelogItem(item)));ensureEmptyNotes()}
|
||||
async function saveConfig(extra={}){const body={enabled:$('enabled').checked,telemetryEnabled:$('telemetryEnabled').checked,uploadUrl:$('uploadUrl').value.trim(),...extra};const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});return r}
|
||||
$('loginForm').onsubmit=async ev=>{ev.preventDefault();const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});if(r.status===200){$('pw').value='';$('loginMsg').textContent='';check()}else esc($('loginMsg'),r.body.error||'Sign-in failed')};
|
||||
$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});clearInterval(timer);timer=null;check()};
|
||||
$('refresh').onclick=()=>loadEvents(true);$('loadMore').onclick=async()=>{offset=events.length;await loadEvents(false)};$('search').oninput=()=>renderEvents();$('filterProduct').onchange=()=>loadEvents(true);$('filterCategory').onchange=()=>loadEvents(true);$('filterVehicle').onchange=()=>loadEvents(true);
|
||||
document.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>setView(b.dataset.view));document.querySelectorAll('[data-goto]').forEach(b=>b.onclick=()=>setView(b.dataset.goto));
|
||||
$('enabled').onchange=()=>{$('intakeBadge').textContent=$('enabled').checked?'Uploads enabled':'Uploads paused';$('intakeBadge').style.color=$('enabled').checked?'var(--teal)':'var(--amber)'};
|
||||
$('saveConfig').onclick=async()=>{const r=await saveConfig();esc($('cfgStatus'),r.status===200?'Settings saved.':'Save failed: '+(r.body.error||r.status));if(r.status===200)loadConfig()};
|
||||
$('announcement').oninput=()=>$('annCount').textContent=$('announcement').value.length+' / 2,000';$('saveAnnouncement').onclick=async()=>{const r=await saveConfig({announcement:$('announcement').value});esc($('annStatus'),r.status===200?'Announcement published.':r.body.error||'Save failed');if(r.status===200)loadConfig()};$('clearAnnouncement').onclick=()=>{$('announcement').value='';$('annCount').textContent='0 / 2,000'};
|
||||
$('addChangelog').onclick=()=>{$('changelogList').querySelector('.empty')?.remove();$('changelogList').prepend(changelogItem());$('changelogList').querySelector('input')?.focus()};$('saveChangelog').onclick=async()=>{const changelog=[...$('changelogList').querySelectorAll('.changeitem')].map(x=>({version:x.querySelector('.version').value.trim(),title:x.querySelector('.title').value.trim(),notes:x.querySelector('textarea').value.trim()})).filter(x=>x.version||x.title||x.notes);const r=await saveConfig({changelog});esc($('changeStatus'),r.status===200?'Release notes saved.':r.body.error||'Save failed');if(r.status===200)loadConfig()};
|
||||
$('copyFleet').onclick=()=>copyText(JSON.stringify(fleet.installs||[],null,2),'Fleet summary');$('copyCrashes').onclick=()=>copyText(JSON.stringify(fleet.crashes||[],null,2),'Crash summary');$('export').onclick=()=>{location.href='/admin/api/export'};$('closeDetail').onclick=closeDetail;$('detailOverlay').onclick=e=>{if(e.target===$('detailOverlay'))closeDetail()};document.addEventListener('keydown',e=>{if(e.key==='Escape')closeDetail()});$('copyDetail').onclick=async()=>{try{await navigator.clipboard.writeText($('detailText').textContent);toast('Diagnostic details copied')}catch(_){toast('Clipboard unavailable')}};
|
||||
$('deleteDetail').onclick=async()=>{if(!selected||!confirm('Delete this report permanently?'))return;const r=await api('/admin/api/events/'+encodeURIComponent(selected.id),{method:'DELETE'});if(r.status===200){closeDetail();await loadEvents(true);toast('Report deleted')}else toast('Could not delete report')};
|
||||
check();
|
||||
</script>
|
||||
</body></html>
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "mg-utility-telemetry",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Local MG Utility diagnostics and announcements service",
|
||||
"scripts": {"start": "node server.js", "test": "node --test"},
|
||||
"engines": {"node": ">=20"}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
VAULT_CLI=/root/.openclaw/workspace/scripts/bw
|
||||
VAULT_ITEM_ID=b06d15fd-1a7f-4d65-a396-60211709b640
|
||||
TMPDIR=/root/.hermes/cache/scratch
|
||||
export TMPDIR
|
||||
ITEM_FILE=$(mktemp)
|
||||
chmod 600 "$ITEM_FILE"
|
||||
trap 'rm -f "$ITEM_FILE"' EXIT HUP INT TERM
|
||||
"$VAULT_CLI" get item "$VAULT_ITEM_ID" > "$ITEM_FILE"
|
||||
ADMIN_PASSWORD=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["login"]["password"],end="")' "$ITEM_FILE")
|
||||
test -n "$ADMIN_PASSWORD"
|
||||
export ADMIN_PASSWORD
|
||||
rm -f "$ITEM_FILE"
|
||||
trap - EXIT HUP INT TERM
|
||||
cd "$ROOT"
|
||||
exec node server.js
|
||||
@@ -1,450 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { randomUUID, randomBytes, createHmac, timingSafeEqual } = require('node:crypto');
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
const PORT = Number(process.env.PORT || 7013);
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
|
||||
const CONFIG_FILE = process.env.CONFIG_FILE || path.join(__dirname, 'client-config.json');
|
||||
|
||||
const DATABASE_FILE = process.env.DATABASE_FILE || path.join(DATA_DIR, 'analytics.sqlite');
|
||||
const SESSION_COOKIE = 'mgadm';
|
||||
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
|
||||
const MAX_BODY = 256 * 1024;
|
||||
const MAX_EVENTS = 20000;
|
||||
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
|
||||
try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {}
|
||||
const db = new DatabaseSync(DATABASE_FILE);
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS events (
|
||||
id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, product TEXT NOT NULL, appVersion TEXT,
|
||||
platform TEXT, vehicleId TEXT, appProfile TEXT, category TEXT NOT NULL, message TEXT,
|
||||
details TEXT, kind TEXT NOT NULL DEFAULT 'support'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS events_receivedAt_idx ON events(receivedAt);
|
||||
CREATE INDEX IF NOT EXISTS events_vehicleId_idx ON events(vehicleId);
|
||||
CREATE TABLE IF NOT EXISTS installs (vehicleId TEXT PRIMARY KEY, firstSeenAt TEXT NOT NULL, lastSeenAt TEXT NOT NULL,
|
||||
appVersion TEXT, platform TEXT, manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT);
|
||||
CREATE TABLE IF NOT EXISTS crashes (id TEXT PRIMARY KEY, receivedAt TEXT NOT NULL, vehicleId TEXT, appVersion TEXT, platform TEXT,
|
||||
manufacturer TEXT, carModel TEXT, carBuild TEXT, appProfile TEXT, exceptionType TEXT, message TEXT, stack TEXT);
|
||||
`);
|
||||
try { fs.chmodSync(DATABASE_FILE, 0o600); } catch (_) {}
|
||||
|
||||
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
|
||||
try { fs.chmodSync(DATA_DIR, 0o700); } catch (_) {}
|
||||
// Admin password is injected from the credential store by the service launcher;
|
||||
// never persist credentials beside application data. Session signing key is ephemeral.
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
|
||||
const SESSION_SECRET = randomBytes(32).toString('hex');
|
||||
|
||||
function json(res, status, body) {
|
||||
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer' });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
function readBody(req, limit) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let data = ''; let size = 0;
|
||||
req.on('data', chunk => {
|
||||
size += chunk.length;
|
||||
if (size > (limit || MAX_BODY)) { reject(Object.assign(new Error('request too large'), { status: 413 })); req.destroy(); return; }
|
||||
data += chunk.toString('utf8');
|
||||
});
|
||||
req.on('end', () => resolve(data));
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
function readJsonBody(req, limit) {
|
||||
return readBody(req, limit).then(text => { try { return JSON.parse(text || '{}'); } catch (_) { throw Object.assign(new Error('invalid JSON'), { status: 400 }); } });
|
||||
}
|
||||
function safeText(value, limit) {
|
||||
return typeof value === 'string' ? value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, limit) : '';
|
||||
}
|
||||
function loopback(req) {
|
||||
const addr = req.socket.remoteAddress || '';
|
||||
return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
|
||||
}
|
||||
function loadConfig() {
|
||||
try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); }
|
||||
catch (_) { return { schema: 1, enabled: false, uploadUrl: '', announcement: null, changelog: [] }; }
|
||||
}
|
||||
function saveConfig(config) {
|
||||
const tmp = CONFIG_FILE + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n');
|
||||
fs.renameSync(tmp, CONFIG_FILE);
|
||||
}
|
||||
function registerInstall(event) {
|
||||
const config = loadConfig();
|
||||
if (config.telemetryEnabled === false) return false;
|
||||
if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); }
|
||||
const id = safeText(event.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, '');
|
||||
if (!id) return false;
|
||||
const receivedAt = new Date().toISOString();
|
||||
const values = [safeText(event.appVersion,40), safeText(event.platform,60), safeText(event.manufacturer,80), safeText(event.carModel,100), safeText(event.carBuild,180), safeText(event.appProfile,100)];
|
||||
db.prepare(`INSERT INTO installs(vehicleId,firstSeenAt,lastSeenAt,appVersion,platform,manufacturer,carModel,carBuild,appProfile)
|
||||
VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(vehicleId) DO UPDATE SET lastSeenAt=excluded.lastSeenAt,appVersion=excluded.appVersion,
|
||||
platform=excluded.platform,manufacturer=excluded.manufacturer,carModel=excluded.carModel,carBuild=excluded.carBuild,appProfile=excluded.appProfile`)
|
||||
.run(id,receivedAt,receivedAt,...values);
|
||||
return true;
|
||||
}
|
||||
function insertCrash(input) {
|
||||
const config = loadConfig();
|
||||
if (config.telemetryEnabled === false) return false;
|
||||
if (config.telemetryEnabled === undefined) { config.telemetryEnabled = true; saveConfig(config); }
|
||||
const fields = [safeText(input.vehicleId,80),safeText(input.appVersion,40),safeText(input.platform,60),safeText(input.manufacturer,80),safeText(input.carModel,100),safeText(input.carBuild,180),safeText(input.appProfile,100),safeText(input.exceptionType,160),safeText(input.message,2000),safeText(input.stack,12000)];
|
||||
if (!fields[0] || !fields[7]) return false;
|
||||
db.prepare(`INSERT INTO crashes(id,receivedAt,vehicleId,appVersion,platform,manufacturer,carModel,carBuild,appProfile,exceptionType,message,stack)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(randomUUID(),new Date().toISOString(),...fields);
|
||||
return true;
|
||||
}
|
||||
|
||||
function analyticsPage() {
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow"><title>MG Utility Analytics</title><style>
|
||||
:root{color-scheme:dark;--bg:#0b1115;--panel:#111a20;--line:#26383e;--text:#edf5f2;--muted:#93a7a7;--teal:#59e0c0;--red:#ff7c79}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,sans-serif}.shell{max-width:1100px;margin:auto;padding:20px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:15px;padding:18px;margin:14px 0}.row{display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap}.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.stat{padding:16px;background:#0d1519;border:1px solid var(--line);border-radius:12px}.stat small{color:var(--muted)}.stat b{display:block;font-size:28px}.entry{border-top:1px solid var(--line);padding:14px 0}.muted{color:var(--muted);font-size:13px}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#080e11;padding:14px;border-radius:10px;max-height:55vh;overflow:auto;font:12px/1.5 ui-monospace,monospace}button,input{font:inherit;color:inherit;background:#162329;border:1px solid var(--line);border-radius:10px;padding:10px 13px}button{cursor:pointer}button.primary{background:var(--teal);color:#06221d;font-weight:700}input{width:min(100%,340px)}#login{max-width:420px;margin:12vh auto}@media(max-width:650px){.stats{grid-template-columns:1fr 1fr}.shell{padding:14px}}
|
||||
</style></head><body><main class="shell"><header class="row"><div><strong>MG Utility · Compatibility analytics</strong><div class="muted">Anonymous install fingerprints, crash summaries, and voluntary diagnostics</div></div><button id="logout" hidden>Sign out</button></header>
|
||||
<section id="login" class="panel" hidden><h2>Admin sign in</h2><form id="loginForm"><input id="pw" type="password" autocomplete="current-password" placeholder="Admin password" required><button class="primary">Sign in</button><p id="loginMsg" class="muted"></p></form></section>
|
||||
<section id="app" hidden><div class="stats"><div class="stat"><small>Known app installs</small><b id="installs">—</b></div><div class="stat"><small>Car models</small><b id="models">—</b></div><div class="stat"><small>Crash reports</small><b id="crashes">—</b></div></div>
|
||||
<section class="panel"><div class="row"><div><h2>Car/build fingerprints</h2><div class="muted">Random app-install IDs; no VIN or hardware ID.</div></div><button id="copyFleet">Copy fleet summary</button></div><div id="fleet"></div></section>
|
||||
<section class="panel"><div class="row"><div><h2>Crash reports</h2><div class="muted">Crash summaries captured locally then sent on next launch.</div></div><button id="copyCrashes">Copy crash summary</button></div><div id="crashList"></div></section>
|
||||
<section class="panel"><div class="row"><div><h2>User-submitted diagnostics</h2><div class="muted">Only uploaded after the user requests it in Settings.</div><button id="copyReports">Copy report bundle</button></div></div><div id="reports"></div></section></section></main>
|
||||
<script>const $=id=>document.getElementById(id);let data={};async function api(path,opts={}){const r=await fetch(path,{credentials:'same-origin',...opts});return{status:r.status,body:await r.json().catch(()=>({}))}}function copy(x){navigator.clipboard.writeText(JSON.stringify(x,null,2)).then(()=>alert('Copied'))}function card(host,title,meta,detail){const d=document.createElement('article');d.className='entry';const h=document.createElement('strong');h.textContent=title;const m=document.createElement('div');m.className='muted';m.textContent=meta;d.append(h,m);if(detail){const p=document.createElement('pre');p.textContent=detail;d.append(p)}host.append(d)}async function load(){const r=await api('/admin/api/analytics');if(r.status!==200)return;data=r.body;const installs=data.installs||[],crashes=data.crashes||[],reports=data.events||[];$('installs').textContent=data.stats?.activeInstalls||0;$('models').textContent=new Set(installs.map(x=>x.carModel).filter(Boolean)).size;$('crashes').textContent=data.stats?.crashReports||0;const f=$('fleet');f.textContent='';installs.forEach(x=>card(f,x.carModel||'Unknown model',[x.manufacturer,x.platform,'app '+x.appVersion,'first '+x.firstSeenAt,'last '+x.lastSeenAt].filter(Boolean).join(' · '),JSON.stringify(x,null,2)));if(!installs.length)f.textContent='No installs yet.';const c=$('crashList');c.textContent='';crashes.forEach(x=>card(c,x.exceptionType+': '+x.message,[x.carModel,x.manufacturer,x.appVersion,x.platform,x.receivedAt].filter(Boolean).join(' · '),JSON.stringify(x,null,2)));if(!crashes.length)c.textContent='No crash reports yet.';const e=$('reports');e.textContent='';reports.forEach(x=>card(e,x.message||x.category,[x.appVersion,x.platform,x.receivedAt].filter(Boolean).join(' · '),x.details));if(!reports.length)e.textContent='No detailed uploads yet.'}
|
||||
async function check(){const r=await api('/admin/api/session');$('login').hidden=!!r.body.authorized;$('app').hidden=!r.body.authorized;$('logout').hidden=!r.body.authorized;if(r.body.authorized)load()}$('loginForm').onsubmit=async ev=>{ev.preventDefault();const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});if(r.status===200){$('pw').value='';check()}else $('loginMsg').textContent=r.body.error||'Login failed'};$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});check()};$('copyFleet').onclick=()=>copy(data.installs||[]);$('copyCrashes').onclick=()=>copy(data.crashes||[]);$('copyReports').onclick=()=>copy(data.events||[]);check();</script></body></html>`;
|
||||
}
|
||||
function readEvents() {
|
||||
return db.prepare('SELECT * FROM events ORDER BY receivedAt ASC').all();
|
||||
}
|
||||
function appendEvent(event) {
|
||||
db.prepare(`INSERT INTO events(id,receivedAt,product,appVersion,platform,vehicleId,appProfile,category,message,details,kind)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?)`).run(event.id,event.receivedAt,event.product,event.appVersion,event.platform,event.vehicleId,event.appProfile,event.category,event.message,event.details,event.kind || 'support');
|
||||
|
||||
const old = db.prepare('SELECT id FROM events ORDER BY receivedAt DESC LIMIT -1 OFFSET ?').all(MAX_EVENTS);
|
||||
const remove = db.prepare('DELETE FROM events WHERE id=?');
|
||||
for (const row of old) remove.run(row.id);
|
||||
}
|
||||
|
||||
// --- Sessions (HMAC-signed token; no server-side store) ---
|
||||
function sign(value) { return createHmac('sha256', SESSION_SECRET).update(value).digest('base64url'); }
|
||||
function issueSession() {
|
||||
const payload = String(Date.now() + SESSION_TTL_MS);
|
||||
return payload + '.' + sign(payload);
|
||||
}
|
||||
function validSession(token) {
|
||||
if (typeof token !== 'string') return false;
|
||||
const dot = token.lastIndexOf('.');
|
||||
if (dot < 1) return false;
|
||||
const payload = token.slice(0, dot), mac = token.slice(dot + 1);
|
||||
const expected = sign(payload);
|
||||
if (mac.length !== expected.length) return false;
|
||||
try { if (!timingSafeEqual(Buffer.from(mac), Buffer.from(expected))) return false; } catch (_) { return false; }
|
||||
return Number(payload) > Date.now();
|
||||
}
|
||||
function cookies(req) {
|
||||
const out = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq > 0) out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const loginFails = new Map();
|
||||
function loginAllowed(ip) {
|
||||
const entry = loginFails.get(ip);
|
||||
return !entry || entry.until < Date.now();
|
||||
}
|
||||
function recordLoginFail(ip) {
|
||||
const entry = loginFails.get(ip) || { count: 0, until: 0 };
|
||||
entry.count += 1;
|
||||
entry.until = Date.now() + Math.min(5 * entry.count, 30) * 1000;
|
||||
loginFails.set(ip, entry);
|
||||
}
|
||||
function authorized(req) { return validSession(cookies(req)[SESSION_COOKIE]); }
|
||||
|
||||
// --- Dashboard (single page; all dynamic content rendered via textContent) ---
|
||||
function legacyPage() {
|
||||
return `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="robots" content="noindex,nofollow"><title>MG Utility Telemetry</title>
|
||||
<style>
|
||||
:root{color-scheme:dark}
|
||||
body{margin:0;font:14px/1.45 system-ui,sans-serif;background:#0e1116;color:#e6e6e6}
|
||||
header{display:flex;gap:12px;align-items:center;padding:12px 20px;background:#161b22;border-bottom:1px solid #232a33}
|
||||
header h1{font-size:16px;margin:0 auto 0 0}
|
||||
main{max-width:1100px;margin:0 auto;padding:20px}
|
||||
button,input,select,textarea{background:#1c232d;color:#e6e6e6;border:1px solid #333c47;border-radius:6px;padding:6px 10px;font:inherit}
|
||||
button{cursor:pointer}button:hover{background:#253040}
|
||||
table{width:100%;border-collapse:collapse;margin-top:12px}
|
||||
th,td{text-align:left;padding:8px 10px;border-bottom:1px solid #232a33;vertical-align:top}
|
||||
th{color:#9aa4b0;font-weight:600;font-size:12px;text-transform:uppercase}
|
||||
tr.ev{cursor:pointer}tr.ev:hover{background:#161b22}
|
||||
pre{white-space:pre-wrap;word-break:break-word;background:#161b22;border:1px solid #232a33;border-radius:6px;padding:10px;max-height:320px;overflow:auto}
|
||||
.meta{color:#9aa4b0;font-size:12px}
|
||||
.hidden{display:none}
|
||||
.card{background:#161b22;border:1px solid #232a33;border-radius:8px;padding:16px;margin-bottom:16px}
|
||||
.card h2{margin-top:0}
|
||||
label{display:block;margin:8px 0 4px;color:#9aa4b0;font-size:12px;text-transform:uppercase}
|
||||
label.inline{display:inline;margin:0;text-transform:none;color:#e6e6e6}
|
||||
</style></head><body>
|
||||
<header><h1>MG Utility Telemetry</h1><span id="who" class="meta"></span><button id="logout" class="hidden">Log out</button></header>
|
||||
<main>
|
||||
<section id="login" class="card hidden">
|
||||
<h2>Admin log in</h2>
|
||||
<form id="loginForm"><label for="pw">Password</label><input id="pw" type="password" autocomplete="current-password" style="width:280px">
|
||||
<button type="submit">Log in</button><span id="loginMsg" class="meta" style="margin-left:10px"></span></form>
|
||||
<p class="meta">Admin access requires the configured credential-store password.</p>
|
||||
</section>
|
||||
<section id="app" class="hidden">
|
||||
<div class="card">
|
||||
<h2>Events</h2>
|
||||
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
|
||||
<select id="product"><option value="">All products</option></select>
|
||||
<select id="category"><option value="">All categories</option></select>
|
||||
<button id="refresh">Refresh</button>
|
||||
<label class="inline"><input type="checkbox" id="auto"> Auto-refresh 10s</label>
|
||||
<span id="status" class="meta"></span>
|
||||
</div>
|
||||
<table><thead><tr><th style="width:160px">Received</th><th style="width:120px">Product</th><th style="width:90px">Version</th><th style="width:170px">Category</th><th>Message</th></tr></thead>
|
||||
<tbody id="rows"></tbody></table>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>In-app announcement</h2>
|
||||
<textarea id="announcement" rows="3" style="width:100%"></textarea>
|
||||
<div style="margin-top:10px;display:flex;gap:10px;align-items:center">
|
||||
<button id="saveAnnouncement">Save announcement</button><span id="annStatus" class="meta"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Client diagnostics configuration</h2>
|
||||
<label class="inline"><input type="checkbox" id="enabled"> Enable diagnostic uploads</label>
|
||||
<label for="uploadUrl">Upload endpoint base URL (HTTPS)</label>
|
||||
<input id="uploadUrl" type="url" placeholder="https://your-host/" style="width:min(100%,600px)">
|
||||
<div style="margin-top:10px;display:flex;gap:10px;align-items:center"><button id="saveConfig">Save client config</button><span id="cfgStatus" class="meta"></span></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id);
|
||||
function esc(node,text){node.textContent=text==null?'':String(text);return node}
|
||||
let timer=null;
|
||||
async function api(path,opts){const r=await fetch(path,Object.assign({credentials:'same-origin'},opts));return{status:r.status,body:await r.json().catch(()=>({}))}}
|
||||
async function check(){
|
||||
const c=await api('/admin/api/session');
|
||||
if(c.body.authorized){$('login').classList.add('hidden');$('app').classList.remove('hidden');$('logout').classList.remove('hidden');$('who').textContent='admin';
|
||||
loadEvents();loadConfig();
|
||||
if(!$('auto').dataset.bound){$('auto').dataset.bound='1';$('auto').onchange=()=>{if($('auto').checked)timer=setInterval(loadEvents,10000);else clearInterval(timer)};}
|
||||
} else {$('app').classList.add('hidden');$('login').classList.remove('hidden');$('logout').classList.add('hidden');$('who').textContent='';}
|
||||
}
|
||||
async function loadEvents(){
|
||||
$('status').textContent='loading…';
|
||||
const q=new URLSearchParams();if($('product').value)q.set('product',$('product').value);if($('category').value)q.set('category',$('category').value);
|
||||
const r=await api('/admin/api/events?'+q);
|
||||
if(r.status!==200){$('status').textContent='failed ('+r.status+')';return}
|
||||
const events=r.body.events||[];
|
||||
$('status').textContent=events.length+' event(s)';
|
||||
const cats=new Set(),products=new Set();
|
||||
const tbody=$('rows');tbody.textContent='';
|
||||
for(const e of events.slice().reverse()){
|
||||
products.add(e.product||'mg-utility');cats.add(e.category||'');
|
||||
const tr=document.createElement('tr');tr.className='ev';
|
||||
const td=(w,t)=>{const d=document.createElement('td');esc(d,t);if(w)d.style.width=w;return d};
|
||||
tr.append(td('160px',(e.receivedAt||'').replace('T',' ').slice(0,19)),td('120px',e.product),td('90px',e.appVersion),td('170px',e.category),td(null,e.message));
|
||||
tr.onclick=()=>show(e);tbody.append(tr);
|
||||
}
|
||||
fill($('product'),[...products]);fill($('category'),[...cats]);
|
||||
}
|
||||
function fill(sel,items){const cur=sel.value;for(const it of items){if(![...sel.options].some(o=>o.value===it)){const o=document.createElement('option');o.value=it;o.textContent=it;sel.append(o)}}sel.value=cur}
|
||||
function show(e){
|
||||
const old=document.getElementById('detail');if(old)old.remove();
|
||||
const tr=document.createElement('tr');tr.id='detail';const td=document.createElement('td');td.colSpan=5;
|
||||
const pre=document.createElement('pre');esc(pre,JSON.stringify({details:e.details,platform:e.platform,appVersion:e.appVersion,id:e.id,receivedAt:e.receivedAt},null,2));
|
||||
td.append(pre);tr.append(td);$('rows').append(tr);
|
||||
}
|
||||
async function loadConfig(){const c=await api('/admin/api/config');if(c.status===200){$('announcement').value=c.body.announcement?c.body.announcement.text:'';$('enabled').checked=!!c.body.enabled;$('uploadUrl').value=c.body.uploadUrl||''}}
|
||||
$('refresh').onclick=loadEvents;
|
||||
$('logout').onclick=async()=>{await api('/admin/api/logout',{method:'POST'});clearInterval(timer);check()};
|
||||
$('loginForm').onsubmit=async ev=>{ev.preventDefault();
|
||||
const r=await api('/admin/api/login',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({password:$('pw').value})});
|
||||
if(r.status===200){$('pw').value='';$('loginMsg').textContent='';check()}else{$('loginMsg').textContent=r.body.error||'login failed'}};
|
||||
$('saveAnnouncement').onclick=async()=>{
|
||||
const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({announcement:$('announcement').value})});
|
||||
$('annStatus').textContent=r.status===200?'saved':'save failed ('+r.status+')';setTimeout(()=>{$('annStatus').textContent=''},3000)};
|
||||
$('saveConfig').onclick=async()=>{
|
||||
const r=await api('/admin/api/config',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({enabled:$('enabled').checked,uploadUrl:$('uploadUrl').value})});
|
||||
$('cfgStatus').textContent=r.status===200?'saved':'save failed ('+r.status+')';setTimeout(()=>{$('cfgStatus').textContent=''},3000)};
|
||||
check();
|
||||
</script></body></html>`;
|
||||
}
|
||||
|
||||
function page() { return fs.readFileSync(path.join(__dirname, 'dashboard.html'), 'utf8'); }
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const p = url.pathname;
|
||||
const ip = req.socket.remoteAddress || '';
|
||||
|
||||
if (req.method === 'GET' && p === '/health') return json(res, 200, { ok: true, service: 'mg-utility-telemetry' });
|
||||
|
||||
// Public client config: fetched by every app instance on startup.
|
||||
if (req.method === 'GET' && p === '/v1/config') {
|
||||
const c = loadConfig();
|
||||
return json(res, 200, { schema: 1, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), announcement: c.announcement || null, changelog: Array.isArray(c.changelog) ? c.changelog.slice(-50) : [] });
|
||||
}
|
||||
|
||||
// Minimal startup compatibility snapshot and crash-only intake.
|
||||
if (req.method === 'POST' && p === '/v1/install') {
|
||||
try {
|
||||
const input = await readJsonBody(req, 8192);
|
||||
if (!registerInstall(input)) return json(res, 400, { error: 'invalid install identity' });
|
||||
return json(res, 202, { accepted: true });
|
||||
} catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); }
|
||||
}
|
||||
if (req.method === 'POST' && p === '/v1/crashes') {
|
||||
try {
|
||||
const input = await readJsonBody(req, 20000);
|
||||
if (!insertCrash(input)) return json(res, 400, { error: 'invalid crash report' });
|
||||
return json(res, 202, { accepted: true });
|
||||
} catch (error) { return json(res, error.status || 400, { error: 'invalid request' }); }
|
||||
}
|
||||
|
||||
// Public intake endpoint used by the app's explicit upload action.
|
||||
if (req.method === 'POST' && p === '/v1/events') {
|
||||
try {
|
||||
const input = await readJsonBody(req);
|
||||
if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' });
|
||||
const product = safeText(input.product, 60).replace(/[^a-zA-Z0-9._-]/g, '') || 'mg-utility';
|
||||
const vehicleId = safeText(input.vehicleId, 80).replace(/[^a-zA-Z0-9._-]/g, '');
|
||||
const event = {
|
||||
id: randomUUID(), receivedAt: new Date().toISOString(),
|
||||
product, appVersion: safeText(input.appVersion, 40), platform: safeText(input.platform, 60),
|
||||
vehicleId, appProfile: safeText(input.appProfile, 80),
|
||||
category: safeText(input.category, 40), message: safeText(input.message, 4000),
|
||||
details: safeText(input.details, 60000), kind: 'support'
|
||||
};
|
||||
if (!event.category || (!event.message && !event.details)) return json(res, 400, { error: 'category and message or details required' });
|
||||
if (!loadConfig().enabled) return json(res, 403, { error: 'intake disabled' });
|
||||
appendEvent(event);
|
||||
return json(res, 202, { accepted: true, id: event.id });
|
||||
} catch (error) { return json(res, error.status || 400, { error: error.status === 413 ? 'request too large' : 'invalid request' }); }
|
||||
}
|
||||
|
||||
// --- Admin dashboard ---
|
||||
if (req.method === 'GET' && (p === '/admin' || p === '/admin/')) return sendHtml(res, page());
|
||||
if (req.method === 'GET' && p === '/admin/analytics') return sendHtml(res, analyticsPage());
|
||||
if (req.method === 'POST' && p === '/admin/api/login') {
|
||||
if (!loginAllowed(ip)) return json(res, 429, { error: 'too many attempts; wait a moment' });
|
||||
let body = {}; try { body = JSON.parse((await readBody(req, 4096)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); }
|
||||
const pw = Buffer.from(String(body.password || ''));
|
||||
if (!ADMIN_PASSWORD) return json(res, 503, { error: 'admin login is not configured' });
|
||||
const expected = Buffer.from(ADMIN_PASSWORD);
|
||||
if (pw.length === expected.length && timingSafeEqual(pw, expected)) {
|
||||
res.setHeader('set-cookie', `${SESSION_COOKIE}=${issueSession()}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL_MS / 1000}`);
|
||||
loginFails.delete(ip);
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
recordLoginFail(ip);
|
||||
return json(res, 401, { error: 'invalid password' });
|
||||
}
|
||||
if (req.method === 'POST' && p === '/admin/api/logout') {
|
||||
res.setHeader('set-cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
if (p === '/admin/api/session') return json(res, 200, { authorized: authorized(req) });
|
||||
|
||||
if (p.startsWith('/admin/api/')) {
|
||||
if (!authorized(req)) return json(res, 401, { error: 'unauthorized' });
|
||||
if (req.method === 'GET' && p === '/admin/api/analytics') {
|
||||
const installs = db.prepare('SELECT * FROM installs ORDER BY lastSeenAt DESC').all();
|
||||
const crashes = db.prepare('SELECT * FROM crashes ORDER BY receivedAt DESC LIMIT 500').all();
|
||||
const events = db.prepare('SELECT * FROM events ORDER BY receivedAt DESC LIMIT 500').all();
|
||||
return json(res, 200, { installs, crashes, events, stats: { activeInstalls: db.prepare('SELECT COUNT(*) AS n FROM installs').get().n, crashReports: db.prepare('SELECT COUNT(*) AS n FROM crashes').get().n } });
|
||||
}
|
||||
if (req.method === 'GET' && p === '/admin/api/events') {
|
||||
const product = url.searchParams.get('product') || '';
|
||||
const category = url.searchParams.get('category') || '';
|
||||
const vehicleId = url.searchParams.get('vehicleId') || '';
|
||||
const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
|
||||
const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
|
||||
const all = readEvents();
|
||||
let events = all.slice();
|
||||
if (product) events = events.filter(e => e.product === product);
|
||||
if (category) events = events.filter(e => e.category === category);
|
||||
if (vehicleId) events = events.filter(e => e.vehicleId === vehicleId);
|
||||
const productCounts = new Map();
|
||||
for (const event of all) {
|
||||
const name = event.product || 'mg-utility';
|
||||
productCounts.set(name, (productCounts.get(name) || 0) + 1);
|
||||
}
|
||||
const products = [...productCounts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => a.name.localeCompare(b.name));
|
||||
const vehicleCounts = new Map();
|
||||
for (const event of all) if (event.vehicleId) {
|
||||
const row = vehicleCounts.get(event.vehicleId) || { id: event.vehicleId, appProfile: event.appProfile || '', count: 0 };
|
||||
row.count++;
|
||||
if (!row.appProfile && event.appProfile) row.appProfile = event.appProfile;
|
||||
vehicleCounts.set(event.vehicleId, row);
|
||||
}
|
||||
const vehicles = [...vehicleCounts.values()].sort((a, b) => a.id.localeCompare(b.id));
|
||||
const categories = [...new Set(all.map(e => e.category).filter(Boolean))].sort();
|
||||
const dayStart = Date.now() - 86400000;
|
||||
const stats = {
|
||||
total: all.length,
|
||||
last24h: all.filter(e => new Date(e.receivedAt).getTime() >= dayStart).length,
|
||||
builds: new Set(all.map(e => e.appVersion).filter(Boolean)).size,
|
||||
products: products.length,
|
||||
vehicles: vehicles.length,
|
||||
productList: products
|
||||
};
|
||||
events.reverse();
|
||||
return json(res, 200, { events: events.slice(offset, offset + limit), total: events.length, hasMore: offset + limit < events.length, products, vehicles, categories, stats });
|
||||
}
|
||||
if (req.method === 'GET' && p === '/admin/api/export') {
|
||||
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'content-disposition': 'attachment; filename="mg-utility-reports.json"', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
||||
return res.end(JSON.stringify({ exportedAt: new Date().toISOString(), events: readEvents() }, null, 2));
|
||||
}
|
||||
if (req.method === 'DELETE' && p.startsWith('/admin/api/events/')) {
|
||||
const id = p.slice('/admin/api/events/'.length);
|
||||
if (!/^[a-f0-9-]{36}$/i.test(id)) return json(res, 400, { error: 'invalid report id' });
|
||||
const result = db.prepare('DELETE FROM events WHERE id=?').run(id);
|
||||
if (result.changes === 0) return json(res, 404, { error: 'report not found' });
|
||||
return json(res, 200, { deleted: true });
|
||||
}
|
||||
if (req.method === 'GET' && p === '/admin/api/config') {
|
||||
const c = loadConfig();
|
||||
return json(res, 200, { announcement: c.announcement || null, enabled: !!c.enabled, telemetryEnabled: c.telemetryEnabled !== false, uploadUrl: String(c.uploadUrl || ''), changelog: c.changelog || [] });
|
||||
}
|
||||
if (req.method === 'POST' && p === '/admin/api/config') {
|
||||
let body = {}; try { body = JSON.parse((await readBody(req, 65536)) || '{}'); } catch (_) { return json(res, 400, { error: 'invalid request' }); }
|
||||
const c = loadConfig();
|
||||
if (typeof body.announcement === 'string') {
|
||||
c.announcement = body.announcement.trim() ? { text: body.announcement.trim().slice(0, 2000), updatedAt: new Date().toISOString() } : null;
|
||||
}
|
||||
if (typeof body.enabled === 'boolean') c.enabled = body.enabled;
|
||||
if (typeof body.telemetryEnabled === 'boolean') c.telemetryEnabled = body.telemetryEnabled;
|
||||
if (typeof body.uploadUrl === 'string') {
|
||||
const value = body.uploadUrl.trim();
|
||||
if (value && !/^https:\/\//i.test(value)) return json(res, 400, { error: 'uploadUrl must use HTTPS' });
|
||||
c.uploadUrl = value;
|
||||
}
|
||||
if (Array.isArray(body.changelog)) {
|
||||
if (body.changelog.length > 50) return json(res, 400, { error: 'maximum 50 release notes' });
|
||||
c.changelog = body.changelog.map(item => ({
|
||||
version: safeText(item && item.version, 40),
|
||||
title: safeText(item && item.title, 120),
|
||||
notes: safeText(item && item.notes, 2000)
|
||||
})).filter(item => item.version || item.title || item.notes);
|
||||
}
|
||||
saveConfig(c);
|
||||
return json(res, 200, { ok: true, announcement: c.announcement });
|
||||
}
|
||||
}
|
||||
return json(res, 404, { error: 'not found' });
|
||||
});
|
||||
|
||||
function sendHtml(res, html) {
|
||||
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer', 'content-security-policy': "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'" });
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
server.listen(PORT, HOST, () => console.log(`MG Utility telemetry listening on ${HOST}:${PORT}`));
|
||||
@@ -1,73 +0,0 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawn } = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
|
||||
test('health, config and event intake/readback', async t => {
|
||||
const port = 22000 + Math.floor(Math.random() * 20000);
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mg-telemetry-'));
|
||||
const configFile = path.join(dataDir, 'config.json');
|
||||
fs.writeFileSync(configFile, JSON.stringify({ schema: 1, enabled: true, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: null, changelog: [] }));
|
||||
const child = spawn(process.execPath, ['server.js'], { cwd: __dirname, env: { ...process.env, HOST: '127.0.0.1', PORT: String(port), DATA_DIR: dataDir, CONFIG_FILE: configFile, ADMIN_PASSWORD: 'test-only-password' }, stdio: 'ignore' });
|
||||
t.after(() => { child.kill(); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
async function request(method, route, body, cookie) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers = body ? { 'content-type': 'application/json' } : {};
|
||||
if (cookie) headers.cookie = cookie;
|
||||
const req = http.request({ host: '127.0.0.1', port, path: route, method, headers }, res => {
|
||||
let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data), headers: res.headers }));
|
||||
});
|
||||
req.on('error', reject); if (body) req.write(JSON.stringify(body)); req.end();
|
||||
});
|
||||
}
|
||||
let health;
|
||||
for (let i = 0; i < 40; i++) { try { health = await request('GET', '/health'); break; } catch (_) { await new Promise(r => setTimeout(r, 50)); } }
|
||||
assert.equal(health.status, 200);
|
||||
assert.equal((await request('GET', '/v1/config')).body.schema, 1);
|
||||
assert.equal((await request('GET', '/admin/api/events')).status, 401);
|
||||
const login = await request('POST', '/admin/api/login', { password: 'test-only-password' });
|
||||
assert.equal(login.status, 200);
|
||||
const cookie = login.headers['set-cookie'][0].split(';')[0];
|
||||
const vehicleId = 'd49300a0-85b2-4aa1-a8ee-27ac227d53a5';
|
||||
const startup = await request('POST', '/v1/install', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', appProfile: 'unknown-read-only' });
|
||||
assert.equal(startup.status, 202);
|
||||
const crash = await request('POST', '/v1/crashes', { vehicleId, appVersion: '0.3', platform: 'android-28', manufacturer: 'MG', carModel: 'MG4', carBuild: 'test-build', exceptionType: 'IllegalStateException', message: 'synthetic', stack: 'synthetic stack' });
|
||||
assert.equal(crash.status, 202);
|
||||
const analyticsPage = await new Promise((resolve, reject) => http.get({ host: '127.0.0.1', port, path: '/admin/analytics' }, res => { let data = ''; res.on('data', c => data += c); res.on('end', () => resolve({ status: res.statusCode, body: data })); }).on('error', reject));
|
||||
assert.equal(analyticsPage.status, 200);
|
||||
assert.match(analyticsPage.body, /MG Utility · Compatibility analytics/);
|
||||
assert.match(analyticsPage.body, /copyFleet/);
|
||||
const analytics = await request('GET', '/admin/api/analytics', null, cookie);
|
||||
assert.equal(analytics.body.stats.activeInstalls, 1);
|
||||
assert.equal(analytics.body.installs[0].carModel, 'MG4');
|
||||
assert.ok(fs.existsSync(path.join(dataDir, 'analytics.sqlite')));
|
||||
assert.equal(analytics.body.stats.crashReports, 1);
|
||||
assert.equal((await request('GET', '/admin/api/analytics', null, cookie)).body.events.length, 0);
|
||||
assert.equal((await request('GET', '/admin/api/analytics')).status, 401);
|
||||
const submitted = await request('POST', '/v1/events', { product: 'saic-demo', vehicleId, appProfile: 'mg4-luxury-2022-saic-v2', category: 'diagnostic', message: 'test event', details: 'safe test' });
|
||||
assert.equal(submitted.status, 202);
|
||||
const readback = await request('GET', '/admin/api/events', null, cookie);
|
||||
assert.equal(readback.body.events.length, 1);
|
||||
assert.equal(readback.body.events[0].message, 'test event');
|
||||
assert.equal(readback.body.events[0].product, 'saic-demo');
|
||||
assert.equal(readback.body.events[0].vehicleId, vehicleId);
|
||||
assert.equal(readback.body.events[0].appProfile, 'mg4-luxury-2022-saic-v2');
|
||||
assert.equal(readback.body.stats.vehicles, 1);
|
||||
assert.equal((await request('GET', '/admin/api/events?vehicleId=' + vehicleId, null, cookie)).body.total, 1);
|
||||
assert.equal(readback.body.stats.total, 1);
|
||||
assert.equal(readback.body.stats.productList[0].name, 'saic-demo');
|
||||
const deleted = await request('DELETE', '/admin/api/events/' + readback.body.events[0].id, null, cookie);
|
||||
assert.equal(deleted.status, 200);
|
||||
assert.equal((await request('GET', '/admin/api/events', null, cookie)).body.events.length, 0);
|
||||
const config = await request('POST', '/admin/api/config', { enabled: false, telemetryEnabled: true, uploadUrl: 'https://test.invalid/', announcement: 'test announcement', changelog: [{ version: '1.2', title: 'Test release', notes: 'test notes' }] }, cookie);
|
||||
assert.equal(config.status, 200);
|
||||
const publicConfig = (await request('GET', '/v1/config')).body;
|
||||
assert.equal(publicConfig.enabled, false);
|
||||
assert.equal(publicConfig.telemetryEnabled, true);
|
||||
assert.equal(publicConfig.changelog[0].title, 'Test release');
|
||||
assert.equal((await request('POST', '/v1/events', {})).status, 403);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
public final class AudioLevelTest {
|
||||
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); System.out.println("ok - " + what); }
|
||||
public static void main(String[] args) {
|
||||
short[] silence = new short[1000];
|
||||
check(AudioLevel.rms(silence, 1000) == 0, "silence rms is zero");
|
||||
check(AudioLevel.verdict(AudioLevel.peak(silence, 1000)).startsWith("SILENT"), "silence flagged");
|
||||
short[] loud = new short[1000]; for (int i = 0; i < loud.length; i++) loud[i] = (short) (i % 2 == 0 ? 16384 : -16384);
|
||||
check(Math.abs(AudioLevel.rms(loud, 1000) - 0.5) < 1e-6, "square wave rms is half scale");
|
||||
check(Math.abs(AudioLevel.peak(loud, 1000) - 0.5) < 1e-6, "peak is half scale");
|
||||
check(Math.abs(AudioLevel.dbfs(0.5) + 6.0206) < 1e-3, "-6 dBFS at half scale");
|
||||
check(AudioLevel.dbfs(0) == -100.0, "dbfs floor");
|
||||
check(AudioLevel.verdict(0.5).startsWith("OK"), "loud is OK");
|
||||
short[] faint = new short[100]; faint[3] = 200;
|
||||
check(AudioLevel.verdict(AudioLevel.peak(faint, 100)).startsWith("VERY QUIET"), "faint flagged quiet");
|
||||
short[] neg = { Short.MIN_VALUE };
|
||||
check(AudioLevel.peak(neg, 1) == 1.0, "min value peak does not overflow");
|
||||
check(AudioLevel.rms(loud, 0) == 0, "zero count safe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class BackupCodecTest {
|
||||
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); System.out.println("ok - " + what); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Map<String, Map<String, Object>> files = new LinkedHashMap<String, Map<String, Object>>();
|
||||
Map<String, Object> ui = new LinkedHashMap<String, Object>();
|
||||
ui.put("theme", 3); ui.put("dark", true); ui.put("ts", 1730000000000L);
|
||||
ui.put("scale", 1.25f); ui.put("name", "MG \"4\" \u00e6\u00f8\u00e5\nline2");
|
||||
ui.put("set", new TreeSet<String>(Arrays.asList("b", "a", "c")));
|
||||
files.put("ui_state", ui);
|
||||
Map<String, Object> trips = new LinkedHashMap<String, Object>();
|
||||
trips.put("interval", 5000);
|
||||
files.put("trip_tracker", trips);
|
||||
|
||||
String json = BackupCodec.encode(files, 1234L, "0.3.0.9");
|
||||
Map<String, Map<String, Object>> back = BackupCodec.decode(json);
|
||||
check(back.equals(files), "round trip preserves every type exactly");
|
||||
check(back.get("ui_state").get("theme") instanceof Integer, "int stays int");
|
||||
check(back.get("ui_state").get("ts") instanceof Long, "long stays long");
|
||||
check(back.get("ui_state").get("scale") instanceof Float, "float stays float");
|
||||
check(back.get("ui_state").get("set") instanceof Set, "string set stays set");
|
||||
check(BackupCodec.countKeys(files) == 7, "key count");
|
||||
check(BackupCodec.createdAt(json) == 1234L, "created_at");
|
||||
|
||||
Map<String, Map<String, Object>> reordered = new LinkedHashMap<String, Map<String, Object>>();
|
||||
reordered.put("trip_tracker", new LinkedHashMap<String, Object>(trips));
|
||||
Map<String, Object> ui2 = new LinkedHashMap<String, Object>(); List<String> keys = new ArrayList<String>(ui.keySet());
|
||||
Collections.reverse(keys); for (String k : keys) ui2.put(k, ui.get(k));
|
||||
reordered.put("ui_state", ui2);
|
||||
check(BackupCodec.fingerprint(files).equals(BackupCodec.fingerprint(reordered)), "fingerprint ignores ordering");
|
||||
ui2.put("theme", 4);
|
||||
check(!BackupCodec.fingerprint(files).equals(BackupCodec.fingerprint(reordered)), "fingerprint detects a change");
|
||||
|
||||
boolean rejected = false;
|
||||
try { BackupCodec.decode("{\"schema\":1,\"type\":\"other\",\"files\":{}}"); } catch (IllegalArgumentException e) { rejected = true; }
|
||||
check(rejected, "wrong type rejected");
|
||||
rejected = false;
|
||||
try { BackupCodec.decode("{\"schema\":99,\"type\":\"mg-utility-settings-backup\",\"files\":{}}"); } catch (IllegalArgumentException e) { rejected = true; }
|
||||
check(rejected, "wrong schema rejected");
|
||||
rejected = false;
|
||||
try { BackupCodec.decode("not json"); } catch (org.json.JSONException e) { rejected = true; }
|
||||
check(rejected, "corrupt file rejected");
|
||||
check(BackupCodec.decode(BackupCodec.encode(new HashMap<String, Map<String, Object>>(), 1L, null)).isEmpty(), "empty backup decodes");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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<String> writes = new ArrayList<String>();
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package cloud.molberg.mgutility;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public final class DashcamPolicyTest {
|
||||
private static int failures;
|
||||
|
||||
private static void check(boolean ok, String name) {
|
||||
if (ok) System.out.println("ok - " + name);
|
||||
else { System.out.println("FAIL - " + name); failures++; }
|
||||
}
|
||||
|
||||
private static final long MIN = 60_000L;
|
||||
private static final long MB = 1024L * 1024L;
|
||||
|
||||
private static DashcamPolicy.Clip clip(String name, long start, long sizeMb) {
|
||||
return new DashcamPolicy.Clip(name, start, start + MIN, sizeMb * MB);
|
||||
}
|
||||
|
||||
private static List<String> names(List<DashcamPolicy.Clip> clips) {
|
||||
List<String> out = new ArrayList<String>();
|
||||
for (DashcamPolicy.Clip c : clips) out.add(c.name);
|
||||
return out;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
long now = 1_800_000_000_000L;
|
||||
long day = DashcamPolicy.DAY_MS;
|
||||
|
||||
// Names round-trip.
|
||||
String name = DashcamPolicy.clipName(now);
|
||||
long parsed = DashcamPolicy.clipStart(name);
|
||||
check(Math.abs(parsed - now) < 1000L, "clip name round-trips to the second");
|
||||
check(DashcamPolicy.clipStart("notes.txt") == -1L, "foreign file ignored");
|
||||
check(DashcamPolicy.clipStart("20261399_000000.mp4") == -1L, "invalid date ignored");
|
||||
|
||||
// Age-based retention deletes only unprotected clips older than the limit.
|
||||
List<DashcamPolicy.Clip> clips = Arrays.asList(
|
||||
clip("old", now - 40 * day, 50),
|
||||
clip("kept-old", now - 35 * day, 50),
|
||||
clip("recent", now - 2 * day, 50));
|
||||
List<DashcamPolicy.Range> tags = Collections.singletonList(
|
||||
new DashcamPolicy.Range(now - 35 * day + 10_000L, now - 35 * day + 20_000L));
|
||||
List<String> del = names(DashcamPolicy.selectForDeletion(clips, tags, now, 0, 30, 0, null));
|
||||
check(del.equals(Collections.singletonList("old")), "30-day retention removes only the old unprotected clip");
|
||||
del = names(DashcamPolicy.selectForDeletion(clips, tags, now, 0, 0, 0, null));
|
||||
check(del.isEmpty(), "retention 0 disables age deletion");
|
||||
|
||||
// Storage cap deletes oldest unprotected first, skips protected and active.
|
||||
List<DashcamPolicy.Clip> cap = Arrays.asList(
|
||||
clip("a", now - 10 * MIN, 100),
|
||||
clip("b", now - 9 * MIN, 100),
|
||||
clip("c", now - 8 * MIN, 100),
|
||||
clip("d", now - 7 * MIN, 100),
|
||||
clip("live", now - MIN, 100));
|
||||
List<DashcamPolicy.Range> keepB = Collections.singletonList(
|
||||
new DashcamPolicy.Range(now - 9 * MIN + 1000L, now - 9 * MIN + 2000L));
|
||||
del = names(DashcamPolicy.selectForDeletion(cap, keepB, now, 300 * MB, 30, 0, "live"));
|
||||
check(del.equals(Arrays.asList("a", "c")), "cap trims oldest unprotected clips: " + del);
|
||||
del = names(DashcamPolicy.selectForDeletion(cap, keepB, now, 300 * MB, 30, 100 * MB, "live"));
|
||||
check(del.equals(Arrays.asList("a", "c", "d")), "headroom for next segment is respected: " + del);
|
||||
del = names(DashcamPolicy.selectForDeletion(cap, keepB, now, 50 * MB, 30, 0, "live"));
|
||||
check(!del.contains("b") && !del.contains("live"), "never deletes protected or active clip even when over cap");
|
||||
check(DashcamPolicy.protectedBytes(cap, keepB) == 100 * MB, "protected bytes counted");
|
||||
|
||||
// Tag spanning a boundary protects both neighbours.
|
||||
List<DashcamPolicy.Range> span = Collections.singletonList(
|
||||
new DashcamPolicy.Range(now - 8 * MIN - 5000L, now - 8 * MIN + 5000L));
|
||||
check(DashcamPolicy.clipsInRange(cap, span.get(0)).size() == 2, "range across boundary covers two clips");
|
||||
|
||||
// Sessions split on gaps.
|
||||
List<DashcamPolicy.Clip> drive = Arrays.asList(
|
||||
clip("s2b", now + MIN, 1), clip("s1a", now - 60 * MIN, 1),
|
||||
clip("s1b", now - 59 * MIN, 1), clip("s2a", now, 1));
|
||||
List<List<DashcamPolicy.Clip>> sessions = DashcamPolicy.sessions(drive, 2 * MIN);
|
||||
check(sessions.size() == 2 && sessions.get(0).size() == 2 && sessions.get(1).get(0).name.equals("s2a"),
|
||||
"clips grouped into drives");
|
||||
|
||||
// Parked footage is trimmed before driving footage, regardless of age.
|
||||
List<DashcamPolicy.Clip> mixed = Arrays.asList(
|
||||
new DashcamPolicy.Clip("drive-old", now - 10 * MIN, now - 9 * MIN, 100 * MB, false),
|
||||
new DashcamPolicy.Clip("parked-new", now - 5 * MIN, now - 4 * MIN, 30 * MB, true),
|
||||
new DashcamPolicy.Clip("parked-newer", now - 3 * MIN, now - 2 * MIN, 30 * MB, true),
|
||||
new DashcamPolicy.Clip("drive-new", now - 2 * MIN, now - MIN, 100 * MB, false));
|
||||
del = names(DashcamPolicy.selectForDeletion(mixed, Collections.<DashcamPolicy.Range>emptyList(), now, 200 * MB, 30, 0, 0, null));
|
||||
check(del.equals(Arrays.asList("parked-new", "parked-newer")), "parked clips go first: " + del);
|
||||
del = names(DashcamPolicy.selectForDeletion(mixed, Collections.<DashcamPolicy.Range>emptyList(), now, 150 * MB, 30, 0, 0, null));
|
||||
check(del.equals(Arrays.asList("parked-new", "parked-newer", "drive-old")), "then oldest driving clip: " + del);
|
||||
List<DashcamPolicy.Clip> aged = Arrays.asList(
|
||||
new DashcamPolicy.Clip("p", now - 5 * day, now - 5 * day, MB, true),
|
||||
new DashcamPolicy.Clip("d", now - 5 * day, now - 5 * day, MB, false));
|
||||
del = names(DashcamPolicy.selectForDeletion(aged, Collections.<DashcamPolicy.Range>emptyList(), now, 0, 30, 3, 0, null));
|
||||
check(del.equals(Collections.singletonList("p")), "parked retention shorter than driving: " + del);
|
||||
|
||||
check(DashcamPolicy.segmentBytes(9_000_000, 60) == 70_875_000L, "segment size estimate");
|
||||
check(DashcamPolicy.minutesForBudget(10L * 1024 * MB, 9_000_000) == 151L, "minutes for 10 GB at 9 Mbit/s");
|
||||
|
||||
if (failures > 0) {
|
||||
System.out.println(failures + " failure(s)");
|
||||
System.exit(1);
|
||||
}
|
||||
System.out.println("DashcamPolicyTest: all tests passed");
|
||||
}
|
||||
}
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import cloud.molberg.mgutility.UsageDataPolicy;
|
||||
|
||||
public final class UsageDataPolicyTest {
|
||||
public static void main(String[] args) {
|
||||
String line = "1720000000.123 123 456 W MgServiceBridge: failed password=hunter2";
|
||||
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", "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");
|
||||
String safe = UsageDataPolicy.redact("token=abc Bearer xyz vin=LSJW1234567890123 https://example.test/?secret=x aa:bb:cc:dd:ee:ff", 1000);
|
||||
check(!safe.contains("abc") && !safe.contains("xyz") && !safe.contains("LSJW") && !safe.contains("example.test") && !safe.contains("aa:bb"), "sensitive fields removed");
|
||||
check(!UsageDataPolicy.redact("Authorization: Bearer sensitive-token", 1000).contains("sensitive-token"), "authorization bearer redacted");
|
||||
check(!UsageDataPolicy.redact("{\"password\":\"secret phrase\",\"token\":\"abc\"}", 1000).contains("secret phrase"), "quoted credentials redacted");
|
||||
check(UsageDataPolicy.redact(null, 10).isEmpty(), "null text");
|
||||
check(UsageDataPolicy.redact("123456", 3).equals("123"), "bounded text");
|
||||
check(UsageDataPolicy.timestamp(line) == 1720000000.123, "log timestamp");
|
||||
System.out.println("UsageDataPolicyTest passed");
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Encrypts like the phone page (public/js/pair.js in mg-utility-telemetry) using WebCrypto.
|
||||
// Usage: node pair-encrypt.mjs <code> <carPublicKeyB64url> <plaintext>
|
||||
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 }));
|
||||
@@ -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
|
||||
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"
|
||||
@@ -4,6 +4,7 @@ ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
OUT=$(mktemp -d)
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
javac -source 8 -target 8 -d "$OUT" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/UsageDataPolicy.java" "$ROOT/tests/UsageDataPolicyTest.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/PushToTalkPress.java" "$ROOT/tests/PushToTalkPressTest.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsCatalog.java" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/VehicleSettingsProfile.java" \
|
||||
@@ -31,6 +32,7 @@ javac -source 8 -target 8 -d "$OUT" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/plugin/PluginSignatureVerifier.java" "$ROOT/src/cloud/molberg/mgutility/plugin/PluginRepositoryIndexParser.java" \
|
||||
"$ROOT/tests/PluginSdkTest.java" "$ROOT/tests/PluginMarketplaceTest.java"
|
||||
java -cp "$OUT" VehicleSettingsCatalogTest
|
||||
java -cp "$OUT" UsageDataPolicyTest
|
||||
java -cp "$OUT" cloud.molberg.mgutility.PushToTalkPressTest
|
||||
java -cp "$OUT" VehicleSettingsCoordinatorTest
|
||||
java -cp "$OUT" cloud.molberg.mgutility.VehiclePowerOffControllerTest
|
||||
@@ -47,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') \
|
||||
@@ -56,3 +64,14 @@ javac -source 8 -target 8 -d "$OUT/audio" \
|
||||
"$ROOT/src/cloud/molberg/mgutility/LiquidSoundBalanceManager.java" \
|
||||
"$ROOT/tests/LiquidAudioIntegrationTest.java"
|
||||
java -cp "$OUT/audio" cloud.molberg.mgutility.LiquidAudioIntegrationTest
|
||||
mkdir -p "$OUT/backup"
|
||||
JSON_JAR=$(find "$HOME/.gradle" -name 'json-20180813.jar' 2>/dev/null | head -n 1)
|
||||
javac -source 8 -target 8 -d "$OUT/backup" "$ROOT/src/cloud/molberg/mgutility/AudioLevel.java" "$ROOT/tests/AudioLevelTest.java"
|
||||
java -cp "$OUT/backup" cloud.molberg.mgutility.AudioLevelTest
|
||||
mkdir -p "$OUT/dashcam"
|
||||
javac -source 8 -target 8 -d "$OUT/dashcam" "$ROOT/src/cloud/molberg/mgutility/DashcamPolicy.java" "$ROOT/tests/DashcamPolicyTest.java"
|
||||
java -cp "$OUT/dashcam" cloud.molberg.mgutility.DashcamPolicyTest
|
||||
if [ -n "$JSON_JAR" ]; then
|
||||
javac -source 8 -target 8 -cp "$JSON_JAR" -d "$OUT/backup" "$ROOT/src/cloud/molberg/mgutility/BackupCodec.java" "$ROOT/tests/BackupCodecTest.java"
|
||||
java -cp "$OUT/backup:$JSON_JAR" cloud.molberg.mgutility.BackupCodecTest
|
||||
fi
|
||||
Vendored
+595
@@ -0,0 +1,595 @@
|
||||
GNU General Public License
|
||||
==========================
|
||||
|
||||
_Version 3, 29 June 2007_
|
||||
_Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license
|
||||
document, but changing it is not allowed.
|
||||
|
||||
## Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other
|
||||
kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away
|
||||
your freedom to share and change the works. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change all versions of a
|
||||
program--to make sure it remains free software for all its users. We, the Free
|
||||
Software Foundation, use the GNU General Public License for most of our software; it
|
||||
applies also to any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General
|
||||
Public Licenses are designed to make sure that you have the freedom to distribute
|
||||
copies of free software (and charge for them if you wish), that you receive source
|
||||
code or can get it if you want it, that you can change the software or use pieces of
|
||||
it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or
|
||||
asking you to surrender the rights. Therefore, you have certain responsibilities if
|
||||
you distribute copies of the software, or if you modify it: responsibilities to
|
||||
respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee,
|
||||
you must pass on to the recipients the same freedoms that you received. You must make
|
||||
sure that they, too, receive or can get the source code. And you must show them these
|
||||
terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
|
||||
copyright on the software, and **(2)** offer you this License giving you legal permission
|
||||
to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is
|
||||
no warranty for this free software. For both users' and authors' sake, the GPL
|
||||
requires that modified versions be marked as changed, so that their problems will not
|
||||
be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of
|
||||
the software inside them, although the manufacturer can do so. This is fundamentally
|
||||
incompatible with the aim of protecting users' freedom to change the software. The
|
||||
systematic pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we have designed
|
||||
this version of the GPL to prohibit the practice for those products. If such problems
|
||||
arise substantially in other domains, we stand ready to extend this provision to
|
||||
those domains in future versions of the GPL, as needed to protect the freedom of
|
||||
users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should
|
||||
not allow patents to restrict development and use of software on general-purpose
|
||||
computers, but in those that do, we wish to avoid the special danger that patents
|
||||
applied to a free program could make it effectively proprietary. To prevent this, the
|
||||
GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
## TERMS AND CONDITIONS
|
||||
|
||||
### 0. Definitions
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“Copyright” also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
“The Program” refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as “you”. “Licensees” and
|
||||
“recipients” may be individuals or organizations.
|
||||
|
||||
To “modify” a work means to copy from or adapt all or part of the work in
|
||||
a fashion requiring copyright permission, other than the making of an exact copy. The
|
||||
resulting work is called a “modified version” of the earlier work or a
|
||||
work “based on” the earlier work.
|
||||
|
||||
A “covered work” means either the unmodified Program or a work based on
|
||||
the Program.
|
||||
|
||||
To “propagate” a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for infringement under
|
||||
applicable copyright law, except executing it on a computer or modifying a private
|
||||
copy. Propagation includes copying, distribution (with or without modification),
|
||||
making available to the public, and in some countries other activities as well.
|
||||
|
||||
To “convey” a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through a computer
|
||||
network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays “Appropriate Legal Notices” to the
|
||||
extent that it includes a convenient and prominently visible feature that **(1)**
|
||||
displays an appropriate copyright notice, and **(2)** tells the user that there is no
|
||||
warranty for the work (except to the extent that warranties are provided), that
|
||||
licensees may convey the work under this License, and how to view a copy of this
|
||||
License. If the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
### 1. Source Code
|
||||
|
||||
The “source code” for a work means the preferred form of the work for
|
||||
making modifications to it. “Object code” means any non-source form of a
|
||||
work.
|
||||
|
||||
A “Standard Interface” means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of interfaces
|
||||
specified for a particular programming language, one that is widely used among
|
||||
developers working in that language.
|
||||
|
||||
The “System Libraries” of an executable work include anything, other than
|
||||
the work as a whole, that **(a)** is included in the normal form of packaging a Major
|
||||
Component, but which is not part of that Major Component, and **(b)** serves only to
|
||||
enable use of the work with that Major Component, or to implement a Standard
|
||||
Interface for which an implementation is available to the public in source code form.
|
||||
A “Major Component”, in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system (if any) on which
|
||||
the executable work runs, or a compiler used to produce the work, or an object code
|
||||
interpreter used to run it.
|
||||
|
||||
The “Corresponding Source” for a work in object code form means all the
|
||||
source code needed to generate, install, and (for an executable work) run the object
|
||||
code and to modify the work, including scripts to control those activities. However,
|
||||
it does not include the work's System Libraries, or general-purpose tools or
|
||||
generally available free programs which are used unmodified in performing those
|
||||
activities but which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for the work, and
|
||||
the source code for shared libraries and dynamically linked subprograms that the work
|
||||
is specifically designed to require, such as by intimate data communication or
|
||||
control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate
|
||||
automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
### 2. Basic Permissions
|
||||
|
||||
All rights granted under this License are granted for the term of copyright on the
|
||||
Program, and are irrevocable provided the stated conditions are met. This License
|
||||
explicitly affirms your unlimited permission to run the unmodified Program. The
|
||||
output from running a covered work is covered by this License only if the output,
|
||||
given its content, constitutes a covered work. This License acknowledges your rights
|
||||
of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without
|
||||
conditions so long as your license otherwise remains in force. You may convey covered
|
||||
works to others for the sole purpose of having them make modifications exclusively
|
||||
for you, or provide you with facilities for running those works, provided that you
|
||||
comply with the terms of this License in conveying all material for which you do not
|
||||
control copyright. Those thus making or running the covered works for you must do so
|
||||
exclusively on your behalf, under your direction and control, on terms that prohibit
|
||||
them from making any copies of your copyrighted material outside their relationship
|
||||
with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions
|
||||
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
|
||||
|
||||
No covered work shall be deemed part of an effective technological measure under any
|
||||
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
|
||||
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
|
||||
of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of
|
||||
technological measures to the extent such circumvention is effected by exercising
|
||||
rights under this License with respect to the covered work, and you disclaim any
|
||||
intention to limit operation or modification of the work as a means of enforcing,
|
||||
against the work's users, your or third parties' legal rights to forbid circumvention
|
||||
of technological measures.
|
||||
|
||||
### 4. Conveying Verbatim Copies
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any
|
||||
medium, provided that you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice; keep intact all notices stating that this License and
|
||||
any non-permissive terms added in accord with section 7 apply to the code; keep
|
||||
intact all notices of the absence of any warranty; and give all recipients a copy of
|
||||
this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer
|
||||
support or warranty protection for a fee.
|
||||
|
||||
### 5. Conveying Modified Source Versions
|
||||
|
||||
You may convey a work based on the Program, or the modifications to produce it from
|
||||
the Program, in the form of source code under the terms of section 4, provided that
|
||||
you also meet all of these conditions:
|
||||
|
||||
* **a)** The work must carry prominent notices stating that you modified it, and giving a
|
||||
relevant date.
|
||||
* **b)** The work must carry prominent notices stating that it is released under this
|
||||
License and any conditions added under section 7. This requirement modifies the
|
||||
requirement in section 4 to “keep intact all notices”.
|
||||
* **c)** You must license the entire work, as a whole, under this License to anyone who
|
||||
comes into possession of a copy. This License will therefore apply, along with any
|
||||
applicable section 7 additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no permission to license the
|
||||
work in any other way, but it does not invalidate such permission if you have
|
||||
separately received it.
|
||||
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
|
||||
Notices; however, if the Program has interactive interfaces that do not display
|
||||
Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are
|
||||
not by their nature extensions of the covered work, and which are not combined with
|
||||
it such as to form a larger program, in or on a volume of a storage or distribution
|
||||
medium, is called an “aggregate” if the compilation and its resulting
|
||||
copyright are not used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work in an aggregate
|
||||
does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
### 6. Conveying Non-Source Forms
|
||||
|
||||
You may convey a covered work in object code form under the terms of sections 4 and
|
||||
5, provided that you also convey the machine-readable Corresponding Source under the
|
||||
terms of this License, in one of these ways:
|
||||
|
||||
* **a)** Convey the object code in, or embodied in, a physical product (including a
|
||||
physical distribution medium), accompanied by the Corresponding Source fixed on a
|
||||
durable physical medium customarily used for software interchange.
|
||||
* **b)** Convey the object code in, or embodied in, a physical product (including a
|
||||
physical distribution medium), accompanied by a written offer, valid for at least
|
||||
three years and valid for as long as you offer spare parts or customer support for
|
||||
that product model, to give anyone who possesses the object code either **(1)** a copy of
|
||||
the Corresponding Source for all the software in the product that is covered by this
|
||||
License, on a durable physical medium customarily used for software interchange, for
|
||||
a price no more than your reasonable cost of physically performing this conveying of
|
||||
source, or **(2)** access to copy the Corresponding Source from a network server at no
|
||||
charge.
|
||||
* **c)** Convey individual copies of the object code with a copy of the written offer to
|
||||
provide the Corresponding Source. This alternative is allowed only occasionally and
|
||||
noncommercially, and only if you received the object code with such an offer, in
|
||||
accord with subsection 6b.
|
||||
* **d)** Convey the object code by offering access from a designated place (gratis or for
|
||||
a charge), and offer equivalent access to the Corresponding Source in the same way
|
||||
through the same place at no further charge. You need not require recipients to copy
|
||||
the Corresponding Source along with the object code. If the place to copy the object
|
||||
code is a network server, the Corresponding Source may be on a different server
|
||||
(operated by you or a third party) that supports equivalent copying facilities,
|
||||
provided you maintain clear directions next to the object code saying where to find
|
||||
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
|
||||
you remain obligated to ensure that it is available for as long as needed to satisfy
|
||||
these requirements.
|
||||
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
|
||||
other peers where the object code and Corresponding Source of the work are being
|
||||
offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the
|
||||
Corresponding Source as a System Library, need not be included in conveying the
|
||||
object code work.
|
||||
|
||||
A “User Product” is either **(1)** a “consumer product”, which
|
||||
means any tangible personal property which is normally used for personal, family, or
|
||||
household purposes, or **(2)** anything designed or sold for incorporation into a
|
||||
dwelling. In determining whether a product is a consumer product, doubtful cases
|
||||
shall be resolved in favor of coverage. For a particular product received by a
|
||||
particular user, “normally used” refers to a typical or common use of
|
||||
that class of product, regardless of the status of the particular user or of the way
|
||||
in which the particular user actually uses, or expects or is expected to use, the
|
||||
product. A product is a consumer product regardless of whether the product has
|
||||
substantial commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
“Installation Information” for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install and execute
|
||||
modified versions of a covered work in that User Product from a modified version of
|
||||
its Corresponding Source. The information must suffice to ensure that the continued
|
||||
functioning of the modified object code is in no case prevented or interfered with
|
||||
solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for
|
||||
use in, a User Product, and the conveying occurs as part of a transaction in which
|
||||
the right of possession and use of the User Product is transferred to the recipient
|
||||
in perpetuity or for a fixed term (regardless of how the transaction is
|
||||
characterized), the Corresponding Source conveyed under this section must be
|
||||
accompanied by the Installation Information. But this requirement does not apply if
|
||||
neither you nor any third party retains the ability to install modified object code
|
||||
on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to
|
||||
continue to provide support service, warranty, or updates for a work that has been
|
||||
modified or installed by the recipient, or for the User Product in which it has been
|
||||
modified or installed. Access to a network may be denied when the modification itself
|
||||
materially and adversely affects the operation of the network or violates the rules
|
||||
and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with
|
||||
this section must be in a format that is publicly documented (and with an
|
||||
implementation available to the public in source code form), and must require no
|
||||
special password or key for unpacking, reading or copying.
|
||||
|
||||
### 7. Additional Terms
|
||||
|
||||
“Additional permissions” are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions. Additional
|
||||
permissions that are applicable to the entire Program shall be treated as though they
|
||||
were included in this License, to the extent that they are valid under applicable
|
||||
law. If additional permissions apply only to part of the Program, that part may be
|
||||
used separately under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any
|
||||
additional permissions from that copy, or from any part of it. (Additional
|
||||
permissions may be written to require their own removal in certain cases when you
|
||||
modify the work.) You may place additional permissions on material, added by you to a
|
||||
covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a
|
||||
covered work, you may (if authorized by the copyright holders of that material)
|
||||
supplement the terms of this License with terms:
|
||||
|
||||
* **a)** Disclaiming warranty or limiting liability differently from the terms of
|
||||
sections 15 and 16 of this License; or
|
||||
* **b)** Requiring preservation of specified reasonable legal notices or author
|
||||
attributions in that material or in the Appropriate Legal Notices displayed by works
|
||||
containing it; or
|
||||
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
|
||||
modified versions of such material be marked in reasonable ways as different from the
|
||||
original version; or
|
||||
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
|
||||
material; or
|
||||
* **e)** Declining to grant rights under trademark law for use of some trade names,
|
||||
trademarks, or service marks; or
|
||||
* **f)** Requiring indemnification of licensors and authors of that material by anyone
|
||||
who conveys the material (or modified versions of it) with contractual assumptions of
|
||||
liability to the recipient, for any liability that these contractual assumptions
|
||||
directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered “further
|
||||
restrictions” within the meaning of section 10. If the Program as you received
|
||||
it, or any part of it, contains a notice stating that it is governed by this License
|
||||
along with a term that is a further restriction, you may remove that term. If a
|
||||
license document contains a further restriction but permits relicensing or conveying
|
||||
under this License, you may add to a covered work material governed by the terms of
|
||||
that license document, provided that the further restriction does not survive such
|
||||
relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in
|
||||
the relevant source files, a statement of the additional terms that apply to those
|
||||
files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a
|
||||
separately written license, or stated as exceptions; the above requirements apply
|
||||
either way.
|
||||
|
||||
### 8. Termination
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under
|
||||
this License. Any attempt otherwise to propagate or modify it is void, and will
|
||||
automatically terminate your rights under this License (including any patent licenses
|
||||
granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a
|
||||
particular copyright holder is reinstated **(a)** provisionally, unless and until the
|
||||
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
|
||||
if the copyright holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently
|
||||
if the copyright holder notifies you of the violation by some reasonable means, this
|
||||
is the first time you have received notice of violation of this License (for any
|
||||
work) from that copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of
|
||||
parties who have received copies or rights from you under this License. If your
|
||||
rights have been terminated and not permanently reinstated, you do not qualify to
|
||||
receive new licenses for the same material under section 10.
|
||||
|
||||
### 9. Acceptance Not Required for Having Copies
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the
|
||||
Program. Ancillary propagation of a covered work occurring solely as a consequence of
|
||||
using peer-to-peer transmission to receive a copy likewise does not require
|
||||
acceptance. However, nothing other than this License grants you permission to
|
||||
propagate or modify any covered work. These actions infringe copyright if you do not
|
||||
accept this License. Therefore, by modifying or propagating a covered work, you
|
||||
indicate your acceptance of this License to do so.
|
||||
|
||||
### 10. Automatic Licensing of Downstream Recipients
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license
|
||||
from the original licensors, to run, modify and propagate that work, subject to this
|
||||
License. You are not responsible for enforcing compliance by third parties with this
|
||||
License.
|
||||
|
||||
An “entity transaction” is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an organization, or
|
||||
merging organizations. If propagation of a covered work results from an entity
|
||||
transaction, each party to that transaction who receives a copy of the work also
|
||||
receives whatever licenses to the work the party's predecessor in interest had or
|
||||
could give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if the predecessor
|
||||
has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or
|
||||
affirmed under this License. For example, you may not impose a license fee, royalty,
|
||||
or other charge for exercise of rights granted under this License, and you may not
|
||||
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that any patent claim is infringed by making, using, selling, offering for sale, or
|
||||
importing the Program or any portion of it.
|
||||
|
||||
### 11. Patents
|
||||
|
||||
A “contributor” is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The work thus
|
||||
licensed is called the contributor's “contributor version”.
|
||||
|
||||
A contributor's “essential patent claims” are all patent claims owned or
|
||||
controlled by the contributor, whether already acquired or hereafter acquired, that
|
||||
would be infringed by some manner, permitted by this License, of making, using, or
|
||||
selling its contributor version, but do not include claims that would be infringed
|
||||
only as a consequence of further modification of the contributor version. For
|
||||
purposes of this definition, “control” includes the right to grant patent
|
||||
sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
|
||||
under the contributor's essential patent claims, to make, use, sell, offer for sale,
|
||||
import and otherwise run, modify and propagate the contents of its contributor
|
||||
version.
|
||||
|
||||
In the following three paragraphs, a “patent license” is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent (such as an
|
||||
express permission to practice a patent or covenant not to sue for patent
|
||||
infringement). To “grant” such a patent license to a party means to make
|
||||
such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the
|
||||
Corresponding Source of the work is not available for anyone to copy, free of charge
|
||||
and under the terms of this License, through a publicly available network server or
|
||||
other readily accessible means, then you must either **(1)** cause the Corresponding
|
||||
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or **(3)** arrange, in a manner consistent with
|
||||
the requirements of this License, to extend the patent license to downstream
|
||||
recipients. “Knowingly relying” means you have actual knowledge that, but
|
||||
for the patent license, your conveying the covered work in a country, or your
|
||||
recipient's use of the covered work in a country, would infringe one or more
|
||||
identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you
|
||||
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
|
||||
license to some of the parties receiving the covered work authorizing them to use,
|
||||
propagate, modify or convey a specific copy of the covered work, then the patent
|
||||
license you grant is automatically extended to all recipients of the covered work and
|
||||
works based on it.
|
||||
|
||||
A patent license is “discriminatory” if it does not include within the
|
||||
scope of its coverage, prohibits the exercise of, or is conditioned on the
|
||||
non-exercise of one or more of the rights that are specifically granted under this
|
||||
License. You may not convey a covered work if you are a party to an arrangement with
|
||||
a third party that is in the business of distributing software, under which you make
|
||||
payment to the third party based on the extent of your activity of conveying the
|
||||
work, and under which the third party grants, to any of the parties who would receive
|
||||
the covered work from you, a discriminatory patent license **(a)** in connection with
|
||||
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
|
||||
primarily for and in connection with specific products or compilations that contain
|
||||
the covered work, unless you entered into that arrangement, or that patent license
|
||||
was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied
|
||||
license or other defenses to infringement that may otherwise be available to you
|
||||
under applicable patent law.
|
||||
|
||||
### 12. No Surrender of Others' Freedom
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise)
|
||||
that contradict the conditions of this License, they do not excuse you from the
|
||||
conditions of this License. If you cannot convey a covered work so as to satisfy
|
||||
simultaneously your obligations under this License and any other pertinent
|
||||
obligations, then as a consequence you may not convey it at all. For example, if you
|
||||
agree to terms that obligate you to collect a royalty for further conveying from
|
||||
those to whom you convey the Program, the only way you could satisfy both those terms
|
||||
and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
### 13. Use with the GNU Affero General Public License
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or
|
||||
combine any covered work with a work licensed under version 3 of the GNU Affero
|
||||
General Public License into a single combined work, and to convey the resulting work.
|
||||
The terms of this License will continue to apply to the part which is the covered
|
||||
work, but the special requirements of the GNU Affero General Public License, section
|
||||
13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
### 14. Revised Versions of this License
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU
|
||||
General Public License from time to time. Such new versions will be similar in spirit
|
||||
to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that
|
||||
a certain numbered version of the GNU General Public License “or any later
|
||||
version” applies to it, you have the option of following the terms and
|
||||
conditions either of that numbered version or of any later version published by the
|
||||
Free Software Foundation. If the Program does not specify a version number of the GNU
|
||||
General Public License, you may choose any version ever published by the Free
|
||||
Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU
|
||||
General Public License can be used, that proxy's public statement of acceptance of a
|
||||
version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no
|
||||
additional obligations are imposed on any author or copyright holder as a result of
|
||||
your choosing to follow a later version.
|
||||
|
||||
### 15. Disclaimer of Warranty
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
|
||||
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
|
||||
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
### 16. Limitation of Liability
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
|
||||
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
|
||||
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
|
||||
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
|
||||
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
|
||||
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
### 17. Interpretation of Sections 15 and 16
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be
|
||||
given local legal effect according to their terms, reviewing courts shall apply local
|
||||
law that most closely approximates an absolute waiver of all civil liability in
|
||||
connection with the Program, unless a warranty or assumption of liability accompanies
|
||||
a copy of the Program in return for a fee.
|
||||
|
||||
_END OF TERMS AND CONDITIONS_
|
||||
|
||||
## How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to
|
||||
the public, the best way to achieve this is to make it free software which everyone
|
||||
can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them
|
||||
to the start of each source file to most effectively state the exclusion of warranty;
|
||||
and each file should have at least the “copyright” line and a pointer to
|
||||
where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type 'show c' for details.
|
||||
|
||||
The hypothetical commands `show w` and `show c` should show the appropriate parts of
|
||||
the General Public License. Of course, your program's commands might be different;
|
||||
for a GUI interface, you would use an “about box”.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to
|
||||
sign a “copyright disclaimer” for the program, if necessary. For more
|
||||
information on this, and how to apply and follow the GNU GPL, see
|
||||
<<http://www.gnu.org/licenses/>>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may consider it
|
||||
more useful to permit linking proprietary applications with the library. If this is
|
||||
what you want to do, use the GNU Lesser General Public License instead of this
|
||||
License. But first, please read
|
||||
<<http://www.gnu.org/philosophy/why-not-lgpl.html>>.
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
# MG4 dashcam native capture
|
||||
|
||||
`src/` is the native part of [Tommasov/MG4_Dashcam](https://github.com/Tommasov/MG4_Dashcam)
|
||||
(itself a fork of [jamakr4/MG4-360-Camera-App](https://github.com/jamakr4/MG4-360-Camera-App)),
|
||||
at the upstream commit recorded in `UPSTREAM_COMMIT`. It reads the four factory cameras from
|
||||
`/dev/video14..17`, composes them into one 1440x1040 grid with a time/speed footer, and encodes
|
||||
H.264 MP4 segments with `AMediaCodec`.
|
||||
|
||||
The only change from upstream is the JNI symbol prefix
|
||||
(`Java_com_drivehub_kamera_CameraProbe_*` → `Java_cloud_molberg_mgutility_DashcamNative_*`) and
|
||||
the library name (`libmgdashcam.so`). Licence: GPL-3.0, see `LICENSE`.
|
||||
|
||||
`prebuilt/arm64-v8a/libmgdashcam.so` is built from `src/` with `build-native.sh` (NDK r28,
|
||||
OpenCV 4.9.0 static, `c++_static`) and stripped. `build.sh` packages it into the APK, so a normal
|
||||
build needs no NDK or OpenCV.
|
||||
|
||||
Access to `/dev/video*` comes from the platform signature + `android.uid.system`, which MG Utility
|
||||
already uses.
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
fe6338ca2f1400151fe01905a8d1c88db905d5f5 2026-11-09 15:25:43 +0100
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Rebuilds prebuilt/arm64-v8a/libmgdashcam.so from src/ (Tommasov/MG4_Dashcam native capture,
|
||||
# GPL-3.0, JNI names moved to cloud.molberg.mgutility.DashcamNative).
|
||||
#
|
||||
# Needs: Android NDK r28 + CMake 3.22 from the SDK, and the OpenCV 4.9.0 Android SDK:
|
||||
# curl -LO https://github.com/opencv/opencv/releases/download/4.9.0/opencv-4.9.0-android-sdk.zip
|
||||
# OPENCV_ANDROID_SDK=/path/to/OpenCV-android-sdk ./build-native.sh
|
||||
# build.sh only packages the prebuilt; run this when src/ changes and commit the result.
|
||||
set -eu
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
SDK=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/opt/android-sdk}}
|
||||
NDK=${ANDROID_NDK:-$(find "$SDK/ndk" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -n 1)}
|
||||
CMAKE_DIR=$(find "$SDK/cmake" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -n 1)
|
||||
: "${OPENCV_ANDROID_SDK:?set OPENCV_ANDROID_SDK to the unpacked OpenCV-android-sdk directory}"
|
||||
OUT=$(mktemp -d)
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
"$CMAKE_DIR/bin/cmake" -S "$HERE/src" -B "$OUT" -G Ninja \
|
||||
-DCMAKE_MAKE_PROGRAM="$CMAKE_DIR/bin/ninja" \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \
|
||||
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-28 -DANDROID_STL=c++_static \
|
||||
-DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS=-std=c++17 \
|
||||
-DOPENCV_ANDROID_SDK="$OPENCV_ANDROID_SDK"
|
||||
"$CMAKE_DIR/bin/cmake" --build "$OUT"
|
||||
mkdir -p "$HERE/prebuilt/arm64-v8a"
|
||||
"$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip" --strip-unneeded \
|
||||
-o "$HERE/prebuilt/arm64-v8a/libmgdashcam.so" "$OUT/libmgdashcam.so"
|
||||
sha256sum "$HERE/prebuilt/arm64-v8a/libmgdashcam.so"
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user