mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-26 14:55:11 +08:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0defb30c6a | |||
| bcafa532a2 | |||
| 667fb666b9 | |||
| 32f49f8527 | |||
| 8e521e6992 | |||
| f8214fe6c6 | |||
| 258cbb76ec | |||
| c7c07799d3 | |||
| 7f7dbc6a65 | |||
| 2e68e2d926 | |||
| 0623c1a0f2 | |||
| 69999fa6cc | |||
| 1f60231a84 | |||
| a651454e7d | |||
| 8928743749 | |||
| 148cba7260 | |||
| d9127cf936 | |||
| 6d51c06692 | |||
| 3a5d376b54 | |||
| c7fb5d545d | |||
| 9d36f4cd0d | |||
| 8693affef0 | |||
| df68b82a5e | |||
| 3980401632 | |||
| 7f48d7c53b | |||
| 6e83349fe2 | |||
| 89c189e528 | |||
| 698496dd60 | |||
| 4d4ed2b3da | |||
| a49d8772f3 | |||
| 639450281e | |||
| dc8d448b35 | |||
| 2a12dbd0ad |
@@ -133,6 +133,10 @@ function launch {
|
||||
# start manager
|
||||
cd system/manager
|
||||
|
||||
if [ -f /AGNOS ]; then
|
||||
timeout 15s python3 "$DIR/tools/galaxy_bluetooth/settings_backup.py" || echo "Galaxy settings backup unavailable"
|
||||
fi
|
||||
|
||||
sp_launch_timing "launch_param_migrations_start"
|
||||
if ! python3 ./launch_param_migrations.py; then
|
||||
echo "Launch param migrations failed; continuing boot."
|
||||
|
||||
@@ -16,6 +16,7 @@ from openpilot.system.ui.lib.wifi_manager import WifiManager
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.system.ui.widgets.bluetooth import BluetoothManagerUI
|
||||
from openpilot.system.ui.widgets.network import NetworkUI
|
||||
from openpilot.tools.galaxy_bluetooth.comma_pairing_tici import pair_phone_item
|
||||
|
||||
# Constants
|
||||
COLLAPSED_WIDTH = 0
|
||||
@@ -80,7 +81,7 @@ class SettingsLayout(Widget):
|
||||
PanelType.STARPILOT: PanelInfo(tr_noop("StarPilot"), StarPilotLayout()),
|
||||
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayout()),
|
||||
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUI(wifi_manager)),
|
||||
PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothManagerUI(bluetooth_manager)),
|
||||
PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothManagerUI(bluetooth_manager, phone_pairing=pair_phone_item())),
|
||||
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout()),
|
||||
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayout()),
|
||||
PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayout()),
|
||||
|
||||
@@ -6,6 +6,7 @@ from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, Bi
|
||||
from openpilot.system.ui.lib.application import FontWeight, MousePos, gui_app
|
||||
from openpilot.system.ui.lib.bluetooth_manager import BluetoothManager
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
from openpilot.tools.galaxy_bluetooth.comma_pairing import PairPhoneButton
|
||||
|
||||
|
||||
class BluetoothDeviceButton(BigButton):
|
||||
@@ -149,9 +150,10 @@ class BluetoothLayoutMici(NavScroller):
|
||||
self._scan_btn = BigButton("scan for devices", "scan", self._dialog_icon, scroll=True)
|
||||
self._scan_btn.set_click_callback(lambda: self._manager.set_scanning(True))
|
||||
self._scanning_btn = BluetoothScanningButton()
|
||||
self._pair_phone_btn = PairPhoneButton()
|
||||
self._device_buttons = {}
|
||||
self._scan_on_ready = False
|
||||
self._scroller.add_widgets([self._power_btn, self._scan_btn, self._scanning_btn])
|
||||
self._scroller.add_widgets([self._power_btn, self._pair_phone_btn, self._scan_btn, self._scanning_btn])
|
||||
self._rebuild()
|
||||
|
||||
def show_event(self):
|
||||
@@ -177,7 +179,7 @@ class BluetoothLayoutMici(NavScroller):
|
||||
self._power_btn.set_value("on" if status.enabled else "off")
|
||||
self._power_btn.set_enabled(status.available and status.offroad)
|
||||
self._scan_btn.set_enabled(status.enabled and status.offroad)
|
||||
items = [self._power_btn]
|
||||
items = [self._power_btn, self._pair_phone_btn]
|
||||
for device in status.devices:
|
||||
button = self._device_buttons.get(device.address)
|
||||
if button is None:
|
||||
|
||||
@@ -9,6 +9,8 @@ from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.selfdrive.ui.stall_monitor import UIStallMonitor
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
|
||||
from openpilot.tools.galaxy_bluetooth.companion import publish_telemetry
|
||||
|
||||
BIG_UI = gui_app.big_ui()
|
||||
|
||||
|
||||
@@ -76,6 +78,7 @@ def main():
|
||||
stall_monitor.progress("ui.after_watchdog")
|
||||
ui_state.update(progress_hook=stall_monitor.progress)
|
||||
stall_monitor.progress("ui.after_state_update")
|
||||
publish_telemetry(ui_state, gui_app)
|
||||
now = time.monotonic()
|
||||
if now - context_update_time >= 1.0:
|
||||
stall_monitor.set_context(_stall_context())
|
||||
@@ -96,3 +99,4 @@ def main():
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
@@ -134,6 +134,13 @@ function normalizeGithubRemote(remoteValue, commitsUrlValue = "") {
|
||||
return remote
|
||||
}
|
||||
|
||||
function branchLabel(branch) {
|
||||
const remote = normalizeGithubRemote(state.status?.originRemote, state.status?.commitsUrl)
|
||||
return remote.toLowerCase() === "https://github.com/natehuby76/starpilotbt" && branch === "Nate/galaxy-bluetooth"
|
||||
? "Nate's BT Build"
|
||||
: branch
|
||||
}
|
||||
|
||||
function currentOrSelectedBranchForCommits() {
|
||||
const selected = String(state.selectedBranch || "").trim()
|
||||
if (selected) return selected
|
||||
@@ -152,7 +159,7 @@ function activeCommitsUrl() {
|
||||
function activeCommitsLabel() {
|
||||
const branch = currentOrSelectedBranchForCommits()
|
||||
return branch
|
||||
? `View latest commit for the "${branch}" branch`
|
||||
? `View latest commit for "${branchLabel(branch)}"`
|
||||
: "View latest commit for this branch"
|
||||
}
|
||||
|
||||
@@ -785,7 +792,7 @@ export function UpdateManager() {
|
||||
${() => !state.loading ? html`
|
||||
<div class="updateCard">
|
||||
<div class="updateGrid">
|
||||
<p><strong>Current Branch:</strong> ${state.status?.branch || "Unknown"}</p>
|
||||
<p><strong>Current Branch:</strong> ${branchLabel(state.status?.branch) || "Unknown"}</p>
|
||||
<p><strong>Installed Commit:</strong> ${shortHash(state.status?.localCommit)}</p>
|
||||
<p><strong>Latest Commit:</strong> ${shortHash(state.status?.remoteCommit)}</p>
|
||||
<p><strong>Update Available:</strong> ${state.status?.updateAvailable ? "Yes" : "No"}</p>
|
||||
@@ -872,7 +879,7 @@ export function UpdateManager() {
|
||||
}
|
||||
}}">
|
||||
${() => state.branches.length
|
||||
? state.branches.map((branch) => html`<option value="${branch}" selected="${() => branch === state.selectedBranch || false}">${branch}${branch === state.status?.branch ? " (current)" : ""}</option>`)
|
||||
? state.branches.map((branch) => html`<option value="${branch}" selected="${() => branch === state.selectedBranch || false}">${branchLabel(branch)}${branch === state.status?.branch ? " (current)" : ""}</option>`)
|
||||
: html`<option value="">No branches found</option>`
|
||||
}
|
||||
</select>
|
||||
|
||||
@@ -10734,6 +10734,8 @@ def main():
|
||||
|
||||
app = Flask(__name__, static_folder="assets", static_url_path="/assets")
|
||||
setup(app)
|
||||
from openpilot.tools.galaxy_bluetooth.companion import register_routes
|
||||
register_routes(app)
|
||||
threading.Thread(target=_testing_ground_custom_reserved_worker, daemon=True).start()
|
||||
|
||||
# Desktop-only debug mode. On-device must stay on 8082 to match Galaxy FRP routing.
|
||||
@@ -10751,3 +10753,4 @@ def main():
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
@@ -219,6 +219,7 @@ procs = [
|
||||
procs += [
|
||||
PythonProcess("bluetooth_managerd", "starpilot.system.bluetooth.daemon", bluetooth_enabled, enabled=TICI),
|
||||
PythonProcess("wheel_controlsd", "starpilot.system.wheel_controls.wheel_controlsd", wheel_controls_enabled, enabled=TICI, nice=19),
|
||||
PythonProcess("galaxy_ble_setup", "tools.galaxy_bluetooth.bootstrap", always_run, enabled=not PC, nice=19),
|
||||
PythonProcess("the_galaxy", "starpilot.system.the_galaxy.the_galaxy", always_run, nice=10),
|
||||
PythonProcess("galaxy", "starpilot.system.galaxy.galaxy", always_run, nice=10),
|
||||
]
|
||||
|
||||
@@ -1161,6 +1161,8 @@ class GuiApplication:
|
||||
if self._grid_size > 0:
|
||||
self._draw_grid()
|
||||
|
||||
from openpilot.tools.galaxy_bluetooth.companion import capture_frame
|
||||
capture_frame()
|
||||
self._mark_progress("gui_app.before_end_drawing")
|
||||
rl.end_drawing()
|
||||
self._mark_progress("gui_app.after_end_drawing")
|
||||
@@ -1411,3 +1413,4 @@ class GuiApplication:
|
||||
|
||||
|
||||
gui_app = GuiApplication()
|
||||
|
||||
|
||||
@@ -177,8 +177,9 @@ class BluetoothAudioTestDialog(Widget):
|
||||
|
||||
class BluetoothManagerUI(Widget):
|
||||
"""Big UI Bluetooth settings panel backed by the existing Bluetooth manager daemon."""
|
||||
def __init__(self, manager: BluetoothManager):
|
||||
def __init__(self, manager: BluetoothManager, phone_pairing: Widget | None = None):
|
||||
super().__init__()
|
||||
self._phone_pairing = phone_pairing
|
||||
self._manager = manager
|
||||
self._scroll_panel = GuiScrollPanel()
|
||||
self._power_toggle = Toggle(initial_state=False, callback=self._toggle_power)
|
||||
@@ -378,7 +379,11 @@ class BluetoothManagerUI(Widget):
|
||||
header_rect = rl.Rectangle(rect.x, rect.y, rect.width, HEADER_HEIGHT)
|
||||
self._render_header(header_rect, status)
|
||||
|
||||
content_rect = rl.Rectangle(rect.x, rect.y + HEADER_HEIGHT, rect.width, rect.height - HEADER_HEIGHT)
|
||||
content_y = rect.y + HEADER_HEIGHT
|
||||
if self._phone_pairing is not None:
|
||||
self._phone_pairing.render(rl.Rectangle(rect.x + HEADER_PADDING, content_y, rect.width - 2 * HEADER_PADDING, ITEM_HEIGHT))
|
||||
content_y += ITEM_HEIGHT
|
||||
content_rect = rl.Rectangle(rect.x, content_y, rect.width, rect.y + rect.height - content_y)
|
||||
if not status.available:
|
||||
gui_label(content_rect, tr("Bluetooth is not available on this device."), font_size=62,
|
||||
color=TEXT_SECONDARY, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
.DS_Store
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
DerivedData/
|
||||
xcuserdata/
|
||||
pairing.json
|
||||
@@ -0,0 +1,97 @@
|
||||
# Run this fork as the installed StarPilot on comma
|
||||
|
||||
The pilot branch is based on the user's installed upstream Dom commit
|
||||
`15bbbf3cc4ad251c173abf01fff931951202331a`. Its tree differs from that version
|
||||
under `tools/galaxy_bluetooth` plus phone-pairing, diagnostics and screen-capture
|
||||
hooks. Driving-control code and prebuilt files are retained from Dom.
|
||||
This establishes source equality for driving code, not new road testing.
|
||||
|
||||
Run the following in the comma SSH terminal while parked. The existing theme
|
||||
changes are outside the added folder and can remain in the checkout. Commands
|
||||
use normal Git switching; they do not force-reset or delete your changes. If Git
|
||||
reports a conflict, stop and inspect it rather than forcing the switch.
|
||||
|
||||
## Switch the installed repository
|
||||
|
||||
```sh
|
||||
git -C /data/openpilot remote add galaxy-bt https://github.com/natehuby76/StarPilotBT.git
|
||||
git -C /data/openpilot fetch galaxy-bt refs/heads/Nate/galaxy-bluetooth:refs/remotes/galaxy-bt/Nate/galaxy-bluetooth
|
||||
git -C /data/openpilot switch --track galaxy-bt/Nate/galaxy-bluetooth
|
||||
git -C /data/openpilot remote set-url origin https://github.com/natehuby76/StarPilotBT.git
|
||||
git -C /data/openpilot config branch.Nate/galaxy-bluetooth.remote origin
|
||||
git -C /data/openpilot config branch.Nate/galaxy-bluetooth.merge refs/heads/Nate/galaxy-bluetooth
|
||||
```
|
||||
|
||||
Run one command at a time, stopping on an error. The remote-add step is needed
|
||||
only once. Setting origin and branch tracking to this fork makes subsequent
|
||||
updates target this fork/branch rather than upstream Dom.
|
||||
|
||||
Check the result:
|
||||
|
||||
```sh
|
||||
git -C /data/openpilot branch --show-current
|
||||
git -C /data/openpilot remote get-url origin
|
||||
```
|
||||
|
||||
Expected branch: `Nate/galaxy-bluetooth`. Expected origin:
|
||||
`https://github.com/natehuby76/StarPilotBT.git`.
|
||||
|
||||
## Automatic Bluetooth setup
|
||||
|
||||
Restart comma after switching to the pilot branch. While parked, the branch
|
||||
installs the bridge in `/data/galaxy-ble/venv`, preserves its pairing key and
|
||||
starts it automatically. First setup needs internet on comma. Later boots work
|
||||
offline unless dependencies need updating. No `/data/continue.sh` edits or
|
||||
manual service installation are needed. An older background service hook may
|
||||
remain; startup is idempotent.
|
||||
|
||||
In Settings → Bluetooth → Pair phone, check setup status. Enable Bluetooth on
|
||||
comma. If setup fails, connect comma to internet and choose Retry setup.
|
||||
Installation errors are in `/data/galaxy-ble/setup.log`; bridge errors are in
|
||||
`sudo journalctl -u galaxy-ble-fork.service -b --no-pager`.
|
||||
|
||||
## Existing settings
|
||||
|
||||
Bluetooth setup does not write or reset StarPilot parameters. Before the usual
|
||||
launch migrations, the first boot with this feature privately saves persistent
|
||||
parameters and caches to `/data/galaxy-ble/settings-before-pilot.tar.gz`. It keeps
|
||||
the first successful snapshot across boots and updates. This contains private
|
||||
credentials: do not send it with tester logs. A failed snapshot is reported in
|
||||
the startup log and retried on the next boot; it does not clear existing settings.
|
||||
|
||||
The pilot retains Dom's existing migrations. Switching from a different version
|
||||
may run those migrations and change individual settings. Check driving settings
|
||||
after switching. The snapshot is for recovery with assistance; automatic restore
|
||||
could overwrite newer settings and is intentionally absent. Factory flashing is
|
||||
a separate operation and may erase device data.
|
||||
|
||||
## Pair a phone without copying a key
|
||||
|
||||
On comma 4 while offroad, open Settings → Bluetooth → Pair phone → pair phone. In the updated
|
||||
iPhone app, choose Scan pairing code, allow camera access and scan the displayed
|
||||
code. Select the comma found by Bluetooth. The app saves the key in Keychain only
|
||||
after its encrypted bridge handshake succeeds. No internet is needed to scan.
|
||||
Enable Bluetooth in StarPilot and wait for automatic setup to show Ready to pair. A native iPhone app rebuild is required for scanning.
|
||||
|
||||
The QR contains a private shared Bluetooth key, not a Galaxy web link. Keep it
|
||||
private. The display closes after two minutes or when going onroad; this hides
|
||||
the code but does not expire the shared credential. Multiple phones may share
|
||||
it. Settings → Bluetooth → Pair phone → forget paired phones requires a confirmation slide
|
||||
and replaces the key atomically. The bridge closes old sessions and rejects old
|
||||
keys without restarting its Bluetooth advertisement. Previously accepted setting
|
||||
requests cannot be undone by revocation. Revocation affects this BLE bridge, not
|
||||
Galaxy's existing web password, cloud sessions or iPhone Bluetooth bonds.
|
||||
|
||||
Pilot validation: iOS generic build and automated QR parsing/key preservation,
|
||||
rotation, old-key rejection and permission checks. Actual comma screen, camera
|
||||
scanning and revoke/re-pair hardware checks remain required.
|
||||
|
||||
## Comma 3X pilot
|
||||
|
||||
The same branch and automatic bridge setup apply. Enable Bluetooth in Settings, then pair from **Settings → Bluetooth → Pair phone**. Run `tools/galaxy_bluetooth/bridge/probe.py` with `/data/galaxy-ble/venv/bin/python` and send the report before testing. Physical 3X validation is still pending. See `ios/QUICK-START.md` for the reboot, revocation and Live View checks.
|
||||
|
||||
## Updates from Galaxy
|
||||
|
||||
Galaxy labels `Nate/galaxy-bluetooth` in this fork as **Nate's BT Build**. Advanced Updates lists branches from the installed repository's `origin`; this fork will not appear on devices whose origin still points to official StarPilot. Complete the fork switch and bridge/boot setup above once per comma.
|
||||
|
||||
After setup, open Galaxy's Update Manager, check for updates and follow its confirmation/reboot steps while parked. The comma must have internet through Wi-Fi, a phone hotspot or its own cellular connection. The phone may send the update request over Bluetooth, but Bluetooth does not supply internet to comma. Native iPhone updates come through TestFlight; Galaxy's update buttons update comma software. Dependency changes automatically trigger setup while parked; comma needs internet for those updates.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Nate’s Galaxy companion
|
||||
|
||||
iPhone app for StarPilot’s Galaxy interface. Uses local Wi-Fi first, with encrypted Bluetooth fallback. Screens are saved for offline use and updated from `Nate/galaxy-bluetooth`.
|
||||
|
||||
## Setup
|
||||
|
||||
- [Install on comma](INSTALL-ON-COMMA.md)
|
||||
- [iPhone tester quick start](ios/QUICK-START.md)
|
||||
- [Connection testing details](ios/TESTER-GUIDE.md)
|
||||
- [Live View and CarPlay pilot](ios/CARPLAY-PILOT.md)
|
||||
|
||||
Open `ios/GalaxyBluetooth.xcodeproj`, select your signing team and iPhone, then Run. On comma 4, open **Settings → Bluetooth → Pair phone**. Scan its code in the app and select the comma. The bridge installs automatically on the first parked boot with internet access.
|
||||
|
||||
## Connection
|
||||
|
||||
Galaxy screens → native transport → LAN HTTP or encrypted BLE → Galaxy on comma.
|
||||
|
||||
Local settings work without internet. Downloads and online maps still need internet on the device handling them. Remote cellular access and automatic hotspot activation are not implemented.
|
||||
|
||||
The Bluetooth bridge uses a shared key, session challenges and request counters. **Forget paired phones** replaces the key for all phones. Setting changes are never replayed automatically. LAN uses Galaxy’s existing HTTP endpoint; its device-ID check prevents accidental mixups but does not add TLS or authentication.
|
||||
|
||||
## Status
|
||||
|
||||
iOS build, bridge tests and routing/update checks pass. Bluetooth startup after reboot was verified on the pilot comma. Camera scanning, revoke/re-pair and network switching still need hardware checks.
|
||||
|
||||
See [validation](VALIDATION.md) and [upstream notices](UPSTREAM-NOTICES.md).
|
||||
|
||||
Comma 3X: phone pairing is available in Bluetooth settings. The bridge and capture hooks are shared; physical 3X testing is pending. `bridge/probe.py` reports Bluetooth and encoder compatibility without credentials. See `ios/QUICK-START.md`.
|
||||
|
||||
## Automatic bridge setup
|
||||
|
||||
The pilot's manager runs `bootstrap.py` on comma. First parked boot installs the
|
||||
bridge in its own environment; later boots reuse it. Dependency changes are
|
||||
installed while parked. Bluetooth settings show setup status and Retry setup.
|
||||
`settings_backup.py` saves one private parameter/cache snapshot before existing
|
||||
launch migrations. Setup never resets StarPilot parameters or pairing keys.
|
||||
Do not share the backup; it contains credentials. See INSTALL-ON-COMMA.md.
|
||||
|
||||
|
||||
## Find comma on Wi-Fi
|
||||
|
||||
The iPhone app's **Settings → Find comma on Wi-Fi** searches for up to 12 seconds
|
||||
without needing a Bluetooth connection. Allow the app's Local Network permission,
|
||||
put iPhone and comma on the same Wi-Fi or hotspot, then select the named result.
|
||||
The app verifies Galaxy's response and any previously paired device identity before
|
||||
using the discovered address. Discovery does not create or replace pairing credentials.
|
||||
Manual IP entry and Bluetooth discovery remain available.
|
||||
|
||||
This requires the `galaxy-lan-discovery.service` included in this branch. On the
|
||||
first update, park and give comma internet access so its bootstrap can install the
|
||||
additional dependency in `/data/galaxy-ble/venv`. Existing settings and pairing keys
|
||||
are preserved. The discovery service starts independently of Bluetooth and publishes
|
||||
`_starpilot-galaxy._tcp.local.` on port 8082 only on private IPv4 Wi-Fi/Ethernet
|
||||
interfaces while Galaxy is listening. TXT records contain a protocol version, never
|
||||
pairing keys or Galaxy session tokens. It checks interface changes every 30 seconds;
|
||||
there is no subnet scan, camera capture, or extra telemetry polling.
|
||||
|
||||
Some hotspots and guest networks block multicast discovery or communication between
|
||||
clients. If no result appears, enter comma's local IP manually. For troubleshooting,
|
||||
inspect `journalctl -u galaxy-lan-discovery.service --no-pager -n 50` on comma.
|
||||
@@ -0,0 +1,8 @@
|
||||
Copyright (c) 2018, Comma.ai, Inc.
|
||||
Copyright (c) 2026, firestar5683 and StarPilot contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,125 @@
|
||||
# Third-Party Notices
|
||||
|
||||
This file supplements StarPilot's root `LICENSE`. StarPilot-original contributions are offered
|
||||
under that MIT license. Third-party material remains subject to its original terms; inclusion here
|
||||
does not relicense it or imply endorsement by an upstream project or contributor.
|
||||
|
||||
## BluePilot `bp-7.0` Ford support
|
||||
|
||||
Portions of StarPilot's Ford lateral control, CAN integration, panda safety logic, vehicle data,
|
||||
and related tests are adapted from the public BluePilot repository:
|
||||
|
||||
- Source: <https://github.com/BluePilotDev/bluepilot/tree/bp-7.0>
|
||||
- Audited `bp-7.0` snapshot: [`e1d051d7ba270261b4455068bd68f1a58db15a4a`](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a)
|
||||
- Historical reconstruction: [CREDITS.md](CREDITS.md#ford-support-adapted-from-bluepilot)
|
||||
- Provenance and contributors: [CREDITS.md](CREDITS.md)
|
||||
|
||||
## sunnypilot Hyundai, Kia, and Genesis support
|
||||
|
||||
Portions of StarPilot's HKG angle steering, CAN integration, panda safety enforcement and tests,
|
||||
firmware fingerprints, platform data, and cruise-button management are adapted directly from the
|
||||
public sunnypilot repositories:
|
||||
|
||||
- Source: <https://github.com/sunnypilot/sunnypilot/tree/hkg-angle-steering-2025>
|
||||
- Audited superproject snapshot: [`cfb38312db33779f4727c983d372474a56ccb5d8`](https://github.com/sunnypilot/sunnypilot/commit/cfb38312db33779f4727c983d372474a56ccb5d8)
|
||||
- Source: <https://github.com/sunnypilot/opendbc/tree/hkg-angle-steering-2025>
|
||||
- Audited angle-branch snapshot: [`cc4b08625a98e94b318cab15e45e05dad58042bd`](https://github.com/sunnypilot/opendbc/commit/cc4b08625a98e94b318cab15e45e05dad58042bd)
|
||||
- Later HKG history was audited against `sunnypilot/opendbc` `master` at
|
||||
[`f95f996f5917dcbbf2e32fe51b606a24cf836af6`](https://github.com/sunnypilot/opendbc/commit/f95f996f5917dcbbf2e32fe51b606a24cf836af6).
|
||||
- Historical reconstruction and contributors: [CREDITS.md](CREDITS.md#hyundai-kia-and-genesis-support-adapted-from-sunnypilot)
|
||||
|
||||
## Applicable upstream license notices
|
||||
|
||||
The upstream repositories and branches identified above publish both `LICENSE` and `LICENSE.md`.
|
||||
Their READMEs point to `LICENSE` for openpilot licensing, while some extension files point to
|
||||
`LICENSE.md`. Because the scope of those two notices is not unambiguous, StarPilot preserves both
|
||||
and treats the more restrictive notice conservatively for upstream-derived material. This is a
|
||||
record of the published notices, not a legal conclusion about their scope.
|
||||
|
||||
### Upstream `LICENSE` notice (MIT)
|
||||
|
||||
Copyright (c) 2018, Comma.ai, Inc.
|
||||
|
||||
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.
|
||||
|
||||
### Upstream `opendbc` `LICENSE` notice (MIT)
|
||||
|
||||
Copyright (c) 2020, Comma.ai, Inc.
|
||||
|
||||
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.
|
||||
|
||||
### Upstream extension file notice
|
||||
|
||||
Several upstream Ford and HKG extension files carry this file-level notice:
|
||||
|
||||
> Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
>
|
||||
> This file is part of sunnypilot and is licensed under the MIT License.
|
||||
> See the LICENSE.md file in the root directory for more details.
|
||||
|
||||
StarPilot's Ford and HKG integrations were informed by extension files carrying this notice. The
|
||||
reference to “MIT License” conflicts with the nonstandard restrictions in the referenced upstream
|
||||
`LICENSE.md`; both texts are retained here rather than silently choosing between them.
|
||||
|
||||
### Upstream `LICENSE.md` notice (published as “Custom MIT License”)
|
||||
|
||||
The following notice is reproduced verbatim from the reference branch:
|
||||
|
||||
> # Custom MIT License
|
||||
>
|
||||
> Copyright (c) 2024, Haibin Wen, SUNNYPILOT LLC
|
||||
>
|
||||
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to view and modify the Software, subject to the following conditions:
|
||||
>
|
||||
> 1. **Permission Required**: Permission Required for Commercial, For-Profit, or Closed Source Use: Use of the Software, in whole or in part, for any commercial purposes, for-profit projects, or in closed source projects requires explicit written permission from the original author(s).
|
||||
>
|
||||
> 2. **Redistribution**: Any redistribution of the Software, modified or unmodified, must retain this license notice and the following acknowledgment:
|
||||
> "This software is licensed under a custom license requiring permission for use."
|
||||
>
|
||||
> 3. **Visibility**: Any project that uses the Software must visibly mention the following acknowledgment:
|
||||
> "This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use."
|
||||
>
|
||||
> 4. **No Warranty**: 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.
|
||||
>
|
||||
> Contact sunnypilot Support <support@sunnypilot.ai> for permission requests.
|
||||
>
|
||||
> ---
|
||||
>
|
||||
> Haibin Wen, SUNNYPILOT LLC
|
||||
|
||||
Required upstream acknowledgments:
|
||||
|
||||
> This software is licensed under a custom license requiring permission for use.
|
||||
>
|
||||
> This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use.
|
||||
|
||||
For commercial, for-profit, or closed-source use, consult the upstream notice and obtain any
|
||||
permission it requires. The upstream repository's simultaneous publication of two differently
|
||||
scoped notices should be clarified with the relevant copyright holders before relying on one to
|
||||
the exclusion of the other.
|
||||
@@ -0,0 +1 @@
|
||||
{"repository":"https://github.com/firestar5683/StarPilot","revision":"2a12dbd0ad94b46f8a7b6099d32d7216b7676f79","path":"starpilot/system/the_galaxy","bundleChanges":["Treat native shell as installed in mobile/js/install.js","Use phone loopback for localDeviceUrl in mobile/js/views/Galaxy.js and Recordings.js","Keep settings load errors visible, provide a read-only retry button, and prevent duplicate initial developer-mode loads in mobile/js/views/Settings.js","Read only LanguageSetting during startup in mobile/js/api.js and components/AppShell.js","Toggles requests a settings-only snapshot and no longer downloads unused defaults in mobile/js/api.js and views/Settings.js","Use platform-neutral filenames for web app icons"],"additionalResources":[{"source":"https://github.com/firestar5683/StarPilot/blob/934dadbcdbaaaac78dd6badd09a1ebadd298bae8/starpilot/common/assets/device_settings_layout.json","bundlePath":"assets/components/tools/device_settings_layout.json","sha256":"ead70dc1cd550249ab5318160b88c246620de5f35e0a411a006b6ef7adff7517","changes":"None; used only when the authenticated comma catalog digest matches."}]}
|
||||
@@ -0,0 +1,25 @@
|
||||
# Validation
|
||||
|
||||
- iOS generic and development-signed builds passed.
|
||||
- 28 Python bridge/pairing tests passed: framing, authentication, replay rejection, key rotation, old-key rejection and file permissions.
|
||||
- Swift QR parsing passed with a Python-generated payload and malformed/version/size cases.
|
||||
- LAN routing tests passed: priority, read fallback, no write replay, device identity and private IP validation.
|
||||
- Local HTTP framing, redirect, size-bound and cancellation checks passed.
|
||||
- Asset updates passed: file hashes, offline restart, rollback, traversal rejection and active-screen retention.
|
||||
- Bluetooth startup after reboot reached bridge-ready on the pilot comma.
|
||||
|
||||
Pending: camera scan on iPhone, comma QR layout, revoke/re-pair, hotspot and LAN/BLE switching, setting write/read-back, release distribution.
|
||||
|
||||
Live / CarPlay pilot: 36 bridge/companion tests pass; iOS builds pass. GPU capture, capture overhead and physical CarPlay remain untested. MJPEG fragmentation/chunking/size-bound tests pass. CarPlay requires the approved entitlement; regular phone signing is unchanged.
|
||||
|
||||
Encoder integration with StarPilot’s pinned raylib 5.5.0.2: 40 distinct 960×480 JPEGs in 2.23 seconds on Mac, latest frame age 0.053 seconds. This does not measure comma GPU readback or end-to-end phone FPS.
|
||||
|
||||
## Automatic setup and settings preservation
|
||||
|
||||
- 51 Python tests pass, including install retry/offroad gating, unchanged keys,
|
||||
stale bridge readiness, and byte-for-byte first settings snapshot retention.
|
||||
- Real isolated installer passes using local wheels with ensurepip disabled.
|
||||
Repeat and quiet installs preserve the key and never print it.
|
||||
- Python compilation and launcher/installer shell syntax checks pass.
|
||||
- Launch migrations match the pilot's Dom base exactly. No new parameter resets.
|
||||
- First-boot installation, status UI and reboot behavior await physical testing.
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Install and supervise the phone bridge without changing StarPilot settings."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
DATA = Path('/data/galaxy-ble')
|
||||
BRIDGE = Path(__file__).resolve().parent / 'bridge'
|
||||
UNIT = 'galaxy-ble-fork.service'
|
||||
LAN_UNIT = 'galaxy-lan-discovery.service'
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
fd, temporary = tempfile.mkstemp(dir=path.parent, prefix='.setup-')
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
def setup_status(data=DATA):
|
||||
try:
|
||||
value = json.loads((data / 'setup-status.json').read_text())
|
||||
if time.time() - value['updated'] > 45:
|
||||
return 'Bridge startup pending'
|
||||
return value['message']
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return 'Bridge startup pending'
|
||||
|
||||
|
||||
def retry_setup(data=DATA):
|
||||
write_json(data / 'retry-setup.json', {'requested': time.time()})
|
||||
|
||||
|
||||
class Bootstrap:
|
||||
def __init__(self, params, data=DATA, bridge=BRIDGE, run=subprocess.run):
|
||||
self.params, self.data, self.bridge, self.run = params, data, bridge, run
|
||||
self.verified = None
|
||||
self.next_attempt = 0
|
||||
self.registered = False
|
||||
self.discovery_registered = False
|
||||
|
||||
def status(self, state, message):
|
||||
write_json(self.data / 'setup-status.json', {'state': state, 'message': message, 'updated': time.time()})
|
||||
|
||||
def command(self, args, timeout=20, **kwargs):
|
||||
return self.run(args, timeout=timeout, check=True, **kwargs)
|
||||
|
||||
def systemctl(self, *args, **kwargs):
|
||||
return self.command(['sudo', '-n', 'systemctl', *args], **kwargs)
|
||||
|
||||
def step(self):
|
||||
requested = self.data / 'retry-setup.json'
|
||||
if requested.exists():
|
||||
requested.unlink(missing_ok=True)
|
||||
self.next_attempt = 0
|
||||
self.verified = None
|
||||
self.registered = False
|
||||
if time.monotonic() < self.next_attempt:
|
||||
self.status('error', 'Setup failed. Connect comma to internet, then Retry setup. See setup.log.')
|
||||
return
|
||||
try:
|
||||
digest = hashlib.sha256((self.bridge / 'requirements.txt').read_bytes()).hexdigest()
|
||||
python = self.data / 'venv/bin/python'
|
||||
receipt = self.data / 'installed-requirements'
|
||||
if self.verified != digest:
|
||||
valid = python.exists() and receipt.exists() and receipt.read_text() == digest
|
||||
if valid:
|
||||
try:
|
||||
self.command([str(python), '-c', 'import dbus_next; import zeroconf; from Crypto.Cipher import AES'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
valid = False
|
||||
if not valid:
|
||||
if self.params.get_bool('IsOnroad'):
|
||||
self.status('waiting', 'Park to finish Bluetooth setup')
|
||||
return
|
||||
self.status('installing', 'Installing Bluetooth bridge. Comma needs internet.')
|
||||
self.run(['sudo', '-n', 'systemctl', 'stop', UNIT, LAN_UNIT], timeout=20, check=False,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
log_path = self.data / 'setup.log'
|
||||
if log_path.exists() and log_path.stat().st_size > 256 * 1024:
|
||||
os.replace(log_path, self.data / 'setup.previous.log')
|
||||
env = dict(os.environ, GALAXY_BLE_DATA_DIR=str(self.data), GALAXY_BLE_QUIET='1')
|
||||
with log_path.open('a') as log:
|
||||
os.chmod(log_path, 0o600)
|
||||
self.command(['sh', str(self.bridge / 'install.sh')], timeout=180,
|
||||
stdout=log, stderr=subprocess.STDOUT, env=env)
|
||||
receipt.write_text(digest)
|
||||
os.chmod(receipt, 0o600)
|
||||
self.registered = False
|
||||
self.verified = digest
|
||||
if not self.registered:
|
||||
self.systemctl('link', '--runtime', str(self.bridge / UNIT), stdout=subprocess.DEVNULL)
|
||||
self.systemctl('daemon-reload', stdout=subprocess.DEVNULL)
|
||||
self.registered = True
|
||||
# Discovery remains available when Bluetooth is off or the BLE service retries.
|
||||
# An optional discovery failure must not prevent Bluetooth startup.
|
||||
try:
|
||||
if not self.discovery_registered:
|
||||
self.systemctl('link', '--runtime', str(self.bridge / LAN_UNIT), stdout=subprocess.DEVNULL)
|
||||
self.systemctl('daemon-reload', stdout=subprocess.DEVNULL)
|
||||
self.discovery_registered = True
|
||||
self.systemctl('start', LAN_UNIT, stdout=subprocess.DEVNULL)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
self.systemctl('start', UNIT, stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
pid = json.loads((self.data / 'bridge-ready.json').read_text())['pid']
|
||||
result = self.systemctl('show', UNIT, '--property=MainPID', '--value', capture_output=True, text=True)
|
||||
running = pid == int(result.stdout.strip()) and pid > 0
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
running = False
|
||||
self.status('ready' if running else 'waiting', 'Ready to pair' if running else 'Waiting for Bluetooth. Enable Bluetooth on comma.')
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
self.next_attempt = time.monotonic() + 60
|
||||
self.status('error', 'Setup failed. Connect comma to internet, then Retry setup. See setup.log.')
|
||||
|
||||
|
||||
def main():
|
||||
from openpilot.common.params import Params
|
||||
DATA.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
os.chmod(DATA, 0o700)
|
||||
with (DATA / 'bootstrap.lock').open('w') as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return
|
||||
worker = Bootstrap(Params())
|
||||
while True:
|
||||
worker.step()
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=Galaxy Bluetooth bridge from the installed StarPilot fork
|
||||
After=bluetooth.service
|
||||
Requires=bluetooth.service
|
||||
ConditionPathExists=/data/openpilot/tools/galaxy_bluetooth/bridge/server.py
|
||||
ConditionPathExists=/data/galaxy-ble/venv/bin/python
|
||||
ConditionPathExists=/data/galaxy-ble/pairing.json
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=comma
|
||||
WorkingDirectory=/data/openpilot/tools/galaxy_bluetooth/bridge
|
||||
ExecStart=/data/galaxy-ble/venv/bin/python /data/openpilot/tools/galaxy_bluetooth/bridge/server.py --key-file /data/galaxy-ble/pairing.json
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Galaxy Bluetooth request bridge
|
||||
After=bluetooth.service
|
||||
Requires=bluetooth.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=comma
|
||||
WorkingDirectory=/data/galaxy-ble/app/bridge
|
||||
ExecStart=/data/galaxy-ble/venv/bin/python /data/galaxy-ble/app/bridge/server.py
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Galaxy local Wi-Fi discovery
|
||||
After=network.target
|
||||
ConditionPathExists=/data/openpilot/tools/galaxy_bluetooth/bridge/lan_discovery.py
|
||||
ConditionPathExists=/data/galaxy-ble/venv/bin/python
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=comma
|
||||
WorkingDirectory=/data/openpilot/tools/galaxy_bluetooth/bridge
|
||||
ExecStart=/data/galaxy-ble/venv/bin/python /data/openpilot/tools/galaxy_bluetooth/bridge/lan_discovery.py
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Run on the comma after copying the project to /data/galaxy-ble/app.
|
||||
set -eu
|
||||
bridge_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
data_dir=${GALAXY_BLE_DATA_DIR:-/data/galaxy-ble}
|
||||
mkdir -p "$data_dir"
|
||||
chmod 700 "$data_dir"
|
||||
python_bin=${GALAXY_BLE_PYTHON:-}
|
||||
if [ -z "$python_bin" ]; then
|
||||
for candidate in /data/openpilot/.venv-linux-arm64/bin/python /data/openpilot/.venv/bin/python /data/openpilot/.venv/bin/python3 /usr/local/venv/bin/python /usr/local/venv/bin/python3; do
|
||||
if [ -x "$candidate" ]; then
|
||||
python_bin=$candidate
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$python_bin" ]; then
|
||||
python_bin=$(command -v python3)
|
||||
fi
|
||||
fi
|
||||
|
||||
"$python_bin" -m venv --without-pip "$data_dir/venv"
|
||||
uv_bin=$(command -v uv || true)
|
||||
if [ -z "$uv_bin" ] && [ -x /usr/local/venv/bin/uv ]; then
|
||||
uv_bin=/usr/local/venv/bin/uv
|
||||
fi
|
||||
if [ -n "$uv_bin" ]; then
|
||||
"$uv_bin" pip install --python "$data_dir/venv/bin/python" -r "$bridge_dir/requirements.txt"
|
||||
elif "$python_bin" -m pip --help 2>/dev/null | grep -q -- '--python'; then
|
||||
"$python_bin" -m pip --python "$data_dir/venv/bin/python" install -r "$bridge_dir/requirements.txt"
|
||||
elif "$data_dir/venv/bin/python" -m ensurepip --upgrade; then
|
||||
"$data_dir/venv/bin/python" -m pip install -r "$bridge_dir/requirements.txt"
|
||||
else
|
||||
printf '\nNo usable package installer found. The bridge needs uv, pip 22.3+, or ensurepip.\n' >&2
|
||||
printf 'No packages were installed into StarPilot or the system Python.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
"$data_dir/venv/bin/python" -c 'import dbus_next; import zeroconf; from Crypto.Cipher import AES'
|
||||
"$data_dir/venv/bin/python" - "$bridge_dir" "$data_dir/pairing.json" <<'KEY'
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
from pairing import ensure_key
|
||||
ensure_key(Path(sys.argv[2]))
|
||||
KEY
|
||||
if [ "${GALAXY_BLE_QUIET:-0}" != "1" ]; then
|
||||
printf '\nBridge installed. Pair this phone from Settings → Bluetooth → Pair phone.\n'
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Advertise Galaxy on local Ethernet/Wi-Fi independently of Bluetooth."""
|
||||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
SERVICE = '_starpilot-galaxy._tcp.local.'
|
||||
PORT = 8082
|
||||
LOG = logging.getLogger('galaxy-lan-discovery')
|
||||
|
||||
|
||||
def private_addresses(interfaces):
|
||||
addresses = set()
|
||||
for interface in interfaces:
|
||||
name = interface.get('ifname', '')
|
||||
# Never advertise cellular, VPN, loopback, or virtual bridge addresses.
|
||||
if not re.match(r'^(wlan|wl|eth|en)', name) or interface.get('operstate') != 'UP':
|
||||
continue
|
||||
for item in interface.get('addr_info', []):
|
||||
if item.get('family') != 'inet' or item.get('scope') != 'global':
|
||||
continue
|
||||
try:
|
||||
address = ipaddress.IPv4Address(item.get('local', ''))
|
||||
except ipaddress.AddressValueError:
|
||||
continue
|
||||
if any(address in network for network in PRIVATE_NETWORKS):
|
||||
addresses.add(str(address))
|
||||
return sorted(addresses)
|
||||
|
||||
|
||||
PRIVATE_NETWORKS = tuple(ipaddress.IPv4Network(value) for value in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'))
|
||||
|
||||
|
||||
def local_addresses():
|
||||
result = subprocess.run(['ip', '-j', '-4', 'addr', 'show'], check=True, capture_output=True, text=True, timeout=3)
|
||||
return private_addresses(json.loads(result.stdout))
|
||||
|
||||
|
||||
def galaxy_listening():
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1', PORT), timeout=0.3):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
class Advertisement:
|
||||
def __init__(self, factory=None, info_factory=None):
|
||||
if factory is None or info_factory is None:
|
||||
from zeroconf import Zeroconf, ServiceInfo, IPVersion
|
||||
factory = lambda addresses: Zeroconf(interfaces=addresses, ip_version=IPVersion.V4Only)
|
||||
info_factory = ServiceInfo
|
||||
self.factory, self.info_factory = factory, info_factory
|
||||
self.publisher = None
|
||||
self.addresses = []
|
||||
|
||||
def update(self, addresses):
|
||||
if addresses == self.addresses:
|
||||
return
|
||||
self.close()
|
||||
if not addresses:
|
||||
return
|
||||
hostname = re.sub(r'[^A-Za-z0-9-]', '-', socket.gethostname()).strip('-')[:50] or 'comma'
|
||||
publisher = self.factory(addresses)
|
||||
try:
|
||||
info = self.info_factory(SERVICE, f'{hostname}.{SERVICE}', port=PORT,
|
||||
addresses=[socket.inet_aton(address) for address in addresses],
|
||||
properties={'protocol': 'galaxy-lan-1'}, server=f'{hostname}.local.')
|
||||
publisher.register_service(info, allow_name_change=True)
|
||||
except Exception:
|
||||
publisher.close()
|
||||
raise
|
||||
self.publisher, self.addresses = publisher, list(addresses)
|
||||
LOG.info('Galaxy Wi-Fi discovery available on %s local interface(s)', len(addresses))
|
||||
|
||||
def close(self):
|
||||
if self.publisher is not None:
|
||||
# Zeroconf sends goodbye records and stops its own background threads.
|
||||
self.publisher.close()
|
||||
self.publisher = None
|
||||
self.addresses = []
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
||||
stopped = threading.Event()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, lambda *_: stopped.set())
|
||||
advertisement = Advertisement()
|
||||
last_error = None
|
||||
try:
|
||||
while not stopped.is_set():
|
||||
try:
|
||||
advertisement.update(local_addresses() if galaxy_listening() else [])
|
||||
last_error = None
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
||||
advertisement.close()
|
||||
if type(error).__name__ != last_error:
|
||||
LOG.warning('Wi-Fi discovery unavailable: %s', type(error).__name__)
|
||||
last_error = type(error).__name__
|
||||
stopped.wait(30)
|
||||
finally:
|
||||
advertisement.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Local-only pairing credentials shared by comma UI and BLE bridge."""
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import stat
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
|
||||
DEFAULT_KEY_PATH = Path("/data/galaxy-ble/pairing.json")
|
||||
|
||||
|
||||
def load_key(path=DEFAULT_KEY_PATH):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd) as stream:
|
||||
info = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
|
||||
raise ValueError("Pairing file must be a private regular file")
|
||||
raw = stream.read(1025)
|
||||
if len(raw) > 1024:
|
||||
raise ValueError("Pairing file is too large")
|
||||
key_text = json.loads(raw)["key"]
|
||||
if not isinstance(key_text, str) or len(key_text) != 64:
|
||||
raise ValueError("Invalid pairing key")
|
||||
key = bytes.fromhex(key_text)
|
||||
if len(key) != 32:
|
||||
raise ValueError("Invalid pairing key")
|
||||
return key
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _locked(path):
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
fd = os.open(path.with_suffix(".lock"), os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
fcntl.flock(stream, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def _write_key(path, key):
|
||||
fd, tmp = tempfile.mkstemp(prefix=".pairing-", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
os.fchmod(stream.fileno(), 0o600)
|
||||
json.dump({"key": key.hex()}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def ensure_key(path=DEFAULT_KEY_PATH):
|
||||
path = Path(path)
|
||||
with _locked(path):
|
||||
try:
|
||||
return load_key(path)
|
||||
except FileNotFoundError:
|
||||
key = secrets.token_bytes(32)
|
||||
_write_key(path, key)
|
||||
return key
|
||||
|
||||
|
||||
def rotate_key(path=DEFAULT_KEY_PATH):
|
||||
path = Path(path)
|
||||
with _locked(path):
|
||||
key = secrets.token_bytes(32)
|
||||
_write_key(path, key)
|
||||
return key
|
||||
|
||||
|
||||
def qr_payload(key):
|
||||
if len(key) != 32:
|
||||
raise ValueError("Invalid pairing key")
|
||||
return json.dumps({"type": "galaxy-bluetooth", "version": 1, "key": key.hex()}, separators=(",", ":"))
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only check of the on-device BlueZ and Galaxy prerequisites."""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.request
|
||||
|
||||
from dbus_next import BusType
|
||||
from dbus_next.aio import MessageBus
|
||||
|
||||
|
||||
def live_encoder_check():
|
||||
executable = shutil.which("ffmpeg")
|
||||
if not executable:
|
||||
return {"available": False, "error": "ffmpeg not found"}
|
||||
try:
|
||||
result = subprocess.run([
|
||||
executable, "-hide_banner", "-loglevel", "error", "-f", "rawvideo",
|
||||
"-pix_fmt", "rgba", "-s:v", "960x480", "-r", "20", "-i", "pipe:0",
|
||||
"-frames:v", "1", "-an", "-c:v", "mjpeg", "-q:v", "5", "-threads", "1",
|
||||
"-f", "rawvideo", "pipe:1",
|
||||
], input=bytes(960 * 480 * 4), capture_output=True, timeout=15)
|
||||
valid = result.returncode == 0 and result.stdout.startswith(b"\xff\xd8") and result.stdout.endswith(b"\xff\xd9")
|
||||
report = {"path": executable, "available": valid}
|
||||
if not valid:
|
||||
report["error"] = result.stderr.decode("utf-8", errors="replace")[-1000:] or "No complete JPEG produced"
|
||||
return report
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
return {"path": executable, "available": False, "error": str(error)}
|
||||
|
||||
|
||||
async def main():
|
||||
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
|
||||
try:
|
||||
obj = bus.get_proxy_object("org.bluez", "/", await bus.introspect("org.bluez", "/"))
|
||||
objects = await obj.get_interface("org.freedesktop.DBus.ObjectManager").call_get_managed_objects()
|
||||
adapters = []
|
||||
for path, interfaces in objects.items():
|
||||
if "org.bluez.Adapter1" not in interfaces:
|
||||
continue
|
||||
props = interfaces["org.bluez.Adapter1"]
|
||||
ads = interfaces.get("org.bluez.LEAdvertisingManager1", {})
|
||||
adapters.append({"adapter": path.rsplit("/", 1)[-1],
|
||||
"powered": props.get("Powered").value if "Powered" in props else None,
|
||||
"roles": props.get("Roles").value if "Roles" in props else [],
|
||||
"gattServer": "org.bluez.GattManager1" in interfaces,
|
||||
"advertising": bool(ads),
|
||||
"supportedAdvertisements": ads.get("SupportedInstances").value if "SupportedInstances" in ads else 0,
|
||||
"activeAdvertisements": ads.get("ActiveInstances").value if "ActiveInstances" in ads else 0})
|
||||
try:
|
||||
model = Path("/sys/firmware/devicetree/base/model").read_text().strip("\x00\n")
|
||||
except OSError:
|
||||
model = "unknown"
|
||||
result = {"model": model, "python": platform.python_version(), "adapters": adapters,
|
||||
"liveEncoder": live_encoder_check()}
|
||||
try:
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open("http://127.0.0.1:8082/api/device/status", timeout=10) as response:
|
||||
result["galaxyHTTPStatus"] = response.status
|
||||
except Exception as e:
|
||||
result["galaxyError"] = str(e)
|
||||
print(json.dumps(result, indent=2))
|
||||
finally:
|
||||
bus.disconnect()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Galaxy BLE v1: bounded framing and authenticated, direction-bound messages."""
|
||||
import json
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
SERVICE_UUID = "bd490001-6dc1-4de7-a7d0-6cdb441f7650"
|
||||
RX_UUID = "bd490002-6dc1-4de7-a7d0-6cdb441f7650"
|
||||
TX_UUID = "bd490003-6dc1-4de7-a7d0-6cdb441f7650"
|
||||
INFO_UUID = "bd490004-6dc1-4de7-a7d0-6cdb441f7650"
|
||||
NOTIFY_UUID = "bd490005-6dc1-4de7-a7d0-6cdb441f7650"
|
||||
NOTIFICATION_WINDOW = 8
|
||||
MAX_FRAME = 2 * 1024 * 1024
|
||||
MAX_BODY = 1024 * 1024
|
||||
AAD_PREFIX = b"galaxy-ble-v1/"
|
||||
|
||||
|
||||
def seal(value, key, direction, nonce=None, compact_body=False):
|
||||
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce or os.urandom(12))
|
||||
cipher.update(AAD_PREFIX + direction.encode())
|
||||
plaintext = json.dumps(value, separators=(",", ":")).encode()
|
||||
if len(plaintext) > MAX_FRAME:
|
||||
raise ValueError("Decoded message exceeds limit")
|
||||
compressed = zlib.compress(plaintext, wbits=-15)
|
||||
encoded = (b"\x01" + struct.pack(">I", len(plaintext)) + compressed
|
||||
if len(compressed) < len(plaintext) else b"\x00" + struct.pack(">I", len(plaintext)) + plaintext)
|
||||
# Compress HTTP bytes before base64 encoding.
|
||||
if compact_body and isinstance(value.get("body"), str):
|
||||
body = base64.b64decode(value["body"], validate=True)
|
||||
if len(body) > MAX_BODY:
|
||||
raise ValueError("Body exceeds limit")
|
||||
metadata = json.dumps({k: v for k, v in value.items() if k != "body"}, separators=(",", ":")).encode()
|
||||
payload = struct.pack(">I", len(metadata)) + metadata + body
|
||||
if len(payload) > MAX_FRAME:
|
||||
raise ValueError("Decoded message exceeds limit")
|
||||
compact = b"\x02" + struct.pack(">I", len(payload)) + zlib.compress(payload, wbits=-15)
|
||||
if len(compact) < len(encoded):
|
||||
encoded = compact
|
||||
ciphertext, tag = cipher.encrypt_and_digest(encoded)
|
||||
data = cipher.nonce + ciphertext + tag
|
||||
if len(data) > MAX_FRAME:
|
||||
raise ValueError("Message exceeds BLE frame limit")
|
||||
return struct.pack(">I", len(data)) + data
|
||||
|
||||
|
||||
def open_message(data, key, direction):
|
||||
if not 28 <= len(data) <= MAX_FRAME:
|
||||
raise ValueError("Invalid message length")
|
||||
cipher = AES.new(key, AES.MODE_GCM, nonce=data[:12])
|
||||
cipher.update(AAD_PREFIX + direction.encode())
|
||||
encoded = cipher.decrypt_and_verify(data[12:-16], data[-16:])
|
||||
if len(encoded) < 5:
|
||||
raise ValueError("Invalid compressed envelope")
|
||||
length = struct.unpack(">I", encoded[1:5])[0]
|
||||
if not 1 <= length <= MAX_FRAME:
|
||||
raise ValueError("Invalid decoded message length")
|
||||
if encoded[0] in (1, 2):
|
||||
decoder = zlib.decompressobj(wbits=-15)
|
||||
plaintext = decoder.decompress(encoded[5:], length + 1)
|
||||
if not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:
|
||||
raise ValueError("Invalid compressed message")
|
||||
elif encoded[0] == 0:
|
||||
plaintext = encoded[5:]
|
||||
else:
|
||||
raise ValueError("Unknown compression codec")
|
||||
if len(plaintext) != length:
|
||||
raise ValueError("Incorrect decoded message length")
|
||||
if encoded[0] == 2:
|
||||
if len(plaintext) < 4:
|
||||
raise ValueError("Invalid body envelope")
|
||||
metadata_length = struct.unpack(">I", plaintext[:4])[0]
|
||||
if not 1 <= metadata_length <= len(plaintext) - 4:
|
||||
raise ValueError("Invalid metadata length")
|
||||
value = json.loads(plaintext[4:4 + metadata_length])
|
||||
body = plaintext[4 + metadata_length:]
|
||||
if not isinstance(value, dict) or "body" in value or len(body) > MAX_BODY:
|
||||
raise ValueError("Invalid body envelope")
|
||||
value["body"] = base64.b64encode(body).decode()
|
||||
return value
|
||||
value = json.loads(plaintext)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Expected an object")
|
||||
return value
|
||||
|
||||
|
||||
class Assembler:
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.buffer = bytearray()
|
||||
self.sequence = 0
|
||||
self.length = None
|
||||
|
||||
def add(self, packet):
|
||||
if len(packet) < 6 or packet[0] != 1:
|
||||
raise ValueError("Invalid data packet")
|
||||
sequence = struct.unpack(">I", packet[1:5])[0]
|
||||
if sequence != self.sequence:
|
||||
raise ValueError("Out-of-order fragment")
|
||||
self.sequence += 1
|
||||
self.buffer.extend(packet[5:])
|
||||
if self.length is None and len(self.buffer) >= 4:
|
||||
self.length = struct.unpack(">I", self.buffer[:4])[0]
|
||||
if not 28 <= self.length <= MAX_FRAME:
|
||||
self.reset()
|
||||
raise ValueError("Invalid frame length")
|
||||
if len(self.buffer) > MAX_FRAME + 4:
|
||||
self.reset()
|
||||
raise ValueError("Frame limit exceeded")
|
||||
if self.length is not None and len(self.buffer) >= self.length + 4:
|
||||
if len(self.buffer) != self.length + 4:
|
||||
self.reset()
|
||||
raise ValueError("Trailing frame bytes")
|
||||
result = bytes(self.buffer[4:])
|
||||
self.reset()
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
def packets(frame, size=180):
|
||||
if not 20 <= size <= 512:
|
||||
raise ValueError("Invalid ATT payload size")
|
||||
for sequence, start in enumerate(range(0, len(frame), size - 5)):
|
||||
yield b"\x01" + struct.pack(">I", sequence) + frame[start:start + size - 5]
|
||||
|
||||
|
||||
def stream_tag(session, counter):
|
||||
return hashlib.sha256(bytes.fromhex(session) + struct.pack(">Q", counter)).digest()[:8]
|
||||
|
||||
|
||||
def notification_packets(frame, tag, size):
|
||||
if len(tag) != 8 or not 20 <= size <= 512:
|
||||
raise ValueError("Invalid notification framing")
|
||||
for sequence, start in enumerate(range(0, len(frame), size - 13)):
|
||||
yield b"\x03" + tag + struct.pack(">I", sequence) + frame[start:start + size - 13]
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Only proxies relative Galaxy requests to the fixed comma loopback endpoint."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from protocol import MAX_BODY
|
||||
|
||||
REQUEST_HEADERS = {"content-type", "accept", "cookie", "range", "x-companion-nonce", "x-companion-mac"}
|
||||
RESPONSE_HEADERS = {"content-type", "content-range", "accept-ranges", "content-disposition"}
|
||||
METHODS = {"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
MEDIA_PREFIXES = ("/video/", "/screen_recordings/", "/api/screen_recordings/download/", "/api/sentry/video/")
|
||||
# StarPilot includes this binary learning history in its all-parameters endpoint.
|
||||
PARAMS_SNAPSHOT_LIMIT = 8 * MAX_BODY
|
||||
INTERNAL_PARAMS = {"LiveTorqueParameters"}
|
||||
CATALOG_PATH = "/assets/components/tools/device_settings_layout.json"
|
||||
# Trim unused fields only when the settings catalog matches.
|
||||
FAST_SETTINGS_CATALOG_SHA256 = "ead70dc1cd550249ab5318160b88c246620de5f35e0a411a006b6ef7adff7517"
|
||||
SETTINGS_UNUSED_PARAMS = {"GalaxyDashboardStats", "CarParamsPrevRoute", "StarPilotStats",
|
||||
"GitDiff", "ApiCache_NavDestinations"}
|
||||
|
||||
|
||||
def validate_target(target):
|
||||
if not isinstance(target, str) or len(target) > 8192 or any(ord(c) < 32 for c in target):
|
||||
raise ValueError("Invalid request path")
|
||||
parsed = urllib.parse.urlsplit(target)
|
||||
decoded = urllib.parse.unquote(parsed.path)
|
||||
if parsed.scheme or parsed.netloc or parsed.fragment or not decoded.startswith("/"):
|
||||
raise ValueError("Only relative Galaxy paths are allowed")
|
||||
if "\\" in decoded or "//" in decoded or any(p in (".", "..") for p in decoded.split("/")):
|
||||
raise ValueError("Invalid path segments")
|
||||
if any(ord(c) < 32 for c in decoded) or "%" in decoded:
|
||||
raise ValueError("Invalid encoded path")
|
||||
if not (decoded.startswith("/api/") or decoded == "/assets/components/tools/device_settings_layout.json"):
|
||||
raise ValueError("Path is outside the Galaxy API")
|
||||
return target
|
||||
|
||||
|
||||
def error_response(request_id, status, message):
|
||||
return {"id": request_id, "status": status, "headers": {"content-type": "application/json"},
|
||||
"body": base64.b64encode(json.dumps({"error": message}).encode()).decode()}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
class GalaxyProxy:
|
||||
def __init__(self, port=8082):
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("Invalid Galaxy port")
|
||||
self.base = f"http://127.0.0.1:{port}"
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
|
||||
def catalog_digest(self):
|
||||
try:
|
||||
with self.opener.open(self.base + CATALOG_PATH, timeout=3) as response:
|
||||
data = response.read(MAX_BODY + 1)
|
||||
if response.status == 200 and len(data) <= MAX_BODY and isinstance(json.loads(data), list):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def handle(self, request):
|
||||
request_id = str(request.get("id", ""))
|
||||
try:
|
||||
if request.get("path") == "/_bridge/health" and request.get("method") == "GET":
|
||||
health = {"protocol": 1, "transport": "bluetooth", "readStream": True, "notificationStream": True}
|
||||
digest = self.catalog_digest()
|
||||
if digest:
|
||||
health["catalogSHA256"] = digest
|
||||
return {"id": request_id, "status": 200, "headers": {"content-type": "application/json"},
|
||||
"body": base64.b64encode(json.dumps(health, separators=(",", ":")).encode()).decode()}
|
||||
target = validate_target(request.get("path"))
|
||||
if target.split("?")[0] in ("/api/companion/frame", "/api/companion/stream"):
|
||||
return error_response(request_id, 501, "Live View requires local Wi-Fi; Bluetooth carries diagnostics only.")
|
||||
method = request.get("method", "GET")
|
||||
if method not in METHODS:
|
||||
raise ValueError("Unsupported HTTP method")
|
||||
if target.split("?")[0].startswith(MEDIA_PREFIXES):
|
||||
return error_response(request_id, 501, "Video transfer is not supported by this BLE prototype.")
|
||||
body = base64.b64decode(request.get("body", ""), validate=True)
|
||||
if len(body) > MAX_BODY:
|
||||
return error_response(request_id, 413, "Upload exceeds the 1 MiB BLE limit.")
|
||||
supplied_headers = request.get("headers", {})
|
||||
if not isinstance(supplied_headers, dict):
|
||||
raise ValueError("Invalid headers")
|
||||
headers = {str(k): str(v) for k, v in supplied_headers.items() if str(k).lower() in REQUEST_HEADERS}
|
||||
if any("\r" in v or "\n" in v for v in headers.values()):
|
||||
raise ValueError("Invalid header value")
|
||||
upstream = urllib.request.Request(self.base + target, data=body if body else None, method=method, headers=headers)
|
||||
try:
|
||||
response = self.opener.open(upstream, timeout=35)
|
||||
except urllib.error.HTTPError as e:
|
||||
response = e
|
||||
with response:
|
||||
content_type = response.headers.get("content-type", "")
|
||||
if content_type.startswith(("video/", "multipart/x-mixed-replace")):
|
||||
return error_response(request_id, 501, "Continuous media streams are not supported over this BLE bridge.")
|
||||
if content_type.startswith("text/event-stream") and target.split("?")[0] not in ("/api/routes", "/api/screen_recordings/list"):
|
||||
return error_response(request_id, 501, "Continuous event streams are not supported; use a snapshot endpoint.")
|
||||
compact_parameters = method == "GET" and target.split("?")[0] == "/api/params/all"
|
||||
read_limit = PARAMS_SNAPSHOT_LIMIT if compact_parameters else MAX_BODY
|
||||
chunks, total = [], 0
|
||||
deadline = time.monotonic() + 35
|
||||
while total <= read_limit:
|
||||
if time.monotonic() > deadline:
|
||||
return error_response(request_id, 504, "Galaxy response took too long to complete.")
|
||||
chunk = response.read1(min(65536, read_limit + 1 - total))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
total += len(chunk)
|
||||
data = b"".join(chunks)
|
||||
if len(data) > read_limit:
|
||||
return error_response(request_id, 413, "Galaxy response exceeds the bounded bridge read limit.")
|
||||
if compact_parameters and response.status == 200:
|
||||
try:
|
||||
values = json.loads(data)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return error_response(request_id, 502, "Galaxy returned invalid settings JSON.")
|
||||
if not isinstance(values, dict):
|
||||
return error_response(request_id, 502, "Galaxy returned an invalid settings snapshot.")
|
||||
excluded = INTERNAL_PARAMS
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlsplit(target).query)
|
||||
if (query.get("galaxy_ble_settings") == ["1"]
|
||||
and self.catalog_digest() == FAST_SETTINGS_CATALOG_SHA256):
|
||||
excluded = INTERNAL_PARAMS | SETTINGS_UNUSED_PARAMS
|
||||
data = json.dumps({k: v for k, v in values.items() if k not in excluded},
|
||||
separators=(",", ":"), ensure_ascii=False).encode()
|
||||
if len(data) > MAX_BODY:
|
||||
return error_response(request_id, 413, "Response exceeds the 1 MiB BLE limit.")
|
||||
if 300 <= response.status < 400:
|
||||
return error_response(request_id, 502, "Galaxy redirected the request; redirects are disabled in the BLE bridge.")
|
||||
return {"id": request_id, "status": response.status,
|
||||
"headers": {k.lower(): v for k, v in response.headers.items() if k.lower() in RESPONSE_HEADERS},
|
||||
"body": base64.b64encode(data).decode()}
|
||||
except (ValueError, TypeError, KeyError) as e:
|
||||
return error_response(request_id, 400, str(e))
|
||||
except Exception:
|
||||
return error_response(request_id, 502, "Galaxy did not answer on the comma's loopback port. Check that Galaxy is running.")
|
||||
@@ -0,0 +1,3 @@
|
||||
dbus-next==0.2.3
|
||||
pycryptodome==3.23.0
|
||||
zeroconf==0.151.3
|
||||
Executable
+473
@@ -0,0 +1,473 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add a GATT peripheral beside StarPilot's existing Bluetooth service."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import signal
|
||||
import struct
|
||||
import time
|
||||
|
||||
from dbus_next import BusType, DBusError, Variant
|
||||
from dbus_next.aio import MessageBus
|
||||
from dbus_next.constants import PropertyAccess
|
||||
from dbus_next.service import ServiceInterface, dbus_property, method
|
||||
|
||||
from protocol import (Assembler, INFO_UUID, RX_UUID, SERVICE_UUID, TX_UUID, NOTIFY_UUID,
|
||||
NOTIFICATION_WINDOW, open_message, packets, seal, stream_tag, notification_packets)
|
||||
from proxy import GalaxyProxy, error_response
|
||||
from pairing import load_key
|
||||
from setup_health import write_ready, clear_ready
|
||||
|
||||
ROOT = "/link/galaxy/ble"
|
||||
SERVICE_PATH = ROOT + "/service0"
|
||||
GATT_SERVICE = "org.bluez.GattService1"
|
||||
GATT_CHAR = "org.bluez.GattCharacteristic1"
|
||||
LOG = logging.getLogger("galaxy-ble")
|
||||
NOTIFICATION_ACK_TIMEOUT = 15
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self):
|
||||
self.challenge = secrets.token_bytes(16)
|
||||
self.counter = 0
|
||||
self.assembler = Assembler()
|
||||
self.response = []
|
||||
self.index = 0
|
||||
self.busy = False
|
||||
self.last_seen = time.monotonic()
|
||||
self.task = None
|
||||
self.packet_size = 20
|
||||
self.read_stream = False
|
||||
self.response_started = 0
|
||||
self.notification_stream = False
|
||||
self.notification_tag = b""
|
||||
self.notification_ack = asyncio.Event()
|
||||
self.notification_expected_ack = None
|
||||
self.notification_task = None
|
||||
self.closed = False
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
if self.task:
|
||||
self.task.cancel()
|
||||
if self.notification_task:
|
||||
self.notification_task.cancel()
|
||||
|
||||
|
||||
class Gateway:
|
||||
def __init__(self, key, proxy, key_path=None):
|
||||
self.key = key
|
||||
self.key_path = key_path
|
||||
self.proxy = proxy
|
||||
self.sessions = {}
|
||||
self.notifier = None
|
||||
self.notification_lock = asyncio.Lock()
|
||||
|
||||
def refresh_key(self):
|
||||
if self.key_path is None:
|
||||
return
|
||||
try:
|
||||
key = load_key(self.key_path)
|
||||
except Exception:
|
||||
# Fail closed if the local credential is removed or invalid.
|
||||
key = None
|
||||
if key != self.key:
|
||||
for state in self.sessions.values():
|
||||
state.close()
|
||||
self.sessions.clear()
|
||||
self.key = key
|
||||
LOG.info("Pairing credentials changed; Bluetooth sessions revoked")
|
||||
if key is None:
|
||||
raise DBusError("org.bluez.Error.NotAuthorized", "Pairing credentials unavailable")
|
||||
|
||||
async def watch_key(self):
|
||||
while True:
|
||||
await asyncio.sleep(0.5)
|
||||
try:
|
||||
self.refresh_key()
|
||||
except DBusError:
|
||||
pass
|
||||
|
||||
def session(self, options, fresh=False):
|
||||
self.refresh_key()
|
||||
device = options.get("device")
|
||||
if not device or not isinstance(device.value, str):
|
||||
raise DBusError("org.bluez.Error.NotAuthorized", "A device identity is required")
|
||||
path = device.value
|
||||
for old_path, state in list(self.sessions.items()):
|
||||
if time.monotonic() - state.last_seen > 180:
|
||||
state.close()
|
||||
del self.sessions[old_path]
|
||||
if fresh and path in self.sessions:
|
||||
self.sessions.pop(path).close()
|
||||
if path not in self.sessions:
|
||||
if len(self.sessions) >= 4:
|
||||
raise DBusError("org.bluez.Error.InProgress", "Too many sessions")
|
||||
self.sessions[path] = Session()
|
||||
state = self.sessions[path]
|
||||
state.last_seen = time.monotonic()
|
||||
if "mtu" in options:
|
||||
state.packet_size = min(512, max(20, int(options["mtu"].value) - 3))
|
||||
return state
|
||||
|
||||
def write(self, value, options):
|
||||
state = self.session(options)
|
||||
if options.get("offset", Variant("q", 0)).value:
|
||||
raise DBusError("org.bluez.Error.InvalidOffset", "Long writes are not used")
|
||||
try:
|
||||
if len(value) == 13 and value[0] == 4:
|
||||
sequence = struct.unpack(">I", value[9:])[0]
|
||||
if (not state.notification_stream or not state.response or bytes(value[1:9]) != state.notification_tag
|
||||
or sequence != state.notification_expected_ack or state.index != sequence + 1
|
||||
or state.notification_ack.is_set()):
|
||||
raise ValueError("Unexpected notification acknowledgement")
|
||||
state.notification_ack.set()
|
||||
state.notification_expected_ack = None
|
||||
if state.index == len(state.response):
|
||||
self.acknowledged(state)
|
||||
return
|
||||
if len(value) == 5 and value[0] == 2:
|
||||
sequence = struct.unpack(">I", value[1:])[0]
|
||||
if state.notification_stream:
|
||||
raise ValueError("Notification responses require a tagged acknowledgement")
|
||||
elif state.read_stream and state.response:
|
||||
if state.index != len(state.response) or sequence != len(state.response) - 1:
|
||||
raise ValueError("Unexpected stream acknowledgement")
|
||||
self.acknowledged(state)
|
||||
elif state.response and sequence == state.index:
|
||||
state.index += 1
|
||||
if state.index == len(state.response):
|
||||
self.acknowledged(state)
|
||||
else:
|
||||
raise ValueError("Unexpected acknowledgement")
|
||||
return
|
||||
if state.busy:
|
||||
raise DBusError("org.bluez.Error.InProgress", "Previous response has not been acknowledged")
|
||||
data = state.assembler.add(bytes(value))
|
||||
if data is not None:
|
||||
state.busy = True
|
||||
state.task = asyncio.create_task(self.process(state, data))
|
||||
except ValueError as e:
|
||||
state.assembler.reset()
|
||||
raise DBusError("org.bluez.Error.InvalidValueLength", str(e))
|
||||
|
||||
def acknowledged(self, state):
|
||||
LOG.info("Response delivered: %d packets in %.2fs (%s)", len(state.response),
|
||||
time.monotonic() - state.response_started,
|
||||
"notification stream" if state.notification_stream else "read stream" if state.read_stream else "per-packet ACK")
|
||||
state.response = []
|
||||
state.index = 0
|
||||
state.busy = False
|
||||
|
||||
def read(self, options):
|
||||
state = self.session(options)
|
||||
if options.get("offset", Variant("q", 0)).value:
|
||||
raise DBusError("org.bluez.Error.InvalidOffset", "Packets fit inside the negotiated MTU")
|
||||
if state.notification_stream:
|
||||
return b"\x00"
|
||||
if not state.response or state.index >= len(state.response):
|
||||
return b"\x00"
|
||||
packet = state.response[state.index]
|
||||
if state.read_stream:
|
||||
# ACK once after the read stream is verified.
|
||||
state.index += 1
|
||||
return packet
|
||||
|
||||
async def process(self, state, data):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
self.refresh_key()
|
||||
if state.closed:
|
||||
return
|
||||
request = open_message(data, self.key, "request")
|
||||
counter = request.get("counter")
|
||||
if request.get("session") != state.challenge.hex() or type(counter) is not int or counter <= state.counter:
|
||||
raise ValueError("Invalid session or replayed request")
|
||||
if not isinstance(request.get("id"), str) or len(request["id"]) > 64:
|
||||
raise ValueError("Invalid request identifier")
|
||||
if counter > 0xffffffffffffffff:
|
||||
raise ValueError("Invalid counter")
|
||||
fast = request.get("responseCodec") == 2
|
||||
notify = fast and request.get("responseFlow") == "notify-window8"
|
||||
if notify and (self.notifier is None or not self.notifier.notifying):
|
||||
raise ValueError("Subscribe to notifications before requesting that response flow")
|
||||
state.counter = counter # Consume before invoking any mutating endpoint.
|
||||
response = await asyncio.to_thread(self.proxy.handle, request)
|
||||
self.refresh_key()
|
||||
if state.closed:
|
||||
return
|
||||
response["session"] = state.challenge.hex()
|
||||
response["counter"] = counter
|
||||
state.notification_stream = notify
|
||||
state.notification_tag = stream_tag(state.challenge.hex(), counter) if notify else b""
|
||||
state.read_stream = fast and request.get("responseFlow") == "read-stream"
|
||||
frame = seal(response, self.key, "response", compact_body=fast)
|
||||
size = state.packet_size if fast else min(180, state.packet_size)
|
||||
state.response = list(notification_packets(frame, state.notification_tag, size) if notify else packets(frame, size))
|
||||
state.index = 0
|
||||
state.response_started = time.monotonic()
|
||||
LOG.info("Response prepared: %d bytes, %d packets, ATT payload %d, %.2fs (%s)",
|
||||
len(frame), len(state.response), size, time.monotonic() - started,
|
||||
"notification stream" if notify else "read stream" if state.read_stream else "per-packet ACK")
|
||||
if notify:
|
||||
state.notification_task = asyncio.create_task(self.push_response(state))
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
# No unauthenticated error oracle; never log payloads or keys.
|
||||
LOG.warning("Rejected invalid or unauthenticated BLE message")
|
||||
state.busy = False
|
||||
finally:
|
||||
state.task = None
|
||||
|
||||
async def push_response(self, state):
|
||||
response = state.response
|
||||
try:
|
||||
# Serialize broadcasts and tag each client’s frames.
|
||||
async with self.notification_lock:
|
||||
while state.response is response and response and not state.closed:
|
||||
if self.notifier is None or not self.notifier.notifying:
|
||||
raise RuntimeError("Notification subscription ended")
|
||||
window = response[state.index:state.index + NOTIFICATION_WINDOW]
|
||||
state.notification_ack.clear()
|
||||
state.notification_expected_ack = state.index + len(window) - 1
|
||||
for packet in window:
|
||||
if state.closed or not self.notifier.notifying:
|
||||
raise RuntimeError("Notification session ended")
|
||||
state.index += 1
|
||||
self.notifier.send(packet)
|
||||
# Bound the burst and yield to D-Bus/ATT.
|
||||
await asyncio.sleep(0.004)
|
||||
await asyncio.wait_for(state.notification_ack.wait(), timeout=NOTIFICATION_ACK_TIMEOUT)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as error:
|
||||
LOG.warning("Notification transfer interrupted (%s); reconnect to check request outcome", type(error).__name__)
|
||||
# Keep the session busy until a fresh INFO handshake replaces it.
|
||||
finally:
|
||||
if state.notification_task is asyncio.current_task():
|
||||
state.notification_task = None
|
||||
|
||||
|
||||
class GattService(ServiceInterface):
|
||||
def __init__(self):
|
||||
super().__init__(GATT_SERVICE)
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def UUID(self) -> 's':
|
||||
return SERVICE_UUID
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Primary(self) -> 'b':
|
||||
return True
|
||||
|
||||
def props(self):
|
||||
return {"UUID": Variant("s", self.UUID), "Primary": Variant("b", True)}
|
||||
|
||||
|
||||
class Characteristic(ServiceInterface):
|
||||
def __init__(self, uuid, flags, gateway, kind):
|
||||
super().__init__(GATT_CHAR)
|
||||
self.uuid = uuid
|
||||
self.flags = flags
|
||||
self.gateway = gateway
|
||||
self.kind = kind
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def UUID(self) -> 's':
|
||||
return self.uuid
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Service(self) -> 'o':
|
||||
return SERVICE_PATH
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Flags(self) -> 'as':
|
||||
return self.flags
|
||||
|
||||
@method()
|
||||
def ReadValue(self, options: 'a{sv}') -> 'ay':
|
||||
if self.kind == "info":
|
||||
if options.get("offset", Variant("q", 0)).value:
|
||||
raise DBusError("org.bluez.Error.InvalidOffset", "Invalid offset")
|
||||
return b"\x01" + self.gateway.session(options, fresh=True).challenge
|
||||
if self.kind == "tx":
|
||||
return self.gateway.read(options)
|
||||
raise DBusError("org.bluez.Error.NotSupported", "Write-only characteristic")
|
||||
|
||||
@method()
|
||||
def WriteValue(self, value: 'ay', options: 'a{sv}'):
|
||||
if self.kind != "rx":
|
||||
raise DBusError("org.bluez.Error.NotSupported", "Read-only characteristic")
|
||||
self.gateway.write(value, options)
|
||||
|
||||
def props(self):
|
||||
return {"UUID": Variant("s", self.UUID), "Service": Variant("o", self.Service), "Flags": Variant("as", self.Flags)}
|
||||
|
||||
|
||||
class NotificationCharacteristic(Characteristic):
|
||||
def __init__(self, gateway):
|
||||
super().__init__(NOTIFY_UUID, ["notify"], gateway, "notify")
|
||||
self.value = b""
|
||||
self.notifying = False
|
||||
gateway.notifier = self
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Value(self) -> 'ay':
|
||||
return self.value
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Notifying(self) -> 'b':
|
||||
return self.notifying
|
||||
|
||||
@method()
|
||||
def StartNotify(self):
|
||||
if not self.notifying:
|
||||
self.notifying = True
|
||||
self.emit_properties_changed({"Notifying": True})
|
||||
LOG.info("Bluetooth push enabled")
|
||||
|
||||
@method()
|
||||
def StopNotify(self):
|
||||
self.notifying = False
|
||||
self.emit_properties_changed({"Notifying": False})
|
||||
LOG.info("Bluetooth push disabled")
|
||||
for state in self.gateway.sessions.values():
|
||||
if state.notification_task:
|
||||
state.notification_task.cancel()
|
||||
|
||||
def send(self, packet):
|
||||
if not self.notifying:
|
||||
raise RuntimeError("Not subscribed")
|
||||
self.value = bytes(packet)
|
||||
self.emit_properties_changed({"Value": self.value})
|
||||
|
||||
def props(self):
|
||||
return {**super().props(), "Value": Variant("ay", self.value), "Notifying": Variant("b", self.notifying)}
|
||||
|
||||
|
||||
class Application(ServiceInterface):
|
||||
def __init__(self, objects):
|
||||
super().__init__("org.freedesktop.DBus.ObjectManager")
|
||||
self.objects = objects
|
||||
|
||||
@method()
|
||||
def GetManagedObjects(self) -> 'a{oa{sa{sv}}}':
|
||||
return {path: {interface.name: interface.props()} for path, interface in self.objects.items()}
|
||||
|
||||
|
||||
class Advertisement(ServiceInterface):
|
||||
def __init__(self):
|
||||
super().__init__("org.bluez.LEAdvertisement1")
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def Type(self) -> 's':
|
||||
return "peripheral"
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def ServiceUUIDs(self) -> 'as':
|
||||
return [SERVICE_UUID]
|
||||
|
||||
@dbus_property(access=PropertyAccess.READ)
|
||||
def LocalName(self) -> 's':
|
||||
return "Galaxy"
|
||||
|
||||
@method()
|
||||
def Release(self):
|
||||
LOG.info("BLE advertisement released")
|
||||
|
||||
|
||||
def create_key(path):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
key = secrets.token_bytes(32)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump({"key": key.hex()}, f)
|
||||
return key
|
||||
|
||||
|
||||
async def serve(args):
|
||||
key_path = Path(args.key_file)
|
||||
clear_ready(key_path.parent)
|
||||
key = load_key(key_path)
|
||||
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
|
||||
gateway = Gateway(key, GalaxyProxy(args.galaxy_port), key_path)
|
||||
objects = {
|
||||
SERVICE_PATH: GattService(),
|
||||
SERVICE_PATH + "/rx": Characteristic(RX_UUID, ["write"], gateway, "rx"),
|
||||
SERVICE_PATH + "/tx": Characteristic(TX_UUID, ["read"], gateway, "tx"),
|
||||
SERVICE_PATH + "/info": Characteristic(INFO_UUID, ["read"], gateway, "info"),
|
||||
SERVICE_PATH + "/notify": NotificationCharacteristic(gateway),
|
||||
}
|
||||
bus.export(ROOT, Application(objects))
|
||||
for path, interface in objects.items():
|
||||
bus.export(path, interface)
|
||||
ad_path = ROOT + "/advertisement"
|
||||
bus.export(ad_path, Advertisement())
|
||||
introspection = await bus.introspect("org.bluez", "/")
|
||||
manager = bus.get_proxy_object("org.bluez", "/", introspection).get_interface("org.freedesktop.DBus.ObjectManager")
|
||||
managed = await manager.call_get_managed_objects()
|
||||
adapters = [path for path, interfaces in managed.items()
|
||||
if "org.bluez.GattManager1" in interfaces and "org.bluez.LEAdvertisingManager1" in interfaces]
|
||||
if args.adapter:
|
||||
adapters = [p for p in adapters if p.endswith("/" + args.adapter)]
|
||||
if not adapters:
|
||||
raise RuntimeError("No BlueZ adapter exposes GATT server and LE advertising. Enable Bluetooth in StarPilot and inspect bluetoothctl show.")
|
||||
adapter_path = adapters[0]
|
||||
obj = bus.get_proxy_object("org.bluez", adapter_path, await bus.introspect("org.bluez", adapter_path))
|
||||
properties = obj.get_interface("org.freedesktop.DBus.Properties")
|
||||
if not (await properties.call_get("org.bluez.Adapter1", "Powered")).value:
|
||||
raise RuntimeError("Bluetooth is off. Enable it in StarPilot before starting the bridge.")
|
||||
gatt = obj.get_interface("org.bluez.GattManager1")
|
||||
advertising = obj.get_interface("org.bluez.LEAdvertisingManager1")
|
||||
await gatt.call_register_application(ROOT, {})
|
||||
watcher = asyncio.create_task(gateway.watch_key())
|
||||
try:
|
||||
await advertising.call_register_advertisement(ad_path, {})
|
||||
write_ready(key_path.parent)
|
||||
LOG.info("Galaxy BLE bridge ready on %s; forwarding to localhost:%s", adapter_path, args.galaxy_port)
|
||||
stopped = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
loop.add_signal_handler(sig, stopped.set)
|
||||
await stopped.wait()
|
||||
finally:
|
||||
clear_ready(key_path.parent)
|
||||
watcher.cancel()
|
||||
try:
|
||||
await watcher
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
for state in gateway.sessions.values():
|
||||
state.close()
|
||||
try:
|
||||
await advertising.call_unregister_advertisement(ad_path)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await gatt.call_unregister_application(ROOT)
|
||||
finally:
|
||||
bus.disconnect()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--key-file", default="/data/galaxy-ble/pairing.json")
|
||||
parser.add_argument("--galaxy-port", type=int, default=8082)
|
||||
parser.add_argument("--adapter", help="Optional adapter, e.g. hci0")
|
||||
parser.add_argument("--init-key", action="store_true", help="Create a private pairing key and print it once")
|
||||
args = parser.parse_args()
|
||||
if args.init_key:
|
||||
print(create_key(Path(args.key_file)).hex())
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
asyncio.run(serve(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
|
||||
def clear_ready(data):
|
||||
(Path(data) / 'bridge-ready.json').unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_ready(data):
|
||||
fd, temporary = tempfile.mkstemp(dir=data, prefix='.ready-')
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump({'pid': os.getpid()}, stream)
|
||||
os.replace(temporary, Path(data) / 'bridge-ready.json')
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Called in the background by /data/continue.sh; systemd owns the bridge.
|
||||
unit=/data/openpilot/tools/galaxy_bluetooth/bridge/galaxy-ble-fork.service
|
||||
if [ ! -r "$unit" ]; then
|
||||
echo "Galaxy BLE startup skipped: service file missing"
|
||||
exit 0
|
||||
fi
|
||||
timeout 20s sudo -n systemctl link --runtime "$unit" || exit 1
|
||||
timeout 20s sudo -n systemctl start galaxy-ble-fork.service
|
||||
@@ -0,0 +1,115 @@
|
||||
"""On-device, offroad-only native app pairing for comma 4."""
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pyray as rl
|
||||
import qrcode
|
||||
|
||||
from openpilot.selfdrive.ui.mici.layouts.settings.galaxy import GalaxyQRDialog
|
||||
from openpilot.selfdrive.ui.mici.widgets.button import BigButton
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialog, BigMultiOptionDialog
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.tools.galaxy_bluetooth.bootstrap import setup_status, retry_setup
|
||||
from openpilot.tools.galaxy_bluetooth.bridge.pairing import ensure_key, load_key, rotate_key, qr_payload
|
||||
|
||||
|
||||
class PhoneQRDialog(GalaxyQRDialog):
|
||||
def __init__(self, key):
|
||||
self._key = key
|
||||
self._expires = time.monotonic() + 120
|
||||
super().__init__(qr_payload(key))
|
||||
self._title = UnifiedLabel("scan in Galaxy app\nBluetooth pairing\nkeep this code private",
|
||||
font_size=36, font_weight=FontWeight.BOLD)
|
||||
|
||||
def _generate_qr_code(self):
|
||||
# Standard dark modules with a four-module quiet zone for phone cameras.
|
||||
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=8, border=4)
|
||||
qr.add_data(self._url)
|
||||
qr.make(fit=True)
|
||||
image = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
|
||||
pixels = np.array(image, dtype=np.uint8)
|
||||
raw = rl.Image()
|
||||
raw.data = rl.ffi.cast("void *", pixels.ctypes.data)
|
||||
raw.width, raw.height = image.size
|
||||
raw.mipmaps = 1
|
||||
raw.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
|
||||
self._qr_texture = rl.load_texture_from_image(raw)
|
||||
rl.set_texture_filter(self._qr_texture, rl.TextureFilter.TEXTURE_FILTER_POINT)
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
try:
|
||||
current = load_key()
|
||||
except Exception:
|
||||
current = None
|
||||
if ui_state.started or current != self._key or time.monotonic() >= self._expires:
|
||||
self.dismiss()
|
||||
|
||||
def hide_event(self):
|
||||
# A popped dialog must not retain a visible pairing code in a GPU texture.
|
||||
if self._qr_texture and self._qr_texture.id:
|
||||
rl.unload_texture(self._qr_texture)
|
||||
self._qr_texture = None
|
||||
self._key = None
|
||||
self._url = ""
|
||||
super().hide_event()
|
||||
|
||||
|
||||
class PairPhoneButton(BigButton):
|
||||
def __init__(self):
|
||||
super().__init__("pair phone", "Galaxy app", gui_app.texture("icons_mici/settings/bluetooth.png", 64, 64))
|
||||
self.set_click_callback(self._show_options)
|
||||
|
||||
def _get_label_font_size(self):
|
||||
return 64
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
self.set_enabled(not ui_state.started)
|
||||
self.set_value(setup_status())
|
||||
|
||||
def _show_qr(self):
|
||||
if ui_state.started:
|
||||
return
|
||||
try:
|
||||
gui_app.push_widget(PhoneQRDialog(ensure_key()))
|
||||
except Exception:
|
||||
# Do not log credential contents or put a code on a web endpoint.
|
||||
gui_app.push_widget(BigDialog("pair phone", "Could not open pairing. Check the Galaxy bridge installation."))
|
||||
|
||||
def _forget(self):
|
||||
if ui_state.started:
|
||||
return
|
||||
try:
|
||||
rotate_key()
|
||||
gui_app.push_widget(BigDialog("phones forgotten", "All phones must scan a new code to use Galaxy Bluetooth."))
|
||||
except Exception:
|
||||
gui_app.push_widget(BigDialog("pair phone", "Could not forget phones. Try again."))
|
||||
|
||||
def _show_options(self):
|
||||
if ui_state.started:
|
||||
return
|
||||
holder = {}
|
||||
|
||||
def apply():
|
||||
if ui_state.started:
|
||||
return
|
||||
if holder["dialog"].get_selected_option() == "pair phone":
|
||||
self._show_qr()
|
||||
elif holder["dialog"].get_selected_option() == "retry setup":
|
||||
try:
|
||||
retry_setup()
|
||||
gui_app.push_widget(BigDialog("Bluetooth setup", "Setup queued. Connect comma to internet for first setup."))
|
||||
except OSError:
|
||||
gui_app.push_widget(BigDialog("Bluetooth setup", "Could not queue setup. Restart comma and try again."))
|
||||
elif holder["dialog"].get_selected_option() == "forget paired phones":
|
||||
gui_app.push_widget(BigConfirmationDialog(
|
||||
"forget all phones?\nscan again to reconnect",
|
||||
gui_app.texture("icons_mici/settings/bluetooth.png", 64, 64), self._forget, red=True))
|
||||
|
||||
dialog = BigMultiOptionDialog(options=["pair phone", "forget paired phones", "retry setup"],
|
||||
default="pair phone", right_btn_callback=apply)
|
||||
holder["dialog"] = dialog
|
||||
gui_app.push_widget(dialog)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Phone pairing for the comma 3/3X settings layout."""
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pyray as rl
|
||||
import qrcode
|
||||
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.widgets import Widget, DialogResult
|
||||
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog, alert_dialog
|
||||
from openpilot.system.ui.widgets.list_view import button_item
|
||||
from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog
|
||||
from openpilot.tools.galaxy_bluetooth.bootstrap import setup_status, retry_setup
|
||||
from openpilot.tools.galaxy_bluetooth.bridge.pairing import ensure_key, load_key, rotate_key, qr_payload
|
||||
|
||||
|
||||
class PhoneQRDialog(Widget):
|
||||
def __init__(self, key):
|
||||
super().__init__()
|
||||
self._key = key
|
||||
self._expires = time.monotonic() + 120
|
||||
self._texture = None
|
||||
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=8, border=4)
|
||||
qr.add_data(qr_payload(key))
|
||||
qr.make(fit=True)
|
||||
image = qr.make_image(fill_color="black", back_color="white").convert("RGBA")
|
||||
pixels = np.array(image, dtype=np.uint8)
|
||||
raw = rl.Image()
|
||||
raw.data = rl.ffi.cast("void *", pixels.ctypes.data)
|
||||
raw.width, raw.height = image.size
|
||||
raw.mipmaps = 1
|
||||
raw.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
|
||||
self._texture = rl.load_texture_from_image(raw)
|
||||
rl.set_texture_filter(self._texture, rl.TextureFilter.TEXTURE_FILTER_POINT)
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
try:
|
||||
current = load_key()
|
||||
except Exception:
|
||||
current = None
|
||||
if ui_state.started or current != self._key or time.monotonic() >= self._expires:
|
||||
gui_app.pop_widget()
|
||||
|
||||
def hide_event(self):
|
||||
if self._texture and self._texture.id:
|
||||
rl.unload_texture(self._texture)
|
||||
self._texture = None
|
||||
self._key = None
|
||||
super().hide_event()
|
||||
|
||||
def _handle_mouse_release(self, _):
|
||||
gui_app.pop_widget()
|
||||
|
||||
def _text(self, rect, text, y, size):
|
||||
font = gui_app.font(FontWeight.MEDIUM)
|
||||
width = measure_text_cached(font, text, size).x
|
||||
rl.draw_text_ex(font, text, rl.Vector2(rect.x + (rect.width - width) / 2, y), size, 0, rl.WHITE)
|
||||
|
||||
def _render(self, rect):
|
||||
rl.clear_background(rl.Color(26, 26, 48, 255))
|
||||
self._text(rect, "Scan in the Galaxy app", rect.y + 40, 60)
|
||||
if self._texture:
|
||||
size = min(rect.height * 0.60, rect.width * 0.60)
|
||||
target = rl.Rectangle(rect.x + (rect.width - size) / 2, rect.y + 140, size, size)
|
||||
source = rl.Rectangle(0, 0, self._texture.width, self._texture.height)
|
||||
rl.draw_texture_pro(self._texture, source, target, rl.Vector2(0, 0), 0, rl.WHITE)
|
||||
self._text(rect, "Bluetooth pairing • Keep this code private", rect.y + rect.height - 140, 36)
|
||||
self._text(rect, "Tap anywhere to dismiss", rect.y + rect.height - 80, 34)
|
||||
|
||||
|
||||
def pair_phone_item():
|
||||
def show_qr():
|
||||
if ui_state.started:
|
||||
return
|
||||
try:
|
||||
gui_app.push_widget(PhoneQRDialog(ensure_key()))
|
||||
except Exception:
|
||||
gui_app.push_widget(alert_dialog("Could not open pairing. Check the Galaxy bridge installation."))
|
||||
|
||||
def forget(result):
|
||||
if result != DialogResult.CONFIRM or ui_state.started:
|
||||
return
|
||||
try:
|
||||
rotate_key()
|
||||
gui_app.push_widget(alert_dialog("Phones forgotten. Scan a new code to reconnect."))
|
||||
except Exception:
|
||||
gui_app.push_widget(alert_dialog("Could not forget phones. Try again."))
|
||||
|
||||
def show_options():
|
||||
if ui_state.started:
|
||||
return
|
||||
|
||||
def apply(result):
|
||||
if result != DialogResult.CONFIRM or ui_state.started:
|
||||
return
|
||||
if dialog.selection == "Pair phone":
|
||||
show_qr()
|
||||
elif dialog.selection == "Retry setup":
|
||||
try:
|
||||
retry_setup()
|
||||
gui_app.push_widget(alert_dialog("Setup queued. Connect comma to internet for first setup."))
|
||||
except OSError:
|
||||
gui_app.push_widget(alert_dialog("Could not queue setup. Restart comma and try again."))
|
||||
elif dialog.selection == "Forget paired phones":
|
||||
gui_app.push_widget(ConfirmDialog("Forget all phones? Scan again to reconnect.", "Forget", callback=forget))
|
||||
|
||||
dialog = MultiOptionDialog(setup_status(), ["Pair phone", "Forget paired phones", "Retry setup"], "Pair phone", callback=apply)
|
||||
gui_app.push_widget(dialog)
|
||||
|
||||
return button_item("Pair phone", "MANAGE", lambda: setup_status(),
|
||||
callback=show_options, enabled=ui_state.is_offroad)
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Opt-in diagnostics and screen snapshots for the iPhone pilot."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import queue
|
||||
import struct
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
DATA = Path('/dev/shm/galaxy-companion')
|
||||
ENABLED = Path('/data/galaxy-ble/diagnostics-enabled')
|
||||
_lock = threading.Lock()
|
||||
_nonces = {}
|
||||
|
||||
|
||||
def atomic_write(name, content):
|
||||
DATA.mkdir(mode=0o700, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(dir=DATA, prefix=name + '.', suffix='.tmp', delete=False) as output:
|
||||
temporary = Path(output.name)
|
||||
try:
|
||||
output.write(content)
|
||||
output.flush()
|
||||
os.replace(temporary, DATA / name)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def register_routes(app):
|
||||
from flask import Response, jsonify, request, stream_with_context
|
||||
from openpilot.tools.galaxy_bluetooth.bridge.pairing import load_key
|
||||
|
||||
def allowed(path):
|
||||
if not ENABLED.exists():
|
||||
return False
|
||||
nonce = request.headers.get('X-Companion-Nonce', '')
|
||||
mac = request.headers.get('X-Companion-MAC', '')
|
||||
if len(nonce) != 32 or any(c not in '0123456789abcdef' for c in nonce):
|
||||
return False
|
||||
try:
|
||||
expected = hmac.new(load_key(), f'{nonce}\nGET\n{path}'.encode(), hashlib.sha256).hexdigest()
|
||||
except (OSError, ValueError, KeyError):
|
||||
return False
|
||||
if not hmac.compare_digest(mac, expected):
|
||||
return False
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
for key, expiry in list(_nonces.items()):
|
||||
if expiry <= now:
|
||||
del _nonces[key]
|
||||
if nonce in _nonces or len(_nonces) >= 1024:
|
||||
return False
|
||||
_nonces[nonce] = now + 120
|
||||
return True
|
||||
|
||||
def denial(path):
|
||||
if not ENABLED.exists():
|
||||
return jsonify(error='Diagnostics are disabled on comma.'), 503
|
||||
if not allowed(path):
|
||||
return jsonify(error='Phone pairing was rejected.'), 403
|
||||
return None
|
||||
|
||||
@app.get('/api/companion/diagnostics')
|
||||
def diagnostics():
|
||||
rejected = denial('/api/companion/diagnostics')
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
try:
|
||||
sample = json.loads((DATA / 'diagnostics.json').read_bytes())
|
||||
sample['ageSeconds'] = max(0, time.monotonic() - sample.pop('monotonic'))
|
||||
response = jsonify(sample)
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
except (OSError, ValueError, KeyError):
|
||||
return jsonify(error='Waiting for comma UI telemetry.'), 503
|
||||
|
||||
@app.get('/api/companion/frame')
|
||||
def frame():
|
||||
rejected = denial('/api/companion/frame')
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
atomic_write('capture-request', str(time.monotonic()).encode())
|
||||
try:
|
||||
raw = (DATA / 'frame.bin').read_bytes()
|
||||
captured = struct.unpack('!d', raw[:8])[0]
|
||||
age = max(0, time.monotonic() - captured)
|
||||
if age > 1 or len(raw) > 650008:
|
||||
return jsonify(error='Waiting for a fresh screen frame.'), 503
|
||||
response = jsonify(image=base64.b64encode(raw[8:]).decode(), ageSeconds=age)
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
except (OSError, ValueError, struct.error):
|
||||
return jsonify(error='Waiting for screen capture.'), 503
|
||||
|
||||
@app.get('/api/companion/stream')
|
||||
def stream():
|
||||
rejected = denial('/api/companion/stream')
|
||||
if rejected is not None:
|
||||
return rejected
|
||||
session_key = load_key()
|
||||
|
||||
@stream_with_context
|
||||
def frames():
|
||||
last = None
|
||||
started = time.monotonic()
|
||||
lease = 0.0
|
||||
while ENABLED.exists() and time.monotonic() - started < 60:
|
||||
now = time.monotonic()
|
||||
if now - lease >= 1:
|
||||
try:
|
||||
if not hmac.compare_digest(session_key, load_key()):
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
atomic_write('capture-request', str(now).encode())
|
||||
lease = now
|
||||
yield b'\r\n'
|
||||
try:
|
||||
raw = (DATA / 'frame.bin').read_bytes()
|
||||
captured = struct.unpack('!d', raw[:8])[0]
|
||||
if captured != last and 0 <= now - captured < 1 and 8 < len(raw) <= 650008:
|
||||
last = captured
|
||||
image = raw[8:]
|
||||
yield b'--galaxy-frame\r\nContent-Type: image/jpeg\r\nContent-Length: ' + str(len(image)).encode() + b'\r\n\r\n' + image + b'\r\n'
|
||||
except (OSError, ValueError, struct.error):
|
||||
pass
|
||||
time.sleep(0.01)
|
||||
|
||||
response = Response(frames(), content_type='multipart/x-mixed-replace; boundary=galaxy-frame')
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
response.headers['X-Accel-Buffering'] = 'no'
|
||||
return response
|
||||
|
||||
|
||||
|
||||
class CompanionPublisher:
|
||||
def __init__(self):
|
||||
self.last = 0.0
|
||||
self.previous = {}
|
||||
self.received = {}
|
||||
self.last_capture = 0.0
|
||||
self.capture_failed_until = 0.0
|
||||
self.extra = None
|
||||
self.images = queue.Queue(maxsize=1)
|
||||
self.encoder = None
|
||||
self.process = None
|
||||
self.video_size = None
|
||||
self.sent_times = queue.Queue(maxsize=8)
|
||||
self.capture_hook = 0.0
|
||||
self.last_encoded = 0.0
|
||||
self.capture_error = None
|
||||
self.encoder_error = None
|
||||
self.encoder_stderr = None
|
||||
|
||||
def update(self, ui, gui):
|
||||
if not ENABLED.exists():
|
||||
return
|
||||
now = time.monotonic()
|
||||
if self.extra is None:
|
||||
from cereal import messaging
|
||||
self.extra = messaging.SubMaster(['driverCameraState', 'chestnutState'])
|
||||
self.extra.update(0)
|
||||
rates = []
|
||||
sm = ui.sm
|
||||
sources = [('UI', gui.frame, 'FPS', now)]
|
||||
for source in (sm, self.extra):
|
||||
for service in source.services:
|
||||
recv = source.recv_time[service]
|
||||
if recv <= 0 or not source.valid.get(service, False):
|
||||
continue
|
||||
message = source[service]
|
||||
if hasattr(message, 'frameId'):
|
||||
sources.append((service, int(message.frameId), 'FPS', recv))
|
||||
else:
|
||||
seen = source.recv_frame[service]
|
||||
previous = self.received.get(service, (-1, 0))
|
||||
count = previous[1] + int(seen != previous[0])
|
||||
self.received[service] = (seen, count)
|
||||
sources.append((service, count, 'Hz observed', recv))
|
||||
if now - self.last < 1:
|
||||
return
|
||||
elapsed = now - self.last
|
||||
for name, count, unit, recv in sources:
|
||||
old = self.previous.get(name)
|
||||
fresh = now - recv < 3
|
||||
value = (count - old) / elapsed if old is not None and count >= old and fresh else None
|
||||
rates.append({'name': name, 'value': round(value, 1) if value is not None else None, 'unit': unit})
|
||||
self.previous = {name: count for name, count, _, _ in sources}
|
||||
self.last = now
|
||||
capture_status = {
|
||||
'hookAgeSeconds': round(now - self.capture_hook, 2) if self.capture_hook else None,
|
||||
'frameAgeSeconds': round(now - self.last_encoded, 2) if self.last_encoded else None,
|
||||
'queuedImages': self.images.qsize(), 'captureError': self.capture_error,
|
||||
'encoderError': self.encoder_error,
|
||||
'encoderStderr': self.encoder_stderr,
|
||||
'encoderExitCode': self.process.poll() if self.process is not None else None,
|
||||
'videoSize': list(self.video_size) if self.video_size else None,
|
||||
'encoderRunning': self.process is not None and self.process.poll() is None,
|
||||
}
|
||||
atomic_write('capture-status.json', json.dumps(capture_status).encode())
|
||||
temperatures = []
|
||||
device = sm['deviceState']
|
||||
if sm.valid['deviceState'] and now - sm.recv_time['deviceState'] < 3:
|
||||
for field in ('cpuTempC', 'gpuTempC', 'dspTempC', 'memoryTempC', 'modemTempC', 'pmicTempC', 'intakeTempC', 'exhaustTempC', 'gnssTempC', 'bottomSocTempC'):
|
||||
value = getattr(device, field, None)
|
||||
values = [value] if isinstance(value, (int, float)) else list(value or [])
|
||||
for i, reading in enumerate(values):
|
||||
reading = float(reading)
|
||||
names = {'cpu': 'CPU', 'gpu': 'GPU', 'dsp': 'DSP', 'pmic': 'PMIC', 'gnss': 'GNSS', 'bottomSoc': 'Bottom SoC'}
|
||||
stem = field.removesuffix('TempC')
|
||||
label = names.get(stem, stem.capitalize()) + (f' {i + 1}' if len(values) > 1 else '')
|
||||
temperatures.append({'name': label, 'value': round(reading, 1) if math.isfinite(reading) and reading > 0 else None, 'unit': '°C'})
|
||||
if self.extra.valid['chestnutState'] and now - self.extra.recv_time['chestnutState'] < 3:
|
||||
chestnut = self.extra['chestnutState']
|
||||
for label, field in [('External GPU', 'tempC'), ('External GPU memory', 'memoryTempC')]:
|
||||
value = float(getattr(chestnut, field, 0))
|
||||
temperatures.append({'name': label, 'value': round(value, 1) if math.isfinite(value) and value > 0 else None, 'unit': '°C'})
|
||||
for zone in sorted(Path('/sys/class/thermal').glob('thermal_zone*')):
|
||||
try:
|
||||
value = float((zone / 'temp').read_text()) / 1000
|
||||
if math.isfinite(value) and 0 < value < 200:
|
||||
temperatures.append({'name': 'Sensor: ' + (zone / 'type').read_text().strip(), 'value': round(value, 1), 'unit': '°C'})
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
for monitor in sorted(Path('/sys/class/hwmon').glob('hwmon*')):
|
||||
for sensor in sorted(monitor.glob('temp*_input')):
|
||||
try:
|
||||
value = float(sensor.read_text()) / 1000
|
||||
name = (monitor / 'name').read_text().strip()
|
||||
label_path = sensor.with_name(sensor.name.replace('_input', '_label'))
|
||||
label = label_path.read_text().strip() if label_path.exists() else sensor.stem
|
||||
if math.isfinite(value) and 0 < value < 200:
|
||||
temperatures.append({'name': f'Sensor: {name} {label}', 'value': round(value, 1), 'unit': '°C'})
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
atomic_write('diagnostics.json', json.dumps({'monotonic': now, 'engaged': bool(ui.engaged) if sm.valid.get('selfdriveState', False) and now - sm.recv_time.get('selfdriveState', 0) < 3 else None, 'temperatures': temperatures,
|
||||
'rates': rates, 'captureLimitFPS': 20, 'capture': capture_status}, allow_nan=False, separators=(',', ':')).encode())
|
||||
|
||||
def capture(self):
|
||||
if not ENABLED.exists():
|
||||
return
|
||||
now = time.monotonic()
|
||||
self.capture_hook = now
|
||||
if now < self.capture_failed_until or now - self.last_capture < 0.045 or self.images.full():
|
||||
return
|
||||
try:
|
||||
if now - float((DATA / 'capture-request').read_text()) > 4:
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
import pyray as rl
|
||||
image = None
|
||||
self.last_capture = now
|
||||
try:
|
||||
rl.rl_draw_render_batch_active()
|
||||
image = rl.load_image_from_screen()
|
||||
if not image.data or image.width <= 0 or image.height <= 0:
|
||||
raise ValueError('No screen pixels')
|
||||
width = min(image.width, 960)
|
||||
height = max(1, round(image.height * width / image.width))
|
||||
rl.image_resize(image, width, height)
|
||||
if self.encoder is None:
|
||||
self.encoder = threading.Thread(target=self.encode, daemon=True)
|
||||
self.encoder.start()
|
||||
self.images.put_nowait((image, now))
|
||||
self.capture_error = None
|
||||
image = None
|
||||
|
||||
except Exception as error:
|
||||
self.capture_error = str(error)[:500]
|
||||
logging.getLogger("galaxy-companion").warning("Screen capture: %s", error)
|
||||
self.capture_failed_until = now + 10
|
||||
finally:
|
||||
if image is not None:
|
||||
rl.unload_image(image)
|
||||
|
||||
def read_encoded(self, process, times):
|
||||
buffer = bytearray()
|
||||
try:
|
||||
while True:
|
||||
chunk = process.stdout.read1(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buffer.extend(chunk)
|
||||
if len(buffer) > 1300000:
|
||||
return
|
||||
while True:
|
||||
start = buffer.find(b'\xff\xd8')
|
||||
end = buffer.find(b'\xff\xd9', max(0, start))
|
||||
if start < 0 or end < 0:
|
||||
break
|
||||
raw = bytes(buffer[start:end + 2])
|
||||
del buffer[:end + 2]
|
||||
captured = times.get(timeout=2)
|
||||
if len(raw) <= 650000 and time.monotonic() - captured < 1 and ENABLED.exists():
|
||||
atomic_write('frame.bin', struct.pack('!d', captured) + raw)
|
||||
self.last_encoded = captured
|
||||
except (OSError, ValueError, queue.Empty):
|
||||
pass
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
|
||||
def encode(self):
|
||||
import pyray as rl
|
||||
while True:
|
||||
image, captured = self.images.get()
|
||||
try:
|
||||
if not ENABLED.exists() or time.monotonic() - captured > 1:
|
||||
continue
|
||||
dimensions = (image.width, image.height)
|
||||
if self.process is None or self.process.poll() is not None or self.video_size != dimensions:
|
||||
if self.process is not None and self.process.poll() is None:
|
||||
self.process.kill()
|
||||
self.process.wait(timeout=2)
|
||||
self.sent_times = queue.Queue(maxsize=8)
|
||||
self.process = subprocess.Popen([
|
||||
'ffmpeg', '-loglevel', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgba',
|
||||
'-s:v', f'{image.width}x{image.height}', '-r', '20', '-i', 'pipe:0',
|
||||
'-an', '-c:v', 'mjpeg', '-q:v', '5', '-threads', '1', '-f', 'rawvideo',
|
||||
'-flush_packets', '1', 'pipe:1'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
self.video_size = dimensions
|
||||
self.encoder_error = None
|
||||
self.encoder_stderr = None
|
||||
threading.Thread(target=self.read_encoder_errors, args=(self.process,), daemon=True).start()
|
||||
threading.Thread(target=self.read_encoded, args=(self.process, self.sent_times), daemon=True).start()
|
||||
rl.image_format(image, rl.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)
|
||||
raw = bytes(rl.ffi.buffer(image.data, image.width * image.height * 4))
|
||||
self.sent_times.put_nowait(captured)
|
||||
self.process.stdin.write(raw)
|
||||
self.process.stdin.flush()
|
||||
except Exception as error:
|
||||
self.encoder_error = str(error)[:500]
|
||||
logging.getLogger("galaxy-companion").warning("Screen encoder: %s", error)
|
||||
self.capture_failed_until = time.monotonic() + 10
|
||||
if self.process is not None and self.process.poll() is None:
|
||||
self.process.kill()
|
||||
finally:
|
||||
rl.unload_image(image)
|
||||
self.images.task_done()
|
||||
|
||||
def read_encoder_errors(self, process):
|
||||
try:
|
||||
for line in process.stderr:
|
||||
if process is self.process:
|
||||
self.encoder_stderr = line.decode(errors='replace').strip()[:500]
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
publisher = CompanionPublisher()
|
||||
|
||||
|
||||
def publish_telemetry(ui, gui):
|
||||
try:
|
||||
publisher.update(ui, gui)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def capture_frame():
|
||||
try:
|
||||
publisher.capture()
|
||||
except Exception as error:
|
||||
publisher.capture_error = str(error)[:500]
|
||||
@@ -0,0 +1,47 @@
|
||||
diff --git a/selfdrive/ui/layouts/settings/settings.py b/selfdrive/ui/layouts/settings/settings.py
|
||||
--- a/selfdrive/ui/layouts/settings/settings.py
|
||||
+++ b/selfdrive/ui/layouts/settings/settings.py
|
||||
@@ -16,6 +16,7 @@
|
||||
from openpilot.system.ui.widgets import Widget
|
||||
from openpilot.system.ui.widgets.bluetooth import BluetoothManagerUI
|
||||
from openpilot.system.ui.widgets.network import NetworkUI
|
||||
+from openpilot.tools.galaxy_bluetooth.comma_pairing_tici import pair_phone_item
|
||||
|
||||
# Constants
|
||||
COLLAPSED_WIDTH = 0
|
||||
@@ -80,7 +81,7 @@
|
||||
PanelType.STARPILOT: PanelInfo(tr_noop("StarPilot"), StarPilotLayout()),
|
||||
PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayout()),
|
||||
PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUI(wifi_manager)),
|
||||
- PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothManagerUI(bluetooth_manager)),
|
||||
+ PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothManagerUI(bluetooth_manager, phone_pairing=pair_phone_item())),
|
||||
PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout()),
|
||||
PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayout()),
|
||||
PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayout()),
|
||||
diff --git a/system/ui/widgets/bluetooth.py b/system/ui/widgets/bluetooth.py
|
||||
--- a/system/ui/widgets/bluetooth.py
|
||||
+++ b/system/ui/widgets/bluetooth.py
|
||||
@@ -177,8 +177,9 @@
|
||||
|
||||
class BluetoothManagerUI(Widget):
|
||||
"""Big UI Bluetooth settings panel backed by the existing Bluetooth manager daemon."""
|
||||
- def __init__(self, manager: BluetoothManager):
|
||||
+ def __init__(self, manager: BluetoothManager, phone_pairing: Widget | None = None):
|
||||
super().__init__()
|
||||
+ self._phone_pairing = phone_pairing
|
||||
self._manager = manager
|
||||
self._scroll_panel = GuiScrollPanel()
|
||||
self._power_toggle = Toggle(initial_state=False, callback=self._toggle_power)
|
||||
@@ -378,7 +379,11 @@
|
||||
header_rect = rl.Rectangle(rect.x, rect.y, rect.width, HEADER_HEIGHT)
|
||||
self._render_header(header_rect, status)
|
||||
|
||||
- content_rect = rl.Rectangle(rect.x, rect.y + HEADER_HEIGHT, rect.width, rect.height - HEADER_HEIGHT)
|
||||
+ content_y = rect.y + HEADER_HEIGHT
|
||||
+ if self._phone_pairing is not None:
|
||||
+ self._phone_pairing.render(rl.Rectangle(rect.x + HEADER_PADDING, content_y, rect.width - 2 * HEADER_PADDING, ITEM_HEIGHT))
|
||||
+ content_y += ITEM_HEIGHT
|
||||
+ content_rect = rl.Rectangle(rect.x, content_y, rect.width, rect.y + rect.height - content_y)
|
||||
if not status.available:
|
||||
gui_label(content_rect, tr("Bluetooth is not available on this device."), font_size=62,
|
||||
color=TEXT_SECONDARY, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER)
|
||||
@@ -0,0 +1,49 @@
|
||||
# StarPilot Live / CarPlay pilot
|
||||
|
||||
The phone receives a continuous JPEG stream of the full comma display over local Wi-Fi, targeting 20 FPS at 960 pixels wide. The actual received FPS is shown on the phone. Bluetooth carries diagnostics only. Hardware throughput and capture overhead still need measurement.
|
||||
|
||||
CarPlay shows read-only temperatures, frame rates and observed message rates. Opening it selects Live View on the phone for when the phone is foregrounded. It does not unlock the phone or force it to the foreground. Custom driving-screen video is not included in the CarPlay display.
|
||||
|
||||
## Enable on comma
|
||||
|
||||
Update the installed fork to `Nate/galaxy-bluetooth`. Check its Git remote and branch before pulling. While parked, run in the comma SSH terminal:
|
||||
|
||||
```sh
|
||||
command -v ffmpeg
|
||||
mkdir -p /data/galaxy-ble
|
||||
touch /data/galaxy-ble/diagnostics-enabled
|
||||
sudo systemctl restart galaxy-ble-fork.service
|
||||
sudo reboot
|
||||
```
|
||||
|
||||
Confirm the first command prints an FFmpeg path before enabling capture. Reboot loads the Galaxy routes and UI capture hooks. The bridge must already be installed. Capture is disabled without the flag and only runs while an authenticated phone requests frames; it stops about four seconds after requests stop.
|
||||
|
||||
To disable:
|
||||
|
||||
```sh
|
||||
rm -f /data/galaxy-ble/diagnostics-enabled
|
||||
```
|
||||
|
||||
## Phone check
|
||||
|
||||
1. Rebuild/run in Xcode. Pair with comma once in this build to update the stored key’s accessibility for CarPlay after the phone’s first unlock.
|
||||
2. Connect via local Wi-Fi, then open **Live View & diagnostics** or **Live** from Galaxy.
|
||||
3. Check the displayed image against the complete comma screen, including overlays. Verify orientation and text readability. Capture uses raylib’s framebuffer. FFmpeg JPEG encoding runs in a background worker with a one-frame queue; old frames are dropped. Hardware capture and performance have not yet been verified.
|
||||
4. Compare UI FPS with Live View on and off. Stop if capture causes UI stalls. Errors stop capture temporarily; stale images are removed from the phone.
|
||||
5. Disconnect Wi-Fi: the image disappears, while diagnostics may continue through paired Bluetooth. Stop the comma UI or disconnect the phone and confirm stale values disappear.
|
||||
|
||||
If no fresh frame arrives for ten seconds, tap **Copy diagnostics** and paste the report to the developer. It includes recent connection events and capture/encoder errors, without pairing keys or authentication headers. Update both the phone app and comma fork for capture details. On comma, the same capture report is available at `/dev/shm/galaxy-companion/capture-status.json`.
|
||||
|
||||
Temperatures include reported CPU, onboard GPU, memory, DSP, modem, PMIC, intake, exhaust, GNSS and SoC values; available kernel thermal/hwmon sensors; and Chestnut GPU/memory when present. Sensor availability varies, and some kernel sensors duplicate existing readings. Missing/default zero values are not displayed as measured temperatures.
|
||||
|
||||
FPS is derived from UI frames and camera/model frame counters. Other subscribed services show observed updates per second, not rendering FPS. It is not an FPS measurement of every Linux process. First samples need another update to establish rates.
|
||||
|
||||
## CarPlay check
|
||||
|
||||
`CarPlaySceneDelegate.swift` and the scene configuration are included. Physical CarPlay requires Apple’s approved driving-task entitlement and a matching signing profile. TestFlight alone does not grant it. The entitlement file is provided but is **not enabled in the regular phone build**.
|
||||
|
||||
With approval, set the target’s **Code Signing Entitlements** to `GalaxyBluetooth/CarPlay.entitlements`, build and test through CarPlay. The delegate presents a native read-only list and selects the phone’s Live View. Simulator/live vehicle behavior remains untested. CarPlay cannot display an arbitrary full-screen camera/overlay stream through these templates.
|
||||
|
||||
## Scope
|
||||
|
||||
This adds one optional helper and small hooks in the UI renderer, UI state loop and Galaxy startup. No vehicle controls or settings are written. Screen/diagnostics reads require an opt-in flag and HMAC requests signed with the existing pairing key. LAN responses use Galaxy’s existing HTTP and are not encrypted; use a trusted local network. No screen recordings are retained on disk; only the latest JPEG and telemetry live in shared memory. A stream session reconnects every minute and rechecks pairing-key revocation. FFmpeg must be available in the comma UI environment. If encoding fails, capture pauses and the phone shows no live frame.
|
||||
@@ -0,0 +1,85 @@
|
||||
// !$*UTF8*$!
|
||||
{ archiveVersion = 1; classes = {}; objectVersion = 56; objects = {
|
||||
D47658A09FCC6A6C73D1A1A3 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BluetoothTransport.swift"; sourceTree = "<group>"; };
|
||||
140107256F4F4DF2910BED61 = { isa = PBXBuildFile; fileRef = D47658A09FCC6A6C73D1A1A3; };
|
||||
8F213860FC7A532DBD355109 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CarPlaySceneDelegate.swift"; sourceTree = "<group>"; };
|
||||
A6D597850E6DD0CDFB754EF8 = { isa = PBXBuildFile; fileRef = 8F213860FC7A532DBD355109; };
|
||||
8AD85D1A585138AF80FEADB9 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CompanionDiagnostics.swift"; sourceTree = "<group>"; };
|
||||
28D504D2BD92FF8A8AEB68A7 = { isa = PBXBuildFile; fileRef = 8AD85D1A585138AF80FEADB9; };
|
||||
4A6311E858CDB1BD4920077F = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "GalaxyAssetStore.swift"; sourceTree = "<group>"; };
|
||||
2A682386E9EC74235CD11405 = { isa = PBXBuildFile; fileRef = 4A6311E858CDB1BD4920077F; };
|
||||
3356A9DC86451A9D92F074F8 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "GalaxyBluetoothApp.swift"; sourceTree = "<group>"; };
|
||||
36EBF9BB2BE027F139572ADA = { isa = PBXBuildFile; fileRef = 3356A9DC86451A9D92F074F8; };
|
||||
80D0F5CDB02B33E408C75D8C = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "GalaxyRequestTransport.swift"; sourceTree = "<group>"; };
|
||||
8BA587954B4079F504AAD35E = { isa = PBXBuildFile; fileRef = 80D0F5CDB02B33E408C75D8C; };
|
||||
BF41C7E4AB86DEB71B85E4F6 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "GalaxyWebView.swift"; sourceTree = "<group>"; };
|
||||
DE64BADD40C934E610D4D505 = { isa = PBXBuildFile; fileRef = BF41C7E4AB86DEB71B85E4F6; };
|
||||
34DE7063A67F0755E6E69BF7 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HTTP.swift"; sourceTree = "<group>"; };
|
||||
1698566BBEF2185D9C80B6BB = { isa = PBXBuildFile; fileRef = 34DE7063A67F0755E6E69BF7; };
|
||||
F3032D4A3D2E5EE30499DF81 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LiveStream.swift"; sourceTree = "<group>"; };
|
||||
2B85690770820EED1B745258 = { isa = PBXBuildFile; fileRef = F3032D4A3D2E5EE30499DF81; };
|
||||
B07071562661895558F74EE6 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LoopbackServer.swift"; sourceTree = "<group>"; };
|
||||
5992DC6B04748581DE47AA02 = { isa = PBXBuildFile; fileRef = B07071562661895558F74EE6; };
|
||||
1E4606411FF46FC358A57309 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NetworkTransport.swift"; sourceTree = "<group>"; };
|
||||
B43A299D9DC20C1A52EF0FA8 = { isa = PBXBuildFile; fileRef = 1E4606411FF46FC358A57309; };
|
||||
43A1199899003FF3F5F30831 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PairingKeyStore.swift"; sourceTree = "<group>"; };
|
||||
BC3706D8A74BDB5B0AA8063E = { isa = PBXBuildFile; fileRef = 43A1199899003FF3F5F30831; };
|
||||
0BD8AAC162EE2668A9FD16BA = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PairingScanner.swift"; sourceTree = "<group>"; };
|
||||
2E4A82AC9BEEE068C5B22A47 = { isa = PBXBuildFile; fileRef = 0BD8AAC162EE2668A9FD16BA; };
|
||||
6A4F45F0CE946309B0256EB0 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PrivateLANHTTP.swift"; sourceTree = "<group>"; };
|
||||
F554251230F20602FFF9DDB5 = { isa = PBXBuildFile; fileRef = 6A4F45F0CE946309B0256EB0; };
|
||||
F48B8D06AA8D8C4AC21E5982 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Wire.swift"; sourceTree = "<group>"; };
|
||||
7F54642B30B38C648001D4ED = { isa = PBXBuildFile; fileRef = F48B8D06AA8D8C4AC21E5982; };
|
||||
9CEEC13202AFBF12EE3ABB99 = { isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
4B5E57F6EB2F42B9039B3D1E = { isa = PBXFileReference; lastKnownFileType = folder; path = Resources/Web; sourceTree = "<group>"; };
|
||||
4E7D2B65B79ACE4A91B667A2 = { isa = PBXBuildFile; fileRef = 4B5E57F6EB2F42B9039B3D1E; };
|
||||
9F0B8B04FE0E80BA046C0042 = { isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Resources/Branding.xcassets; sourceTree = "<group>"; };
|
||||
606A672A792903E98EFFC2D9 = { isa = PBXBuildFile; fileRef = 9F0B8B04FE0E80BA046C0042; };
|
||||
A172CEDCAE47474B615C54D5 = { isa = PBXFileReference; explicitFileType = wrapper.application; path = GalaxyBluetooth.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
9E61AFF607A3704A97803240 = { isa = PBXGroup; children = (D47658A09FCC6A6C73D1A1A3,8F213860FC7A532DBD355109,8AD85D1A585138AF80FEADB9,4A6311E858CDB1BD4920077F,3356A9DC86451A9D92F074F8,80D0F5CDB02B33E408C75D8C,BF41C7E4AB86DEB71B85E4F6,34DE7063A67F0755E6E69BF7,F3032D4A3D2E5EE30499DF81,B07071562661895558F74EE6,1E4606411FF46FC358A57309,43A1199899003FF3F5F30831,0BD8AAC162EE2668A9FD16BA,6A4F45F0CE946309B0256EB0,F48B8D06AA8D8C4AC21E5982,9CEEC13202AFBF12EE3ABB99,4B5E57F6EB2F42B9039B3D1E,9F0B8B04FE0E80BA046C0042); path = GalaxyBluetooth; sourceTree = "<group>"; };
|
||||
0A3E27B8CA818264D75C8D81 = { isa = PBXGroup; children = (A172CEDCAE47474B615C54D5); name = Products; sourceTree = "<group>"; };
|
||||
C69913C7EE4DFDD011BE172F = { isa = PBXGroup; children = (9E61AFF607A3704A97803240,0A3E27B8CA818264D75C8D81); sourceTree = "<group>"; };
|
||||
878A52FC5FF6A57D50B7B870 = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (140107256F4F4DF2910BED61,A6D597850E6DD0CDFB754EF8,28D504D2BD92FF8A8AEB68A7,2A682386E9EC74235CD11405,36EBF9BB2BE027F139572ADA,8BA587954B4079F504AAD35E,DE64BADD40C934E610D4D505,1698566BBEF2185D9C80B6BB,2B85690770820EED1B745258,5992DC6B04748581DE47AA02,B43A299D9DC20C1A52EF0FA8,BC3706D8A74BDB5B0AA8063E,2E4A82AC9BEEE068C5B22A47,F554251230F20602FFF9DDB5,7F54642B30B38C648001D4ED); runOnlyForDeploymentPostprocessing = 0; };
|
||||
41D311A605520FC7B8B9A980 = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (4E7D2B65B79ACE4A91B667A2,606A672A792903E98EFFC2D9); runOnlyForDeploymentPostprocessing = 0; };
|
||||
E2AA269EB967A8853A258BFA = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
|
||||
488864B3D19480A82F7F1786 = { isa = XCBuildConfiguration; name = Debug; buildSettings = { SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 17.0; CLANG_ENABLE_MODULES = YES; }; };
|
||||
952548237D7F645F11D1E7B6 = { isa = XCBuildConfiguration; name = Debug; buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = link.galaxy.bluetooth;
|
||||
INFOPLIST_FILE = GalaxyBluetooth/Info.plist;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
SWIFT_VERSION = 5.0;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
}; };
|
||||
35B1014F135DE9B45529B733 = { isa = XCBuildConfiguration; name = Release; buildSettings = { SDKROOT = iphoneos; IPHONEOS_DEPLOYMENT_TARGET = 17.0; CLANG_ENABLE_MODULES = YES; }; };
|
||||
E2D3A31BEAA1368FC62DA77A = { isa = XCBuildConfiguration; name = Release; buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = link.galaxy.bluetooth;
|
||||
INFOPLIST_FILE = GalaxyBluetooth/Info.plist;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
SWIFT_VERSION = 5.0;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
}; };
|
||||
442D61E217DD044EA4245BF2 = { isa = XCConfigurationList; buildConfigurations = (488864B3D19480A82F7F1786,35B1014F135DE9B45529B733); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
|
||||
EE8ED050E3386ACB51F5825B = { isa = XCConfigurationList; buildConfigurations = (952548237D7F645F11D1E7B6,E2D3A31BEAA1368FC62DA77A); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
|
||||
34A04005BCAF206EEC990BD9 = { isa = PBXNativeTarget; name = GalaxyBluetooth; productName = GalaxyBluetooth;
|
||||
productReference = A172CEDCAE47474B615C54D5; productType = "com.apple.product-type.application";
|
||||
buildConfigurationList = EE8ED050E3386ACB51F5825B;
|
||||
buildPhases = (878A52FC5FF6A57D50B7B870,E2AA269EB967A8853A258BFA,41D311A605520FC7B8B9A980); buildRules = (); dependencies = (); };
|
||||
244210E48437B6556980A702 = { isa = PBXProject; attributes = { LastUpgradeCheck = 1600; };
|
||||
buildConfigurationList = 442D61E217DD044EA4245BF2; compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en; knownRegions = (en, Base); mainGroup = C69913C7EE4DFDD011BE172F;
|
||||
productRefGroup = 0A3E27B8CA818264D75C8D81; projectDirPath = ""; projectRoot = ""; targets = (34A04005BCAF206EEC990BD9); };
|
||||
}; rootObject = 244210E48437B6556980A702; }
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme LastUpgradeVersion="1600" version="1.3">
|
||||
<BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="34A04005BCAF206EEC990BD9" BuildableName="GalaxyBluetooth.app" BlueprintName="GalaxyBluetooth" ReferencedContainer="container:GalaxyBluetooth.xcodeproj"/></BuildActionEntry></BuildActionEntries></BuildAction>
|
||||
<LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.IDEFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" debugServiceExtension="internal" allowLocationSimulation="YES"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="34A04005BCAF206EEC990BD9" BuildableName="GalaxyBluetooth.app" BlueprintName="GalaxyBluetooth" ReferencedContainer="container:GalaxyBluetooth.xcodeproj"/></BuildableProductRunnable></LaunchAction>
|
||||
<ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="34A04005BCAF206EEC990BD9" BuildableName="GalaxyBluetooth.app" BlueprintName="GalaxyBluetooth" ReferencedContainer="container:GalaxyBluetooth.xcodeproj"/></BuildableProductRunnable></ProfileAction>
|
||||
<AnalyzeAction buildConfiguration="Debug"/>
|
||||
<ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,470 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import CoreBluetooth
|
||||
import CryptoKit
|
||||
|
||||
struct NearbyDevice: Identifiable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let signal: Int
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class BluetoothTransport: NSObject, ObservableObject, GalaxyRequestTransport, @preconcurrency CBCentralManagerDelegate, @preconcurrency CBPeripheralDelegate {
|
||||
@Published var devices: [NearbyDevice] = []
|
||||
@Published var status = "Turn on Bluetooth, then scan for your comma."
|
||||
@Published var isScanning = false
|
||||
@Published var connected = false
|
||||
@Published var connecting = false
|
||||
|
||||
private var central: CBCentralManager!
|
||||
private var peripherals: [UUID: CBPeripheral] = [:]
|
||||
private var peripheral: CBPeripheral?
|
||||
private var rx: CBCharacteristic?
|
||||
private var tx: CBCharacteristic?
|
||||
private var notify: CBCharacteristic?
|
||||
private var key: SymmetricKey?
|
||||
private var keyText = ""
|
||||
private var session = ""
|
||||
var sessionIdentifier: String { session }
|
||||
private(set) var catalogSHA256: String?
|
||||
private var supportsReadStream = false
|
||||
private var activeReadStream = false
|
||||
private var supportsNotifications = false
|
||||
private var activeNotifications = false
|
||||
private var pairingVerified = false
|
||||
private var notificationTag = Data()
|
||||
private var notificationCount = 0
|
||||
private var notificationBuffer: [Data] = []
|
||||
private var notificationTimeout: Task<Void, Never>?
|
||||
private var counter: UInt64 = 0
|
||||
private var queue: [Pending] = []
|
||||
private var active: Pending?
|
||||
private var outgoing: [Data] = []
|
||||
private var writeIndex = 0
|
||||
private var assembler = FrameAssembler()
|
||||
private var awaitingAck = false
|
||||
private var completedResponse: BridgeResponse?
|
||||
private var activeCancelled = false
|
||||
private var timeoutTask: Task<Void, Never>?
|
||||
private var scanTimeout: Task<Void, Never>?
|
||||
private var connectionTimeout: Task<Void, Never>?
|
||||
|
||||
private struct Pending {
|
||||
let id: String
|
||||
let path: String
|
||||
let method: String
|
||||
let headers: [String: String]
|
||||
let body: Data
|
||||
let completion: CheckedContinuation<BridgeResponse, Error>
|
||||
}
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
central = CBCentralManager(delegate: self, queue: .main)
|
||||
}
|
||||
|
||||
func reconnectSaved(pairingKey: String) {
|
||||
guard !connected, !connecting, central.state == .poweredOn,
|
||||
let value = UserDefaults.standard.string(forKey: "galaxy.bluetooth.device"),
|
||||
let id = UUID(uuidString: value),
|
||||
let found = central.retrievePeripherals(withIdentifiers: [id]).first else { return }
|
||||
peripherals[id] = found
|
||||
connect(NearbyDevice(id: id, name: found.name ?? "comma", signal: 0), pairingKey: pairingKey)
|
||||
}
|
||||
|
||||
func forgetSavedDevice() {
|
||||
disconnect()
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.bluetooth.device")
|
||||
}
|
||||
|
||||
func scan() {
|
||||
guard central.state == .poweredOn else { status = "Bluetooth is unavailable or permission is required."; return }
|
||||
devices = []
|
||||
peripherals = [:]
|
||||
central.scanForPeripherals(withServices: [CBUUID(string: Wire.service)], options: nil)
|
||||
isScanning = true
|
||||
status = "Looking for the Galaxy Bluetooth bridge…"
|
||||
scanTimeout?.cancel()
|
||||
scanTimeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 15_000_000_000)
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
self.central.stopScan()
|
||||
self.isScanning = false
|
||||
self.status = self.devices.isEmpty ? "No bridge found. Start the bridge on your comma and enable Bluetooth in StarPilot." : "Select your comma to connect."
|
||||
}
|
||||
}
|
||||
|
||||
func connect(_ device: NearbyDevice, pairingKey: String) {
|
||||
guard let bytes = Data(hex: pairingKey), bytes.count == 32 else {
|
||||
status = "Paste the 64-character pairing key created on your comma."
|
||||
return
|
||||
}
|
||||
guard let found = peripherals[device.id] else { return }
|
||||
disconnect()
|
||||
key = SymmetricKey(data: bytes)
|
||||
keyText = bytes.hex
|
||||
peripheral = found
|
||||
found.delegate = self
|
||||
connecting = true
|
||||
status = "Connecting to \(device.name)…"
|
||||
central.connect(found, options: nil)
|
||||
connectionTimeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 20_000_000_000)
|
||||
guard !Task.isCancelled, let self, !self.connected else { return }
|
||||
self.failConnection("Bluetooth connection timed out. Check the comma bridge and pairing key.")
|
||||
}
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
central.stopScan()
|
||||
scanTimeout?.cancel()
|
||||
connectionTimeout?.cancel()
|
||||
isScanning = false
|
||||
connected = false
|
||||
connecting = false
|
||||
failAll(BridgeError.message("Bluetooth connection closed."))
|
||||
if let peripheral { central.cancelPeripheralConnection(peripheral) }
|
||||
peripheral = nil
|
||||
rx = nil
|
||||
tx = nil
|
||||
notify = nil
|
||||
session = ""
|
||||
counter = 0
|
||||
catalogSHA256 = nil
|
||||
supportsReadStream = false
|
||||
activeReadStream = false
|
||||
supportsNotifications = false
|
||||
activeNotifications = false
|
||||
pairingVerified = false
|
||||
notificationBuffer = []
|
||||
}
|
||||
|
||||
private func failConnection(_ message: String) {
|
||||
disconnect()
|
||||
status = message
|
||||
}
|
||||
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse {
|
||||
let id = UUID().uuidString
|
||||
return try await withTaskCancellationHandler(operation: {
|
||||
try Task.checkCancellation()
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
guard rx != nil, tx != nil, !session.isEmpty else {
|
||||
continuation.resume(throwing: BridgeError.message("Connect to your comma over Bluetooth first."))
|
||||
return
|
||||
}
|
||||
guard queue.count < 32, body.count <= Wire.maxBody else {
|
||||
continuation.resume(throwing: BridgeError.message("Bluetooth queue is full or upload exceeds 1 MiB."))
|
||||
return
|
||||
}
|
||||
queue.append(Pending(id: id, path: path, method: method, headers: headers, body: body, completion: continuation))
|
||||
pump()
|
||||
}
|
||||
}, onCancel: { [weak self] in
|
||||
DispatchQueue.main.async { self?.cancel(id) }
|
||||
})
|
||||
}
|
||||
|
||||
private func cancel(_ id: String) {
|
||||
if let index = queue.firstIndex(where: { $0.id == id }) {
|
||||
queue.remove(at: index).completion.resume(throwing: CancellationError())
|
||||
} else if active?.id == id {
|
||||
if writeIndex >= outgoing.count {
|
||||
// Drain cancelled reads without disconnecting Bluetooth.
|
||||
activeCancelled = true
|
||||
} else {
|
||||
failConnection("Request cancelled. Reconnect before sending another request.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func pump() {
|
||||
guard active == nil, !queue.isEmpty, let peripheral, let key, !session.isEmpty else { return }
|
||||
active = queue.removeFirst()
|
||||
guard let active else { return }
|
||||
counter += 1
|
||||
assembler = FrameAssembler()
|
||||
completedResponse = nil
|
||||
activeCancelled = false
|
||||
awaitingAck = false
|
||||
writeIndex = 0
|
||||
activeNotifications = supportsNotifications && active.path != "/_bridge/health"
|
||||
notificationCount = 0
|
||||
notificationBuffer = []
|
||||
activeReadStream = supportsReadStream && active.path != "/_bridge/health"
|
||||
do {
|
||||
notificationTag = try Wire.streamTag(session: session, counter: counter)
|
||||
let request = BridgeRequest(id: active.id, session: session, counter: counter, path: active.path,
|
||||
method: active.method, headers: active.headers, body: active.body.base64EncodedString(),
|
||||
responseCodec: 2, responseFlow: activeNotifications ? "notify-window8" : activeReadStream ? "read-stream" : nil)
|
||||
outgoing = Wire.packets(try Wire.seal(request, key: key, direction: "request"),
|
||||
size: min(supportsNotifications ? 512 : 180, peripheral.maximumWriteValueLength(for: .withoutResponse)))
|
||||
timeoutTask = Task { @MainActor [weak self] in
|
||||
let seconds: UInt64 = active.path == "/_bridge/health" ? 10 : 90
|
||||
try? await Task.sleep(nanoseconds: seconds * 1_000_000_000)
|
||||
guard !Task.isCancelled, let self, self.active?.id == active.id else { return }
|
||||
self.failConnection("Bluetooth request timed out. Its outcome may be unknown; reconnect to check before retrying.")
|
||||
}
|
||||
writeNext()
|
||||
} catch {
|
||||
finish(.failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
private func writeNext() {
|
||||
guard let peripheral, let rx, active != nil else { return }
|
||||
if writeIndex < outgoing.count {
|
||||
peripheral.writeValue(outgoing[writeIndex], for: rx, type: .withResponse)
|
||||
} else if activeNotifications {
|
||||
drainNotifications()
|
||||
} else if let tx {
|
||||
peripheral.readValue(for: tx)
|
||||
}
|
||||
}
|
||||
|
||||
private func finish(_ result: Result<BridgeResponse, Error>) {
|
||||
timeoutTask?.cancel()
|
||||
notificationTimeout?.cancel()
|
||||
timeoutTask = nil
|
||||
let previous = active
|
||||
active = nil
|
||||
outgoing = []
|
||||
notificationBuffer = []
|
||||
if activeCancelled { previous?.completion.resume(throwing: CancellationError()) }
|
||||
else { previous?.completion.resume(with: result) }
|
||||
activeCancelled = false
|
||||
pump()
|
||||
}
|
||||
|
||||
private func failAll(_ error: Error) {
|
||||
timeoutTask?.cancel()
|
||||
notificationTimeout?.cancel()
|
||||
let pending = queue
|
||||
queue = []
|
||||
let previous = active
|
||||
active = nil
|
||||
outgoing = []
|
||||
notificationBuffer = []
|
||||
previous?.completion.resume(throwing: error)
|
||||
pending.forEach { $0.completion.resume(throwing: error) }
|
||||
}
|
||||
|
||||
func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
||||
switch central.state {
|
||||
case .poweredOn: status = "Ready to scan for your comma."
|
||||
case .unauthorized: failConnection("Allow Bluetooth access in iPhone Settings.")
|
||||
case .poweredOff: failConnection("Bluetooth is turned off.")
|
||||
default: failConnection("Bluetooth is unavailable.")
|
||||
}
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
|
||||
advertisementData: [String: Any], rssi RSSI: NSNumber) {
|
||||
peripherals[peripheral.identifier] = peripheral
|
||||
let device = NearbyDevice(id: peripheral.identifier,
|
||||
name: advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? peripheral.name ?? "Galaxy",
|
||||
signal: RSSI.intValue)
|
||||
if let index = devices.firstIndex(where: { $0.id == device.id }) { devices[index] = device }
|
||||
else { devices.append(device) }
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
peripheral.discoverServices([CBUUID(string: Wire.service)])
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
failConnection(error?.localizedDescription ?? "Could not connect to your comma.")
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
failConnection(error?.localizedDescription ?? "Your comma disconnected. Scan to reconnect.")
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
guard error == nil, let service = peripheral.services?.first(where: { $0.uuid == CBUUID(string: Wire.service) }) else {
|
||||
failConnection("Galaxy Bluetooth service was not found."); return
|
||||
}
|
||||
peripheral.discoverCharacteristics([CBUUID(string: Wire.rx), CBUUID(string: Wire.tx), CBUUID(string: Wire.info), CBUUID(string: Wire.notify)], for: service)
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
guard error == nil else { failConnection(error!.localizedDescription); return }
|
||||
rx = service.characteristics?.first { $0.uuid == CBUUID(string: Wire.rx) }
|
||||
tx = service.characteristics?.first { $0.uuid == CBUUID(string: Wire.tx) }
|
||||
notify = service.characteristics?.first { $0.uuid == CBUUID(string: Wire.notify) }
|
||||
guard rx != nil, tx != nil, let info = service.characteristics?.first(where: { $0.uuid == CBUUID(string: Wire.info) }) else {
|
||||
failConnection("The comma bridge has incompatible Bluetooth characteristics."); return
|
||||
}
|
||||
peripheral.readValue(for: info)
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard peripheral == self.peripheral, characteristic.uuid == CBUUID(string: Wire.rx), active != nil else { return }
|
||||
if let error { failConnection(error.localizedDescription); return }
|
||||
if awaitingAck {
|
||||
awaitingAck = false
|
||||
if let response = completedResponse {
|
||||
completedResponse = nil
|
||||
finish(.success(response))
|
||||
} else if activeNotifications {
|
||||
drainNotifications()
|
||||
} else if let tx {
|
||||
peripheral.readValue(for: tx)
|
||||
}
|
||||
} else {
|
||||
writeIndex += 1
|
||||
writeNext()
|
||||
}
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
if let error { failConnection(error.localizedDescription); return }
|
||||
guard let data = characteristic.value else { failConnection("Empty Bluetooth response."); return }
|
||||
if characteristic.uuid == CBUUID(string: Wire.notify) {
|
||||
receiveNotification(data)
|
||||
return
|
||||
}
|
||||
if characteristic.uuid == CBUUID(string: Wire.info) {
|
||||
guard data.count == 17, data.first == 1 else { failConnection("Unsupported bridge protocol."); return }
|
||||
session = Data(data.dropFirst()).hex
|
||||
let handshakeSession = session
|
||||
status = "Verifying the pairing key…"
|
||||
Task { @MainActor [weak self, weak peripheral] in
|
||||
guard let self, let peripheral else { return }
|
||||
do {
|
||||
let response = try await self.request(path: "/_bridge/health", method: "GET", headers: [:], body: Data())
|
||||
guard peripheral == self.peripheral, self.session == handshakeSession else { return }
|
||||
guard response.status == 200 else { throw BridgeError.message("Bridge verification failed.") }
|
||||
let health = try JSONDecoder().decode(BridgeHealth.self, from: response.bodyData)
|
||||
guard health.protocol == 1, health.transport == "bluetooth" else {
|
||||
throw BridgeError.message("Unsupported bridge protocol.")
|
||||
}
|
||||
self.catalogSHA256 = health.catalogSHA256
|
||||
self.supportsReadStream = health.readStream == true
|
||||
self.pairingVerified = true
|
||||
if health.notificationStream == true {
|
||||
guard let notify = self.notify, notify.properties.contains(.notify) else {
|
||||
throw BridgeError.message("Bluetooth services are cached. Forget Galaxy in iPhone Bluetooth Settings, then reconnect.")
|
||||
}
|
||||
self.status = "Enabling fast Bluetooth transfers…"
|
||||
peripheral.setNotifyValue(true, for: notify)
|
||||
} else {
|
||||
try self.completeConnection()
|
||||
}
|
||||
} catch {
|
||||
guard peripheral == self.peripheral, self.session == handshakeSession else { return }
|
||||
self.failConnection("Pairing failed: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
guard characteristic.uuid == CBUUID(string: Wire.tx), active != nil, let rx else { return }
|
||||
if data == Data([0]) {
|
||||
let requestID = active?.id
|
||||
Task { @MainActor [weak self, weak peripheral] in
|
||||
try? await Task.sleep(nanoseconds: 75_000_000)
|
||||
guard !Task.isCancelled, let self, self.active?.id == requestID, self.active != nil, let tx = self.tx,
|
||||
let peripheral, peripheral == self.peripheral else { return }
|
||||
peripheral.readValue(for: tx)
|
||||
}
|
||||
return
|
||||
}
|
||||
do {
|
||||
if let message = try assembler.append(data), let key {
|
||||
let response = try Wire.open(message, as: BridgeResponse.self, key: key, direction: "response")
|
||||
guard response.id == active?.id, response.session == session, response.counter == counter,
|
||||
(100...599).contains(response.status), Data(base64Encoded: response.body) != nil else {
|
||||
throw BridgeError.message("Bluetooth response identity did not match the request.")
|
||||
}
|
||||
completedResponse = response
|
||||
}
|
||||
if activeReadStream, completedResponse == nil, let tx {
|
||||
peripheral.readValue(for: tx)
|
||||
return
|
||||
}
|
||||
awaitingAck = true
|
||||
peripheral.writeValue(Data([2]) + data.subdata(in: 1..<5), for: rx, type: .withResponse)
|
||||
} catch { failConnection("Could not verify the encrypted response: \(error.localizedDescription)") }
|
||||
}
|
||||
|
||||
private func completeConnection() throws {
|
||||
try PairingKeyStore.save(keyText)
|
||||
connectionTimeout?.cancel()
|
||||
if let peripheral { UserDefaults.standard.set(peripheral.identifier.uuidString, forKey: "galaxy.bluetooth.device") }
|
||||
connected = true
|
||||
connecting = false
|
||||
status = supportsNotifications ? "Connected with fast Bluetooth transfers" : "Connected over Bluetooth"
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard peripheral == self.peripheral, characteristic.uuid == CBUUID(string: Wire.notify), pairingVerified else { return }
|
||||
guard error == nil, characteristic.isNotifying else {
|
||||
failConnection(error?.localizedDescription ?? "Bluetooth push subscription ended. Reconnect to check any pending setting change.")
|
||||
return
|
||||
}
|
||||
supportsNotifications = true
|
||||
do { try completeConnection() }
|
||||
catch { failConnection(error.localizedDescription) }
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
|
||||
guard peripheral == self.peripheral, invalidatedServices.contains(where: { $0.uuid == CBUUID(string: Wire.service) }) else { return }
|
||||
failConnection("The bridge's Bluetooth services changed. Scan and reconnect.")
|
||||
}
|
||||
|
||||
private func receiveNotification(_ data: Data) {
|
||||
guard active != nil, activeNotifications else { return }
|
||||
do {
|
||||
// Unrelated client/request frames must not enter this assembler.
|
||||
guard try Wire.notificationPacket(data, tag: notificationTag) != nil else { return }
|
||||
notificationTimeout?.cancel()
|
||||
let requestID = active?.id
|
||||
notificationTimeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 15_000_000_000)
|
||||
guard !Task.isCancelled, let self, self.active?.id == requestID else { return }
|
||||
self.failConnection("Bluetooth push stalled. Reconnect to check any pending setting change.")
|
||||
}
|
||||
if awaitingAck || writeIndex < outgoing.count {
|
||||
guard notificationBuffer.count < Wire.notificationWindow else {
|
||||
throw BridgeError.message("Bluetooth notification window exceeded.")
|
||||
}
|
||||
notificationBuffer.append(data)
|
||||
} else {
|
||||
try consumeNotification(data)
|
||||
}
|
||||
} catch { failConnection("Could not verify Bluetooth push data: \(error.localizedDescription)") }
|
||||
}
|
||||
|
||||
private func drainNotifications() {
|
||||
while active != nil, activeNotifications, !awaitingAck, !notificationBuffer.isEmpty {
|
||||
let data = notificationBuffer.removeFirst()
|
||||
do { try consumeNotification(data) }
|
||||
catch { failConnection("Could not verify Bluetooth push data: \(error.localizedDescription)") }
|
||||
}
|
||||
}
|
||||
|
||||
private func consumeNotification(_ data: Data) throws {
|
||||
guard let packet = try Wire.notificationPacket(data, tag: notificationTag), let peripheral, let rx else { return }
|
||||
if let message = try assembler.append(packet), let key {
|
||||
let response = try Wire.open(message, as: BridgeResponse.self, key: key, direction: "response")
|
||||
guard response.id == active?.id, response.session == session, response.counter == counter,
|
||||
(100...599).contains(response.status), let body = Data(base64Encoded: response.body), body.count <= Wire.maxBody else {
|
||||
throw BridgeError.message("Bluetooth response identity did not match the request.")
|
||||
}
|
||||
completedResponse = response
|
||||
}
|
||||
notificationCount += 1
|
||||
if completedResponse != nil || notificationCount % Wire.notificationWindow == 0 {
|
||||
awaitingAck = true
|
||||
let sequence = Wire.number(packet.subdata(in: 1..<5))
|
||||
peripheral.writeValue(Wire.notificationAck(tag: notificationTag, sequence: sequence), for: rx, type: .withResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.developer.carplay-driving-task</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,39 @@
|
||||
import CarPlay
|
||||
|
||||
@MainActor
|
||||
final class CarPlaySceneDelegate: NSObject, CPTemplateApplicationSceneDelegate {
|
||||
private var controller: CPInterfaceController?
|
||||
private var template: CPListTemplate?
|
||||
private var timer: Timer?
|
||||
|
||||
func templateApplicationScene(_ scene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) {
|
||||
controller = interfaceController
|
||||
let root = CPListTemplate(title: "StarPilot", sections: [])
|
||||
template = root
|
||||
interfaceController.setRootTemplate(root, animated: false, completion: nil)
|
||||
let model = AppModel.shared
|
||||
model.setCarPlayActive(true)
|
||||
model.diagnostics.live = true
|
||||
model.showDiagnostics = true
|
||||
refresh()
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in self?.refresh() }
|
||||
}
|
||||
}
|
||||
func templateApplicationScene(_ scene: CPTemplateApplicationScene, didDisconnectInterfaceController interfaceController: CPInterfaceController) {
|
||||
timer?.invalidate(); timer = nil; controller = nil; template = nil
|
||||
AppModel.shared.setCarPlayActive(false)
|
||||
}
|
||||
private func refresh() {
|
||||
let model = AppModel.shared
|
||||
let diagnostics = model.diagnostics
|
||||
var sections = [CPListSection(items: [CPListItem(text: diagnostics.fresh ? model.transport.label : "Disconnected / outdated",
|
||||
detailText: diagnostics.fresh ? "Live View selected on iPhone" : diagnostics.status)])]
|
||||
if diagnostics.fresh, let sample = diagnostics.snapshot {
|
||||
sections.append(CPListSection(items: [CPListItem(text: "Driving status", detailText: sample.engaged.map { $0 ? "Engaged" : "Not engaged" } ?? "Not reported")]))
|
||||
sections.append(CPListSection(items: sample.temperatures.map { CPListItem(text: $0.name, detailText: $0.display) }, header: "Temperatures", sectionIndexTitle: nil))
|
||||
sections.append(CPListSection(items: sample.rates.map { CPListItem(text: $0.name, detailText: $0.display) }, header: "Frame / message rates", sectionIndexTitle: nil))
|
||||
}
|
||||
template?.updateSections(sections)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import SwiftUI
|
||||
import CryptoKit
|
||||
import UIKit
|
||||
import ImageIO
|
||||
|
||||
struct DiagnosticMetric: Decodable, Identifiable {
|
||||
let name: String
|
||||
let value: Double?
|
||||
let unit: String
|
||||
var id: String { name }
|
||||
var display: String { value.map { String(format: "%.1f %@", $0, unit) } ?? "Not reported" }
|
||||
}
|
||||
struct DiagnosticSnapshot: Decodable {
|
||||
let ageSeconds: Double
|
||||
let engaged: Bool?
|
||||
let temperatures: [DiagnosticMetric]
|
||||
let rates: [DiagnosticMetric]
|
||||
let capture: CaptureStatus?
|
||||
}
|
||||
|
||||
struct CaptureStatus: Codable {
|
||||
let hookAgeSeconds: Double?
|
||||
let frameAgeSeconds: Double?
|
||||
let queuedImages: Int?
|
||||
let captureError: String?
|
||||
let encoderError: String?
|
||||
let encoderStderr: String?
|
||||
let encoderExitCode: Int?
|
||||
let videoSize: [Int]?
|
||||
let encoderRunning: Bool?
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class CompanionDiagnostics: ObservableObject {
|
||||
@Published var snapshot: DiagnosticSnapshot?
|
||||
@Published var screen: UIImage?
|
||||
@Published var status = "Connect and pair with comma to read diagnostics." { didSet { record(status) } }
|
||||
@Published var screenStatus = "Live View uses local Wi-Fi." { didSet { record(screenStatus) } }
|
||||
@Published var live = true { didSet { if live { waitingSince = Date() } } }
|
||||
@Published var phoneVisible = false { didSet { if phoneVisible && !oldValue { waitingSince = Date(); copiedLog = false }; updateActivity() } }
|
||||
@Published var carPlayActive = false { didSet { updateActivity() } }
|
||||
@Published private(set) var receivedAt: Date?
|
||||
@Published private(set) var frameAt: Date?
|
||||
@Published var copiedLog = false
|
||||
var transport: PreferredTransport?
|
||||
var lan: LANTransport?
|
||||
var phoneActive = true { didSet { updateActivity() } }
|
||||
private var task: Task<Void, Never>?
|
||||
private var stream: LiveStream?
|
||||
private var streamHost = ""
|
||||
private var streamStarted = Date.distantPast
|
||||
private var streamGeneration = UUID()
|
||||
private var lastStreamAttempt = Date.distantPast
|
||||
private var frameCount = 0
|
||||
private var fpsStarted = Date()
|
||||
@Published private(set) var displayFPS = 0.0
|
||||
private var lastDiagnostics = Date.distantPast
|
||||
private var waitingSince = Date()
|
||||
private var events: [String] = []
|
||||
private var lastEvent = ""
|
||||
private var captureSample: CaptureStatus?
|
||||
private var captureSampleAt: Date?
|
||||
|
||||
var canCopyLog: Bool {
|
||||
live && phoneVisible && !frameFresh && Date().timeIntervalSince(waitingSince) >= 10
|
||||
}
|
||||
private func record(_ message: String) {
|
||||
guard message != lastEvent else { return }
|
||||
lastEvent = message
|
||||
events.append("\(ISO8601DateFormatter().string(from: Date())) \(message.prefix(500))")
|
||||
if events.count > 30 { events.removeFirst(events.count - 30) }
|
||||
}
|
||||
func diagnosticLog() -> String {
|
||||
let info = Bundle.main.infoDictionary ?? [:]
|
||||
var lines = ["StarPilot Live diagnostics", ISO8601DateFormatter().string(from: Date()),
|
||||
"App: \(info["CFBundleShortVersionString"] ?? "unknown") (\(info["CFBundleVersion"] ?? "unknown"))",
|
||||
"iOS: \(UIDevice.current.systemVersion)",
|
||||
"Connection: \(transport?.label ?? "Disconnected")",
|
||||
"LAN connected: \(lan?.connected == true)",
|
||||
"Telemetry: \(status)", "Stream: \(screenStatus)",
|
||||
"No frame for: \(Int(Date().timeIntervalSince(waitingSince))) seconds"]
|
||||
if let captureSample, let captureSampleAt,
|
||||
let data = try? JSONEncoder().encode(captureSample), let text = String(data: data, encoding: .utf8) {
|
||||
lines.append("Capture sample age: \(Int(Date().timeIntervalSince(captureSampleAt))) seconds")
|
||||
lines.append("Comma capture: \(text)")
|
||||
} else { lines.append("Comma capture details unavailable; update the comma fork if telemetry is connected.") }
|
||||
lines.append("Recent events:")
|
||||
lines.append(contentsOf: events)
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
var fresh: Bool {
|
||||
guard let snapshot, let receivedAt, transport?.connected == true else { return false }
|
||||
return snapshot.ageSeconds + Date().timeIntervalSince(receivedAt) < 5
|
||||
}
|
||||
var frameFresh: Bool {
|
||||
guard let frameAt, lan?.connected == true else { return false }
|
||||
return Date().timeIntervalSince(frameAt) < 3
|
||||
}
|
||||
private func headers(_ path: String) throws -> [String: String] {
|
||||
let text = PairingKeyStore.load()
|
||||
guard text.count == 64 else { throw BridgeError.message("Pair this phone with comma before opening diagnostics.") }
|
||||
var bytes = Data()
|
||||
var index = text.startIndex
|
||||
while index < text.endIndex {
|
||||
let next = text.index(index, offsetBy: 2)
|
||||
guard let byte = UInt8(text[index..<next], radix: 16) else { throw BridgeError.message("Invalid pairing key.") }
|
||||
bytes.append(byte); index = next
|
||||
}
|
||||
let nonce = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
|
||||
let signature = HMAC<SHA256>.authenticationCode(for: Data("\(nonce)\nGET\n\(path)".utf8), using: SymmetricKey(data: bytes))
|
||||
return ["X-Companion-Nonce": nonce, "X-Companion-MAC": signature.map { String(format: "%02x", $0) }.joined()]
|
||||
}
|
||||
private func updateActivity() {
|
||||
let active = carPlayActive || (phoneVisible && phoneActive)
|
||||
if !active { task?.cancel(); task = nil; stopStream(); return }
|
||||
guard task == nil else { return }
|
||||
task = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
guard let self else { return }
|
||||
await self.poll()
|
||||
do { try await Task.sleep(nanoseconds: 500_000_000) } catch { return }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func poll() async {
|
||||
if Date().timeIntervalSince(lastDiagnostics) >= 2 {
|
||||
lastDiagnostics = Date()
|
||||
do {
|
||||
guard let transport else { return }
|
||||
let path = "/api/companion/diagnostics"
|
||||
let response = try await transport.request(path: path, method: "GET", headers: headers(path), body: Data())
|
||||
try Task.checkCancellation()
|
||||
guard response.status == 200 else { throw BridgeError.message(response.status == 403 ? "Enable diagnostics on comma and pair this phone." : "Waiting for comma telemetry.") }
|
||||
let sample = try JSONDecoder().decode(DiagnosticSnapshot.self, from: response.bodyData)
|
||||
guard sample.ageSeconds.isFinite, sample.ageSeconds >= 0 else { throw BridgeError.message("Invalid telemetry age.") }
|
||||
snapshot = sample; receivedAt = Date(); status = sample.ageSeconds < 5 ? "Connected · read only" : "Telemetry is outdated"
|
||||
if let capture = sample.capture { captureSample = capture; captureSampleAt = Date() }
|
||||
} catch { if !Task.isCancelled { status = error.localizedDescription; snapshot = nil; receivedAt = nil } }
|
||||
}
|
||||
guard live, phoneVisible, phoneActive else { stopStream(); return }
|
||||
guard let lan, lan.connected, let host = lan.endpoint?.host else {
|
||||
stopStream(); screenStatus = "Live View needs local Wi-Fi. Diagnostics also work over Bluetooth."; return
|
||||
}
|
||||
if stream != nil && streamHost != host { stopStream() }
|
||||
if let frameAt, Date().timeIntervalSince(frameAt) > 3 { stopStream() }
|
||||
if stream != nil, frameAt == nil, Date().timeIntervalSince(streamStarted) > 5 { stopStream() }
|
||||
guard stream == nil, Date().timeIntervalSince(lastStreamAttempt) >= 1 else { return }
|
||||
lastStreamAttempt = Date()
|
||||
do {
|
||||
let headers = try headers("/api/companion/stream")
|
||||
let generation = UUID(); streamGeneration = generation; streamHost = host
|
||||
fpsStarted = Date(); frameCount = 0
|
||||
let stream = LiveStream(host: host, headers: headers, frame: { [weak self] data in
|
||||
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
|
||||
let image = CGImageSourceCreateImageAtIndex(source, 0, [kCGImageSourceShouldCacheImmediately: true] as CFDictionary) else { return }
|
||||
let picture = UIImage(cgImage: image)
|
||||
Task { @MainActor in
|
||||
guard let self, self.streamGeneration == generation else { return }
|
||||
self.screen = picture; self.frameAt = Date(); self.frameCount += 1
|
||||
self.waitingSince = Date()
|
||||
let elapsed = Date().timeIntervalSince(self.fpsStarted)
|
||||
if elapsed >= 1 {
|
||||
self.displayFPS = Double(self.frameCount) / elapsed
|
||||
self.frameCount = 0; self.fpsStarted = Date()
|
||||
}
|
||||
self.screenStatus = String(format: "Full comma display · %.1f FPS · Wi-Fi", self.displayFPS)
|
||||
}
|
||||
}, failure: { [weak self] message in
|
||||
Task { @MainActor in
|
||||
guard let self, self.streamGeneration == generation else { return }
|
||||
self.stopStream(); self.screenStatus = message
|
||||
}
|
||||
})
|
||||
streamStarted = Date(); self.stream = stream; stream.start()
|
||||
screenStatus = "Connecting live stream…"
|
||||
} catch { screenStatus = error.localizedDescription }
|
||||
|
||||
}
|
||||
private func stopStream() {
|
||||
streamGeneration = UUID(); stream?.stop(); stream = nil
|
||||
screen = nil; frameAt = nil; displayFPS = 0
|
||||
}
|
||||
}
|
||||
|
||||
struct CompanionView: View {
|
||||
@ObservedObject var diagnostics: CompanionDiagnostics
|
||||
private let purple = Color(red: 0.55, green: 0.36, blue: 0.96)
|
||||
var body: some View {
|
||||
TimelineView(.periodic(from: .now, by: 1)) { _ in
|
||||
if diagnostics.live { liveView } else { diagnosticView }
|
||||
}
|
||||
.background(Color.black)
|
||||
.onAppear { diagnostics.phoneVisible = true; UIApplication.shared.isIdleTimerDisabled = diagnostics.live }
|
||||
.onChange(of: diagnostics.live) { _, live in UIApplication.shared.isIdleTimerDisabled = live }
|
||||
.onDisappear { diagnostics.phoneVisible = false; UIApplication.shared.isIdleTimerDisabled = false }
|
||||
}
|
||||
private var liveView: some View {
|
||||
VStack(spacing: 16) {
|
||||
GeometryReader { space in
|
||||
if diagnostics.frameFresh, let image = diagnostics.screen {
|
||||
Image(uiImage: image).resizable().scaledToFit()
|
||||
.frame(width: space.size.width, height: space.size.height)
|
||||
.accessibilityLabel("Live comma display")
|
||||
} else {
|
||||
ContentUnavailableView("Waiting for live video", systemImage: "play.rectangle", description: Text(diagnostics.screenStatus))
|
||||
.frame(width: space.size.width, height: space.size.height)
|
||||
}
|
||||
}.background(.white.opacity(0.04), in: RoundedRectangle(cornerRadius: 20))
|
||||
Label(diagnostics.screenStatus, systemImage: diagnostics.frameFresh ? "wifi" : "clock")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if diagnostics.canCopyLog {
|
||||
Text("No frame received. Copy diagnostics to share what happened.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
copyButton
|
||||
}
|
||||
}.padding(16)
|
||||
}
|
||||
private var diagnosticView: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 24) {
|
||||
HStack(alignment: .top) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Live diagnostics").font(.title2.bold())
|
||||
Text(diagnostics.fresh ? "Updating every 2 seconds" : diagnostics.status)
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Text("READ ONLY").font(.system(size: 9, weight: .bold)).tracking(1)
|
||||
.padding(8).background(purple.opacity(0.18), in: Capsule()).foregroundStyle(purple)
|
||||
}
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "car.side.fill").font(.title2).foregroundStyle(purple)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(drivingStatus).font(.headline)
|
||||
Text(diagnostics.fresh ? "Telemetry connected" : "Waiting for fresh telemetry")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Circle().fill(diagnostics.fresh ? Color.green : Color.orange).frame(width: 8, height: 8)
|
||||
}.padding(18).background(.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 18))
|
||||
metricSection("Temperatures", icon: "thermometer.medium", values: temperatures.filter { !isExternalGPU($0) }, thermal: true)
|
||||
metricSection("Frame rates", icon: "speedometer", values: rates.filter { $0.unit == "FPS" && !isExternalGPU($0) }, thermal: false)
|
||||
metricSection("Message rates", icon: "waveform.path", values: rates.filter { $0.unit != "FPS" && !isExternalGPU($0) }, thermal: false)
|
||||
externalGPUView
|
||||
Text("Unavailable sensors show no reading. Message rates reflect updates observed by the comma UI.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
copyButton.frame(maxWidth: .infinity)
|
||||
}.padding(20).frame(maxWidth: 700).frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
private var temperatures: [DiagnosticMetric] {
|
||||
diagnostics.fresh ? diagnostics.snapshot?.temperatures ?? [] : []
|
||||
}
|
||||
private var rates: [DiagnosticMetric] {
|
||||
diagnostics.fresh ? diagnostics.snapshot?.rates ?? [] : []
|
||||
}
|
||||
private func isExternalGPU(_ metric: DiagnosticMetric) -> Bool {
|
||||
let name = metric.name.lowercased()
|
||||
return name.contains("external gpu") || name.contains("chestnut") || name.hasPrefix("sensor: amdgpu")
|
||||
}
|
||||
private var externalGPUView: some View {
|
||||
let sensors = temperatures.filter(isExternalGPU)
|
||||
let updates = rates.filter(isExternalGPU)
|
||||
return VStack(alignment: .leading, spacing: 16) {
|
||||
HStack {
|
||||
Label("External GPU", systemImage: "cpu").font(.title3.bold())
|
||||
Spacer()
|
||||
Text("CHESTNUT").font(.system(size: 9, weight: .bold)).tracking(1).foregroundStyle(purple)
|
||||
}
|
||||
if sensors.isEmpty && updates.isEmpty {
|
||||
Text("No Chestnut telemetry reported.").font(.subheadline).foregroundStyle(.secondary)
|
||||
} else {
|
||||
if !sensors.isEmpty { metricCards("Temperatures", icon: "thermometer.medium", values: sensors) }
|
||||
if !updates.isEmpty { metricCards("Telemetry rates", icon: "waveform.path", values: updates) }
|
||||
}
|
||||
}.padding(18).background(purple.opacity(0.08), in: RoundedRectangle(cornerRadius: 20))
|
||||
.overlay(RoundedRectangle(cornerRadius: 20).stroke(purple.opacity(0.25), lineWidth: 1))
|
||||
}
|
||||
private func metricName(_ metric: DiagnosticMetric) -> String {
|
||||
switch metric.name {
|
||||
case "External GPU": "GPU temperature"
|
||||
case "External GPU memory": "Memory temperature"
|
||||
case "chestnutState": "Telemetry updates"
|
||||
default: metric.name
|
||||
}
|
||||
}
|
||||
private func component(_ metric: DiagnosticMetric, thermal: Bool) -> String {
|
||||
let name = metric.name.lowercased()
|
||||
if thermal {
|
||||
if name.hasPrefix("sensor:") { return "Additional hardware sensors" }
|
||||
if name.contains("cpu") || name.contains("dsp") || name.contains("soc") { return "Processors" }
|
||||
if name.contains("gpu") { return "Onboard GPU" }
|
||||
if name.contains("memory") { return "Memory" }
|
||||
if name.contains("pmic") { return "Power management" }
|
||||
if name.contains("modem") || name.contains("gnss") { return "Connectivity & positioning" }
|
||||
if name.contains("intake") || name.contains("exhaust") { return "Cooling" }
|
||||
return "Other temperatures"
|
||||
}
|
||||
if name.contains("camera") { return "Cameras" }
|
||||
if name == "ui" { return "Display" }
|
||||
if name.contains("model") || name.contains("plan") { return "Models & planning" }
|
||||
if name.contains("carstate") || name.contains("carcontrol") || name.contains("selfdrive") { return "Driving" }
|
||||
if name.contains("device") || name.contains("peripheral") { return "Device" }
|
||||
return "Other services"
|
||||
}
|
||||
private func metricSection(_ title: String, icon: String, values: [DiagnosticMetric], thermal: Bool) -> some View {
|
||||
let order = thermal
|
||||
? ["Processors", "Onboard GPU", "Memory", "Power management", "Cooling", "Connectivity & positioning", "Other temperatures", "Additional hardware sensors"]
|
||||
: ["Display", "Cameras", "Models & planning", "Driving", "Device", "Other services"]
|
||||
return VStack(alignment: .leading, spacing: 16) {
|
||||
Label(title, systemImage: icon).font(.title3.bold())
|
||||
if values.isEmpty {
|
||||
Text("No readings available").font(.subheadline).foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(order, id: \.self) { group in
|
||||
let readings = values.filter { component($0, thermal: thermal) == group }
|
||||
if !readings.isEmpty {
|
||||
if group == "Additional hardware sensors" || group == "Other services" || group == "Other temperatures" {
|
||||
DisclosureGroup {
|
||||
metricCards("", icon: icon, values: readings).padding(.top, 12)
|
||||
} label: {
|
||||
HStack {
|
||||
Text(group).font(.subheadline.weight(.medium))
|
||||
Spacer()
|
||||
Text("\(readings.count)").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}.tint(purple).padding(16)
|
||||
.background(.white.opacity(0.04), in: RoundedRectangle(cornerRadius: 16))
|
||||
} else {
|
||||
metricCards(group, icon: icon, values: readings)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private var drivingStatus: String {
|
||||
guard diagnostics.fresh, let engaged = diagnostics.snapshot?.engaged else { return "Driving status unavailable" }
|
||||
return engaged ? "StarPilot engaged" : "StarPilot not engaged"
|
||||
}
|
||||
private var copyButton: some View {
|
||||
Button(diagnostics.copiedLog ? "Copied diagnostics" : "Copy diagnostics", systemImage: diagnostics.copiedLog ? "checkmark" : "doc.on.doc") {
|
||||
UIPasteboard.general.string = diagnostics.diagnosticLog()
|
||||
diagnostics.copiedLog = true
|
||||
}.buttonStyle(.bordered).tint(purple)
|
||||
}
|
||||
private func metricCards(_ title: String, icon: String, values: [DiagnosticMetric]) -> some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if !title.isEmpty { Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(.secondary) }
|
||||
if values.isEmpty {
|
||||
Text("No readings available").font(.subheadline).foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).padding(18)
|
||||
.background(.white.opacity(0.04), in: RoundedRectangle(cornerRadius: 16))
|
||||
} else {
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 145), spacing: 12)], spacing: 12) {
|
||||
ForEach(Array(values.enumerated()), id: \.offset) { _, metric in
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text(metricName(metric)).font(.caption.weight(.medium)).foregroundStyle(.secondary)
|
||||
.lineLimit(2).frame(minHeight: 30, alignment: .topLeading)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 4) {
|
||||
Text(metric.value.map { String(format: "%.1f", $0) } ?? "—")
|
||||
.font(.system(size: 29, weight: .semibold, design: .rounded)).monospacedDigit()
|
||||
Text(metric.unit).font(.caption).foregroundStyle(purple).lineLimit(1).minimumScaleFactor(0.6)
|
||||
}.minimumScaleFactor(0.7).lineLimit(1)
|
||||
}.frame(maxWidth: .infinity, alignment: .leading).padding(16)
|
||||
.background(.white.opacity(0.06), in: RoundedRectangle(cornerRadius: 16))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Combine
|
||||
|
||||
struct GalaxyAssetManifest: Codable {
|
||||
struct File: Codable { let path: String; let sha256: String; let size: Int }
|
||||
let schema: Int
|
||||
let nativeBridge: Int
|
||||
let files: [File]
|
||||
func validate() throws {
|
||||
guard schema == 1, nativeBridge == 1, (1...512).contains(files.count),
|
||||
Set(files.map(\.path)).count == files.count else { throw BridgeError.message("Galaxy update needs a compatible app version.") }
|
||||
var total = 0
|
||||
for file in files {
|
||||
let parts = file.path.split(separator: "/", omittingEmptySubsequences: false)
|
||||
guard !parts.isEmpty, parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }),
|
||||
file.path.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || [45, 46, 47, 95].contains($0) }),
|
||||
file.path == "classic.html" || file.path.hasPrefix("assets/"),
|
||||
(0...4_194_304).contains(file.size), Self.isHash(file.sha256) else {
|
||||
throw BridgeError.message("Invalid Galaxy update file.")
|
||||
}
|
||||
total += file.size
|
||||
}
|
||||
guard total <= 32 * 1_048_576, files.contains(where: { $0.path == "assets/mobile/index.html" }),
|
||||
files.contains(where: { $0.path == "assets/mobile/js/api.js" }) else { throw BridgeError.message("Galaxy update is incomplete or too large.") }
|
||||
}
|
||||
static func isHash(_ value: String) -> Bool { value.count == 64 && value.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } }
|
||||
static func digest(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class GalaxyAssetStore: ObservableObject {
|
||||
// Nate’s pilot update channel.
|
||||
static let repository = "natehuby76/StarPilotBT"
|
||||
static let branch = "Nate/galaxy-bluetooth"
|
||||
static let resourcePath = "tools/galaxy_bluetooth/ios/GalaxyBluetooth/Resources/Web"
|
||||
@Published private(set) var status = "Galaxy is available offline."
|
||||
@Published private(set) var checking = false
|
||||
@Published private(set) var readyRoot: URL?
|
||||
var inUseRoot: URL?
|
||||
let bundledRoot: URL
|
||||
private let cacheRoot: URL
|
||||
private let defaults: UserDefaults
|
||||
private let fetch: (URLRequest, Int) async throws -> (Data, HTTPURLResponse)
|
||||
init(bundledRoot: URL? = nil, cacheRoot: URL? = nil, defaults: UserDefaults = .standard,
|
||||
fetch: @escaping (URLRequest, Int) async throws -> (Data, HTTPURLResponse) = { try await BoundedHTTP.load($0, limit: $1) }) {
|
||||
self.bundledRoot = bundledRoot ?? Bundle.main.resourceURL!.appendingPathComponent("Web", isDirectory: true)
|
||||
self.cacheRoot = cacheRoot ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("GalaxyUpdates", isDirectory: true)
|
||||
self.defaults = defaults
|
||||
self.fetch = fetch
|
||||
// Validate saved assets before trusting a previous completed update.
|
||||
if let hash = defaults.string(forKey: "galaxy.assets.manifest"), GalaxyAssetManifest.isHash(hash) {
|
||||
let root = self.cacheRoot.appendingPathComponent(hash, isDirectory: true)
|
||||
if Self.verify(root) { readyRoot = root; status = "Using saved Galaxy from GitHub." }
|
||||
}
|
||||
}
|
||||
private static func verify(_ root: URL) -> Bool {
|
||||
guard let data = try? Data(contentsOf: root.appendingPathComponent("manifest.json")),
|
||||
GalaxyAssetManifest.digest(data) == root.lastPathComponent,
|
||||
let manifest = try? JSONDecoder().decode(GalaxyAssetManifest.self, from: data),
|
||||
(try? manifest.validate()) != nil else { return false }
|
||||
return manifest.files.allSatisfy { file in
|
||||
guard let data = try? Data(contentsOf: root.appendingPathComponent(file.path)) else { return false }
|
||||
return data.count == file.size && GalaxyAssetManifest.digest(data) == file.sha256
|
||||
}
|
||||
}
|
||||
func check() async {
|
||||
guard !checking else { return }
|
||||
checking = true
|
||||
status = "Checking GitHub for Galaxy updates…"
|
||||
defer { checking = false }
|
||||
var stage: URL?
|
||||
do {
|
||||
struct Commit: Decodable { let sha: String }
|
||||
let branch = Self.branch.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/")))!
|
||||
let (commitData, _) = try await download(URL(string: "https://api.github.com/repos/\(Self.repository)/commits/\(branch)")!, limit: 1_048_576)
|
||||
let commit = try JSONDecoder().decode(Commit.self, from: commitData).sha
|
||||
guard commit.count == 40, commit.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else {
|
||||
throw BridgeError.message("Invalid GitHub revision.")
|
||||
}
|
||||
let base = URL(string: "https://raw.githubusercontent.com/\(Self.repository)/\(commit)/\(Self.resourcePath)/")!
|
||||
let (data, _) = try await download(base.appendingPathComponent("galaxy-native-manifest.json"), limit: 262_144)
|
||||
let manifest = try JSONDecoder().decode(GalaxyAssetManifest.self, from: data)
|
||||
try manifest.validate()
|
||||
let hash = GalaxyAssetManifest.digest(data)
|
||||
if readyRoot?.lastPathComponent == hash { status = "Galaxy is up to date."; return }
|
||||
let manager = FileManager.default
|
||||
try manager.createDirectory(at: cacheRoot, withIntermediateDirectories: true)
|
||||
let staging = cacheRoot.appendingPathComponent("staging-" + UUID().uuidString, isDirectory: true)
|
||||
stage = staging
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: true)
|
||||
var completed = 0
|
||||
// Verify every file before publishing an update.
|
||||
for offset in stride(from: 0, to: manifest.files.count, by: 4) {
|
||||
try Task.checkCancellation()
|
||||
let batch = Array(manifest.files[offset..<min(offset + 4, manifest.files.count)])
|
||||
let saved = readyRoot
|
||||
let bundled = bundledRoot
|
||||
let fetch = self.fetch
|
||||
try await withThrowingTaskGroup(of: (String, Data).self) { group in
|
||||
for file in batch {
|
||||
group.addTask {
|
||||
for root in [saved, bundled].compactMap({ $0 }) {
|
||||
if let bytes = try? Data(contentsOf: root.appendingPathComponent(file.path)), bytes.count == file.size,
|
||||
GalaxyAssetManifest.digest(bytes) == file.sha256 { return (file.path, bytes) }
|
||||
}
|
||||
var request = URLRequest(url: base.appendingPathComponent(file.path))
|
||||
request.timeoutInterval = 15
|
||||
let (bytes, response) = try await fetch(request, max(file.size, 1))
|
||||
guard response.statusCode == 200, bytes.count == file.size,
|
||||
GalaxyAssetManifest.digest(bytes) == file.sha256 else { throw BridgeError.message("Galaxy update verification failed.") }
|
||||
return (file.path, bytes)
|
||||
}
|
||||
}
|
||||
for try await (path, bytes) in group {
|
||||
let destination = staging.appendingPathComponent(path)
|
||||
try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try bytes.write(to: destination, options: .atomic)
|
||||
completed += 1
|
||||
}
|
||||
}
|
||||
status = "Preparing Galaxy update (\(completed)/\(manifest.files.count))…"
|
||||
}
|
||||
try data.write(to: staging.appendingPathComponent("manifest.json"), options: .atomic)
|
||||
try Task.checkCancellation()
|
||||
let destination = cacheRoot.appendingPathComponent(hash, isDirectory: true)
|
||||
if manager.fileExists(atPath: destination.path) { try manager.removeItem(at: destination) }
|
||||
try manager.moveItem(at: staging, to: destination)
|
||||
stage = nil
|
||||
// Keep one previous version while an open WebView is still using it.
|
||||
let previous = readyRoot
|
||||
readyRoot = destination
|
||||
defaults.set(hash, forKey: "galaxy.assets.manifest")
|
||||
if let contents = try? manager.contentsOfDirectory(at: cacheRoot, includingPropertiesForKeys: nil) {
|
||||
for root in contents where root.standardizedFileURL.path != destination.standardizedFileURL.path && root.standardizedFileURL.path != previous?.standardizedFileURL.path && root.standardizedFileURL.path != inUseRoot?.standardizedFileURL.path { try? manager.removeItem(at: root) }
|
||||
}
|
||||
status = "Galaxy update ready. It applies when you next open Galaxy."
|
||||
} catch {
|
||||
if let stage { try? FileManager.default.removeItem(at: stage) }
|
||||
status = "GitHub unavailable or update incompatible. Using saved Galaxy."
|
||||
}
|
||||
}
|
||||
private func download(_ url: URL, limit: Int) async throws -> (Data, HTTPURLResponse) {
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 8
|
||||
request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
|
||||
request.setValue("Galaxy-iPhone-Pilot", forHTTPHeaderField: "User-Agent")
|
||||
let result = try await fetch(request, limit)
|
||||
guard result.1.statusCode == 200 else { throw BridgeError.message("GitHub update unavailable.") }
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import SwiftUI
|
||||
import Network
|
||||
|
||||
@main
|
||||
struct GalaxyBluetoothApp: App {
|
||||
@StateObject private var model = AppModel.shared
|
||||
var body: some Scene { WindowGroup { GalaxyRootView(model: model) } }
|
||||
}
|
||||
|
||||
enum CompanionTab: String, CaseIterable, Identifiable {
|
||||
case galaxy = "Galaxy", live = "Live View", diagnostics = "Diagnostics", connections = "Settings"
|
||||
var id: String { rawValue }
|
||||
var icon: String {
|
||||
switch self {
|
||||
case .galaxy: "sparkles"
|
||||
case .live: "play.rectangle"
|
||||
case .diagnostics: "chart.xyaxis.line"
|
||||
case .connections: "gearshape.fill"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class AppModel: ObservableObject {
|
||||
static let shared = AppModel()
|
||||
let diagnostics = CompanionDiagnostics()
|
||||
@Published var showDiagnostics = false
|
||||
@Published var tab: CompanionTab = .connections
|
||||
private var phoneActive = false
|
||||
private var carPlayActive = false
|
||||
private var monitorTask: Task<Void, Never>?
|
||||
func setPhoneActive(_ active: Bool) { phoneActive = active; diagnostics.phoneActive = active; updateMonitoring() }
|
||||
func setCarPlayActive(_ active: Bool) { carPlayActive = active; diagnostics.carPlayActive = active; updateMonitoring() }
|
||||
private func updateMonitoring() {
|
||||
if phoneActive || carPlayActive {
|
||||
if monitorTask == nil { monitorTask = Task { await monitor() } }
|
||||
} else { monitorTask?.cancel(); monitorTask = nil }
|
||||
}
|
||||
@Published var pairingKey = PairingKeyStore.load()
|
||||
@Published var address = UserDefaults.standard.string(forKey: "galaxy.lan.address") ?? ""
|
||||
@Published var findAddressAutomatically = UserDefaults.standard.object(forKey: "galaxy.lan.auto") as? Bool ?? true {
|
||||
didSet { UserDefaults.standard.set(findAddressAutomatically, forKey: "galaxy.lan.auto") }
|
||||
}
|
||||
@Published var networkDetails = "Comma can use a hotspot, Wi-Fi or its SIM for internet. Your connection here controls how this iPhone reaches comma."
|
||||
@Published var mode = ConnectionMode(rawValue: UserDefaults.standard.string(forKey: "galaxy.connection.mode") ?? "") ?? .automatic {
|
||||
didSet {
|
||||
transport.mode = mode
|
||||
UserDefaults.standard.set(mode.rawValue, forKey: "galaxy.connection.mode")
|
||||
if mode == .lan { bluetooth.disconnect() }
|
||||
if mode == .bluetooth { lan.invalidate() }
|
||||
}
|
||||
}
|
||||
@Published var showConnections = false
|
||||
@Published var showPairingScanner = false
|
||||
@Published var opened = false
|
||||
@Published var connectionMessage = "Choose a connection, or use Automatic for Wi-Fi with Bluetooth fallback."
|
||||
@Published var wantsConnection = true
|
||||
let bluetooth: BluetoothTransport
|
||||
let lan: LANTransport
|
||||
let transport: PreferredTransport
|
||||
let assets: GalaxyAssetStore
|
||||
let server: LoopbackServer
|
||||
private let pathMonitor = NWPathMonitor()
|
||||
private var lastReconnect = Date.distantPast
|
||||
private var lastAddressCheck = Date.distantPast
|
||||
private var identitySession = ""
|
||||
private var addressCheckSession = ""
|
||||
func importPairingKey(_ key: String) {
|
||||
// Save imported keys only after the encrypted handshake.
|
||||
opened = false
|
||||
wantsConnection = false
|
||||
bluetooth.forgetSavedDevice()
|
||||
PairingKeyStore.remove()
|
||||
lan.clearEndpoint()
|
||||
lan.bind(to: nil)
|
||||
address = ""
|
||||
identitySession = ""
|
||||
addressCheckSession = ""
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.comma.identity")
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.lan.address")
|
||||
pairingKey = key
|
||||
if mode == .lan { mode = .automatic }
|
||||
connectionMessage = "Code scanned. Select your comma below to finish pairing."
|
||||
bluetooth.scan()
|
||||
}
|
||||
init() {
|
||||
let bluetooth = BluetoothTransport()
|
||||
let lan = LANTransport()
|
||||
let transport = PreferredTransport(lan: lan, bluetooth: bluetooth, invalidateLAN: { lan.invalidate() })
|
||||
let assets = GalaxyAssetStore()
|
||||
self.bluetooth = bluetooth; self.lan = lan; self.transport = transport; self.assets = assets
|
||||
let cache = GalaxyReadCache(transport: transport, sessionID: {
|
||||
transport.usesLAN ? "lan-" + lan.generation : "ble-" + bluetooth.sessionIdentifier
|
||||
})
|
||||
server = LoopbackServer(transport: cache, webRoot: assets.readyRoot ?? assets.bundledRoot)
|
||||
transport.mode = mode
|
||||
if let saved = UserDefaults.standard.string(forKey: "galaxy.comma.identity"), LANTransport.deviceID(Data(saved.utf8)) != nil {
|
||||
lan.bind(to: saved)
|
||||
}
|
||||
diagnostics.transport = transport; diagnostics.lan = lan
|
||||
server.start()
|
||||
pathMonitor.pathUpdateHandler = { [weak self] _ in
|
||||
Task { @MainActor in
|
||||
guard let self else { return }
|
||||
self.lan.invalidate()
|
||||
self.lastAddressCheck = .distantPast
|
||||
}
|
||||
}
|
||||
pathMonitor.start(queue: .main)
|
||||
}
|
||||
deinit { pathMonitor.cancel() }
|
||||
func connect() {
|
||||
do {
|
||||
if mode != .bluetooth, !address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||||
try lan.configure(address: address)
|
||||
} else if mode == .lan {
|
||||
throw BridgeError.message("Enter comma’s current local IP address, or use Automatic and pair Bluetooth to find it.")
|
||||
}
|
||||
UserDefaults.standard.set(address.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "galaxy.lan.address")
|
||||
wantsConnection = true
|
||||
lastReconnect = .distantPast
|
||||
lastAddressCheck = .distantPast
|
||||
connectionMessage = "Checking your comma…"
|
||||
} catch { connectionMessage = error.localizedDescription }
|
||||
}
|
||||
func openIfReady() {
|
||||
guard wantsConnection, transport.connected, !opened else { return }
|
||||
let root = assets.readyRoot ?? assets.bundledRoot
|
||||
assets.inUseRoot = root
|
||||
server.useWebRoot(root)
|
||||
opened = true
|
||||
if tab == .connections { tab = .galaxy }
|
||||
}
|
||||
func disconnect() {
|
||||
wantsConnection = false; opened = false
|
||||
bluetooth.disconnect(); lan.invalidate()
|
||||
connectionMessage = "Disconnected."
|
||||
}
|
||||
private func learnAddress() async {
|
||||
guard bluetooth.connected, Date().timeIntervalSince(lastAddressCheck) >= 20 || addressCheckSession != bluetooth.sessionIdentifier else { return }
|
||||
lastAddressCheck = Date()
|
||||
let session = bluetooth.sessionIdentifier
|
||||
addressCheckSession = session
|
||||
do {
|
||||
if identitySession != session {
|
||||
let identity = try await bluetooth.request(path: "/api/params?key=DongleId", method: "GET", headers: [:], body: Data())
|
||||
guard wantsConnection, mode != .bluetooth, bluetooth.sessionIdentifier == session else { return }
|
||||
// Only the authenticated BLE peer may establish the automatic LAN identity.
|
||||
guard identity.status == 200, let value = LANTransport.deviceID(identity.bodyData) else {
|
||||
networkDetails = "Automatic local discovery needs a registered device identifier. Bluetooth still works; enter comma’s IP manually for Wi-Fi."
|
||||
return
|
||||
}
|
||||
lan.bind(to: value)
|
||||
UserDefaults.standard.set(value, forKey: "galaxy.comma.identity")
|
||||
identitySession = session
|
||||
}
|
||||
guard findAddressAutomatically, !lan.connected else { return }
|
||||
let response = try await bluetooth.request(path: "/api/device/status", method: "GET", headers: [:], body: Data())
|
||||
guard wantsConnection, mode != .bluetooth, bluetooth.sessionIdentifier == session, response.status == 200,
|
||||
!response.bodyData.isEmpty else { return }
|
||||
if let ip = LANTransport.reportedAddress(response.bodyData) {
|
||||
try lan.configure(address: ip)
|
||||
address = ip
|
||||
UserDefaults.standard.set(ip, forKey: "galaxy.lan.address")
|
||||
networkDetails = "Trying comma’s current local address. If this hotspot or Wi-Fi network blocks direct access, Bluetooth stays available."
|
||||
} else {
|
||||
networkDetails = "Comma has no usable local Wi-Fi address. Bluetooth still controls local settings; comma can use its SIM for online downloads."
|
||||
}
|
||||
// Galaxy's online:true means the server responds, not that comma can reach the internet.
|
||||
} catch { /* Discovery is optional; it must not disrupt working BLE. */ }
|
||||
}
|
||||
func monitor() async {
|
||||
while !Task.isCancelled {
|
||||
if wantsConnection {
|
||||
if mode != .lan, !bluetooth.connected, !bluetooth.connecting, !bluetooth.isScanning,
|
||||
!pairingKey.isEmpty, Date().timeIntervalSince(lastReconnect) >= 25 {
|
||||
lastReconnect = Date()
|
||||
bluetooth.reconnectSaved(pairingKey: pairingKey)
|
||||
}
|
||||
if mode != .bluetooth {
|
||||
await learnAddress()
|
||||
if lan.endpoint == nil, !address.isEmpty {
|
||||
do { try lan.configure(address: address) }
|
||||
catch { connectionMessage = error.localizedDescription }
|
||||
}
|
||||
_ = await lan.probe()
|
||||
}
|
||||
if transport.connected { openIfReady(); connectionMessage = "Connected over \(transport.label)." }
|
||||
else { connectionMessage = "Wi-Fi unavailable. Pair over Bluetooth below, or check your comma’s IP address." }
|
||||
}
|
||||
do { try await Task.sleep(nanoseconds: 3_000_000_000) } catch { return }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GalaxyRootView: View {
|
||||
@ObservedObject var model: AppModel
|
||||
@ObservedObject var bluetooth: BluetoothTransport
|
||||
@ObservedObject var lan: LANTransport
|
||||
@ObservedObject var assets: GalaxyAssetStore
|
||||
@ObservedObject var server: LoopbackServer
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
init(model: AppModel) {
|
||||
self.model = model; bluetooth = model.bluetooth; lan = model.lan; assets = model.assets; server = model.server
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
VStack(spacing: 14) {
|
||||
HStack {
|
||||
Text("StarPilot").font(.title3.bold())
|
||||
Spacer()
|
||||
HStack(spacing: 5) {
|
||||
Circle().fill(model.transport.connected ? Color.green : Color.orange).frame(width: 6, height: 6)
|
||||
Text(model.transport.label).font(.caption.weight(.medium))
|
||||
}.padding(.horizontal, 10).padding(.vertical, 6)
|
||||
.background(.white.opacity(0.07), in: Capsule())
|
||||
}
|
||||
HStack(spacing: 4) {
|
||||
ForEach(CompanionTab.allCases.filter { $0 != .connections }) { tab in
|
||||
Button { select(tab) } label: {
|
||||
VStack(spacing: 5) {
|
||||
Image(systemName: tab.icon).font(.system(size: 17, weight: .semibold))
|
||||
Text(tab.rawValue).font(.system(size: 10, weight: .semibold)).lineLimit(1).minimumScaleFactor(0.8)
|
||||
}.frame(maxWidth: .infinity).padding(.vertical, 10)
|
||||
.foregroundStyle(model.tab == tab ? Color.white : Color.secondary)
|
||||
.background(model.tab == tab ? brandPurple.opacity(0.3) : Color.clear, in: RoundedRectangle(cornerRadius: 12))
|
||||
}.buttonStyle(.plain).accessibilityAddTraits(model.tab == tab ? .isSelected : [])
|
||||
}
|
||||
Button { select(.connections) } label: {
|
||||
VStack(spacing: 4) {
|
||||
Image(systemName: "gearshape.fill").font(.system(size: 17, weight: .semibold))
|
||||
.frame(width: 36, height: 36)
|
||||
.background(model.tab == .connections ? brandPurple.opacity(0.4) : Color.white.opacity(0.08), in: Circle())
|
||||
Text("Settings").font(.system(size: 10, weight: .semibold))
|
||||
}.frame(width: 60).padding(.vertical, 4)
|
||||
.foregroundStyle(model.tab == .connections ? Color.white : Color.secondary)
|
||||
}.buttonStyle(.plain).accessibilityAddTraits(model.tab == .connections ? .isSelected : [])
|
||||
}.padding(4).background(.white.opacity(0.04), in: RoundedRectangle(cornerRadius: 16))
|
||||
}.padding(.horizontal, 16).padding(.top, 10).padding(.bottom, 12)
|
||||
ZStack {
|
||||
if model.opened, let url = server.url {
|
||||
GalaxyWebView(url: url, requestKey: server.localSecret)
|
||||
.opacity(model.tab == .galaxy ? 1 : 0)
|
||||
.allowsHitTesting(model.tab == .galaxy)
|
||||
.accessibilityHidden(model.tab != .galaxy)
|
||||
}
|
||||
if model.tab == .live || model.tab == .diagnostics {
|
||||
CompanionView(diagnostics: model.diagnostics)
|
||||
} else if model.tab == .connections || !model.opened {
|
||||
connectionView
|
||||
}
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
.background(Color.black)
|
||||
.preferredColorScheme(.dark)
|
||||
.onChange(of: model.showConnections) { _, show in
|
||||
if show { select(.connections); model.showConnections = false }
|
||||
}
|
||||
.onChange(of: model.showDiagnostics) { _, show in
|
||||
if show { select(.live); model.showDiagnostics = false }
|
||||
}
|
||||
.onChange(of: bluetooth.connected) { _, connected in if connected { model.openIfReady() } }
|
||||
.task(id: scenePhase) {
|
||||
model.setPhoneActive(scenePhase == .active)
|
||||
if scenePhase == .active { await model.assets.check() }
|
||||
}
|
||||
}
|
||||
private func select(_ tab: CompanionTab) {
|
||||
model.tab = tab
|
||||
model.diagnostics.live = tab == .live
|
||||
}
|
||||
private let brandPurple = Color(red: 0.55, green: 0.36, blue: 0.96)
|
||||
|
||||
private var connectionView: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
VStack(spacing: 8) {
|
||||
Image("StarPilotHero")
|
||||
.resizable().scaledToFit()
|
||||
.frame(maxWidth: 480)
|
||||
.accessibilityLabel("StarPilot")
|
||||
Text("Galaxy companion")
|
||||
.font(.subheadline.weight(.medium)).foregroundStyle(.secondary)
|
||||
}.frame(maxWidth: .infinity).padding(.top, 8)
|
||||
Text("Connect your comma").font(.title2.bold())
|
||||
Picker("Connection", selection: $model.mode) {
|
||||
ForEach(ConnectionMode.allCases) { Text($0.title).tag($0) }
|
||||
}.pickerStyle(.segmented)
|
||||
Text("Automatic prefers local Wi-Fi and falls back to your paired comma over Bluetooth. Internet isn’t needed for local settings.")
|
||||
.font(.subheadline).foregroundStyle(.secondary)
|
||||
Text(model.networkDetails).font(.caption).foregroundStyle(.secondary)
|
||||
if model.mode != .bluetooth {
|
||||
Toggle("Find comma’s address over Bluetooth", isOn: $model.findAddressAutomatically)
|
||||
Text("Comma IP address").font(.headline)
|
||||
TextField("192.168.10.85", text: $model.address)
|
||||
.keyboardType(.numbersAndPunctuation).textInputAutocapitalization(.never).autocorrectionDisabled()
|
||||
.padding(14).background(.white.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))
|
||||
Text(lan.status).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Button { model.connect(); if model.opened { select(.galaxy) } } label: {
|
||||
Text("Connect").font(.headline).frame(maxWidth: .infinity).padding(.vertical, 8)
|
||||
}.buttonStyle(.borderedProminent).tint(brandPurple)
|
||||
Text(model.connectionMessage).font(.subheadline).foregroundStyle(.secondary)
|
||||
if model.mode != .lan {
|
||||
Divider()
|
||||
Text("Bluetooth pairing").font(.headline)
|
||||
Text("On comma, open Settings → Pair phone. Scan its code here, then select your comma below. After pairing once, the app reconnects automatically.")
|
||||
.font(.subheadline).foregroundStyle(.secondary)
|
||||
Button("Scan pairing code") { model.showPairingScanner = true }
|
||||
.buttonStyle(.borderedProminent).tint(brandPurple)
|
||||
.sheet(isPresented: $model.showPairingScanner) {
|
||||
PairingScannerSheet { model.importPairingKey($0) }
|
||||
}
|
||||
SecureField("64-character pairing key", text: $model.pairingKey)
|
||||
.textInputAutocapitalization(.never).autocorrectionDisabled()
|
||||
.font(.system(.body, design: .monospaced))
|
||||
.padding(14).background(.white.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))
|
||||
Button(bluetooth.isScanning ? "Scanning…" : "Scan for comma") { model.wantsConnection = true; bluetooth.scan() }
|
||||
.buttonStyle(.bordered).disabled(bluetooth.isScanning || bluetooth.connecting)
|
||||
Text(bluetooth.status).font(.subheadline).foregroundStyle(.secondary)
|
||||
ForEach(bluetooth.devices) { device in
|
||||
Button {
|
||||
model.opened = false
|
||||
model.wantsConnection = true
|
||||
model.lan.clearEndpoint()
|
||||
model.lan.bind(to: nil)
|
||||
model.address = ""
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.comma.identity")
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.lan.address")
|
||||
bluetooth.connect(device, pairingKey: model.pairingKey)
|
||||
} label: {
|
||||
HStack {
|
||||
Image(systemName: "car.side.fill"); Text(device.name).font(.headline)
|
||||
Spacer(); Image(systemName: "chevron.right")
|
||||
}.padding(16).background(.white.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))
|
||||
}.buttonStyle(.plain).disabled(bluetooth.connecting)
|
||||
}
|
||||
if bluetooth.connecting { Button("Cancel Bluetooth connection") { bluetooth.disconnect() } }
|
||||
Button("Forget Bluetooth pairing") {
|
||||
bluetooth.forgetSavedDevice(); PairingKeyStore.remove(); model.pairingKey = ""
|
||||
model.lan.bind(to: nil); UserDefaults.standard.removeObject(forKey: "galaxy.comma.identity")
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Divider()
|
||||
Text(assets.status).font(.caption).foregroundStyle(.secondary)
|
||||
Button("Check Galaxy updates") { Task { await assets.check() } }.disabled(assets.checking)
|
||||
Text("Screens are saved on your iPhone. GitHub updates apply next time you open Galaxy, without interrupting your current screen.")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
if model.opened {
|
||||
Button("Back to Galaxy") { select(.galaxy) }
|
||||
Button("Disconnect") { model.disconnect(); select(.connections) }
|
||||
}
|
||||
if !server.error.isEmpty { Text(server.error).foregroundStyle(.red) }
|
||||
}.padding(24).frame(maxWidth: 560).frame(maxWidth: .infinity)
|
||||
}.background(Color.black).tint(brandPurple)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
protocol GalaxyRequestTransport: AnyObject {
|
||||
var connected: Bool { get }
|
||||
var catalogSHA256: String? { get }
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse
|
||||
}
|
||||
|
||||
extension GalaxyRequestTransport {
|
||||
var catalogSHA256: String? { nil }
|
||||
}
|
||||
|
||||
/// Share concurrent settings reads and reuse only stable metadata.
|
||||
@MainActor
|
||||
final class GalaxyReadCache: GalaxyRequestTransport {
|
||||
private let transport: any GalaxyRequestTransport
|
||||
private let sessionID: () -> String
|
||||
private let now: () -> TimeInterval
|
||||
private var session = ""
|
||||
private var generation: UInt64 = 0
|
||||
private var entries: [String: (BridgeResponse, TimeInterval)] = [:]
|
||||
private var pending: [String: (UUID, Task<BridgeResponse, Error>)] = [:]
|
||||
var connected: Bool { transport.connected }
|
||||
var catalogSHA256: String? { transport.catalogSHA256 }
|
||||
|
||||
init(transport: any GalaxyRequestTransport, sessionID: @escaping () -> String,
|
||||
now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
|
||||
self.transport = transport
|
||||
self.sessionID = sessionID
|
||||
self.now = now
|
||||
}
|
||||
|
||||
private func invalidate() {
|
||||
generation += 1
|
||||
entries.removeAll()
|
||||
// Already-sent reads still drain, but new reads cannot join an old one.
|
||||
pending.removeAll()
|
||||
}
|
||||
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse {
|
||||
try Task.checkCancellation()
|
||||
if session != sessionID() {
|
||||
session = sessionID()
|
||||
invalidate()
|
||||
}
|
||||
guard connected else { throw BridgeError.message("Connect to your comma over Bluetooth first.") }
|
||||
if method != "GET" {
|
||||
invalidate()
|
||||
defer { invalidate() }
|
||||
return try await transport.request(path: path, method: method, headers: headers, body: body)
|
||||
}
|
||||
let metadata = path == "/api/params/defaults"
|
||||
|| path == "/assets/components/tools/device_settings_layout.json?v=settings-tier-1"
|
||||
guard body.isEmpty, metadata || path == "/api/params/all" || path == "/api/params/all?galaxy_ble_settings=1" else {
|
||||
return try await transport.request(path: path, method: method, headers: headers, body: body)
|
||||
}
|
||||
let relevantHeaders = headers.filter { ["accept", "cookie", "range"].contains($0.key.lowercased()) }
|
||||
.map { "\($0.key.lowercased()):\($0.value)" }.sorted().joined(separator: "\n")
|
||||
let cacheKey = path + "\n" + relevantHeaders
|
||||
if let (response, expires) = entries[cacheKey], expires > now() { return response }
|
||||
let token: UUID
|
||||
let task: Task<BridgeResponse, Error>
|
||||
if let existing = pending[cacheKey] {
|
||||
(token, task) = existing
|
||||
} else {
|
||||
// Bound cache variants even when a local client changes headers.
|
||||
guard pending.count < 16 else {
|
||||
return try await transport.request(path: path, method: method, headers: headers, body: body)
|
||||
}
|
||||
token = UUID()
|
||||
task = Task { try await transport.request(path: path, method: method, headers: headers, body: body) }
|
||||
pending[cacheKey] = (token, task)
|
||||
}
|
||||
let readGeneration = generation
|
||||
let readSession = session
|
||||
defer { if pending[cacheKey]?.0 == token { pending.removeValue(forKey: cacheKey) } }
|
||||
let response = try await task.value
|
||||
if metadata, response.status == 200, response.bodyData.count <= Wire.maxBody,
|
||||
readGeneration == generation, readSession == sessionID(), connected {
|
||||
if entries.count >= 16 { entries.removeAll() }
|
||||
entries[cacheKey] = (response, now() + 300)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
return response
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
struct GalaxyWebView: UIViewRepresentable {
|
||||
let url: URL
|
||||
let requestKey: String
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(origin: url) }
|
||||
|
||||
func makeUIView(context: Context) -> WKWebView {
|
||||
let config = WKWebViewConfiguration()
|
||||
config.allowsInlineMediaPlayback = true
|
||||
config.defaultWebpagePreferences.allowsContentJavaScript = true
|
||||
// Keep Galaxy on one local origin.
|
||||
let script = """
|
||||
(() => {
|
||||
if (location.origin !== '\(url.scheme!)://\(url.host!):\(url.port!)') return;
|
||||
window.__galaxyNative = true;
|
||||
const key = '\(requestKey)';
|
||||
const local = (u) => new URL(u, location.href).origin === location.origin;
|
||||
const originalFetch = window.fetch.bind(window);
|
||||
window.fetch = (input, init = {}) => {
|
||||
const req = new Request(input, init);
|
||||
if (!local(req.url)) return originalFetch(req);
|
||||
const headers = new Headers(req.headers);
|
||||
headers.set('X-Galaxy-Local', key);
|
||||
return originalFetch(new Request(req, { headers }));
|
||||
};
|
||||
const originalOpen = XMLHttpRequest.prototype.open;
|
||||
const originalSend = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function(method, url, ...rest) {
|
||||
this.__galaxyLocal = local(url);
|
||||
return originalOpen.call(this, method, url, ...rest);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function(body) {
|
||||
if (this.__galaxyLocal) this.setRequestHeader('X-Galaxy-Local', key);
|
||||
return originalSend.call(this, body);
|
||||
};
|
||||
})();
|
||||
"""
|
||||
config.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false))
|
||||
let webView = WKWebView(frame: .zero, configuration: config)
|
||||
webView.navigationDelegate = context.coordinator
|
||||
webView.uiDelegate = context.coordinator
|
||||
webView.isOpaque = false
|
||||
webView.backgroundColor = UIColor(red: 0.06, green: 0.05, blue: 0.09, alpha: 1)
|
||||
webView.scrollView.contentInsetAdjustmentBehavior = .never
|
||||
webView.load(URLRequest(url: url))
|
||||
return webView
|
||||
}
|
||||
|
||||
func updateUIView(_ uiView: WKWebView, context: Context) {}
|
||||
|
||||
final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {
|
||||
let origin: URL
|
||||
init(origin: URL) { self.origin = origin }
|
||||
|
||||
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
|
||||
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
|
||||
guard let url = action.request.url else { decisionHandler(.cancel); return }
|
||||
if url.scheme == origin.scheme, url.host == origin.host, url.port == origin.port {
|
||||
decisionHandler(.allow)
|
||||
} else if url.scheme == "about" || url.scheme == "blob" {
|
||||
decisionHandler(.allow)
|
||||
} else {
|
||||
if action.navigationType == .linkActivated, ["https", "http"].contains(url.scheme ?? "") {
|
||||
UIApplication.shared.open(url)
|
||||
}
|
||||
decisionHandler(.cancel)
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration,
|
||||
for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
|
||||
if action.targetFrame == nil, let url = action.request.url, ["https", "http"].contains(url.scheme ?? "") {
|
||||
UIApplication.shared.open(url)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
struct LocalRequest {
|
||||
let method: String
|
||||
let target: String
|
||||
let headers: [String: String]
|
||||
let body: Data
|
||||
|
||||
static func parse(_ data: Data) throws -> LocalRequest? {
|
||||
guard let separator = data.range(of: Data("\r\n\r\n".utf8)) else {
|
||||
if data.count > 16_384 { throw BridgeError.message("HTTP headers are too large.") }
|
||||
return nil
|
||||
}
|
||||
guard separator.lowerBound <= 16_384,
|
||||
let head = String(data: data[..<separator.lowerBound], encoding: .utf8) else {
|
||||
throw BridgeError.message("Invalid HTTP headers.")
|
||||
}
|
||||
let lines = head.components(separatedBy: "\r\n")
|
||||
let first = (lines.first ?? "").split(separator: " ")
|
||||
guard first.count == 3, ["HTTP/1.1", "HTTP/1.0"].contains(String(first[2])),
|
||||
["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].contains(String(first[0])) else {
|
||||
throw BridgeError.message("Invalid HTTP request.")
|
||||
}
|
||||
var headers: [String: String] = [:]
|
||||
for line in lines.dropFirst() {
|
||||
guard let colon = line.firstIndex(of: ":"), colon != line.startIndex else { throw BridgeError.message("Malformed header.") }
|
||||
let name = line[..<colon].lowercased()
|
||||
guard headers[name] == nil else { throw BridgeError.message("Duplicate HTTP header.") }
|
||||
headers[name] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
guard headers["transfer-encoding"] == nil else { throw BridgeError.message("Chunked uploads are not supported.") }
|
||||
let length: Int
|
||||
if let raw = headers["content-length"] {
|
||||
guard let parsed = Int(raw), parsed >= 0, parsed <= Wire.maxBody else { throw BridgeError.message("Invalid upload size.") }
|
||||
length = parsed
|
||||
} else { length = 0 }
|
||||
let available = data.count - separator.upperBound
|
||||
guard available >= length else { return nil }
|
||||
guard available == length else { throw BridgeError.message("HTTP pipelining is not supported.") }
|
||||
return LocalRequest(method: String(first[0]), target: String(first[1]), headers: headers,
|
||||
body: data.subdata(in: separator.upperBound..<data.count))
|
||||
}
|
||||
}
|
||||
|
||||
struct LocalResponse {
|
||||
let status: Int
|
||||
let headers: [String: String]
|
||||
let body: Data
|
||||
|
||||
static func error(_ status: Int, _ message: String) -> LocalResponse {
|
||||
LocalResponse(status: status, headers: ["content-type": "application/json"],
|
||||
body: (try? JSONSerialization.data(withJSONObject: ["error": message])) ?? Data())
|
||||
}
|
||||
|
||||
func encoded(headOnly: Bool = false) -> Data {
|
||||
var text = "HTTP/1.1 \(status) \(HTTPURLResponse.localizedString(forStatusCode: status))\r\n"
|
||||
for (key, value) in headers where !["content-length", "connection", "cache-control"].contains(key.lowercased()) {
|
||||
guard !key.contains("\r"), !key.contains("\n"), !value.contains("\r"), !value.contains("\n") else { continue }
|
||||
text += "\(key): \(value)\r\n"
|
||||
}
|
||||
text += "Content-Length: \(body.count)\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n"
|
||||
return Data(text.utf8) + (headOnly ? Data() : body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Galaxy Bluetooth</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
<key>NSExceptionDomains</key>
|
||||
<dict>
|
||||
<key>127.0.0.1</key>
|
||||
<dict>
|
||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||
<string>Connect directly to your comma's Galaxy Bluetooth bridge.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Scan the pairing code displayed on your comma to connect the Galaxy app over Bluetooth.</string>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>Connect to Galaxy on your comma over your local Wi-Fi network.</string>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
<false/>
|
||||
<key>UISceneConfigurations</key>
|
||||
<dict>
|
||||
<key>CPTemplateApplicationSceneSessionRoleApplication</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UISceneClassName</key>
|
||||
<string>CPTemplateApplicationScene</string>
|
||||
<key>UISceneConfigurationName</key>
|
||||
<string>StarPilot CarPlay</string>
|
||||
<key>UISceneDelegateClassName</key>
|
||||
<string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,137 @@
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
struct MJPEGParser {
|
||||
private var wire = Data()
|
||||
private var body = Data()
|
||||
private var headersRead = false
|
||||
private var chunked = false
|
||||
private var chunkRemaining: Int?
|
||||
private var chunkTrailer = false
|
||||
private var frameLength: Int?
|
||||
private let delimiter = Data("\r\n\r\n".utf8)
|
||||
mutating func append(_ data: Data) throws -> [Data] {
|
||||
wire.append(data)
|
||||
guard wire.count <= 750_000 else { throw URLError(.dataLengthExceedsMaximum) }
|
||||
if !headersRead {
|
||||
guard let end = wire.range(of: delimiter) else {
|
||||
guard wire.count <= 16_384 else { throw URLError(.cannotParseResponse) }; return []
|
||||
}
|
||||
let header = String(decoding: wire[..<end.lowerBound], as: UTF8.self).lowercased()
|
||||
guard let code = header.components(separatedBy: "\r\n").first?.split(separator: " ").dropFirst().first,
|
||||
let status = Int(code) else { throw URLError(.cannotParseResponse) }
|
||||
if status != 200 {
|
||||
let message: String
|
||||
switch status {
|
||||
case 404: message = "Comma is missing the Live View endpoint. Update your fork and reboot comma while parked."
|
||||
case 403: message = "Comma rejected this phone’s pairing, or diagnostics are disabled in an older build. Check comma setup, then reconnect Bluetooth."
|
||||
case 503: message = "Live View is disabled on comma. Enable diagnostics before connecting."
|
||||
default: message = "Comma returned HTTP \(status) for Live View."
|
||||
}
|
||||
throw BridgeError.message(message)
|
||||
}
|
||||
guard header.contains("content-type: multipart/x-mixed-replace"), header.contains("boundary=galaxy-frame") else {
|
||||
throw BridgeError.message("Comma returned an unexpected Live View format (HTTP 200). Check that Galaxy is running the updated fork.")
|
||||
}
|
||||
chunked = header.contains("transfer-encoding: chunked")
|
||||
wire.removeSubrange(..<end.upperBound); headersRead = true
|
||||
}
|
||||
if !chunked { body.append(wire); wire.removeAll(keepingCapacity: true) }
|
||||
else {
|
||||
while !wire.isEmpty {
|
||||
if chunkTrailer {
|
||||
guard wire.count >= 2 else { break }
|
||||
guard wire.prefix(2) == Data("\r\n".utf8) else { throw URLError(.cannotParseResponse) }
|
||||
wire.removeFirst(2); chunkTrailer = false; chunkRemaining = nil
|
||||
}
|
||||
if chunkRemaining == nil {
|
||||
guard let line = wire.range(of: Data("\r\n".utf8)) else {
|
||||
guard wire.count < 128 else { throw URLError(.cannotParseResponse) }; break
|
||||
}
|
||||
let text = String(decoding: wire[..<line.lowerBound], as: UTF8.self).split(separator: ";").first ?? ""
|
||||
guard let size = Int(text, radix: 16), (0...750_000).contains(size) else { throw URLError(.cannotParseResponse) }
|
||||
if size == 0 { throw URLError(.networkConnectionLost) }
|
||||
chunkRemaining = size; wire.removeSubrange(..<line.upperBound)
|
||||
}
|
||||
guard let remaining = chunkRemaining else { break }
|
||||
let count = min(remaining, wire.count)
|
||||
body.append(wire.prefix(count)); wire.removeFirst(count)
|
||||
chunkRemaining = remaining - count
|
||||
if chunkRemaining == 0 { chunkTrailer = true }
|
||||
if count == 0 { break }
|
||||
}
|
||||
}
|
||||
guard body.count <= 750_000 else { throw URLError(.dataLengthExceedsMaximum) }
|
||||
var frames: [Data] = []
|
||||
while true {
|
||||
if frameLength == nil {
|
||||
while body.starts(with: Data("\r\n".utf8)) { body.removeFirst(2) }
|
||||
if body.isEmpty { break }
|
||||
guard let end = body.range(of: delimiter) else {
|
||||
guard body.count <= 1024 else { throw URLError(.cannotParseResponse) }; break
|
||||
}
|
||||
let headers = String(decoding: body[..<end.lowerBound], as: UTF8.self).lowercased()
|
||||
guard headers.contains("--galaxy-frame"), headers.contains("content-type: image/jpeg"),
|
||||
let lengthLine = headers.components(separatedBy: "\r\n").first(where: { $0.hasPrefix("content-length:") }),
|
||||
let size = Int(lengthLine.dropFirst("content-length:".count).trimmingCharacters(in: .whitespacesAndNewlines)),
|
||||
(1...650_000).contains(size) else { throw URLError(.cannotParseResponse) }
|
||||
frameLength = size; body.removeSubrange(..<end.upperBound)
|
||||
}
|
||||
guard let size = frameLength, body.count >= size else { break }
|
||||
frames.append(Data(body.prefix(size))); body.removeFirst(size); frameLength = nil
|
||||
}
|
||||
return frames
|
||||
}
|
||||
}
|
||||
|
||||
final class LiveStream: @unchecked Sendable {
|
||||
private let connection: NWConnection
|
||||
private let queue = DispatchQueue(label: "StarPilot.LiveStream")
|
||||
private let request: Data
|
||||
private let frame: @Sendable (Data) -> Void
|
||||
private let failure: @Sendable (String) -> Void
|
||||
private var parser = MJPEGParser()
|
||||
private var stopped = false
|
||||
init(host: String, headers: [String: String], frame: @escaping @Sendable (Data) -> Void,
|
||||
failure: @escaping @Sendable (String) -> Void) {
|
||||
connection = NWConnection(host: NWEndpoint.Host(host), port: 8082, using: .tcp)
|
||||
let fields = headers.map { "\($0.key): \($0.value)\r\n" }.joined()
|
||||
request = Data("GET /api/companion/stream HTTP/1.1\r\nHost: \(host):8082\r\nConnection: close\r\n\(fields)\r\n".utf8)
|
||||
self.frame = frame; self.failure = failure
|
||||
}
|
||||
func start() {
|
||||
connection.stateUpdateHandler = { [weak self] state in
|
||||
guard let self, !self.stopped else { return }
|
||||
switch state {
|
||||
case .ready:
|
||||
self.connection.send(content: self.request, completion: .contentProcessed { [weak self] error in
|
||||
guard let self else { return }
|
||||
if let error { self.fail(error.localizedDescription) } else { self.receive() }
|
||||
})
|
||||
case .failed(let error): self.fail(error.localizedDescription)
|
||||
default: break
|
||||
}
|
||||
}
|
||||
connection.start(queue: queue)
|
||||
}
|
||||
func stop() { queue.async { [weak self] in self?.stopped = true; self?.connection.cancel() } }
|
||||
private func fail(_ message: String) {
|
||||
guard !stopped else { return }
|
||||
stopped = true; connection.cancel(); failure(message)
|
||||
}
|
||||
private func receive() {
|
||||
guard !stopped else { return }
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { [weak self] data, _, complete, error in
|
||||
guard let self, !self.stopped else { return }
|
||||
if let data {
|
||||
do {
|
||||
// Prefer the newest complete frame when the network batches frames.
|
||||
if let latest = try self.parser.append(data).last { self.frame(latest) }
|
||||
} catch { self.fail(error.localizedDescription); return }
|
||||
}
|
||||
if let error { self.fail(error.localizedDescription) }
|
||||
else if complete { self.fail("Reconnecting live stream…") }
|
||||
else { self.receive() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Network
|
||||
import Combine
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
@MainActor
|
||||
final class LoopbackServer: ObservableObject {
|
||||
@Published var url: URL?
|
||||
@Published var error = ""
|
||||
let localSecret = UUID().uuidString + UUID().uuidString
|
||||
private var listener: NWListener?
|
||||
private var connections: [UUID: LocalConnection] = [:]
|
||||
private var webRoot: URL
|
||||
private let transport: any GalaxyRequestTransport
|
||||
private var catalog: Data?
|
||||
private var catalogSHA256: String?
|
||||
|
||||
init(transport: any GalaxyRequestTransport, webRoot: URL? = nil) {
|
||||
self.transport = transport
|
||||
let root = webRoot ?? Bundle.main.resourceURL!.appendingPathComponent("Web", isDirectory: true)
|
||||
self.webRoot = root
|
||||
self.catalog = try? Data(contentsOf: root.appendingPathComponent("assets/components/tools/device_settings_layout.json"))
|
||||
self.catalogSHA256 = catalog.map { SHA256.hash(data: $0).map { String(format: "%02x", $0) }.joined() }
|
||||
}
|
||||
|
||||
func useWebRoot(_ root: URL) {
|
||||
webRoot = root
|
||||
catalog = try? Data(contentsOf: root.appendingPathComponent("assets/components/tools/device_settings_layout.json"))
|
||||
catalogSHA256 = catalog.map { SHA256.hash(data: $0).map { String(format: "%02x", $0) }.joined() }
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard listener == nil else { return }
|
||||
do {
|
||||
let parameters = NWParameters.tcp
|
||||
parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
|
||||
let listener = try NWListener(using: parameters)
|
||||
self.listener = listener
|
||||
listener.stateUpdateHandler = { [weak self, weak listener] state in
|
||||
Task { @MainActor in
|
||||
guard let self else { return }
|
||||
switch state {
|
||||
case .ready:
|
||||
if let port = listener?.port { self.url = URL(string: "http://127.0.0.1:\(port.rawValue)/") }
|
||||
case .failed(let failure): self.error = failure.localizedDescription
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
listener.newConnectionHandler = { [weak self] connection in
|
||||
Task { @MainActor in self?.accept(connection) }
|
||||
}
|
||||
listener.start(queue: .main)
|
||||
} catch { self.error = error.localizedDescription }
|
||||
}
|
||||
|
||||
func stop() {
|
||||
listener?.cancel()
|
||||
listener = nil
|
||||
url = nil
|
||||
for client in Array(connections.values) { client.close() }
|
||||
}
|
||||
|
||||
private func accept(_ connection: NWConnection) {
|
||||
guard connections.count < 64 else { connection.cancel(); return }
|
||||
let id = UUID()
|
||||
let client = LocalConnection(connection: connection, handle: { [weak self] request in
|
||||
guard let self else { return .error(503, "App is shutting down.") }
|
||||
return await self.handle(request)
|
||||
}, onClose: { [weak self] in self?.connections.removeValue(forKey: id) })
|
||||
connections[id] = client
|
||||
client.start()
|
||||
}
|
||||
|
||||
private func handle(_ request: LocalRequest) async -> LocalResponse {
|
||||
guard let base = url, let port = base.port, request.headers["host"] == "127.0.0.1:\(port)" else {
|
||||
return .error(403, "Invalid local host.")
|
||||
}
|
||||
if let origin = request.headers["origin"], origin != "http://127.0.0.1:\(port)" {
|
||||
return .error(403, "Cross-origin requests are blocked.")
|
||||
}
|
||||
guard request.target.hasPrefix("/"), !request.target.hasPrefix("//"),
|
||||
let components = URLComponents(string: request.target), components.scheme == nil, components.host == nil,
|
||||
let path = components.percentEncodedPath.removingPercentEncoding,
|
||||
!path.contains("\\"), !path.contains("%"), !path.contains("//"),
|
||||
!path.split(separator: "/").contains(where: { $0 == ".." || $0 == "." }) else {
|
||||
return .error(400, "Invalid local path.")
|
||||
}
|
||||
if path.hasPrefix("/_gateway/") { return .error(404, "Choose your connection in the native app.") }
|
||||
let dynamic = path.hasPrefix("/api/") || path == "/assets/components/tools/device_settings_layout.json"
|
||||
if dynamic {
|
||||
guard request.headers["x-galaxy-local"] == localSecret else { return .error(403, "Missing app request key.") }
|
||||
guard transport.connected else { return .error(503, "Your comma is disconnected. Open Connections to reconnect.") }
|
||||
// Verify the device's catalog during the authenticated BLE handshake.
|
||||
if request.method == "GET", request.body.isEmpty,
|
||||
request.target == "/assets/components/tools/device_settings_layout.json?v=settings-tier-1",
|
||||
request.headers["range"] == nil, let catalog, let catalogSHA256,
|
||||
transport.catalogSHA256 == catalogSHA256 {
|
||||
return LocalResponse(status: 200, headers: ["content-type": "application/json"], body: catalog)
|
||||
}
|
||||
do {
|
||||
let response = try await transport.request(path: request.target, method: request.method,
|
||||
headers: request.headers, body: request.body)
|
||||
return LocalResponse(status: response.status, headers: response.headers, body: response.bodyData)
|
||||
} catch { return .error(502, error.localizedDescription) }
|
||||
}
|
||||
guard ["GET", "HEAD"].contains(request.method) else { return .error(405, "Method is not supported for bundled files.") }
|
||||
let assetPath: String
|
||||
if path.hasPrefix("/assets/") { assetPath = String(path.dropFirst()) }
|
||||
else if ["/", "/mobile", "/mobile/"].contains(path) { assetPath = "assets/mobile/index.html" }
|
||||
else if path == "/manifest.json" { assetPath = "assets/manifest.json" }
|
||||
else { assetPath = "classic.html" }
|
||||
let file = webRoot.appendingPathComponent(assetPath).standardizedFileURL
|
||||
guard file.path.hasPrefix(webRoot.standardizedFileURL.path + "/"), let data = try? Data(contentsOf: file) else {
|
||||
return .error(404, "Bundled Galaxy asset was not found.")
|
||||
}
|
||||
let mime: String
|
||||
switch file.pathExtension {
|
||||
case "js", "mjs": mime = "text/javascript"
|
||||
case "css": mime = "text/css"
|
||||
case "html": mime = "text/html; charset=utf-8"
|
||||
case "json", "webmanifest": mime = "application/json"
|
||||
case "svg": mime = "image/svg+xml"
|
||||
default: mime = UTType(filenameExtension: file.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
|
||||
}
|
||||
return LocalResponse(status: 200, headers: ["content-type": mime], body: data)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class LocalConnection {
|
||||
let connection: NWConnection
|
||||
let handle: @MainActor (LocalRequest) async -> LocalResponse
|
||||
let onClose: @MainActor () -> Void
|
||||
private var data = Data()
|
||||
private var requestTask: Task<Void, Never>?
|
||||
private var headerTimeout: Task<Void, Never>?
|
||||
private var closed = false
|
||||
|
||||
init(connection: NWConnection, handle: @escaping @MainActor (LocalRequest) async -> LocalResponse,
|
||||
onClose: @escaping @MainActor () -> Void) {
|
||||
self.connection = connection
|
||||
self.handle = handle
|
||||
self.onClose = onClose
|
||||
}
|
||||
|
||||
func start() {
|
||||
connection.stateUpdateHandler = { [weak self] state in
|
||||
Task { @MainActor in
|
||||
if case .failed = state { self?.close() }
|
||||
if case .cancelled = state { self?.close() }
|
||||
}
|
||||
}
|
||||
connection.start(queue: .main)
|
||||
headerTimeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 10_000_000_000)
|
||||
if !Task.isCancelled { self?.close() }
|
||||
}
|
||||
receive()
|
||||
}
|
||||
|
||||
fileprivate func close() {
|
||||
guard !closed else { return }
|
||||
closed = true
|
||||
headerTimeout?.cancel()
|
||||
requestTask?.cancel()
|
||||
connection.stateUpdateHandler = nil
|
||||
connection.cancel()
|
||||
onClose()
|
||||
}
|
||||
|
||||
private func receive() {
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { [weak self] chunk, _, ended, failure in
|
||||
Task { @MainActor in self?.consume(chunk, ended: ended, failure: failure) }
|
||||
}
|
||||
}
|
||||
|
||||
private func consume(_ chunk: Data?, ended: Bool, failure: NWError?) {
|
||||
guard !closed else { return }
|
||||
data.append(chunk ?? Data())
|
||||
guard failure == nil, data.count <= Wire.maxBody + 16_388 else { close(); return }
|
||||
do {
|
||||
guard let request = try LocalRequest.parse(data) else {
|
||||
if ended { close() } else { receive() }
|
||||
return
|
||||
}
|
||||
headerTimeout?.cancel()
|
||||
data = Data()
|
||||
// Detect browser aborts while a Bluetooth request is queued.
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 1) { [weak self] bytes, _, done, failure in
|
||||
Task { @MainActor in
|
||||
if done || failure != nil || bytes?.isEmpty == false { self?.close() }
|
||||
}
|
||||
}
|
||||
requestTask = Task { @MainActor in
|
||||
let response = await handle(request)
|
||||
guard !Task.isCancelled, !closed else { close(); return }
|
||||
send(response, headOnly: request.method == "HEAD")
|
||||
}
|
||||
} catch { send(.error(400, error.localizedDescription), headOnly: false) }
|
||||
}
|
||||
|
||||
private func send(_ response: LocalResponse, headOnly: Bool) {
|
||||
headerTimeout?.cancel()
|
||||
connection.send(content: response.encoded(headOnly: headOnly), completion: .contentProcessed { [weak self] _ in
|
||||
Task { @MainActor in self?.close() }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// Each request has an isolated, bounded buffer.
|
||||
final class BoundedHTTP: NSObject, URLSessionDataDelegate, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>?
|
||||
private var buffer = Data()
|
||||
private var response: HTTPURLResponse?
|
||||
private var task: URLSessionDataTask?
|
||||
private var session: URLSession?
|
||||
private var cancelled = false
|
||||
private let limit: Int
|
||||
init(limit: Int) { self.limit = limit }
|
||||
|
||||
static func load(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) {
|
||||
let client = BoundedHTTP(limit: limit)
|
||||
return try await withTaskCancellationHandler(operation: {
|
||||
try Task.checkCancellation()
|
||||
return try await withCheckedThrowingContinuation { client.start(request, continuation: $0) }
|
||||
}, onCancel: { client.cancel() })
|
||||
}
|
||||
private func start(_ request: URLRequest, continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard !cancelled else { continuation.resume(throwing: CancellationError()); return }
|
||||
self.continuation = continuation
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.urlCache = nil
|
||||
config.httpCookieStorage = nil
|
||||
config.requestCachePolicy = .reloadIgnoringLocalCacheData
|
||||
config.connectionProxyDictionary = [:]
|
||||
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
|
||||
self.session = session
|
||||
task = session.dataTask(with: request)
|
||||
task?.resume()
|
||||
}
|
||||
private func cancel() {
|
||||
lock.lock(); cancelled = true; let task = task; lock.unlock()
|
||||
task?.cancel()
|
||||
}
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
||||
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
||||
completionHandler(nil)
|
||||
}
|
||||
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
|
||||
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
|
||||
guard let http = response as? HTTPURLResponse, response.expectedContentLength <= limit else {
|
||||
completionHandler(.cancel); return
|
||||
}
|
||||
self.response = http
|
||||
completionHandler(.allow)
|
||||
}
|
||||
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
|
||||
guard buffer.count + data.count <= limit else { dataTask.cancel(); return }
|
||||
buffer.append(data)
|
||||
}
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
||||
lock.lock(); let callback = continuation; continuation = nil; let cancelled = cancelled; lock.unlock()
|
||||
if cancelled { callback?.resume(throwing: CancellationError()) }
|
||||
else if let error { callback?.resume(throwing: error) }
|
||||
else if let response { callback?.resume(returning: (buffer, response)) }
|
||||
else { callback?.resume(throwing: BridgeError.message("Invalid HTTP response.")) }
|
||||
session.finishTasksAndInvalidate()
|
||||
self.session = nil
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class LANTransport: ObservableObject, GalaxyRequestTransport {
|
||||
@Published private(set) var connected = false
|
||||
@Published private(set) var status = "Local connection not checked yet."
|
||||
private(set) var endpoint: URL?
|
||||
private(set) var generation = UUID().uuidString
|
||||
private(set) var expectedDeviceID: String?
|
||||
|
||||
// An explicit private IPv4 address prevents cloud/loopback endpoints from being treated as the local comma.
|
||||
static func endpoint(_ address: String) throws -> URL {
|
||||
let parts = address.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4, parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }),
|
||||
parts.allSatisfy({ String(Int($0) ?? -1) == $0 }),
|
||||
let a = Int(parts[0]), let b = Int(parts[1]), parts.allSatisfy({ (0...255).contains(Int($0) ?? -1) }),
|
||||
a == 10 || (a == 172 && (16...31).contains(b)) || (a == 192 && b == 168),
|
||||
let url = URL(string: "http://\(parts.joined(separator: ".")):8082") else {
|
||||
throw BridgeError.message("Enter your comma’s local IP address, such as 192.168.10.85.")
|
||||
}
|
||||
return url
|
||||
}
|
||||
func configure(address: String) throws {
|
||||
let new = try Self.endpoint(address)
|
||||
if endpoint != new { endpoint = new; invalidate() }
|
||||
}
|
||||
static func reportedAddress(_ data: Data) -> String? {
|
||||
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let ip = json["lanIp"] as? String, (try? endpoint(ip)) != nil else { return nil }
|
||||
return ip
|
||||
}
|
||||
static func deviceID(_ data: Data) -> String? {
|
||||
guard let value = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
value.count == 16, value.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { return nil }
|
||||
return value
|
||||
}
|
||||
func bind(to identity: String?) {
|
||||
if expectedDeviceID != identity { expectedDeviceID = identity; invalidate() }
|
||||
}
|
||||
func clearEndpoint() { endpoint = nil; invalidate() }
|
||||
func invalidate() { connected = false; generation = UUID().uuidString }
|
||||
func probe() async -> Bool {
|
||||
guard let endpoint else { return false }
|
||||
var request = URLRequest(url: endpoint.appendingPathComponent("api/device/status"))
|
||||
request.timeoutInterval = 2
|
||||
let expectedGeneration = generation
|
||||
do {
|
||||
let (data, response) = try await PrivateLANHTTP.load(request, limit: 65_536)
|
||||
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
|
||||
guard !Task.isCancelled, expectedGeneration == generation else { return false }
|
||||
var available = response.statusCode == 200 && json?["online"] as? Bool == true
|
||||
&& ["Parked", "Driving"].contains(json?["status"] as? String ?? "")
|
||||
if available, let expectedDeviceID {
|
||||
var identityRequest = URLRequest(url: URL(string: endpoint.absoluteString + "/api/params?key=DongleId")!)
|
||||
identityRequest.timeoutInterval = 2
|
||||
let (identity, identityResponse) = try await PrivateLANHTTP.load(identityRequest, limit: 256)
|
||||
available = identityResponse.statusCode == 200 && Self.deviceID(identity) == expectedDeviceID
|
||||
}
|
||||
guard !Task.isCancelled, expectedGeneration == generation else { return false }
|
||||
connected = available
|
||||
status = available ? "Local comma verified." : "Local endpoint unavailable or does not match the paired comma."
|
||||
} catch { if !Task.isCancelled, expectedGeneration == generation { status = error.localizedDescription; invalidate() } }
|
||||
return connected
|
||||
}
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse {
|
||||
guard connected, let endpoint else { throw URLError(.notConnectedToInternet) }
|
||||
guard let relative = URLComponents(string: path), relative.scheme == nil, relative.host == nil,
|
||||
relative.fragment == nil, path.hasPrefix("/"), !path.hasPrefix("//"),
|
||||
let decoded = relative.percentEncodedPath.removingPercentEncoding,
|
||||
!decoded.contains("\\"), !decoded.contains("%"), !decoded.contains("//"),
|
||||
!decoded.unicodeScalars.contains(where: { $0.value < 32 }),
|
||||
!decoded.split(separator: "/").contains(where: { $0 == "." || $0 == ".." }),
|
||||
decoded.hasPrefix("/api/") || decoded == "/assets/components/tools/device_settings_layout.json",
|
||||
["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"].contains(method), body.count <= Wire.maxBody,
|
||||
let url = URL(string: endpoint.absoluteString + path) else {
|
||||
throw BridgeError.message("Invalid Galaxy request.")
|
||||
}
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
request.httpBody = body.isEmpty ? nil : body
|
||||
// Bound stale-route delay; long downloads/streams need a separate route.
|
||||
request.timeoutInterval = 8
|
||||
for (name, value) in headers where ["content-type", "accept", "cookie", "range", "x-companion-nonce", "x-companion-mac"].contains(name.lowercased()) {
|
||||
request.setValue(value, forHTTPHeaderField: name)
|
||||
}
|
||||
let (data, response) = try await PrivateLANHTTP.load(request, limit: 8 * Wire.maxBody)
|
||||
var responseHeaders: [String: String] = [:]
|
||||
for (key, value) in response.allHeaderFields {
|
||||
if let name = key as? String, ["content-type", "content-range", "accept-ranges", "content-disposition"].contains(name.lowercased()) {
|
||||
responseHeaders[name.lowercased()] = String(describing: value)
|
||||
}
|
||||
}
|
||||
return BridgeResponse(id: UUID().uuidString, session: generation, counter: 0, status: response.statusCode,
|
||||
headers: responseHeaders, body: data.base64EncodedString())
|
||||
}
|
||||
}
|
||||
|
||||
enum ConnectionMode: String, CaseIterable, Identifiable {
|
||||
case automatic, lan, bluetooth
|
||||
var id: String { rawValue }
|
||||
var title: String { switch self { case .automatic: "Automatic"; case .lan: "Wi-Fi only"; case .bluetooth: "Bluetooth only" } }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class PreferredTransport: ObservableObject, GalaxyRequestTransport {
|
||||
let lan: any GalaxyRequestTransport
|
||||
let bluetooth: any GalaxyRequestTransport
|
||||
var invalidateLAN: () -> Void
|
||||
@Published var mode: ConnectionMode = .automatic
|
||||
var connected: Bool { (mode != .bluetooth && lan.connected) || (mode != .lan && bluetooth.connected) }
|
||||
var usesLAN: Bool { mode != .bluetooth && lan.connected }
|
||||
var label: String { usesLAN ? "Wi-Fi" : bluetooth.connected && mode != .lan ? "Bluetooth" : "Reconnecting…" }
|
||||
var catalogSHA256: String? { usesLAN ? lan.catalogSHA256 : bluetooth.catalogSHA256 }
|
||||
init(lan: any GalaxyRequestTransport, bluetooth: any GalaxyRequestTransport, invalidateLAN: @escaping () -> Void) {
|
||||
self.lan = lan; self.bluetooth = bluetooth; self.invalidateLAN = invalidateLAN
|
||||
}
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse {
|
||||
try Task.checkCancellation()
|
||||
if usesLAN {
|
||||
do { return try await lan.request(path: path, method: method, headers: headers, body: body) }
|
||||
catch {
|
||||
try Task.checkCancellation()
|
||||
guard error is URLError else { throw error }
|
||||
invalidateLAN()
|
||||
// Retry reads only; never replay a setting change.
|
||||
if !["GET", "HEAD"].contains(method) {
|
||||
throw BridgeError.message("Wi-Fi disconnected. This change may have saved; reload the setting to confirm before trying again.")
|
||||
}
|
||||
guard mode == .automatic, bluetooth.connected else { throw error }
|
||||
}
|
||||
}
|
||||
guard mode != .lan, bluetooth.connected else { throw BridgeError.message("Your comma is disconnected. Open Connections to reconnect.") }
|
||||
return try await bluetooth.request(path: path, method: method, headers: headers, body: body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
enum PairingKeyStore {
|
||||
private static let service = "link.galaxy.bluetooth.pairing"
|
||||
private static let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: "comma"]
|
||||
|
||||
static func load() -> String {
|
||||
var request = query
|
||||
request[kSecReturnData as String] = true
|
||||
request[kSecMatchLimit as String] = kSecMatchLimitOne
|
||||
var result: CFTypeRef?
|
||||
guard SecItemCopyMatching(request as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return "" }
|
||||
return String(data: data, encoding: .utf8) ?? ""
|
||||
}
|
||||
|
||||
static func save(_ value: String) throws {
|
||||
let data = Data(value.utf8)
|
||||
let status = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] as CFDictionary)
|
||||
if status == errSecItemNotFound {
|
||||
var item = query
|
||||
item[kSecValueData as String] = data
|
||||
item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
||||
guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { throw BridgeError.message("Could not save pairing key in Keychain.") }
|
||||
} else if status != errSecSuccess { throw BridgeError.message("Could not update pairing key in Keychain.") }
|
||||
}
|
||||
|
||||
static func remove() { SecItemDelete(query as CFDictionary) }
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import Foundation
|
||||
|
||||
struct PairingCode: Decodable {
|
||||
let type: String
|
||||
let version: Int
|
||||
let key: String
|
||||
|
||||
static func parse(_ text: String) throws -> String {
|
||||
guard text.utf8.count <= 512, let data = text.data(using: .utf8),
|
||||
let value = try? JSONDecoder().decode(Self.self, from: data),
|
||||
value.type == "galaxy-bluetooth", value.version == 1,
|
||||
value.key.utf8.count == 64,
|
||||
value.key.utf8.allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }) else {
|
||||
throw NSError(domain: "GalaxyPairing", code: 1, userInfo: [NSLocalizedDescriptionKey:
|
||||
"This isn’t a Galaxy Bluetooth pairing code. Open Pair phone on your comma."])
|
||||
}
|
||||
return value.key.lowercased()
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(VisionKit) && os(iOS)
|
||||
import SwiftUI
|
||||
import VisionKit
|
||||
import AVFoundation
|
||||
|
||||
@MainActor
|
||||
private final class ScannerState: ObservableObject {
|
||||
@Published var ready = false
|
||||
@Published var message = "Open Settings → Pair phone on comma, then point the camera at its code."
|
||||
}
|
||||
|
||||
struct PairingScannerSheet: View {
|
||||
let onKey: (String) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@StateObject private var state = ScannerState()
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
VStack {
|
||||
Text(state.message).padding()
|
||||
if state.ready {
|
||||
PairingCamera { text in
|
||||
do {
|
||||
let key = try PairingCode.parse(text)
|
||||
onKey(key)
|
||||
dismiss()
|
||||
return true
|
||||
} catch { state.message = error.localizedDescription; return false }
|
||||
} onError: { state.message = $0; state.ready = false }
|
||||
} else {
|
||||
Image(systemName: "qrcode.viewfinder").font(.system(size: 80)).padding()
|
||||
Text("You can also enter a pairing key on the connection screen.")
|
||||
.font(.caption).foregroundStyle(.secondary).padding()
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.navigationTitle("Pair with comma")
|
||||
.toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }
|
||||
.task {
|
||||
guard DataScannerViewController.isSupported else {
|
||||
state.message = "Camera scanning isn’t supported on this device."; return
|
||||
}
|
||||
let granted = await AVCaptureDevice.requestAccess(for: .video)
|
||||
guard granted, DataScannerViewController.isAvailable else {
|
||||
state.message = "Allow camera access in iPhone Settings to scan the comma’s code."; return
|
||||
}
|
||||
state.ready = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct PairingCamera: UIViewControllerRepresentable {
|
||||
let onCode: (String) -> Bool
|
||||
let onError: (String) -> Void
|
||||
func makeCoordinator() -> Coordinator { Coordinator(onCode: onCode, onError: onError) }
|
||||
func makeUIViewController(context: Context) -> CameraHost {
|
||||
let scanner = DataScannerViewController(recognizedDataTypes: [.barcode(symbologies: [.qr])],
|
||||
qualityLevel: .accurate, recognizesMultipleItems: false,
|
||||
isHighFrameRateTrackingEnabled: false, isPinchToZoomEnabled: true,
|
||||
isGuidanceEnabled: true, isHighlightingEnabled: true)
|
||||
scanner.delegate = context.coordinator
|
||||
return CameraHost(scanner: scanner, coordinator: context.coordinator)
|
||||
}
|
||||
func updateUIViewController(_ host: CameraHost, context: Context) {}
|
||||
static func dismantleUIViewController(_ host: CameraHost, coordinator: Coordinator) {
|
||||
coordinator.finished = true
|
||||
host.scanner.stopScanning()
|
||||
host.scanner.delegate = nil
|
||||
}
|
||||
final class CameraHost: UIViewController {
|
||||
let scanner: DataScannerViewController
|
||||
let coordinator: Coordinator
|
||||
init(scanner: DataScannerViewController, coordinator: Coordinator) {
|
||||
self.scanner = scanner; self.coordinator = coordinator
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
addChild(scanner); view.addSubview(scanner.view)
|
||||
scanner.view.frame = view.bounds
|
||||
scanner.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
scanner.didMove(toParent: self)
|
||||
}
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
guard !coordinator.finished, !scanner.isScanning else { return }
|
||||
do { try scanner.startScanning() }
|
||||
catch { coordinator.onError("Could not start the camera. Check camera permission and try again.") }
|
||||
}
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
scanner.stopScanning()
|
||||
super.viewWillDisappear(animated)
|
||||
}
|
||||
}
|
||||
final class Coordinator: NSObject, DataScannerViewControllerDelegate {
|
||||
let onCode: (String) -> Bool
|
||||
let onError: (String) -> Void
|
||||
var finished = false
|
||||
init(onCode: @escaping (String) -> Bool, onError: @escaping (String) -> Void) {
|
||||
self.onCode = onCode; self.onError = onError
|
||||
}
|
||||
func accept(_ items: [RecognizedItem], scanner: DataScannerViewController) {
|
||||
guard !finished else { return }
|
||||
for item in items {
|
||||
if case .barcode(let code) = item, let text = code.payloadStringValue, onCode(text) {
|
||||
finished = true; scanner.stopScanning(); return
|
||||
}
|
||||
}
|
||||
}
|
||||
func dataScanner(_ scanner: DataScannerViewController, didAdd items: [RecognizedItem], allItems: [RecognizedItem]) {
|
||||
accept(items, scanner: scanner)
|
||||
}
|
||||
func dataScanner(_ scanner: DataScannerViewController, didTapOn item: RecognizedItem) { accept([item], scanner: scanner) }
|
||||
func dataScanner(_ scanner: DataScannerViewController, becameUnavailableWithError error: DataScannerViewController.ScanningUnavailable) {
|
||||
scanner.stopScanning()
|
||||
onError("Camera scanning became unavailable. Close this screen and try again.")
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,184 @@
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
/// A local-only HTTP client for the one configured comma endpoint.
|
||||
@MainActor
|
||||
final class PrivateLANHTTP {
|
||||
private let connection: NWConnection
|
||||
private let limit: Int
|
||||
private let head: Bool
|
||||
private var continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>?
|
||||
private var parser: LANHTTPParser
|
||||
private var timeout: Task<Void, Never>?
|
||||
private var finished = false
|
||||
private var sent = false
|
||||
private let request: URLRequest
|
||||
private init(_ request: URLRequest, limit: Int, host: String) {
|
||||
self.request = request; self.limit = limit; head = request.httpMethod == "HEAD"
|
||||
parser = LANHTTPParser(limit: limit, headOnly: request.httpMethod == "HEAD")
|
||||
connection = NWConnection(host: NWEndpoint.Host(host), port: 8082, using: .tcp)
|
||||
}
|
||||
static func load(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) {
|
||||
guard let url = request.url, url.scheme == "http", url.port == 8082, let host = url.host,
|
||||
url.user == nil, url.password == nil, url.fragment == nil,
|
||||
(try? LANTransport.endpoint(host)) != nil else { throw BridgeError.message("Invalid local comma endpoint.") }
|
||||
let client = PrivateLANHTTP(request, limit: limit, host: host)
|
||||
return try await withTaskCancellationHandler(operation: {
|
||||
try Task.checkCancellation()
|
||||
return try await withCheckedThrowingContinuation { client.start($0) }
|
||||
}, onCancel: { Task { @MainActor in client.finish(.failure(CancellationError())) } })
|
||||
}
|
||||
private func start(_ callback: CheckedContinuation<(Data, HTTPURLResponse), Error>) {
|
||||
guard !finished else { callback.resume(throwing: CancellationError()); return }
|
||||
continuation = callback
|
||||
let timeoutInterval = request.timeoutInterval
|
||||
timeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: UInt64(max(0.1, timeoutInterval) * 1_000_000_000))
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.finish(.failure(URLError(.timedOut)))
|
||||
}
|
||||
connection.stateUpdateHandler = { [weak self] state in
|
||||
Task { @MainActor in
|
||||
guard let self, !self.finished else { return }
|
||||
switch state {
|
||||
case .ready: self.send()
|
||||
case .failed: self.finish(.failure(URLError(.cannotConnectToHost)))
|
||||
case .cancelled: self.finish(.failure(URLError(.networkConnectionLost)))
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
connection.start(queue: .main)
|
||||
}
|
||||
private func send() {
|
||||
guard !sent else { return }
|
||||
sent = true
|
||||
guard let url = request.url, let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
|
||||
finish(.failure(BridgeError.message("Invalid local URL."))); return
|
||||
}
|
||||
let target = components.percentEncodedPath + (components.percentEncodedQuery.map { "?" + $0 } ?? "")
|
||||
let body = request.httpBody ?? Data()
|
||||
var text = "\(request.httpMethod ?? "GET") \(target) HTTP/1.1\r\nHost: \(url.host!):8082\r\nConnection: close\r\nAccept-Encoding: identity\r\nContent-Length: \(body.count)\r\n"
|
||||
for (name, value) in request.allHTTPHeaderFields ?? [:] where ["content-type", "accept", "cookie", "range", "x-companion-nonce", "x-companion-mac"].contains(name.lowercased()) {
|
||||
guard !value.contains("\r"), !value.contains("\n") else { finish(.failure(BridgeError.message("Invalid request header."))); return }
|
||||
text += "\(name): \(value)\r\n"
|
||||
}
|
||||
guard text.utf8.count <= 16_384 else { finish(.failure(BridgeError.message("HTTP headers are too large."))); return }
|
||||
text += "\r\n"
|
||||
connection.send(content: Data(text.utf8) + body, completion: .contentProcessed { [weak self] error in
|
||||
Task { @MainActor in
|
||||
guard let self, !self.finished else { return }
|
||||
if error != nil { self.finish(.failure(URLError(.networkConnectionLost))) }
|
||||
else { self.receive() }
|
||||
}
|
||||
})
|
||||
}
|
||||
private func receive() {
|
||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { [weak self] data, _, ended, error in
|
||||
Task { @MainActor in
|
||||
guard let self, !self.finished else { return }
|
||||
guard error == nil else { self.finish(.failure(URLError(.networkConnectionLost))); return }
|
||||
do {
|
||||
if let result = try self.parser.consume(data ?? Data(), ended: ended),
|
||||
let response = HTTPURLResponse(url: self.request.url!, statusCode: result.status, httpVersion: "HTTP/1.1", headerFields: result.headers) {
|
||||
self.finish(.success((result.body, response)))
|
||||
} else { self.receive() }
|
||||
} catch { self.finish(.failure(URLError(.cannotParseResponse))) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func finish(_ result: Result<(Data, HTTPURLResponse), Error>) {
|
||||
guard !finished else { return }
|
||||
finished = true; timeout?.cancel(); connection.stateUpdateHandler = nil; connection.cancel()
|
||||
let callback = continuation; continuation = nil
|
||||
callback?.resume(with: result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Incremental HTTP framing with strict bounds, including chunked responses.
|
||||
struct LANHTTPParser {
|
||||
let limit: Int
|
||||
let headOnly: Bool
|
||||
private var buffer = Data()
|
||||
private var body = Data()
|
||||
private var status: Int?
|
||||
private var headers: [String: String] = [:]
|
||||
private var length: Int?
|
||||
private var chunked = false
|
||||
private var chunkLength: Int?
|
||||
private var lastChunk = false
|
||||
private var overhead = 0
|
||||
init(limit: Int, headOnly: Bool) { self.limit = limit; self.headOnly = headOnly }
|
||||
mutating func consume(_ data: Data, ended: Bool) throws -> LocalResponse? {
|
||||
buffer.append(data)
|
||||
guard buffer.count + body.count <= limit + 16_388 else { throw URLError(.dataLengthExceedsMaximum) }
|
||||
if status == nil {
|
||||
guard let range = buffer.range(of: Data("\r\n\r\n".utf8)) else {
|
||||
guard buffer.count <= 16_384, !ended else { throw URLError(.cannotParseResponse) }; return nil
|
||||
}
|
||||
guard range.lowerBound <= 16_384, let text = String(data: buffer[..<range.lowerBound], encoding: .isoLatin1) else { throw URLError(.cannotParseResponse) }
|
||||
let lines = text.components(separatedBy: "\r\n")
|
||||
let first = (lines.first ?? "").split(separator: " ")
|
||||
guard first.count >= 2, ["HTTP/1.0", "HTTP/1.1"].contains(String(first[0])), let code = Int(first[1]), (200...599).contains(code) else { throw URLError(.cannotParseResponse) }
|
||||
status = code
|
||||
for line in lines.dropFirst() {
|
||||
guard let colon = line.firstIndex(of: ":"), colon != line.startIndex else { throw URLError(.cannotParseResponse) }
|
||||
let name = line[..<colon].lowercased()
|
||||
guard headers[name] == nil else { throw URLError(.cannotParseResponse) }
|
||||
headers[name] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
if let coding = headers["content-encoding"], coding.lowercased() != "identity" { throw URLError(.cannotDecodeContentData) }
|
||||
if let encoding = headers["transfer-encoding"] {
|
||||
guard encoding.lowercased() == "chunked", headers["content-length"] == nil else { throw URLError(.cannotParseResponse) }
|
||||
chunked = true
|
||||
}
|
||||
if let value = headers["content-length"] {
|
||||
guard let count = Int(value), (0...limit).contains(count) else { throw URLError(.dataLengthExceedsMaximum) }; length = count
|
||||
}
|
||||
buffer = Data(buffer[range.upperBound...])
|
||||
if headOnly || code == 204 || code == 304 { return result(Data()) }
|
||||
}
|
||||
if chunked {
|
||||
while true {
|
||||
if lastChunk {
|
||||
// Accept an empty trailer or bounded well-formed trailers.
|
||||
if buffer.starts(with: Data("\r\n".utf8)) {
|
||||
guard buffer.count == 2 else { throw URLError(.cannotParseResponse) }; return result(body)
|
||||
}
|
||||
if let range = buffer.range(of: Data("\r\n\r\n".utf8)) {
|
||||
guard range.upperBound == buffer.count, range.lowerBound <= 16_384,
|
||||
let trailers = String(data: buffer[..<range.lowerBound], encoding: .isoLatin1),
|
||||
trailers.components(separatedBy: "\r\n").allSatisfy({ $0.contains(":") }) else { throw URLError(.cannotParseResponse) }
|
||||
return result(body)
|
||||
}
|
||||
guard buffer.count <= 16_384 else { throw URLError(.cannotParseResponse) }; break
|
||||
}
|
||||
if chunkLength == nil {
|
||||
guard let range = buffer.range(of: Data("\r\n".utf8)) else {
|
||||
guard buffer.count <= 1024 else { throw URLError(.cannotParseResponse) }; break
|
||||
}
|
||||
guard range.lowerBound <= 1024, let line = String(data: buffer[..<range.lowerBound], encoding: .ascii),
|
||||
let token = line.split(separator: ";", omittingEmptySubsequences: false).first,
|
||||
!token.isEmpty, token.allSatisfy(\.isHexDigit), let count = Int(token, radix: 16), count <= limit - body.count else { throw URLError(.cannotParseResponse) }
|
||||
overhead += range.upperBound
|
||||
guard overhead <= 65_536 else { throw URLError(.cannotParseResponse) }
|
||||
buffer = Data(buffer[range.upperBound...]); chunkLength = count
|
||||
if count == 0 { lastChunk = true; continue }
|
||||
}
|
||||
let count = chunkLength!
|
||||
guard buffer.count >= count + 2 else { break }
|
||||
guard buffer.subdata(in: count..<count + 2) == Data("\r\n".utf8) else { throw URLError(.cannotParseResponse) }
|
||||
body.append(buffer.prefix(count)); buffer = Data(buffer.dropFirst(count + 2)); chunkLength = nil
|
||||
}
|
||||
} else if let length {
|
||||
guard buffer.count <= length else { throw URLError(.cannotParseResponse) }
|
||||
if buffer.count == length { return result(buffer) }
|
||||
} else {
|
||||
guard buffer.count <= limit else { throw URLError(.dataLengthExceedsMaximum) }
|
||||
if ended { return result(buffer) }
|
||||
}
|
||||
if ended { throw URLError(.cannotParseResponse) }
|
||||
return nil
|
||||
}
|
||||
private func result(_ body: Data) -> LocalResponse { LocalResponse(status: status!, headers: headers, body: body) }
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "StarPilotIcon.png",
|
||||
"idiom": "universal",
|
||||
"platform": "ios",
|
||||
"size": "1024x1024"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "Nate",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info": {
|
||||
"author": "Nate",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "StarPilot.png",
|
||||
"idiom": "universal"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "Nate",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 482 KiB |
+780
@@ -0,0 +1,780 @@
|
||||
.dashboard {
|
||||
--dashboard-accent: #8b6cc5;
|
||||
--dashboard-accent-2: #5ec8c8;
|
||||
--dashboard-border: rgba(139, 108, 197, 0.28);
|
||||
--dashboard-card: #0e1020;
|
||||
--dashboard-card-2: #111525;
|
||||
--dashboard-muted: #c4bfdc;
|
||||
--dashboard-strong: #faf8ff;
|
||||
--dashboard-track: rgba(139, 108, 197, 0.16);
|
||||
box-sizing: border-box;
|
||||
color: var(--dashboard-strong);
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin: 0 auto;
|
||||
max-width: 1280px;
|
||||
min-width: 0;
|
||||
padding: 2rem 2rem 3rem 0.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dashboard *,
|
||||
.dashboard *::before,
|
||||
.dashboard *::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.dashboard h1,
|
||||
.dashboard h2,
|
||||
.dashboard h3,
|
||||
.dashboard p {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.dashboard h1 {
|
||||
color: var(--dashboard-strong);
|
||||
font-size: 1.9rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.dashboard h2 {
|
||||
color: var(--dashboard-strong);
|
||||
font-size: 1.1rem;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.dashboard h3 {
|
||||
color: var(--dashboard-muted);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.dashboard-card {
|
||||
background: linear-gradient(180deg, var(--dashboard-card), var(--dashboard-card-2));
|
||||
border: 1px solid var(--dashboard-border);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
|
||||
color: var(--dashboard-strong);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
padding: 1.1rem;
|
||||
}
|
||||
|
||||
.dashboard-header {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-header p {
|
||||
align-items: center;
|
||||
color: var(--dashboard-muted);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font-size: 0.9rem;
|
||||
gap: 0.35rem;
|
||||
margin-top: 0.55rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-header strong,
|
||||
.dashboard-status-dot,
|
||||
.dashboard-card-kicker,
|
||||
.dashboard-drive-metrics strong:last-child,
|
||||
.dashboard-key-values strong,
|
||||
.dashboard-engaged-cell strong {
|
||||
color: var(--dashboard-accent);
|
||||
}
|
||||
|
||||
.dashboard-status-dot,
|
||||
.dashboard-card-kicker span,
|
||||
.dashboard-section-label span {
|
||||
background: var(--dashboard-accent);
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
flex: 0 0 auto;
|
||||
height: 0.5rem;
|
||||
width: 0.5rem;
|
||||
}
|
||||
|
||||
.dashboard-refresh {
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border: 1px solid var(--dashboard-border);
|
||||
border-radius: 8px;
|
||||
color: var(--dashboard-strong);
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
font: inherit;
|
||||
gap: 0.45rem;
|
||||
justify-content: center;
|
||||
min-height: 2.45rem;
|
||||
padding: 0 0.9rem;
|
||||
}
|
||||
|
||||
.dashboard-refresh:hover {
|
||||
background: rgba(139, 108, 197, 0.16);
|
||||
border-color: rgba(139, 108, 197, 0.42);
|
||||
}
|
||||
|
||||
.dashboard-analysis-status {
|
||||
align-items: center;
|
||||
background: rgba(139, 108, 197, 0.12);
|
||||
border: 1px solid var(--dashboard-border);
|
||||
border-radius: 8px;
|
||||
color: var(--dashboard-muted);
|
||||
display: inline-flex;
|
||||
font-size: 0.88rem;
|
||||
font-weight: var(--font-weight-bold);
|
||||
gap: 0.5rem;
|
||||
justify-self: start;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0.55rem 0.75rem;
|
||||
}
|
||||
|
||||
.dashboard-analysis-status i {
|
||||
color: var(--dashboard-accent-2);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.dashboard-analysis-status span {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-last-drive {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
.dashboard-card-kicker,
|
||||
.dashboard-section-label {
|
||||
align-items: center;
|
||||
color: var(--dashboard-muted);
|
||||
display: inline-flex;
|
||||
font-size: 0.86rem;
|
||||
font-weight: var(--font-weight-bold);
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.dashboard-card-kicker {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.65rem;
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.dashboard-drive-date,
|
||||
.dashboard-muted,
|
||||
.dashboard-empty,
|
||||
.dashboard-software-list span,
|
||||
.dashboard-key-values span,
|
||||
.dashboard-record-row p,
|
||||
.dashboard-record-row small,
|
||||
.dashboard-model-row small,
|
||||
.dashboard-drive-main span,
|
||||
.dashboard-drive-details,
|
||||
.dashboard-attention {
|
||||
color: var(--dashboard-muted);
|
||||
}
|
||||
|
||||
.dashboard-drive-metrics,
|
||||
.dashboard-stat-row,
|
||||
.dashboard-week-metrics {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.dashboard-stat-row {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.dashboard-drive-metrics div,
|
||||
.dashboard-stat-row div,
|
||||
.dashboard-week-metrics div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-drive-metrics strong,
|
||||
.dashboard-stat-row strong,
|
||||
.dashboard-week-metrics strong {
|
||||
color: var(--dashboard-strong);
|
||||
display: block;
|
||||
font-size: 1.18rem;
|
||||
line-height: 1.1;
|
||||
overflow-wrap: normal;
|
||||
word-break: keep-all;
|
||||
}
|
||||
|
||||
.dashboard-stat-row strong {
|
||||
font-size: 1.08rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-metrics span,
|
||||
.dashboard-stat-row span,
|
||||
.dashboard-week-metrics span {
|
||||
color: var(--dashboard-muted);
|
||||
display: block;
|
||||
font-size: 0.82rem;
|
||||
margin-top: 0.28rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.55rem 1rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-drive-footer span {
|
||||
align-items: center;
|
||||
color: var(--dashboard-muted);
|
||||
display: inline-flex;
|
||||
font-size: 0.85rem;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-section-label {
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
|
||||
.dashboard-summary-grid,
|
||||
.dashboard-device-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.dashboard-device-grid {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr);
|
||||
}
|
||||
|
||||
.dashboard-summary-card h2 {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-two-column {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: minmax(0, 1.4fr) minmax(320px, 1fr);
|
||||
}
|
||||
|
||||
.dashboard-model-storage {
|
||||
grid-template-columns: minmax(320px, 1fr) minmax(0, 1.4fr);
|
||||
}
|
||||
|
||||
.dashboard-week {
|
||||
display: grid;
|
||||
gap: 1.2rem;
|
||||
}
|
||||
|
||||
.dashboard-week-top,
|
||||
.dashboard-model-layout {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: 1.4rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-donut,
|
||||
.dashboard-favorite-donut {
|
||||
align-items: center;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
flex: 0 0 auto;
|
||||
justify-items: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.dashboard-donut {
|
||||
--value: 0;
|
||||
background: conic-gradient(var(--dashboard-accent) calc(var(--value) * 1%), var(--dashboard-track) 0);
|
||||
flex-basis: 116px;
|
||||
height: 116px;
|
||||
max-height: 116px;
|
||||
max-width: 116px;
|
||||
min-height: 116px;
|
||||
min-width: 116px;
|
||||
width: 116px;
|
||||
}
|
||||
|
||||
.dashboard-donut::after,
|
||||
.dashboard-favorite-donut::after {
|
||||
background: var(--dashboard-card);
|
||||
border-radius: 50%;
|
||||
content: "";
|
||||
inset: 10px;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.dashboard-donut strong,
|
||||
.dashboard-donut span {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.dashboard-donut strong {
|
||||
color: var(--dashboard-strong);
|
||||
font-size: 1.45rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.dashboard-donut span {
|
||||
color: var(--dashboard-muted);
|
||||
font-size: 0.68rem;
|
||||
}
|
||||
|
||||
.dashboard-week-metrics {
|
||||
flex: 1 1 auto;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.dashboard-bars {
|
||||
align-items: end;
|
||||
display: grid;
|
||||
gap: 0.7rem;
|
||||
grid-template-columns: repeat(7, minmax(0, 1fr));
|
||||
height: 120px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-day {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
grid-template-rows: 1fr auto;
|
||||
height: 100%;
|
||||
justify-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-day-bar {
|
||||
align-self: end;
|
||||
background: linear-gradient(180deg, var(--dashboard-accent), var(--dashboard-accent-2));
|
||||
border-radius: 4px 4px 0 0;
|
||||
min-height: 4px;
|
||||
width: min(100%, 54px);
|
||||
}
|
||||
|
||||
.dashboard-day span {
|
||||
color: var(--dashboard-muted);
|
||||
font-size: 0.74rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-records {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.dashboard-records h2 {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-record-row {
|
||||
align-items: center;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
min-width: 0;
|
||||
padding: 0.85rem 0;
|
||||
}
|
||||
|
||||
.dashboard-record-row:first-of-type {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.dashboard-record-row > span {
|
||||
align-items: center;
|
||||
background: rgba(139, 108, 197, 0.16);
|
||||
border-radius: 8px;
|
||||
color: var(--dashboard-accent);
|
||||
display: inline-flex;
|
||||
height: 2.1rem;
|
||||
justify-content: center;
|
||||
width: 2.1rem;
|
||||
}
|
||||
|
||||
.dashboard-record-row strong {
|
||||
color: var(--dashboard-strong);
|
||||
display: inline;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-record-row small {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-recent {
|
||||
padding-bottom: 0.65rem;
|
||||
}
|
||||
|
||||
.dashboard-recent h2 {
|
||||
margin-bottom: 0.85rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-row {
|
||||
align-items: center;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: minmax(170px, 1.35fr) minmax(150px, 0.75fr) minmax(190px, 1fr) minmax(170px, 0.85fr) auto;
|
||||
min-width: 0;
|
||||
padding: 0.9rem 0;
|
||||
}
|
||||
|
||||
.dashboard-drive-row:first-of-type {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.dashboard-drive-row.is-pending {
|
||||
color: var(--dashboard-muted);
|
||||
}
|
||||
|
||||
.dashboard-drive-row.is-ignored {
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.dashboard-drive-main,
|
||||
.dashboard-drive-details,
|
||||
.dashboard-attention,
|
||||
.dashboard-engaged-cell,
|
||||
.dashboard-drive-actions {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-drive-main strong,
|
||||
.dashboard-drive-main span {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dashboard-drive-main strong {
|
||||
color: var(--dashboard-strong);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-main span {
|
||||
font-size: 0.82rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-details,
|
||||
.dashboard-attention {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font-size: 0.82rem;
|
||||
gap: 0.45rem 0.8rem;
|
||||
}
|
||||
|
||||
.dashboard-engaged-cell {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
gap: 0.55rem;
|
||||
grid-template-columns: 1fr auto;
|
||||
}
|
||||
|
||||
.dashboard-drive-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.dashboard-drive-stats-action {
|
||||
align-items: center;
|
||||
background: transparent;
|
||||
border: 1px solid var(--dashboard-border);
|
||||
border-radius: 6px;
|
||||
color: var(--dashboard-muted);
|
||||
display: inline-flex;
|
||||
font-size: 0.78rem;
|
||||
gap: 0.4rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dashboard-drive-stats-action:hover {
|
||||
border-color: var(--dashboard-accent);
|
||||
color: var(--dashboard-strong);
|
||||
}
|
||||
|
||||
.dashboard-drive-stats-action:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.dashboard-mini-bar,
|
||||
.dashboard-storage-track {
|
||||
background: var(--dashboard-track);
|
||||
border-radius: 999px;
|
||||
height: 0.45rem;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dashboard-mini-bar span,
|
||||
.dashboard-storage-track span {
|
||||
background: linear-gradient(90deg, var(--dashboard-accent), var(--dashboard-accent-2));
|
||||
border-radius: inherit;
|
||||
display: block;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.dashboard-model-layout {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.dashboard-favorite-donut {
|
||||
background: conic-gradient(var(--dashboard-track) 0 100%);
|
||||
flex-basis: 132px;
|
||||
height: 132px;
|
||||
max-height: 132px;
|
||||
max-width: 132px;
|
||||
min-height: 132px;
|
||||
min-width: 132px;
|
||||
width: 132px;
|
||||
}
|
||||
|
||||
.dashboard-model-list {
|
||||
display: grid;
|
||||
flex: 1 1 auto;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-model-row {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
gap: 0.55rem;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-model-row strong,
|
||||
.dashboard-model-row small {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dashboard-swatch {
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
height: 0.7rem;
|
||||
width: 0.7rem;
|
||||
}
|
||||
|
||||
.dashboard-device-card {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-storage-track {
|
||||
border-radius: 4px;
|
||||
height: 0.72rem;
|
||||
}
|
||||
|
||||
.dashboard-key-values,
|
||||
.dashboard-software-list {
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.dashboard-key-values div,
|
||||
.dashboard-software-list div {
|
||||
align-items: center;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
min-width: 0;
|
||||
padding: 0.85rem 0;
|
||||
}
|
||||
|
||||
.dashboard-key-values div:first-child,
|
||||
.dashboard-software-list div:first-child {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.dashboard-key-values strong,
|
||||
.dashboard-software-list strong {
|
||||
color: var(--dashboard-strong);
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.dashboard-software-list {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0 1.4rem;
|
||||
}
|
||||
|
||||
.dashboard-software-list div {
|
||||
align-items: start;
|
||||
gap: 0.35rem;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.dashboard-software-list strong {
|
||||
overflow-wrap: anywhere;
|
||||
text-align: left;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.dashboard-software-list a {
|
||||
color: inherit;
|
||||
text-decoration-color: rgba(139, 108, 197, 0.65);
|
||||
text-underline-offset: 0.16em;
|
||||
}
|
||||
|
||||
.dashboard-software-list a:hover {
|
||||
color: var(--dashboard-accent-2);
|
||||
}
|
||||
|
||||
.dashboard-empty,
|
||||
.dashboard-loading,
|
||||
.dashboard-error {
|
||||
color: var(--dashboard-muted);
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.dashboard-error {
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
.dashboard-narrow {
|
||||
max-width: 780px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 1180px) {
|
||||
.dashboard {
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-row {
|
||||
grid-template-columns: minmax(170px, 1fr) minmax(210px, 1fr);
|
||||
}
|
||||
|
||||
.dashboard-drive-actions {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 900px) {
|
||||
.dashboard-summary-grid,
|
||||
.dashboard-two-column,
|
||||
.dashboard-model-storage,
|
||||
.dashboard-device-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.dashboard-summary-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) {
|
||||
.dashboard {
|
||||
gap: 0.85rem;
|
||||
padding: 1.25rem 0 2rem;
|
||||
}
|
||||
|
||||
.dashboard-header {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.dashboard h1 {
|
||||
font-size: 1.55rem;
|
||||
}
|
||||
|
||||
.dashboard-card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-summary-grid,
|
||||
.dashboard-drive-metrics,
|
||||
.dashboard-stat-row {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.dashboard-drive-row {
|
||||
align-items: stretch;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 8px;
|
||||
grid-template-columns: 1fr;
|
||||
margin-bottom: 0.65rem;
|
||||
padding: 0.85rem;
|
||||
}
|
||||
|
||||
.dashboard-drive-row:first-of-type {
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.dashboard-drive-main strong,
|
||||
.dashboard-drive-main span {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.dashboard-drive-stats-action {
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 560px) {
|
||||
.dashboard-header,
|
||||
.dashboard-week-top,
|
||||
.dashboard-model-layout {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dashboard-donut,
|
||||
.dashboard-favorite-donut {
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.dashboard-refresh {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dashboard-drive-metrics,
|
||||
.dashboard-stat-row,
|
||||
.dashboard-week-metrics,
|
||||
.dashboard-summary-grid,
|
||||
.dashboard-software-list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.dashboard-bars {
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.dashboard-day-bar {
|
||||
width: min(100%, 36px);
|
||||
}
|
||||
|
||||
.dashboard-key-values div,
|
||||
.dashboard-software-list div,
|
||||
.dashboard-engaged-cell {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.dashboard-key-values strong,
|
||||
.dashboard-software-list strong {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
import { html } from "/assets/vendor/arrow-core.js";
|
||||
|
||||
const HOME_STATE = {
|
||||
status: "loading",
|
||||
data: null,
|
||||
unit: "miles",
|
||||
error: "",
|
||||
initialized: false,
|
||||
refreshTimer: null,
|
||||
};
|
||||
|
||||
const FAVORITE_COLORS = ["#5ec8c8", "#8b6cc5", "#d4a060", "#e05577", "#6cc56e", "#8aa3ff"];
|
||||
const TOP_MODEL_LIMIT = 3;
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timerId = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
||||
promise.then((value) => {
|
||||
clearTimeout(timerId);
|
||||
resolve(value);
|
||||
}).catch((err) => {
|
||||
clearTimeout(timerId);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? "")
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function safeUrl(value) {
|
||||
const text = String(value ?? "").trim();
|
||||
return text.startsWith("https://github.com/") ? text : "";
|
||||
}
|
||||
|
||||
function numberValue(value, fallback = 0) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
function formatInt(value) {
|
||||
return Math.round(numberValue(value)).toLocaleString("en-US", { maximumFractionDigits: 0 });
|
||||
}
|
||||
|
||||
function formatOneDecimal(value) {
|
||||
return numberValue(value).toLocaleString("en-US", { maximumFractionDigits: 1 });
|
||||
}
|
||||
|
||||
function formatPercent(value) {
|
||||
return `${Math.max(0, Math.min(100, Math.round(numberValue(value))))}%`;
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
const total = Math.max(0, Math.round(numberValue(seconds)));
|
||||
const hours = Math.floor(total / 3600);
|
||||
const minutes = Math.floor((total % 3600) / 60);
|
||||
if (hours > 0) return `${hours}h ${minutes}m`;
|
||||
return `${minutes}m`;
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return "No drives yet";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return String(value);
|
||||
return date.toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function formatDriveTimeRange(startValue, endValue) {
|
||||
if (!startValue) return "No drives yet";
|
||||
const start = new Date(startValue);
|
||||
const end = new Date(endValue);
|
||||
if (Number.isNaN(start.getTime())) return String(startValue);
|
||||
if (Number.isNaN(end.getTime()) || end <= start) return formatDate(startValue);
|
||||
|
||||
const dateLabel = start.toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
||||
const startTime = start.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
|
||||
const endTime = end.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
|
||||
if (start.toDateString() === end.toDateString()) {
|
||||
return `${dateLabel}, ${startTime}-${endTime}`;
|
||||
}
|
||||
|
||||
const endDateLabel = end.toLocaleDateString("en-US", { month: "short", day: "numeric" });
|
||||
return `${dateLabel}, ${startTime}-${endDateLabel}, ${endTime}`;
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const value = Math.max(0, numberValue(bytes));
|
||||
if (value >= 2 ** 30) return `${formatOneDecimal(value / (2 ** 30))} GB`;
|
||||
if (value >= 2 ** 20) return `${formatOneDecimal(value / (2 ** 20))} MB`;
|
||||
return `${formatInt(value / 1024)} KB`;
|
||||
}
|
||||
|
||||
function statBlock(title, stats = {}, unit) {
|
||||
return `
|
||||
<section class="dashboard-card dashboard-summary-card">
|
||||
<h2>${escapeHtml(title)}</h2>
|
||||
<div class="dashboard-stat-row">
|
||||
<div><strong>${formatInt(stats.drives)}</strong><span>drives</span></div>
|
||||
<div><strong>${formatOneDecimal(stats.distance)}</strong><span>${escapeHtml(stats.unit || unit)}</span></div>
|
||||
<div><strong>${formatOneDecimal(stats.hours)}</strong><span>hours</span></div>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function fallbackDashboard(data, unit) {
|
||||
const disk = Array.isArray(data?.diskUsage) ? data.diskUsage[0] : {};
|
||||
const usedText = String(disk?.used || "0 GB");
|
||||
const sizeText = String(disk?.size || "0 GB");
|
||||
return {
|
||||
lastDrive: {
|
||||
date: "",
|
||||
distance: 0,
|
||||
duration: 0,
|
||||
avgSpeed: 0,
|
||||
engagedPercent: 0,
|
||||
model: "Unknown model",
|
||||
segmentCount: 0,
|
||||
distractedMoments: 0,
|
||||
unresponsiveMoments: 0,
|
||||
attentionKnown: true,
|
||||
distanceUnit: unit,
|
||||
speedUnit: unit === "kilometers" ? "kph" : "mph",
|
||||
},
|
||||
recentDrives: [],
|
||||
week: {
|
||||
distance: 0,
|
||||
duration: 0,
|
||||
hours: 0,
|
||||
drives: 0,
|
||||
engagedPercent: 0,
|
||||
dailyDistance: [],
|
||||
distanceUnit: unit,
|
||||
},
|
||||
records: {
|
||||
longestDrive: { value: "0", detail: unit },
|
||||
mostEngagedDay: { value: "0%", detail: "No drives" },
|
||||
bestWeek: { value: "0", detail: unit },
|
||||
highestStreak: { value: "0 days", detail: "No drives" },
|
||||
longestUndistractedDrive: { value: "0.0 hours", detail: "No clean drives" },
|
||||
cleanDriveStreak: { value: "0 drives", detail: "No clean drives" },
|
||||
},
|
||||
device: { status: "Parked", online: true, uptimeSeconds: null, cpuTempC: null, gpuTempC: null },
|
||||
storage: {
|
||||
freeBytes: 0,
|
||||
usedBytes: 0,
|
||||
totalBytes: 0,
|
||||
usedPercent: Number.parseFloat(disk?.usedPercentage) || 0,
|
||||
legacyText: `${usedText} used of ${sizeText}`,
|
||||
segmentCounts: { standard: 0, highResolution: 0, alternate: 0 },
|
||||
},
|
||||
favoriteModels: [],
|
||||
};
|
||||
}
|
||||
|
||||
function driveStatsReady(drive) {
|
||||
return drive?.ignored === true || drive?.attentionKnown !== false;
|
||||
}
|
||||
|
||||
function dashboardPendingDriveCount(dashboard) {
|
||||
const recent = Array.isArray(dashboard?.recentDrives) ? dashboard.recentDrives : [];
|
||||
return recent.filter(drive => !driveStatsReady(drive)).length;
|
||||
}
|
||||
|
||||
function dashboardShouldAutoRefresh(dashboard) {
|
||||
const analysis = dashboard?.analysis || {};
|
||||
return Boolean(analysis.running)
|
||||
|| numberValue(analysis.pendingRoutes) > 0
|
||||
|| dashboardPendingDriveCount(dashboard) > 0;
|
||||
}
|
||||
|
||||
function clearDashboardRefreshTimer() {
|
||||
if (HOME_STATE.refreshTimer) {
|
||||
clearTimeout(HOME_STATE.refreshTimer);
|
||||
HOME_STATE.refreshTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleDashboardRefresh(dashboard) {
|
||||
clearDashboardRefreshTimer();
|
||||
if (!dashboardShouldAutoRefresh(dashboard)) return;
|
||||
HOME_STATE.refreshTimer = setTimeout(() => initializeHome(false), 3500);
|
||||
}
|
||||
|
||||
function renderAnalysisStatus(dashboard) {
|
||||
const analysis = dashboard?.analysis || {};
|
||||
const pendingRoutes = Math.max(0, Math.round(numberValue(analysis.pendingRoutes)));
|
||||
const pendingDrives = dashboardPendingDriveCount(dashboard);
|
||||
const count = Math.max(pendingRoutes, pendingDrives);
|
||||
if (!analysis.running && count <= 0) return "";
|
||||
|
||||
const runningCount = count || Math.max(1, Math.round(numberValue(analysis.batchSize)));
|
||||
const label = analysis.running
|
||||
? `Analyzing ${runningCount} ${runningCount === 1 ? "drive" : "drives"}`
|
||||
: `${count} ${count === 1 ? "drive" : "drives"} queued`;
|
||||
|
||||
return `
|
||||
<div class="dashboard-analysis-status">
|
||||
<i class="bi bi-hourglass-split"></i>
|
||||
<span>${escapeHtml(label)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderLastDrive(drive) {
|
||||
const ready = driveStatsReady(drive);
|
||||
return `
|
||||
<section class="dashboard-card dashboard-last-drive">
|
||||
<div class="dashboard-card-kicker"><span></span>Last drive</div>
|
||||
<div class="dashboard-drive-date">${escapeHtml(formatDriveTimeRange(drive.date, drive.endDate))}</div>
|
||||
<div class="dashboard-drive-metrics">
|
||||
<div><strong>${ready ? formatOneDecimal(drive.distance) : "..."}</strong><span>${ready ? escapeHtml(drive.distanceUnit || "miles") : "analyzing"}</span></div>
|
||||
<div><strong>${formatDuration(drive.duration)}</strong><span>duration</span></div>
|
||||
<div><strong>${ready ? formatInt(drive.avgSpeed) : "..."}</strong><span>${ready ? `${escapeHtml(drive.speedUnit || "mph")} avg` : "speed"}</span></div>
|
||||
<div><strong>${ready ? formatPercent(drive.engagedPercent) : "..."}</strong><span>engaged</span></div>
|
||||
</div>
|
||||
<div class="dashboard-drive-footer">
|
||||
<span><i class="bi bi-cpu"></i>${escapeHtml(drive.model || "Unknown model")}</span>
|
||||
${ready
|
||||
? `<span><i class="bi bi-eye"></i>${formatInt(drive.distractedMoments)} distracted</span>
|
||||
<span><i class="bi bi-exclamation-triangle"></i>${formatInt(drive.unresponsiveMoments)} unresponsive</span>`
|
||||
: `<span><i class="bi bi-hourglass-split"></i>Analyzing stats</span>`}
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderWeekChart(week) {
|
||||
const days = Array.isArray(week.dailyDistance) && week.dailyDistance.length
|
||||
? week.dailyDistance
|
||||
: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map(label => ({ label, distance: 0 }));
|
||||
const maxDistance = Math.max(1, ...days.map(day => numberValue(day.distance)));
|
||||
const bars = days.map(day => {
|
||||
const height = Math.max(4, (numberValue(day.distance) / maxDistance) * 100);
|
||||
return `
|
||||
<div class="dashboard-day">
|
||||
<div class="dashboard-day-bar" style="height:${height}%"></div>
|
||||
<span>${escapeHtml(day.label)}</span>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
return `
|
||||
<section class="dashboard-card dashboard-week">
|
||||
<h2>This week</h2>
|
||||
<div class="dashboard-week-top">
|
||||
<div class="dashboard-donut" style="--value:${Math.max(0, Math.min(100, numberValue(week.engagedPercent)))}">
|
||||
<strong>${formatPercent(week.engagedPercent)}</strong>
|
||||
<span>engaged</span>
|
||||
</div>
|
||||
<div class="dashboard-week-metrics">
|
||||
<div><strong>${formatOneDecimal(week.distance)}</strong><span>${escapeHtml(week.distanceUnit || "miles")}</span></div>
|
||||
<div><strong>${formatOneDecimal(week.hours)}</strong><span>hours</span></div>
|
||||
<div><strong>${formatInt(week.drives)}</strong><span>drives</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<h3>Distance per day</h3>
|
||||
<div class="dashboard-bars">${bars}</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function recordRow(icon, title, record) {
|
||||
return `
|
||||
<div class="dashboard-record-row">
|
||||
<span><i class="bi ${icon}"></i></span>
|
||||
<div>
|
||||
<p>${escapeHtml(title)}</p>
|
||||
<strong>${escapeHtml(record?.value ?? "0")}</strong>
|
||||
<small>${escapeHtml(record?.detail ?? "")}</small>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderRecords(records) {
|
||||
return `
|
||||
<section class="dashboard-card dashboard-records">
|
||||
<h2>Personal records</h2>
|
||||
${recordRow("bi-arrow-right", "Longest drive", records.longestDrive)}
|
||||
${recordRow("bi-check2-circle", "Most-engaged day", records.mostEngagedDay)}
|
||||
${recordRow("bi-graph-up-arrow", "Best week", records.bestWeek)}
|
||||
${recordRow("bi-lightning-charge", "Highest streak", records.highestStreak)}
|
||||
${recordRow("bi-shield-check", "Longest undistracted drive", records.longestUndistractedDrive)}
|
||||
${recordRow("bi-stars", "Clean-drive streak", records.cleanDriveStreak)}
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderRecentDrives(drives) {
|
||||
if (!Array.isArray(drives) || drives.length === 0) {
|
||||
return `
|
||||
<section class="dashboard-card dashboard-recent">
|
||||
<h2>Recent drives</h2>
|
||||
<div class="dashboard-empty">No local drives found yet.</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
const rows = drives.map(drive => {
|
||||
const ignored = drive?.ignored === true;
|
||||
const ready = driveStatsReady(drive);
|
||||
const routeNames = Array.isArray(drive?.routeNames) ? drive.routeNames.filter(Boolean) : [];
|
||||
return `
|
||||
<div class="dashboard-drive-row ${ready ? "" : "is-pending"} ${ignored ? "is-ignored" : ""}">
|
||||
<div class="dashboard-drive-main">
|
||||
<strong>${escapeHtml(formatDriveTimeRange(drive.date, drive.endDate))}</strong>
|
||||
<span>${escapeHtml(drive.model || "Unknown model")}</span>
|
||||
</div>
|
||||
<div class="dashboard-drive-details">
|
||||
<span>${ignored && drive.attentionKnown === false ? "Stats excluded" : (ready ? `${formatOneDecimal(drive.distance)} ${escapeHtml(drive.distanceUnit || "miles")}` : "Analyzing stats")}</span>
|
||||
<span>${formatDuration(drive.duration)}</span>
|
||||
</div>
|
||||
<div class="dashboard-attention">
|
||||
${ignored
|
||||
? `<span><i class="bi bi-eye-slash"></i> Ignored from stats</span>`
|
||||
: ready
|
||||
? `<span>${formatInt(drive.distractedMoments)} distracted</span><span>${formatInt(drive.unresponsiveMoments)} unresponsive</span>`
|
||||
: `<span>Waiting for full route analysis</span>`}
|
||||
</div>
|
||||
<div class="dashboard-engaged-cell">
|
||||
<div class="dashboard-mini-bar"><span style="width:${ready && !ignored ? Math.max(0, Math.min(100, numberValue(drive.engagedPercent))) : 0}%"></span></div>
|
||||
<strong>${ignored ? "Excluded" : (ready ? `${formatPercent(drive.engagedPercent)} engaged` : "Pending")}</strong>
|
||||
</div>
|
||||
${routeNames.length === 0 ? "" : `
|
||||
<div class="dashboard-drive-actions">
|
||||
<button
|
||||
class="dashboard-drive-stats-action"
|
||||
data-action="${ignored ? "include" : "ignore"}"
|
||||
data-route-names="${escapeHtml(JSON.stringify(routeNames))}"
|
||||
title="${ignored ? "Include this drive in local dashboard statistics" : "Exclude this drive from local dashboard statistics"}">
|
||||
<i class="bi ${ignored ? "bi-arrow-counterclockwise" : "bi-eye-slash"}"></i>
|
||||
<span>${ignored ? "Include drive stats" : "Ignore drive stats"}</span>
|
||||
</button>
|
||||
</div>
|
||||
`}
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
return `
|
||||
<section class="dashboard-card dashboard-recent">
|
||||
<h2>Recent drives</h2>
|
||||
${rows}
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function favoriteChart(models) {
|
||||
if (!Array.isArray(models) || models.length === 0) {
|
||||
return {
|
||||
style: "background: conic-gradient(var(--dashboard-track) 0 100%)",
|
||||
rows: `<div class="dashboard-empty">No model usage recorded yet.</div>`,
|
||||
};
|
||||
}
|
||||
|
||||
const topModels = models.slice(0, TOP_MODEL_LIMIT);
|
||||
const total = topModels.reduce((sum, model) => sum + Math.max(1, numberValue(model.weight)), 0);
|
||||
let start = 0;
|
||||
const segments = topModels.map((model, index) => {
|
||||
const end = start + (Math.max(1, numberValue(model.weight)) / total) * 100;
|
||||
const segment = `${FAVORITE_COLORS[index]} ${start}% ${end}%`;
|
||||
start = end;
|
||||
return segment;
|
||||
});
|
||||
|
||||
const rows = topModels.map((model, index) => `
|
||||
<div class="dashboard-model-row">
|
||||
<span class="dashboard-swatch" style="background:${FAVORITE_COLORS[index]}"></span>
|
||||
<div>
|
||||
<strong>${escapeHtml(model.name)}</strong>
|
||||
<small>${formatInt(model.drives)} ${numberValue(model.drives) === 1 ? "drive" : "drives"} using this model</small>
|
||||
</div>
|
||||
</div>
|
||||
`).join("");
|
||||
|
||||
return {
|
||||
style: `background: conic-gradient(${segments.join(", ")})`,
|
||||
rows,
|
||||
};
|
||||
}
|
||||
|
||||
function renderFavoriteModels(models) {
|
||||
const chart = favoriteChart(models);
|
||||
return `
|
||||
<section class="dashboard-card dashboard-models">
|
||||
<h2>Most used models</h2>
|
||||
<div class="dashboard-model-layout">
|
||||
<div class="dashboard-favorite-donut" style="${chart.style}"></div>
|
||||
<div class="dashboard-model-list">${chart.rows}</div>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderStorage(storage) {
|
||||
const usedPercent = Math.max(0, Math.min(100, numberValue(storage.usedPercent)));
|
||||
const counts = storage.segmentCounts || {};
|
||||
const summary = storage.legacyText || `${formatBytes(storage.usedBytes)} used of ${formatBytes(storage.totalBytes)}`;
|
||||
return `
|
||||
<section class="dashboard-card dashboard-device-card">
|
||||
<h2>Storage</h2>
|
||||
<p class="dashboard-muted">${escapeHtml(summary)}</p>
|
||||
<div class="dashboard-storage-track"><span style="width:${usedPercent}%"></span></div>
|
||||
<div class="dashboard-key-values">
|
||||
<div><span>Dashcam footage</span><strong>${formatInt(counts.standard)} segments</strong></div>
|
||||
<div><span>High-resolution footage</span><strong>${formatInt(counts.highResolution)} segments</strong></div>
|
||||
<div><span>Konik footage</span><strong>${formatInt(counts.alternate)} segments</strong></div>
|
||||
<div><span>Free space</span><strong>${formatBytes(storage.freeBytes)}</strong></div>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderVitals(device) {
|
||||
const uptime = device.uptimeSeconds == null ? "unknown" : formatDuration(device.uptimeSeconds);
|
||||
const cpu = device.cpuTempC == null ? "unknown" : `${formatInt(device.cpuTempC)} C`;
|
||||
const gpu = device.gpuTempC == null ? "unknown" : `${formatInt(device.gpuTempC)} C`;
|
||||
const lanIp = device.lanIp || "unknown";
|
||||
const networkName = device.networkName || "No wireless connectivity";
|
||||
return `
|
||||
<section class="dashboard-card dashboard-device-card">
|
||||
<h2>Vitals</h2>
|
||||
<div class="dashboard-key-values">
|
||||
<div><span>Status</span><strong>${escapeHtml(device.status || "Parked")}</strong></div>
|
||||
<div><span>LAN IP</span><strong>${escapeHtml(lanIp)}</strong></div>
|
||||
<div><span>Network</span><strong>${escapeHtml(networkName)}</strong></div>
|
||||
<div><span>Uptime</span><strong>${escapeHtml(uptime)}</strong></div>
|
||||
<div><span>CPU temp</span><strong>${escapeHtml(cpu)}</strong></div>
|
||||
<div><span>GPU temp</span><strong>${escapeHtml(gpu)}</strong></div>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderSoftware(info = {}) {
|
||||
const changelogUrl = safeUrl(info.changelogUrl);
|
||||
const commitUrl = safeUrl(info.commitUrl);
|
||||
const commitHref = changelogUrl || commitUrl;
|
||||
const fields = [
|
||||
{ label: "Branch", value: info.branchName },
|
||||
{ label: "Build", value: info.buildEnvironment },
|
||||
{ label: "Commit", value: info.commitHash, href: commitHref },
|
||||
{ label: "Version date", value: info.versionDate },
|
||||
{ label: "Fork maintainer", value: info.forkMaintainer },
|
||||
{ label: "Update available", value: info.updateAvailable },
|
||||
];
|
||||
|
||||
return `
|
||||
<section class="dashboard-card dashboard-device-card">
|
||||
<h2>Software</h2>
|
||||
<div class="dashboard-software-list">
|
||||
${fields.map((field) => `
|
||||
<div>
|
||||
<span>${escapeHtml(field.label)}</span>
|
||||
<strong>${field.href ? `<a href="${escapeHtml(field.href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(field.value ?? "unknown")}</a>` : escapeHtml(field.value ?? "unknown")}</strong>
|
||||
</div>
|
||||
`).join("")}
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
function bindDashboardActions() {
|
||||
const refreshButton = document.getElementById("dashboard_refresh");
|
||||
if (refreshButton) {
|
||||
refreshButton.onclick = () => initializeHome(true);
|
||||
}
|
||||
|
||||
document.querySelectorAll(".dashboard-drive-stats-action").forEach((button) => {
|
||||
button.onclick = async () => {
|
||||
let routeNames = [];
|
||||
try {
|
||||
routeNames = JSON.parse(button.dataset.routeNames || "[]");
|
||||
} catch {
|
||||
routeNames = [];
|
||||
}
|
||||
if (!Array.isArray(routeNames) || routeNames.length === 0) return;
|
||||
|
||||
const action = button.dataset.action === "include" ? "include" : "ignore";
|
||||
const confirmed = action === "include" || window.confirm(
|
||||
"Ignore this drive's statistics?\n\n" +
|
||||
"It will no longer affect local weekly totals, records, model usage, engagement, or attention streaks."
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
button.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/api/stats/${action}_drive`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ routeNames }),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || `Unable to ${action} drive statistics.`);
|
||||
await initializeHome(false);
|
||||
} catch (error) {
|
||||
window.alert(error?.message || `Unable to ${action} drive statistics.`);
|
||||
button.disabled = false;
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function renderDashboard(state) {
|
||||
const shell = document.getElementById("home_shell");
|
||||
if (!shell) return;
|
||||
|
||||
if (state.status === "error") {
|
||||
clearDashboardRefreshTimer();
|
||||
shell.innerHTML = `
|
||||
<div class="dashboard dashboard-narrow">
|
||||
<div class="dashboard-error">Failed to load dashboard: ${escapeHtml(state.error)}</div>
|
||||
<button id="dashboard_refresh" class="dashboard-refresh"><i class="bi bi-arrow-clockwise"></i>Refresh</button>
|
||||
</div>
|
||||
`;
|
||||
bindDashboardActions();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status !== "ready" || !state.data) {
|
||||
shell.innerHTML = `
|
||||
<div class="dashboard dashboard-narrow">
|
||||
<div class="dashboard-loading">Loading dashboard...</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const data = state.data || {};
|
||||
const dashboard = data.dashboard || fallbackDashboard(data, state.unit);
|
||||
const driveStats = data.driveStats || {};
|
||||
const device = dashboard.device || {};
|
||||
const status = device.status || "Parked";
|
||||
const onlineText = device.online === false ? "device offline" : "device online";
|
||||
|
||||
shell.innerHTML = `
|
||||
<main class="dashboard">
|
||||
<header class="dashboard-header">
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<p><span class="dashboard-status-dot"></span><strong>${escapeHtml(status)}</strong> - ${escapeHtml(onlineText)}</p>
|
||||
</div>
|
||||
<button id="dashboard_refresh" class="dashboard-refresh"><i class="bi bi-arrow-clockwise"></i>Refresh</button>
|
||||
</header>
|
||||
|
||||
${renderLastDrive(dashboard.lastDrive || fallbackDashboard(data, state.unit).lastDrive)}
|
||||
${renderAnalysisStatus(dashboard)}
|
||||
|
||||
<div class="dashboard-section-label"><span></span>Your driving</div>
|
||||
<div class="dashboard-summary-grid">
|
||||
${statBlock("All time", driveStats.all, state.unit)}
|
||||
${statBlock("Past week", driveStats.week, state.unit)}
|
||||
${statBlock("StarPilot", driveStats.starpilot, state.unit)}
|
||||
</div>
|
||||
|
||||
<div class="dashboard-two-column">
|
||||
${renderWeekChart(dashboard.week || {})}
|
||||
${renderRecords(dashboard.records || {})}
|
||||
</div>
|
||||
|
||||
${renderRecentDrives(dashboard.recentDrives || [])}
|
||||
|
||||
<div class="dashboard-two-column dashboard-model-storage">
|
||||
${renderFavoriteModels(dashboard.favoriteModels || [])}
|
||||
${renderStorage(dashboard.storage || {})}
|
||||
</div>
|
||||
|
||||
<div class="dashboard-section-label"><span></span>Your device</div>
|
||||
<div class="dashboard-device-grid">
|
||||
${renderVitals(device)}
|
||||
${renderSoftware(data.softwareInfo || {})}
|
||||
</div>
|
||||
</main>
|
||||
`;
|
||||
|
||||
bindDashboardActions();
|
||||
scheduleDashboardRefresh(dashboard);
|
||||
}
|
||||
|
||||
const STATS_ATTEMPT_TIMEOUTS_MS = [5000, 20000];
|
||||
|
||||
async function fetchDashboardStats(timeoutMs) {
|
||||
const statsResponse = await withTimeout(fetch("/api/stats"), timeoutMs, "stats request");
|
||||
|
||||
if (!statsResponse.ok) throw new Error(`stats API error: ${statsResponse.status}`);
|
||||
|
||||
return withTimeout(statsResponse.json(), timeoutMs, "stats JSON parse");
|
||||
}
|
||||
|
||||
async function initializeHome(force = false) {
|
||||
if (force) {
|
||||
clearDashboardRefreshTimer();
|
||||
HOME_STATE.status = "loading";
|
||||
renderDashboard(HOME_STATE);
|
||||
}
|
||||
|
||||
let statsJson = null;
|
||||
let lastError = null;
|
||||
for (const timeoutMs of STATS_ATTEMPT_TIMEOUTS_MS) {
|
||||
try {
|
||||
statsJson = await fetchDashboardStats(timeoutMs);
|
||||
lastError = null;
|
||||
break;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError) {
|
||||
HOME_STATE.status = "error";
|
||||
HOME_STATE.error = lastError?.message || String(lastError);
|
||||
} else {
|
||||
const payloadUnit = statsJson?.dashboard?.week?.distanceUnit || statsJson?.driveStats?.all?.unit;
|
||||
|
||||
HOME_STATE.data = statsJson;
|
||||
HOME_STATE.unit = payloadUnit || HOME_STATE.unit || "miles";
|
||||
HOME_STATE.status = "ready";
|
||||
}
|
||||
|
||||
renderDashboard(HOME_STATE);
|
||||
}
|
||||
|
||||
export function Home() {
|
||||
setTimeout(() => {
|
||||
renderDashboard(HOME_STATE);
|
||||
if (!HOME_STATE.initialized) {
|
||||
HOME_STATE.initialized = true;
|
||||
initializeHome();
|
||||
}
|
||||
}, 0);
|
||||
|
||||
return html`<div id="home_shell"><p>Loading dashboard...</p></div>`;
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
:root {
|
||||
/* Borders */
|
||||
--border-color-base: var(--sidebar-border-color);
|
||||
--border-radius-sm: 4px;
|
||||
--border-radius-base: 5px;
|
||||
--border-radius-md: 8px;
|
||||
--border-radius-lg: 10px;
|
||||
--border-radius-xl: 1rem;
|
||||
--border-width-thin: 1px;
|
||||
--border-width-base: 2px;
|
||||
--border-width-thick: 5px;
|
||||
--border-solid: solid;
|
||||
--border-style-base: solid;
|
||||
--border-style-input: 1px solid var(--sidebar-border-color);
|
||||
|
||||
/* Breakpoints */
|
||||
--breakpoint-xs: 360px;
|
||||
--breakpoint-sm: 480px;
|
||||
--breakpoint-md: 768px;
|
||||
--breakpoint-lg: 1024px;
|
||||
--breakpoint-xl: 1280px;
|
||||
|
||||
/* Colors — Galaxy palette (cosmic purple · teal · rose · amber) */
|
||||
--accent-bg: #8b6cc5;
|
||||
--accent-hover-bg: #7558b0;
|
||||
--card-bg: #121224;
|
||||
--color-black: #000000;
|
||||
--color-confirm: #8b6cc5;
|
||||
--color-confirm-hover: #7558b0;
|
||||
--color-gray-100: #f0f0f8;
|
||||
--color-gray-200: #d8d8e4;
|
||||
--color-gray-300: #b8b8cc;
|
||||
--color-gray-400: #9898b0;
|
||||
--color-gray-500: #7e7e98;
|
||||
--color-gray-600: #636380;
|
||||
--color-gray-700: #4a4a64;
|
||||
--color-gray-800: #2e2e44;
|
||||
--color-gray-900: #1a1a30;
|
||||
--color-white: #ffffff;
|
||||
--danger-bg: #e05577;
|
||||
--danger-fg: #e05577;
|
||||
--danger-hover-bg: #c04466;
|
||||
--glow-primary: 0 0 0 2px var(--main-fg), 0 0 10px rgba(139, 108, 197, 0.35);
|
||||
--input-bg: #161630;
|
||||
--main-bg: #06060f;
|
||||
--main-fg: #8b6cc5;
|
||||
--secondary-bg: #0e0e1a;
|
||||
--selected-camera-bg: #0b0b18;
|
||||
--sidebar-active-bg: rgba(139, 108, 197, 0.15);
|
||||
--sidebar-bg: #0a0a16;
|
||||
--sidebar-border-color: #1e1e3e;
|
||||
--sidebar-fg: #ffffff;
|
||||
--sidebar-title-fg: #8b6cc5;
|
||||
--success-bg: #5ec8c8;
|
||||
--success-fg: #5ec8c8;
|
||||
--success-hover-bg: #4ab3b3;
|
||||
--switch-inactive-bg: #1e1e3e;
|
||||
--text-color: #e8e8f0;
|
||||
--text-muted: #8080a8;
|
||||
--text-on-primary: var(--sidebar-fg);
|
||||
--text-on-surface: var(--text-color);
|
||||
--thumb-color: #8b6cc5;
|
||||
--track-color: #14142e;
|
||||
--warning-bg: #d4a060;
|
||||
--warning-hover-bg: #b8884a;
|
||||
|
||||
/* Effects */
|
||||
--disabled-opacity: 0.5;
|
||||
--focus-ring-color: var(--main-fg);
|
||||
--hover-opacity: 0.85;
|
||||
--hover-scale-sm: scale(1.01);
|
||||
--hover-scale-base: scale(1.05);
|
||||
--hover-scale-lg: scale(1.1);
|
||||
|
||||
/* Fonts */
|
||||
--font-body: "Inter", "Open Sans", sans-serif;
|
||||
--font-mono: "Courier New", Courier, monospace;
|
||||
--font-size-xs: 0.75rem;
|
||||
--font-size-sm: 0.85rem;
|
||||
--font-size-base: 1rem;
|
||||
--font-size-lg: 1.2rem;
|
||||
--font-size-xl: 1.5rem;
|
||||
--font-weight-normal: 400;
|
||||
--font-weight-demi-bold: 550;
|
||||
--font-weight-bold: 700;
|
||||
--heading-font: var(--font-body);
|
||||
|
||||
/* Layout */
|
||||
--max-width-content: 700px;
|
||||
--sidebar-width: 250px;
|
||||
--width-xs: 100px;
|
||||
--width-sm: 150px;
|
||||
--width-md: 300px;
|
||||
--width-lg: 500px;
|
||||
--width-xl: 750px;
|
||||
--width-xxl: 900px;
|
||||
--width-xxxl: 1050px;
|
||||
--width-xxxxl: 1200px;
|
||||
|
||||
/* Shadows */
|
||||
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
|
||||
/* Spacing */
|
||||
--gap-xxs: 0.125rem;
|
||||
--gap-xs: 0.25rem;
|
||||
--gap-sm: 0.5rem;
|
||||
--gap-md: 1rem;
|
||||
--gap-lg: 1.5rem;
|
||||
--gap-xl: 2rem;
|
||||
--gap-xxl: 3rem;
|
||||
|
||||
--margin-xxs: 0.125rem;
|
||||
--margin-xs: 0.3rem;
|
||||
--margin-sm: 0.5rem;
|
||||
--margin-base: 1rem;
|
||||
--margin-lg: 1.5rem;
|
||||
--margin-xl: 2rem;
|
||||
--margin-xxl: 3rem;
|
||||
|
||||
--padding-xxs: 0.125rem;
|
||||
--padding-xs: 0.3rem;
|
||||
--padding-sm: 0.5rem;
|
||||
--padding-base: 1rem;
|
||||
--padding-lg: 1.5rem;
|
||||
--padding-xl: 2rem;
|
||||
--padding-xxl: 3rem;
|
||||
|
||||
--space-xxs: 0.125rem;
|
||||
--space-xs: 0.25rem;
|
||||
--space-sm: 0.5rem;
|
||||
--space-md: 1rem;
|
||||
--space-lg: 1.5rem;
|
||||
--space-xl: 2rem;
|
||||
--space-xxl: 3rem;
|
||||
|
||||
/* Transitions */
|
||||
--transition-fast: 0.15s ease-in-out;
|
||||
--transition-base: 0.3s ease;
|
||||
--transition-slow: 0.5s ease;
|
||||
|
||||
/* Typography */
|
||||
--letter-spacing-base: 0;
|
||||
--line-height-base: 1.5;
|
||||
|
||||
/* Z-Index */
|
||||
--z-overlay: 800;
|
||||
--z-sidebar: 900;
|
||||
--z-modal: 1000;
|
||||
--z-tooltip: 1100;
|
||||
}
|
||||
|
||||
/* ――― Base elements ――― */
|
||||
a.button {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-base);
|
||||
color: var(--main-fg);
|
||||
display: inline-block;
|
||||
margin: var(--margin-base) 0;
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* clickables share the pointer */
|
||||
a[href],
|
||||
button,
|
||||
[role="button"],
|
||||
input[type="button"],
|
||||
input[type="submit"],
|
||||
input[type="checkbox"],
|
||||
input[type="radio"],
|
||||
.manage-keys-link,
|
||||
.route_card,
|
||||
.sidebar .menu_section>li>ul>li,
|
||||
.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
body {
|
||||
padding-bottom: 0 !important;
|
||||
}
|
||||
|
||||
/* ――― Layout containers ――― */
|
||||
.content {
|
||||
color: var(--main-fg);
|
||||
flex-grow: 1;
|
||||
margin-left: 0;
|
||||
overflow-y: auto;
|
||||
padding-bottom: var(--padding-xl);
|
||||
padding-left: var(--padding-lg);
|
||||
}
|
||||
|
||||
@media only screen and (min-width: 768px) {
|
||||
html.galaxy-sidebar-pinned .content {
|
||||
margin-left: var(--sidebar-width, 250px);
|
||||
}
|
||||
}
|
||||
|
||||
.embedded #sidebar,
|
||||
.embedded #sidebar_shell,
|
||||
.embedded #sidebarUnderlay {
|
||||
display: none !important;
|
||||
}
|
||||
.embedded #menu_button {
|
||||
display: none !important;
|
||||
}
|
||||
.embedded .content {
|
||||
margin-left: 0 !important;
|
||||
padding-left: var(--padding-lg);
|
||||
}
|
||||
|
||||
/* ――― Headings ――― */
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
color: var(--text-color);
|
||||
margin: 0;
|
||||
padding: var(--padding-base) 0 var(--heading-bottom, 10px);
|
||||
}
|
||||
|
||||
/* ――― Helpers & states ――― */
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.no_scroll {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.not_implemented {
|
||||
cursor: not-allowed;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* ――― Base typography & page reset ――― */
|
||||
html,
|
||||
body {
|
||||
background-color: var(--main-bg);
|
||||
font-family: var(--font-body);
|
||||
margin: 0;
|
||||
min-height: 100dvh;
|
||||
overflow-x: hidden;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* weight-override set once for all matching selectors */
|
||||
html,
|
||||
body,
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
.open-sans-regular {
|
||||
font-family: var(--font-body);
|
||||
font-optical-sizing: auto;
|
||||
font-style: normal;
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
}
|
||||
|
||||
/* ――― HR line ――― */
|
||||
hr {
|
||||
background-color: var(--sidebar-border-color);
|
||||
border: none;
|
||||
height: var(--border-width-thin);
|
||||
}
|
||||
|
||||
/* text-inputs keep the I-beam */
|
||||
input[type="email"],
|
||||
input[type="number"],
|
||||
input[type="password"],
|
||||
input[type="search"],
|
||||
input[type="text"],
|
||||
.navkeys-input,
|
||||
.settings .textinput,
|
||||
textarea {
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
label[for] {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ――― Snackbar component ――― */
|
||||
.snackbar {
|
||||
background-color: var(--color-confirm);
|
||||
border-radius: var(--border-radius-base);
|
||||
color: var(--text-color);
|
||||
margin-bottom: var(--margin-base);
|
||||
padding: var(--padding-base);
|
||||
text-align: center;
|
||||
transition: var(--snackbar-transition, 1s);
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.snackbar.show {
|
||||
animation: fadein var(--snackbar-fade-time, 0.5s);
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
/* zero-ed default list / link styles */
|
||||
ul,
|
||||
li,
|
||||
a {
|
||||
display: block;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ――― Snackbar wrapper ――― */
|
||||
#snackbar_wrapper {
|
||||
bottom: var(--snackbar-offset, 30px);
|
||||
left: 0;
|
||||
margin: 0 auto;
|
||||
position: fixed;
|
||||
right: 0;
|
||||
width: min(var(--snackbar-width, 300px), 70%);
|
||||
z-index: var(--z-overlay);
|
||||
}
|
||||
|
||||
@media only screen and (min-width: 768px) {
|
||||
html.galaxy-sidebar-pinned #snackbar_wrapper {
|
||||
left: var(--sidebar-width);
|
||||
}
|
||||
}
|
||||
|
||||
/* ――― Animations ――― */
|
||||
@keyframes fadein {
|
||||
from {
|
||||
bottom: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
bottom: var(--snackbar-offset, 30px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeout {
|
||||
from {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ――― Breakpoint overrides ――― */
|
||||
@media only screen and (max-width: 767px) {
|
||||
.content {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.content {
|
||||
box-sizing: border-box;
|
||||
margin-left: 0;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
#snackbar_wrapper {
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 80%;
|
||||
}
|
||||
}
|
||||
|
||||
/* legacy WebKit keyframes */
|
||||
@-webkit-keyframes fadein {
|
||||
from {
|
||||
bottom: 0;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
bottom: var(--snackbar-offset, 30px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@-webkit-keyframes fadeout {
|
||||
from {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ——— Tunnel notice banner ——— */
|
||||
.tunnel-notice {
|
||||
align-items: center;
|
||||
background: linear-gradient(135deg, var(--card-bg), var(--secondary-bg));
|
||||
border: var(--border-width-thin) var(--border-style-base) var(--sidebar-border-color);
|
||||
border-left: 3px solid var(--main-fg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-md);
|
||||
margin: var(--margin-xl) auto;
|
||||
max-width: var(--width-xl);
|
||||
padding: var(--padding-xl) var(--padding-xxl);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tunnel-notice-icon {
|
||||
font-size: 2.5rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.tunnel-notice-title {
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.tunnel-notice-body {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--font-size-base);
|
||||
line-height: var(--line-height-base);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
height: 8px;
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--track-color);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: var(--thumb-color);
|
||||
border-radius: var(--border-radius-sm);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
.modal {
|
||||
background-color: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-md);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--text-color);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal-actions .btn {
|
||||
background-color: var(--main-fg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
transition: background-color var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.modal-actions .btn.btn-danger {
|
||||
background-color: var(--danger-bg);
|
||||
color: var(--text-on-surface);
|
||||
}
|
||||
|
||||
.modal-actions .btn.btn-danger:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.modal-actions .btn.btn-primary {
|
||||
background-color: var(--color-confirm);
|
||||
color: var(--text-on-surface);
|
||||
}
|
||||
|
||||
.modal-actions .btn.btn-primary:hover {
|
||||
background-color: var(--color-confirm-hover);
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.modal-actions .btn:hover {
|
||||
background-color: var(--success-hover-bg);
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
color: var(--text-base);
|
||||
font-size: var(--font-size-base);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.modal-body strong {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin-bottom: var(--font-size-base);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.modal-input {
|
||||
background-color: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-sm);
|
||||
box-sizing: border-box;
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.modal-overlay {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
justify-content: center;
|
||||
left: 0;
|
||||
padding-left: 137px;
|
||||
padding-top: 5vh;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
z-index: var(--z-tooltip);
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.modal-overlay {
|
||||
padding-left: 0px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { html } from "/assets/vendor/arrow-core.js";
|
||||
|
||||
export function Modal({
|
||||
title,
|
||||
message,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
confirmText = "Confirm",
|
||||
cancelText = "Cancel",
|
||||
confirmClass = "btn-danger",
|
||||
customClass = ""
|
||||
}) {
|
||||
return html`
|
||||
<div class="modal-overlay" tabindex="0"
|
||||
@click="${(e) => {
|
||||
if (e.target.classList.contains('modal-overlay')) {
|
||||
onCancel && onCancel();
|
||||
}
|
||||
}}"
|
||||
@keydown="${(e) => {
|
||||
if (e.key === 'Enter' && onConfirm) {
|
||||
e.preventDefault();
|
||||
onConfirm();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
onCancel && onCancel();
|
||||
}
|
||||
}}"
|
||||
>
|
||||
<div class="modal ${customClass}">
|
||||
<div class="modal-header">${title}</div>
|
||||
<div class="modal-body">${message}</div>
|
||||
<div class="modal-actions">
|
||||
${onCancel ? html`<button class="btn" @click="${onCancel}">${cancelText}</button>` : ''}
|
||||
${onConfirm ? html`<button class="btn ${confirmClass}" @click="${onConfirm}">${confirmText}</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
#map {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#search-field {
|
||||
align-items: center;
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-xl);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: var(--font-size-sm);
|
||||
justify-content: center;
|
||||
padding: var(--border-radius-xl);
|
||||
transition: box-shadow 0.2s, border-color 0.2s;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#search-field:focus {
|
||||
border-color: var(--thumb-color);
|
||||
box-shadow: 0 0 var(--border-radius-sm) var(--thumb-color);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#search-field::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-item {
|
||||
align-items: center;
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
box-sizing: border-box;
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: var(--border-radius-xl);
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-primary,
|
||||
#searchSuggestions .suggestion-secondary {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-primary {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-secondary {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
margin-top: 0.25rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-item:first-child {
|
||||
border-top-left-radius: var(--border-radius-xl);
|
||||
border-top-right-radius: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-item:last-child {
|
||||
border-bottom-left-radius: var(--border-radius-xl);
|
||||
border-bottom-right-radius: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
#searchSuggestions .suggestion-item:hover {
|
||||
background-color: var(--main-fg);
|
||||
color: var(--text-color) !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.favorite-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.favorite-item {
|
||||
align-items: center;
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-md);
|
||||
display: flex;
|
||||
gap: var(--padding-xs);
|
||||
justify-content: space-between;
|
||||
margin-bottom: var(--padding-xs);
|
||||
padding: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.favorite-marker {
|
||||
cursor: pointer;
|
||||
font-size: 24px;
|
||||
text-shadow: 0px 0px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.favorite-marker:hover {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
|
||||
.favorites-toggle-button {
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-xl);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-normal);
|
||||
min-width: 7rem;
|
||||
padding: var(--padding-sm);
|
||||
transition: box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.favorites-toggle-button:hover {
|
||||
background-color: var(--main-fg);
|
||||
box-shadow: var(--glow-primary);
|
||||
color: var(--text-color);
|
||||
font-weight: var(--font-weight-bold);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.home-favorite-button,
|
||||
.work-favorite-button,
|
||||
.edit-favorite-button,
|
||||
.remove-favorite-button {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
padding: 0.25rem;
|
||||
transition: transform 0.1s ease;
|
||||
}
|
||||
|
||||
.home-favorite-button:hover,
|
||||
.work-favorite-button:hover,
|
||||
.edit-favorite-button:hover,
|
||||
.remove-favorite-button:hover {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
|
||||
.home-favorite-button,
|
||||
.work-favorite-button,
|
||||
.edit-favorite-button {
|
||||
color: var(--thumb-color);
|
||||
}
|
||||
|
||||
.keys-required-button {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--border-radius-xl);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
transition: background-color var(--transition-fast), box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.keys-required-button:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--secondary-fg);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.keys-required-text {
|
||||
color: var(--text-color);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.keys-required-title {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.keys-required-widget {
|
||||
align-items: center;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--main-fg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-xl);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.keys-required-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.keys-required-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.loading-status {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
font-size: 1.1em;
|
||||
gap: 0.5em;
|
||||
justify-content: flex-start;
|
||||
padding: var(--padding-lg);
|
||||
}
|
||||
|
||||
.manage-keys-link {
|
||||
background-color: var(--main-fg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--main-fg);
|
||||
display: inline-flex;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-bold);
|
||||
justify-content: center;
|
||||
padding: var(--border-radius-xl);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
transition: background-color var(--transition-fast), color var(--transition-fast), transform var(--transition-fast), box-shadow var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.manage-keys-link:hover {
|
||||
background-color: var(--input-bg);
|
||||
color: var(--main-fg);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.map-wrapper {
|
||||
height: 100vh;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
width: 100vw;
|
||||
}
|
||||
|
||||
@media only screen and (min-width: 768px) {
|
||||
html.galaxy-sidebar-pinned .map-wrapper {
|
||||
left: var(--sidebar-width);
|
||||
width: calc(100vw - var(--sidebar-width));
|
||||
}
|
||||
}
|
||||
|
||||
.mapboxgl-popup-content {
|
||||
background-color: var(--secondary-bg) !important;
|
||||
border-radius: var(--border-radius-md) !important;
|
||||
color: var(--text-color) !important;
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--padding-xs) var(--padding-sm) !important;
|
||||
}
|
||||
|
||||
.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip {
|
||||
border-top-color: var(--secondary-bg) !important;
|
||||
}
|
||||
|
||||
.mapboxgl-popup-anchor-left .mapboxgl-popup-tip {
|
||||
border-right-color: var(--secondary-bg) !important;
|
||||
}
|
||||
|
||||
.mapboxgl-popup-anchor-right .mapboxgl-popup-tip {
|
||||
border-left-color: var(--secondary-bg) !important;
|
||||
}
|
||||
|
||||
.mapboxgl-popup-anchor-top .mapboxgl-popup-tip {
|
||||
border-bottom-color: var(--secondary-bg) !important;
|
||||
}
|
||||
|
||||
.navigation-summary-title {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin-bottom: var(--padding-md);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.navigation-summary-widget {
|
||||
align-items: stretch;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-md);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.navigation-summary-widget .buttonCluster {
|
||||
display: flex;
|
||||
gap: var(--padding-sm);
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.navigation-summary-widget .buttonCluster i {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.navigation-summary-widget .navigation-details {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.navigation-summary-widget .summary-row {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
grid-template-columns: 2rem 6rem 1fr;
|
||||
}
|
||||
|
||||
.navigation-summary-widget .summary-row .emoji {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
font-size: var(--font-size-base);
|
||||
height: 2rem;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.navigation-summary-widget button {
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-xl);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
letter-spacing: var(--border-width-base);
|
||||
margin: var(--border-radius-sm);
|
||||
padding: var(--padding-xs) var(--padding-lg);
|
||||
transition: background-color var(--transition-fast), color var(--transition-fast), transform var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.cancel {
|
||||
background-color: var(--danger-bg);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.cancel:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
box-shadow: 0 0 0 2px var(--danger-fg), 0 0 8px var(--danger-fg);
|
||||
color: var(--text-color);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.directions {
|
||||
background-color: var(--success-bg);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.directions:hover {
|
||||
background-color: var(--success-hover-bg);
|
||||
box-shadow: var(--glow-primary);
|
||||
color: var(--text-color);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.favorite {
|
||||
background-color: var(--danger-bg);
|
||||
}
|
||||
|
||||
.navigation-summary-widget button.favorite:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
box-shadow: 0 0 0 2px var(--danger-fg), 0 0 8px var(--danger-fg);
|
||||
color: var(--text-color);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navigation-summary-widget.horizontal-layout {
|
||||
flex-direction: row;
|
||||
gap: var(--padding-md);
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.navigation-summary-widget.loading-status {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.navigation-summary-widget p {
|
||||
margin: var(--border-radius-xl) 0 0 var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.navigation-summary-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.next-step-panel {
|
||||
align-items: center;
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
min-width: 9rem;
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.next-step-panel .step-icon {
|
||||
font-size: 2rem;
|
||||
margin-bottom: var(--padding-xs);
|
||||
}
|
||||
|
||||
.next-step-panel .step-text {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
}
|
||||
|
||||
.remove-favorite-button {
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
.remove-favorite-button:hover {
|
||||
color: var(--danger-hover-bg);
|
||||
}
|
||||
|
||||
.route-tooltip .mapboxgl-popup-content {
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-md);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--color-white);
|
||||
font-size: var(--font-size-base);
|
||||
}
|
||||
|
||||
.route-tooltip .tooltip-row {
|
||||
column-gap: var(--gap-xxs);
|
||||
display: grid;
|
||||
grid-template-columns: 1.4rem 5.5rem auto;
|
||||
}
|
||||
|
||||
.route-tooltip .tooltip-row .emoji {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.search-controls {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
gap: var(--border-radius-sm);
|
||||
}
|
||||
|
||||
.search-provider-toggle {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: var(--border-radius-md);
|
||||
margin-left: var(--padding-xs);
|
||||
}
|
||||
|
||||
.search-provider-toggle button {
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--track-color);
|
||||
border-radius: var(--border-radius-xl);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-bold);
|
||||
min-width: 7rem;
|
||||
padding: var(--padding-sm) var(--padding-xl);
|
||||
transition: box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.search-provider-toggle button.active {
|
||||
box-shadow: var(--glow-primary);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.search-provider-toggle button:hover {
|
||||
box-shadow: var(--glow-primary);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.search-wrapper {
|
||||
left: var(--border-radius-xl);
|
||||
position: absolute;
|
||||
top: var(--border-radius-xl);
|
||||
width: 30%;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.search-wrapper #infobox .navigation-summary-widget {
|
||||
align-items: flex-start;
|
||||
animation: fadeInUp 0.3s ease-out;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-xl);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
margin-top: var(--margin-sm);
|
||||
overflow: hidden;
|
||||
padding: var(--padding-sm);
|
||||
}
|
||||
|
||||
.search-wrapper #infobox .navigation-summary-widget.loading-status {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: var(--padding-sm);
|
||||
justify-content: flex-start;
|
||||
padding-left: var(--padding-base);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
animation: spin 1s linear infinite;
|
||||
border: var(--border-width-base) solid var(--color-gray-300);
|
||||
border-radius: 50%;
|
||||
border-top: var(--border-width-base) solid var(--color-gray-900);
|
||||
height: 1em;
|
||||
width: 1em;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.map-wrapper {
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
}
|
||||
|
||||
.search-wrapper {
|
||||
left: var(--padding-sm);
|
||||
min-width: 0;
|
||||
width: calc(100% - var(--padding-xl));
|
||||
}
|
||||
}
|
||||
+1053
File diff suppressed because it is too large
Load Diff
+205
@@ -0,0 +1,205 @@
|
||||
.navkeys-btn {
|
||||
all: unset;
|
||||
background-color: var(--main-fg);
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--text-on-primary);
|
||||
cursor: pointer;
|
||||
padding: var(--padding-xs) var(--padding-xs);
|
||||
transition: background-color var(--transition-fast), transform var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.navkeys-btn.delete {
|
||||
background-color: var(--danger-bg);
|
||||
}
|
||||
|
||||
.navkeys-btn.delete:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.navkeys-btn:hover:not(:disabled) {
|
||||
background-color: var(--success-hover-bg);
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.navkeys-btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.navkeys-container {
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
flex: 1 1 400px;
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-sm) var(--font-size-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.navkeys-container:hover {
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navkeys-app-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: var(--margin-base);
|
||||
}
|
||||
|
||||
.navkeys-app-container {
|
||||
flex-basis: min(100%, calc((var(--width-lg) * 2) + var(--gap-lg)));
|
||||
max-width: calc((var(--width-lg) * 2) + var(--gap-lg));
|
||||
}
|
||||
|
||||
.navkeys-copy-btn,
|
||||
.navkeys-link-btn {
|
||||
align-items: center;
|
||||
display: inline-flex;
|
||||
gap: var(--gap-xs);
|
||||
justify-content: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.navkeys-copy-btn {
|
||||
min-width: 5.5rem;
|
||||
}
|
||||
|
||||
.navkeys-icon-btn {
|
||||
align-items: center;
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
min-width: 2.25rem;
|
||||
}
|
||||
|
||||
.navkeys-error {
|
||||
color: var(--danger-bg);
|
||||
font-size: var(--font-size-sm);
|
||||
transition: opacity 0.5s ease;
|
||||
}
|
||||
|
||||
.navkeys-group>.navkeys-row:last-of-type {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.navkeys-help-icon {
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-sm);
|
||||
margin-left: var(--gap-xxs);
|
||||
position: relative;
|
||||
top: -1px;
|
||||
}
|
||||
|
||||
.navkeys-help-img img {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.navkeys-input {
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-width-thin) solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-sm);
|
||||
box-sizing: border-box;
|
||||
color: var(--text-color);
|
||||
cursor: text;
|
||||
flex: 1;
|
||||
font-size: var(--font-size-base);
|
||||
min-width: 0;
|
||||
padding: var(--padding-xs) var(--padding-sm);
|
||||
transition: border-color var(--transition-fast), box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.navkeys-input:hover,
|
||||
.navkeys-input:focus {
|
||||
border-color: var(--thumb-color);
|
||||
box-shadow: var(--glow-primary);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navkeys-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.navkeys-token-input {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.navkeys-label {
|
||||
display: block;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin-bottom: var(--margin-xs);
|
||||
}
|
||||
|
||||
.navkeys-link-btn {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.navkeys-message {
|
||||
color: var(--success-bg);
|
||||
font-size: var(--font-size-sm);
|
||||
transition: opacity 0.5s ease;
|
||||
}
|
||||
|
||||
.navkeys-offset-top {
|
||||
margin-top: var(--margin-xl);
|
||||
}
|
||||
|
||||
.navkeys-row {
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
margin-bottom: var(--margin-base);
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.navkeys-row:hover {
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.navkeys-status {
|
||||
margin-top: var(--padding-xs);
|
||||
min-height: var(--gap-lg);
|
||||
}
|
||||
|
||||
.navkeys-title {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin-bottom: var(--font-size-base);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.navkeys-subtitle {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
margin: calc(var(--margin-base) * -1) 0 var(--margin-base);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.navkeys-wrapper {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--gap-lg);
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.navkeys-btn {
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.navkeys-container {
|
||||
padding: var(--padding-sm);
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.navkeys-input {
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
}
|
||||
+437
@@ -0,0 +1,437 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { Modal } from "/assets/components/modal.js";
|
||||
|
||||
const DEFAULT_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=com.embaucha.galaxynav&hl=en-US&ah=9FldHJ99kxL8oNbSlO5F4sQqwC4"
|
||||
|
||||
export function NavKeys() {
|
||||
const state = reactive({
|
||||
initialMapboxComplete: false,
|
||||
showMapboxHelp: false,
|
||||
visible: false,
|
||||
|
||||
imageVersion: 0,
|
||||
|
||||
error: "",
|
||||
lastGroup: "",
|
||||
message: "",
|
||||
|
||||
amap1Key: "", amap2Key: "",
|
||||
editA1: false, editA2: false,
|
||||
savedA1: false, savedA2: false,
|
||||
|
||||
publicKey: "", secretKey: "",
|
||||
editPublic: false, editSecret: false,
|
||||
savedPublic: false, savedSecret: false,
|
||||
|
||||
galaxyCookieName: "galaxy_session",
|
||||
galaxySessionToken: "",
|
||||
galaxyAppUrl: DEFAULT_PLAY_STORE_URL,
|
||||
galaxyPaired: false,
|
||||
galaxySessionVisible: false,
|
||||
|
||||
showDeleteModal: false,
|
||||
keyToDelete: null,
|
||||
})
|
||||
|
||||
const bumpImageVersion = () => state.imageVersion++
|
||||
|
||||
let clearTimer = null
|
||||
let fadeTimer = null
|
||||
|
||||
function showMessage(type, text, group) {
|
||||
clearTimer && clearTimeout(clearTimer)
|
||||
fadeTimer && clearTimeout(fadeTimer)
|
||||
|
||||
state.error = type === "error" ? text : ""
|
||||
state.message = type === "message" ? text : ""
|
||||
|
||||
state.lastGroup = group
|
||||
|
||||
state.visible = true
|
||||
|
||||
clearTimer = setTimeout(() => { state.message = "", state.error = "" }, 5000)
|
||||
fadeTimer = setTimeout(() => state.visible = false, 5000)
|
||||
}
|
||||
|
||||
const util = {
|
||||
prefix: (key, prefix) => key.startsWith(prefix) ? key : prefix ? prefix + key : key,
|
||||
|
||||
mask: (key) => {
|
||||
if (!key) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const prefix = ["pk.", "sk."].find(p => key.startsWith(p)) || ""
|
||||
return prefix + "x".repeat(key.length - prefix.length)
|
||||
},
|
||||
|
||||
req: async (url, opts) => {
|
||||
const response = await fetch(url, opts)
|
||||
return { ok: response.ok, data: await response.json().catch(() => ({})) }
|
||||
},
|
||||
|
||||
copyText: async (text) => {
|
||||
if (!text) {
|
||||
throw new Error("Nothing to copy")
|
||||
}
|
||||
|
||||
if (navigator.clipboard?.writeText && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return
|
||||
}
|
||||
|
||||
const textarea = document.createElement("textarea")
|
||||
textarea.value = text
|
||||
textarea.setAttribute("readonly", "")
|
||||
textarea.style.position = "fixed"
|
||||
textarea.style.left = "-9999px"
|
||||
textarea.style.opacity = "0"
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
|
||||
try {
|
||||
if (!document.execCommand("copy")) {
|
||||
throw new Error("Copy command failed")
|
||||
}
|
||||
} finally {
|
||||
textarea.remove()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const meta = {
|
||||
amap1: { prop: "amap1Key", saved: "savedA1", edit: "editA1", prefix: "", body: "amap1", minLength: 39 },
|
||||
amap2: { prop: "amap2Key", saved: "savedA2", edit: "editA2", prefix: "", body: "amap2", minLength: 39 },
|
||||
public: { prop: "publicKey", saved: "savedPublic", edit: "editPublic", prefix: "pk.", body: "public", minLength: 80 },
|
||||
secret: { prop: "secretKey", saved: "savedSecret", edit: "editSecret", prefix: "sk.", body: "secret", minLength: 80 }
|
||||
}
|
||||
|
||||
const canSave = (kind) => {
|
||||
const keyMeta = meta[kind];
|
||||
if (!keyMeta) return false;
|
||||
|
||||
const value = state[keyMeta.prop]?.trim() || "";
|
||||
if (!value) return false;
|
||||
|
||||
if (!state[keyMeta.saved]) {
|
||||
const fullValue = util.prefix(value, keyMeta.prefix);
|
||||
return fullValue.length >= keyMeta.minLength;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const getDeleteLabel = (kind) => {
|
||||
switch (kind) {
|
||||
case "amap1": return "AMap / Gaode 1"
|
||||
case "amap2": return "AMap / Gaode 2"
|
||||
case "public": return "Public Mapbox"
|
||||
case "secret": return "Secret Mapbox"
|
||||
default: return kind
|
||||
}
|
||||
}
|
||||
|
||||
const api = {
|
||||
path: {
|
||||
galaxy: "/api/galaxy/session",
|
||||
key: "/api/navigation_key",
|
||||
nav: "/api/navigation"
|
||||
},
|
||||
|
||||
load: async () => {
|
||||
const { ok, data } = await util.req(api.path.nav)
|
||||
if (!ok) {
|
||||
showMessage("error", "Failed to load keys...", "")
|
||||
await api.loadGalaxySession()
|
||||
return
|
||||
}
|
||||
|
||||
state.amap1Key = data.amap1Key ?? ""
|
||||
state.amap2Key = data.amap2Key ?? ""
|
||||
state.savedA1 = !!state.amap1Key
|
||||
state.savedA2 = !!state.amap2Key
|
||||
|
||||
state.publicKey = data.mapboxPublic ?? ""
|
||||
state.secretKey = data.mapboxSecret ?? ""
|
||||
state.savedPublic = !!state.publicKey
|
||||
state.savedSecret = !!state.secretKey
|
||||
|
||||
state.initialMapboxComplete = state.savedPublic && state.savedSecret
|
||||
|
||||
bumpImageVersion()
|
||||
await api.loadGalaxySession()
|
||||
},
|
||||
|
||||
loadGalaxySession: async () => {
|
||||
const { ok, data } = await util.req(api.path.galaxy)
|
||||
if (!ok) {
|
||||
return showMessage("error", "Failed to load Galaxy session...", "app")
|
||||
}
|
||||
|
||||
state.galaxyAppUrl = data.appUrl || DEFAULT_PLAY_STORE_URL
|
||||
state.galaxyCookieName = data.cookieName || "galaxy_session"
|
||||
state.galaxyPaired = !!data.paired
|
||||
state.galaxySessionToken = data.sessionToken || ""
|
||||
state.galaxySessionVisible = false
|
||||
},
|
||||
|
||||
copyGalaxySession: async () => {
|
||||
try {
|
||||
await util.copyText(state.galaxySessionToken)
|
||||
showMessage("message", "Session token copied!", "app")
|
||||
} catch (e) {
|
||||
showMessage("error", "Copy failed...", "app")
|
||||
}
|
||||
},
|
||||
|
||||
save: (kind) => async () => {
|
||||
const group = kind.startsWith("amap") ? "amap" : "mapbox"
|
||||
const keyMeta = meta[kind]
|
||||
const value = util.prefix(state[keyMeta.prop].trim(), keyMeta.prefix)
|
||||
|
||||
const { ok, data } = await util.req(api.path.key, {
|
||||
body: JSON.stringify({ [keyMeta.body]: value }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
method: "POST"
|
||||
})
|
||||
|
||||
if (!ok) {
|
||||
const input = document.getElementById(`${kind}-key`)
|
||||
if (input) {
|
||||
input.value = ""
|
||||
state[keyMeta.edit] = true
|
||||
state[keyMeta.saved] = false
|
||||
state[keyMeta.prop] = ""
|
||||
input.focus()
|
||||
}
|
||||
return showMessage("error", data.error || "Save failed...", group)
|
||||
}
|
||||
|
||||
Object.assign(state, {
|
||||
[keyMeta.edit]: false,
|
||||
[keyMeta.saved]: true,
|
||||
[keyMeta.prop]: value
|
||||
})
|
||||
|
||||
const input = document.getElementById(`${kind}-key`)
|
||||
if (input) {
|
||||
input.blur()
|
||||
input.value = ""
|
||||
requestAnimationFrame(() => { input.value = util.mask(state[keyMeta.prop]) })
|
||||
}
|
||||
|
||||
if (group === "mapbox") {
|
||||
bumpImageVersion()
|
||||
}
|
||||
|
||||
showMessage("message", data.message || "Saved!", group)
|
||||
},
|
||||
|
||||
confirmDelete: (kind) => {
|
||||
state.keyToDelete = kind;
|
||||
state.showDeleteModal = true;
|
||||
},
|
||||
|
||||
delete: async () => {
|
||||
const kind = state.keyToDelete;
|
||||
if (!kind) return;
|
||||
|
||||
const group = kind.startsWith("amap") ? "amap" : "mapbox"
|
||||
const keyMeta = meta[kind]
|
||||
|
||||
const { ok, data } = await util.req(`${api.path.key}?type=${kind}`, {
|
||||
method: "DELETE"
|
||||
})
|
||||
|
||||
state.showDeleteModal = false;
|
||||
|
||||
if (!ok) {
|
||||
return showMessage("error", data.error || "Delete failed...", group)
|
||||
}
|
||||
|
||||
Object.assign(state, {
|
||||
[keyMeta.saved]: false,
|
||||
[keyMeta.prop]: ""
|
||||
})
|
||||
|
||||
if (group === "mapbox") {
|
||||
state.initialMapboxComplete = false
|
||||
bumpImageVersion()
|
||||
}
|
||||
|
||||
showMessage("message", data.message || "Deleted!", group)
|
||||
}
|
||||
}
|
||||
|
||||
queueMicrotask(api.load)
|
||||
|
||||
function renderGroup(title, kinds) {
|
||||
const isMapbox = title === "Mapbox Keys"
|
||||
const isAMap = title === "AMap / Gaode Keys"
|
||||
|
||||
return html`
|
||||
<div class="navkeys-group">
|
||||
<div class="navkeys-title">
|
||||
${title}
|
||||
${isMapbox ? html`
|
||||
<span class="navkeys-help-icon" @click="${() => state.showMapboxHelp = !state.showMapboxHelp}">
|
||||
<i class="bi bi-question-circle-fill"></i>
|
||||
</span>
|
||||
` : ""}
|
||||
</div>
|
||||
${isAMap ? html`<div class="navkeys-subtitle">AMap is the Gaode provider, not Google Maps.</div>` : ""}
|
||||
|
||||
${kinds.map(kind => {
|
||||
const keyMeta = meta[kind]
|
||||
const label = kind[0].toUpperCase() + kind.slice(1).replace(/[0-9]/, d => " " + d)
|
||||
|
||||
return html`
|
||||
<label class="navkeys-label" for="${kind}-key">${label} Key</label>
|
||||
<div class="navkeys-row">
|
||||
<input
|
||||
autocomplete="off"
|
||||
class="navkeys-input"
|
||||
id="${kind}-key"
|
||||
placeholder="${keyMeta.prefix || ""}xxxxxx..."
|
||||
value="${() => state[keyMeta.saved] ? util.mask(state[keyMeta.prop]) : state[keyMeta.prop]}"
|
||||
@keydown="${(e) => {
|
||||
if (state[keyMeta.saved] && !state[keyMeta.edit]) {
|
||||
state[keyMeta.edit] = true
|
||||
state[keyMeta.saved] = false
|
||||
state[keyMeta.prop] = ""
|
||||
e.target.value = ""
|
||||
}
|
||||
}}"
|
||||
@input="${(e) => state[keyMeta.prop] = e.target.value}"
|
||||
/>
|
||||
<button
|
||||
class="${() => `navkeys-btn ${state[keyMeta.saved] ? "delete" : ""}`}"
|
||||
@click="${() => state[keyMeta.saved] ? api.confirmDelete(kind) : api.save(kind)()}"
|
||||
disabled="${() => !state[keyMeta.saved] && !canSave(kind)}">
|
||||
${() => state[keyMeta.saved] ? "🗑️" : "💾"}
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
})}
|
||||
|
||||
${() => {
|
||||
if (isMapbox && state.showMapboxHelp) {
|
||||
return html`
|
||||
<div class="navkeys-help-img">
|
||||
<img
|
||||
alt="Mapbox key setup guide"
|
||||
src="${() => {
|
||||
const bothKeysSet = state.savedPublic && state.savedSecret
|
||||
|
||||
let imageSource = "/mapbox-help/no_keys_set.png"
|
||||
if (bothKeysSet) {
|
||||
imageSource = state.initialMapboxComplete ? "/mapbox-help/setup_completed.png" : "/mapbox-help/both_keys_set.png"
|
||||
} else if (state.savedPublic) {
|
||||
imageSource = "/mapbox-help/public_key_set.png"
|
||||
}
|
||||
return `${imageSource}?v=${state.imageVersion}`
|
||||
}}"
|
||||
/>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
return ""
|
||||
}}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function renderStatus(group) {
|
||||
return html`
|
||||
<div class="navkeys-status">
|
||||
<div
|
||||
class="navkeys-message"
|
||||
style="${() => state.lastGroup === group && state.message ? `opacity: ${state.visible ? 1 : 0}` : "opacity: 0"}">
|
||||
${() => state.message}
|
||||
</div>
|
||||
<div
|
||||
class="navkeys-error"
|
||||
style="${() => state.lastGroup === group && state.error ? `opacity: ${state.visible ? 1 : 0}` : "opacity: 0"}">
|
||||
${() => state.error}
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function renderAppKeys() {
|
||||
return html`
|
||||
<div class="navkeys-title">App Keys</div>
|
||||
|
||||
<div class="navkeys-app-actions">
|
||||
<a
|
||||
class="navkeys-btn navkeys-link-btn"
|
||||
href="${() => state.galaxyAppUrl}"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank">
|
||||
<i class="bi bi-google-play"></i>
|
||||
<span>Install The App</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<label class="navkeys-label" for="galaxy-cookie-name">Cookie Name</label>
|
||||
<div class="navkeys-row">
|
||||
<input
|
||||
class="navkeys-input navkeys-token-input"
|
||||
id="galaxy-cookie-name"
|
||||
readonly
|
||||
value="${() => state.galaxyCookieName}"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label class="navkeys-label" for="galaxy-session-token">Session Token</label>
|
||||
<div class="navkeys-row">
|
||||
<input
|
||||
class="navkeys-input navkeys-token-input"
|
||||
id="galaxy-session-token"
|
||||
placeholder="${() => state.galaxyPaired ? "Session token unavailable..." : "Pair Galaxy to create a session token..."}"
|
||||
readonly
|
||||
type="${() => state.galaxySessionVisible ? "text" : "password"}"
|
||||
value="${() => state.galaxySessionToken}"
|
||||
/>
|
||||
<button
|
||||
aria-label="${() => state.galaxySessionVisible ? "Hide session token" : "Show session token"}"
|
||||
class="navkeys-btn navkeys-icon-btn"
|
||||
@click="${() => { state.galaxySessionVisible = !state.galaxySessionVisible }}"
|
||||
disabled="${() => !state.galaxySessionToken}"
|
||||
title="${() => state.galaxySessionVisible ? "Hide session token" : "Show session token"}">
|
||||
<i class="${() => `bi ${state.galaxySessionVisible ? "bi-eye-slash" : "bi-eye"}`}"></i>
|
||||
</button>
|
||||
<button
|
||||
class="navkeys-btn navkeys-copy-btn"
|
||||
@click="${api.copyGalaxySession}"
|
||||
disabled="${() => !state.galaxySessionToken}">
|
||||
<i class="bi bi-copy"></i>
|
||||
<span>Copy</span>
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="navkeys-wrapper navkeys-offset-top">
|
||||
<div class="navkeys-container">
|
||||
${renderGroup("AMap / Gaode Keys", ["amap1", "amap2"])}
|
||||
${renderStatus("amap")}
|
||||
</div>
|
||||
<div class="navkeys-container">
|
||||
${renderGroup("Mapbox Keys", ["public", "secret"])}
|
||||
${renderStatus("mapbox")}
|
||||
</div>
|
||||
<div class="navkeys-container navkeys-app-container">
|
||||
${renderAppKeys()}
|
||||
${renderStatus("app")}
|
||||
</div>
|
||||
</div>
|
||||
${() => state.showDeleteModal ? Modal({
|
||||
title: "Confirm Delete",
|
||||
message: `Are you sure you want to delete your <strong>${getDeleteLabel(state.keyToDelete)}</strong> key?`,
|
||||
onConfirm: api.delete,
|
||||
onCancel: () => { state.showDeleteModal = false },
|
||||
confirmText: "Yes, Delete"
|
||||
}) : ""}
|
||||
`
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
export function highlightRoute(map, routes, selectedRouteId) {
|
||||
if (!map.isStyleLoaded() || !routes) return;
|
||||
routes.forEach((route, idx) => {
|
||||
const routeId = idx === 0 ? 'main' : `alt-${idx}`;
|
||||
const layerId = `route-line-${routeId}`;
|
||||
if (map.getLayer(layerId)) {
|
||||
const isSelected = routeId === selectedRouteId;
|
||||
map.setPaintProperty(layerId, 'line-width', isSelected ? 5 : 3);
|
||||
map.setPaintProperty(layerId, 'line-opacity', isSelected ? 1 : 0.5);
|
||||
if (isSelected) {
|
||||
map.moveLayer(layerId);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const JAPANESE_KANA_PATTERN = /[\u3040-\u30ff]/u;
|
||||
|
||||
function usesJapaneseLanguage(language) {
|
||||
return typeof language === 'string' && /^(?:main_)?ja(?:[-_]|$)/i.test(language.trim());
|
||||
}
|
||||
|
||||
function isLikelyInJapan(position) {
|
||||
if (!position) return false;
|
||||
|
||||
const latitude = Number(position.latitude);
|
||||
const longitude = Number(position.longitude);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return false;
|
||||
|
||||
// Main islands, Ryukyu Islands, and the Izu/Ogasawara island chains.
|
||||
const mainIslands = latitude >= 30 && latitude <= 45.8 && longitude >= 129.2 && longitude <= 146;
|
||||
const ryukyuIslands = latitude >= 24 && latitude < 30 && longitude >= 122.8 && longitude <= 131.5;
|
||||
const pacificIslands = latitude >= 20 && latitude < 30 && longitude >= 136 && longitude <= 154;
|
||||
return mainIslands || ryukyuIslands || pacificIslands;
|
||||
}
|
||||
|
||||
export function getMapboxSearchContext(query, position, preferredLanguages = []) {
|
||||
const languages = Array.isArray(preferredLanguages) ? preferredLanguages : [preferredLanguages];
|
||||
const japaneseSearch = JAPANESE_KANA_PATTERN.test(query || '') || languages.some(usesJapaneseLanguage);
|
||||
const hasPosition = Number.isFinite(Number(position?.latitude)) && Number.isFinite(Number(position?.longitude));
|
||||
|
||||
if (isLikelyInJapan(position) || (japaneseSearch && !hasPosition)) {
|
||||
return { language: 'ja', country: 'jp' };
|
||||
}
|
||||
if (japaneseSearch) return { language: 'ja' };
|
||||
return {};
|
||||
}
|
||||
|
||||
function addRouteSource(map, sourceId, feature) {
|
||||
if (map.getSource(sourceId)) {
|
||||
const layerId = `route-line-${sourceId.replace('route-', '')}`;
|
||||
const clickLayerId = `route-click-${sourceId.replace('route-', '')}`;
|
||||
if (map.getLayer(layerId)) map.removeLayer(layerId);
|
||||
if (map.getLayer(clickLayerId)) map.removeLayer(clickLayerId);
|
||||
map.removeSource(sourceId);
|
||||
}
|
||||
map.addSource(sourceId, {
|
||||
type: 'geojson',
|
||||
data: { type: 'FeatureCollection', features: [feature] },
|
||||
lineMetrics: true
|
||||
});
|
||||
}
|
||||
|
||||
function addRouteLayers(map, sourceId, layerId, clickLayerId, route) {
|
||||
map.addLayer({
|
||||
id: layerId,
|
||||
type: 'line',
|
||||
source: sourceId,
|
||||
layout: { 'line-cap': 'round', 'line-join': 'round' },
|
||||
paint: {
|
||||
'line-width': 3,
|
||||
'line-opacity': 0.5,
|
||||
'line-gradient': buildGradientExpression(route.geometry.coordinates, route.legs[0].annotation.congestion)
|
||||
}
|
||||
});
|
||||
map.addLayer({
|
||||
id: clickLayerId,
|
||||
type: 'line',
|
||||
source: sourceId,
|
||||
layout: { 'line-cap': 'round', 'line-join': 'round' },
|
||||
paint: { 'line-width': 25, 'line-opacity': 0 }
|
||||
});
|
||||
}
|
||||
|
||||
function safeGetId(fn) {
|
||||
try { return fn?.() ?? null } catch { return null }
|
||||
}
|
||||
|
||||
function handleRouteEvents(map, clickLayerId, onRouteSelect, routes, useMetric, feature, getSelectedRouteId) {
|
||||
const layerId = clickLayerId.replace('click', 'line');
|
||||
const showTooltip = (e) => {
|
||||
map.getCanvas().style.cursor = 'pointer';
|
||||
map.setPaintProperty(layerId, 'line-width', 5);
|
||||
map.setPaintProperty(layerId, 'line-opacity', 1);
|
||||
document.querySelectorAll('.mapboxgl-popup.route-tooltip').forEach(p => p.remove());
|
||||
const props = feature.properties;
|
||||
const duration = useMetric ? formatSecondsToHuman(props.duration) : formatSecondsToAmerican(props.duration);
|
||||
const distance = useMetric ? formatMetersToHuman(props.distance, true) : formatMetersToMiles(props.distance);
|
||||
const arrival = new Date(Date.now() + props.duration * 1000);
|
||||
const isLong = props.duration > 24 * 3600;
|
||||
const timeStr = arrival.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
||||
const month = arrival.toLocaleString([], { month: 'long' });
|
||||
const day = arrival.getDate();
|
||||
const year = arrival.getFullYear();
|
||||
const suffix = getOrdinalSuffix(day);
|
||||
const eta = isLong ? `${month} ${day}${suffix}, ${year}, ${timeStr}` : timeStr;
|
||||
const tooltip = document.createElement('div');
|
||||
tooltip.className = 'custom-tooltip';
|
||||
tooltip.style.whiteSpace = 'nowrap';
|
||||
tooltip.innerHTML = `
|
||||
<div class="tooltip-row"><span class="emoji">🛣️</span><span class="label">Distance:</span><span class="value">${distance}</span></div>
|
||||
<div class="tooltip-row"><span class="emoji">⌛</span><span class="label">Duration:</span><span class="value">${duration}</span></div>
|
||||
<div class="tooltip-row"><span class="emoji">🕗</span><span class="label">ETA:</span><span class="value">${eta}</span></div>
|
||||
`;
|
||||
new mapboxgl.Popup({ closeButton: false, closeOnClick: true, className: 'route-tooltip', maxWidth: 'none' })
|
||||
.setLngLat(e.lngLat)
|
||||
.setDOMContent(tooltip)
|
||||
.addTo(map);
|
||||
};
|
||||
|
||||
map.on('click', clickLayerId, (e) => {
|
||||
e.preventDefault();
|
||||
const routeId = feature.properties.routeId;
|
||||
const route = routes.find((r, i) => (i === 0 ? 'main' : `alt-${i}`) === routeId);
|
||||
onRouteSelect(route, routeId);
|
||||
highlightRoute(map, routes, routeId);
|
||||
showTooltip(e);
|
||||
});
|
||||
map.on('mouseenter', clickLayerId, showTooltip);
|
||||
map.on('mouseleave', clickLayerId, () => {
|
||||
map.getCanvas().style.cursor = '';
|
||||
const id = safeGetId(getSelectedRouteId);
|
||||
highlightRoute(map, routes, id);
|
||||
document.querySelectorAll('.mapboxgl-popup').forEach(p => p.remove());
|
||||
});
|
||||
}
|
||||
|
||||
export function addRouteToMap(map, routes, start, dest, onRouteSelect, useMetric = true, getSelectedRouteId) {
|
||||
routes.forEach((route, idx) => {
|
||||
const routeId = idx === 0 ? 'main' : `alt-${idx}`;
|
||||
const sourceId = `route-${routeId}`;
|
||||
const layerId = `route-line-${routeId}`;
|
||||
const clickLayerId = `route-click-${routeId}`;
|
||||
const feature = {
|
||||
type: 'Feature',
|
||||
geometry: { type: 'LineString', coordinates: route.geometry.coordinates },
|
||||
properties: {
|
||||
congestion: route.legs[0].annotation.congestion,
|
||||
routeId,
|
||||
duration: route.duration,
|
||||
distance: route.distance
|
||||
}
|
||||
};
|
||||
addRouteSource(map, sourceId, feature);
|
||||
addRouteLayers(map, sourceId, layerId, clickLayerId, route);
|
||||
handleRouteEvents(map, clickLayerId, onRouteSelect, routes, useMetric, feature, getSelectedRouteId);
|
||||
});
|
||||
|
||||
map.once('idle', () => {
|
||||
const id = safeGetId(getSelectedRouteId);
|
||||
highlightRoute(map, routes, id);
|
||||
});
|
||||
|
||||
map.on('click', (e) => {
|
||||
setTimeout(() => {
|
||||
if (!e.defaultPrevented) {
|
||||
document.querySelectorAll('.mapboxgl-popup').forEach(p => p.remove());
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
|
||||
const padding = window.innerWidth < 600 ? 100 : 250;
|
||||
map.fitBounds([start, dest], { padding, duration: 1000 });
|
||||
}
|
||||
|
||||
export async function getCoordinatesFromSearch(searchValue, mapboxPublic, searchContext = {}) {
|
||||
const params = new URLSearchParams({ access_token: mapboxPublic, q: searchValue });
|
||||
if (searchContext.language) params.set('language', searchContext.language);
|
||||
if (searchContext.country) params.set('country', searchContext.country);
|
||||
if (searchContext.proximity) params.set('proximity', searchContext.proximity);
|
||||
const response = await fetch(`https://api.mapbox.com/search/geocode/v6/forward?${params.toString()}`);
|
||||
const data = await response.json();
|
||||
return data.features?.[0]?.geometry?.coordinates;
|
||||
}
|
||||
|
||||
export async function getRoutes(from, to, mapboxPublic) {
|
||||
const url = `https://api.mapbox.com/directions/v5/mapbox/driving-traffic/${from};${to}?geometries=geojson&annotations=congestion&overview=full&alternatives=true&access_token=${mapboxPublic}`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
return data.routes;
|
||||
}
|
||||
|
||||
function buildGradientExpression(coords, congestion) {
|
||||
const count = congestion.length;
|
||||
if (count === 0 || coords.length < 2) {
|
||||
return ['interpolate', ['linear'], ['line-progress'], 0, '#ccc', 1, '#ccc'];
|
||||
}
|
||||
const stops = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
stops.push(i / (count - 1), congestionToColor(congestion[i] || 'unknown'));
|
||||
}
|
||||
return ['interpolate', ['linear'], ['line-progress'], ...stops];
|
||||
}
|
||||
|
||||
export function removeRouteFromMap(map) {
|
||||
if (!map || !map.getStyle || !map.getStyle()) return;
|
||||
const layers = map.getStyle().layers || [];
|
||||
layers.forEach(l => {
|
||||
if ((l.id.startsWith('route-line-') || l.id.startsWith('route-click-')) && map.getLayer(l.id)) {
|
||||
map.removeLayer(l.id);
|
||||
}
|
||||
});
|
||||
const sources = map.getStyle().sources || {};
|
||||
Object.keys(sources).forEach(id => {
|
||||
if (id.startsWith('route-') && map.getSource(id)) map.removeSource(id);
|
||||
});
|
||||
}
|
||||
|
||||
export function formatSecondsToHuman(s) {
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
return h > 0 ? `${h}h ${m} min` : `${m} min`;
|
||||
}
|
||||
|
||||
export function formatMetersToHuman(m, metric = true) {
|
||||
return metric ? (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m)} m`) : (m * 3.28084 >= 5280 ? `${((m * 3.28084) / 5280).toFixed(1)} mi` : `${Math.round(m * 3.28084)} ft`);
|
||||
}
|
||||
|
||||
export function formatSecondsToAmerican(s) {
|
||||
const mins = Math.round(s / 60);
|
||||
const h = Math.floor(mins / 60);
|
||||
const m = mins % 60;
|
||||
return h > 0 ? `${h} hr ${m} min` : `${m} min`;
|
||||
}
|
||||
|
||||
export function formatMetersToMiles(m) {
|
||||
const miles = m / 1609.34;
|
||||
return miles >= 0.1 ? `${miles.toFixed(1)} mi` : `${(miles * 5280).toFixed(0)} ft`;
|
||||
}
|
||||
|
||||
function congestionToColor(lvl) {
|
||||
const map = { low: '#2ecc71', moderate: '#f1c40f', heavy: '#e67e22', severe: '#e74c3c', unknown: '#2ecc71' };
|
||||
return map[lvl] || '#999';
|
||||
}
|
||||
|
||||
export function getOrdinalSuffix(n) {
|
||||
const s = ['th', 'st', 'nd', 'rd'];
|
||||
const v = n % 100;
|
||||
return s[(v - 20) % 10] || s[v] || s[0];
|
||||
}
|
||||
+1525
File diff suppressed because it is too large
Load Diff
+988
@@ -0,0 +1,988 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { escapeHtml, isGalaxyTunnel } from "/assets/js/utils.js"
|
||||
import { Modal } from "/assets/components/modal.js"
|
||||
import {
|
||||
buildRouteView,
|
||||
cameraVideoUrl,
|
||||
computeRouteStats,
|
||||
formatApproxDuration,
|
||||
getSegmentOptions,
|
||||
shouldUpgradeFromHeight,
|
||||
supportsLowQuality,
|
||||
groupRoutesForView,
|
||||
MAX_RENDERED_ROUTES,
|
||||
normalizeRoute,
|
||||
routeMetadataErrorMessage,
|
||||
routeViewRenderKey,
|
||||
} from "/assets/components/recordings/dashcam_routes_helpers.js"
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
error: null,
|
||||
routes: [],
|
||||
selectedRoute: null,
|
||||
searchQuery: "",
|
||||
sortOrder: "newest",
|
||||
showPreservedOnly: false,
|
||||
viewMode: "list",
|
||||
progress: 0,
|
||||
total: 0,
|
||||
deleteMode: null,
|
||||
isDeletingAll: false,
|
||||
})
|
||||
|
||||
let routesAbortController = null
|
||||
let routesRequestToken = 0
|
||||
let seenRouteNames = new Set()
|
||||
let overlay = null
|
||||
const routeLogsCache = new Map()
|
||||
const FULL_QUALITY_RETRIES = 2
|
||||
const FULL_QUALITY_RETRY_MS = 1000
|
||||
// Only ask for the full stream once the viewer settles, so scrubbing queues no remuxes.
|
||||
const FULL_QUALITY_SETTLE_MS = 1200
|
||||
|
||||
function routeLabel(route) {
|
||||
return route.displayName || route.displayDate || route.name
|
||||
}
|
||||
|
||||
function mergeRoutes(rawRoutes) {
|
||||
if (!Array.isArray(rawRoutes) || rawRoutes.length === 0) return
|
||||
const additions = []
|
||||
for (const rawRoute of rawRoutes) {
|
||||
const name = String(rawRoute?.name || "")
|
||||
if (!name || seenRouteNames.has(name)) continue
|
||||
seenRouteNames.add(name)
|
||||
additions.push(normalizeRoute(rawRoute))
|
||||
}
|
||||
// Worker completion order is irrelevant: buildRouteView sorts the list at render time.
|
||||
if (additions.length) state.routes = [...state.routes, ...additions]
|
||||
}
|
||||
|
||||
async function fetchRoutes() {
|
||||
const requestToken = ++routesRequestToken
|
||||
routesAbortController?.abort()
|
||||
const controller = new AbortController()
|
||||
routesAbortController = controller
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/routes", { signal: controller.signal })
|
||||
if (!response.ok || !response.body) throw new Error(`Route request failed (${response.status})`)
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
while (true) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
if (requestToken !== routesRequestToken) return
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const events = buffer.split(/\r?\n\r?\n/)
|
||||
buffer = events.pop() || ""
|
||||
for (const event of events) {
|
||||
const dataLines = event.split(/\r?\n/).filter(line => line.startsWith("data:"))
|
||||
if (!dataLines.length) continue
|
||||
try {
|
||||
const payload = JSON.parse(dataLines.map(line => line.slice(5).trimStart()).join("\n"))
|
||||
if (Number.isFinite(payload.progress)) state.progress = payload.progress
|
||||
if (Number.isFinite(payload.total)) state.total = payload.total
|
||||
mergeRoutes(payload.routes)
|
||||
} catch (error) {
|
||||
console.error("Failed to parse route stream event:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.name !== "AbortError") state.error = "Couldn't load routes. Try refreshing."
|
||||
} finally {
|
||||
if (requestToken === routesRequestToken) {
|
||||
state.loading = false
|
||||
if (routesAbortController === controller) routesAbortController = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
state.loading = true
|
||||
state.error = null
|
||||
state.routes = []
|
||||
state.progress = 0
|
||||
state.total = 0
|
||||
seenRouteNames = new Set()
|
||||
return fetchRoutes()
|
||||
}
|
||||
|
||||
function changeSortOrder(event) {
|
||||
const sortOrder = String(event.target.value || "")
|
||||
if (!["newest", "oldest", "longest", "shortest"].includes(sortOrder)) return
|
||||
state.sortOrder = sortOrder
|
||||
}
|
||||
|
||||
if (!isGalaxyTunnel()) refresh()
|
||||
|
||||
function openDialog(htmlString) {
|
||||
const dialog = document.createElement("div")
|
||||
dialog.className = "dialog-overlay"
|
||||
dialog.innerHTML = htmlString
|
||||
document.body.appendChild(dialog)
|
||||
return dialog
|
||||
}
|
||||
|
||||
function closeDialog(dialog) {
|
||||
dialog?.remove()
|
||||
}
|
||||
|
||||
function replaceRoute(updatedRoute) {
|
||||
// Rows bind to this exact object, so replacing it would strand them on the stale one.
|
||||
const existing = state.routes.find(route => route.name === updatedRoute.name)
|
||||
if (existing) Object.assign(existing, updatedRoute)
|
||||
const selected = state.selectedRoute
|
||||
if (selected?.name === updatedRoute.name && selected !== existing) {
|
||||
Object.assign(selected, updatedRoute)
|
||||
}
|
||||
// Reassigning state.routes notifies ArrowJS to re-render views that depend on the routes array
|
||||
state.routes = [...state.routes]
|
||||
}
|
||||
|
||||
async function deleteRoute(route) {
|
||||
const dialog = openDialog(`
|
||||
<div class="dialog-box">
|
||||
<p>Delete “${escapeHtml(routeLabel(route))}”?</p>
|
||||
<div class="dialog-buttons">
|
||||
<button class="btn-cancel" type="button">Cancel</button>
|
||||
<button class="btn-del" type="button">Delete</button>
|
||||
</div>
|
||||
</div>`)
|
||||
dialog.querySelector(".btn-cancel").onclick = () => closeDialog(dialog)
|
||||
dialog.querySelector(".btn-del").onclick = async () => {
|
||||
const response = await fetch(`/api/routes/${route.name}`, { method: "DELETE" })
|
||||
if (!response.ok) {
|
||||
showSnackbar("Delete failed...", "error")
|
||||
return
|
||||
}
|
||||
closeDialog(dialog)
|
||||
closeOverlay()
|
||||
await refresh()
|
||||
showSnackbar("Route deleted!")
|
||||
}
|
||||
}
|
||||
|
||||
async function resetRouteName(route, dialog) {
|
||||
const response = await fetch("/api/routes/reset_name", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: route.name }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
showSnackbar("Resetting name failed...", "error")
|
||||
return
|
||||
}
|
||||
|
||||
const { timestamp } = await response.json()
|
||||
const updatedRoute = normalizeRoute({ ...route, timestamp, isCustomName: false })
|
||||
replaceRoute(updatedRoute)
|
||||
closeDialog(dialog)
|
||||
const title = overlay?.querySelector(".media-player-title-text")
|
||||
if (title) title.textContent = routeLabel(updatedRoute)
|
||||
showSnackbar("Route name reset!")
|
||||
}
|
||||
|
||||
async function renameRoute(route) {
|
||||
const dialog = openDialog(`
|
||||
<div class="dialog-box">
|
||||
<p>Rename “${escapeHtml(routeLabel(route))}”</p>
|
||||
<input class="rn-input" value="${escapeHtml(routeLabel(route))}" aria-label="New route name">
|
||||
<div class="dialog-buttons">
|
||||
<button class="btn-cancel" type="button">Cancel</button>
|
||||
<button class="btn-reset" type="button">Reset</button>
|
||||
<button class="btn-save" type="button">Save</button>
|
||||
</div>
|
||||
</div>`)
|
||||
dialog.querySelector(".btn-cancel").onclick = () => closeDialog(dialog)
|
||||
dialog.querySelector(".btn-reset").onclick = () => resetRouteName(route, dialog)
|
||||
dialog.querySelector(".btn-save").onclick = async () => {
|
||||
const newName = dialog.querySelector(".rn-input").value.trim()
|
||||
if (!newName) return
|
||||
const response = await fetch("/api/routes/rename", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ old: route.name, new: newName }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
showSnackbar("Rename failed...", "error")
|
||||
return
|
||||
}
|
||||
|
||||
const payload = await response.json().catch(() => ({}))
|
||||
const savedName = payload.name || newName
|
||||
const updatedRoute = normalizeRoute({ ...route, timestamp: savedName, isCustomName: true })
|
||||
replaceRoute(updatedRoute)
|
||||
closeDialog(dialog)
|
||||
const title = overlay?.querySelector(".media-player-title-text")
|
||||
if (title) title.textContent = savedName
|
||||
showSnackbar("Route renamed!")
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (!bytes) return "0 MB"
|
||||
const megabytes = bytes / 1e6
|
||||
return megabytes >= 1000 ? `${(megabytes / 1000).toFixed(2)} GB` : `${megabytes.toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function openLogsDialog(route, logsButton, getCachedLogs, setCachedLogs) {
|
||||
const logsDialog = openDialog(`
|
||||
<section class="dialog-box route-logs-dialog" role="dialog" aria-modal="true" aria-labelledby="route-logs-title">
|
||||
<header class="route-logs-toolbar">
|
||||
<div><p class="route-logs-eyebrow">Route data</p><h2 id="route-logs-title">Full logs</h2></div>
|
||||
<button class="route-logs-close" type="button" aria-label="Close full logs">×</button>
|
||||
</header>
|
||||
<div class="route-logs-content" aria-live="polite"><p class="route-logs-message">Looking for full logs…</p></div>
|
||||
</section>`)
|
||||
const content = logsDialog.querySelector(".route-logs-content")
|
||||
const closeButton = logsDialog.querySelector(".route-logs-close")
|
||||
const closeLogsDialog = () => {
|
||||
document.removeEventListener("keydown", handleKeydown)
|
||||
closeDialog(logsDialog)
|
||||
logsButton?.focus()
|
||||
}
|
||||
const handleKeydown = event => { if (event.key === "Escape") closeLogsDialog() }
|
||||
closeButton.onclick = closeLogsDialog
|
||||
logsDialog.addEventListener("click", event => { if (event.target === logsDialog) closeLogsDialog() })
|
||||
document.addEventListener("keydown", handleKeydown)
|
||||
closeButton.focus()
|
||||
|
||||
const renderLogs = data => {
|
||||
content.innerHTML = `
|
||||
<div class="route-logs-summary">
|
||||
<div><strong>${data.segments.length} segment${data.segments.length === 1 ? "" : "s"}</strong><span>${formatBytes(data.totalBytes)} total download</span></div>
|
||||
<a class="route-logs-download-all" href="/api/routes/${route.name}/logs/download" download>Download all <span>.tar</span></a>
|
||||
</div>
|
||||
<ul class="route-logs-list">
|
||||
${data.segments.map(segment => `<li>
|
||||
<div class="route-log-details"><strong>Segment ${Number(segment.segmentNum)}</strong><span>${formatBytes(segment.bytes)} · ${escapeHtml(segment.filename)}</span></div>
|
||||
<a class="route-log-download" href="${escapeHtml(segment.url)}" download>Download</a>
|
||||
</li>`).join("")}
|
||||
</ul>`
|
||||
}
|
||||
|
||||
const cachedLogs = getCachedLogs?.()
|
||||
if (cachedLogs) {
|
||||
renderLogs(cachedLogs)
|
||||
return
|
||||
}
|
||||
|
||||
fetch(`/api/routes/${route.name}/logs`)
|
||||
.then(async response => ({ response, data: await response.json() }))
|
||||
.then(({ response, data }) => {
|
||||
if (!response.ok) {
|
||||
if (content.isConnected) content.innerHTML = `<p class="route-logs-message route-logs-error">${escapeHtml(data.error || "Could not read logs.")}</p>`
|
||||
return
|
||||
}
|
||||
setCachedLogs?.(data)
|
||||
if (content.isConnected) renderLogs(data)
|
||||
})
|
||||
.catch(error => {
|
||||
if (content.isConnected) content.innerHTML = `<p class="route-logs-message route-logs-error">Could not reach the device: ${escapeHtml(error.message)}</p>`
|
||||
})
|
||||
}
|
||||
|
||||
function openLogsFromRow(route, event) {
|
||||
const button = event.currentTarget
|
||||
openLogsDialog(
|
||||
route,
|
||||
button,
|
||||
() => routeLogsCache.get(route.name) || null,
|
||||
value => { routeLogsCache.set(route.name, value) },
|
||||
)
|
||||
}
|
||||
|
||||
async function openOverlay(route) {
|
||||
if (overlay) return
|
||||
overlay = document.createElement("div")
|
||||
overlay.className = "media-player-overlay dashcam-player-overlay"
|
||||
overlay.innerHTML = `
|
||||
<section class="media-player-content dashcam-player" role="dialog" aria-modal="true" aria-label="Route player">
|
||||
<header class="dashcam-player-header">
|
||||
<div class="dashcam-player-heading">
|
||||
<p class="dashcam-player-eyebrow">Dashcam route</p>
|
||||
<div class="dashcam-player-title-row">
|
||||
<h2 class="media-player-title-text">${escapeHtml(routeLabel(route))}</h2>
|
||||
<button class="dashcam-title-rename action-rename" type="button" title="Rename route" aria-label="Rename route"><i class="bi bi-pencil"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="dashcam-player-close" type="button" aria-label="Close player">×</button>
|
||||
</header>
|
||||
<div class="dashcam-video-shell">
|
||||
<video class="dashcam-video active" controls muted playsinline preload="metadata"></video>
|
||||
<video class="dashcam-video staging" muted playsinline preload="none"></video>
|
||||
<div class="dashcam-player-state" role="status">Loading route metadata…</div>
|
||||
</div>
|
||||
<div class="dashcam-player-toolbar">
|
||||
<div class="dashcam-camera-selector" aria-label="Camera selector">
|
||||
<button class="camera-button" data-camera="forward" type="button" disabled hidden>Forward</button>
|
||||
<button class="camera-button" data-camera="wide" type="button" disabled hidden>Wide</button>
|
||||
<button class="camera-button" data-camera="driver" type="button" disabled hidden>Driver</button>
|
||||
</div>
|
||||
<div class="dashcam-segment-bar" hidden>
|
||||
<button class="segment-step action-prev-segment" type="button" title="Previous segment (Shift + \u2190)" aria-label="Previous segment"><i class="bi bi-skip-start-fill"></i></button>
|
||||
<select class="segment-select" aria-label="Jump to segment"></select>
|
||||
<button class="segment-step action-next-segment" type="button" title="Next segment (Shift + \u2192)" aria-label="Next segment"><i class="bi bi-skip-end-fill"></i></button>
|
||||
</div>
|
||||
<div class="dashcam-player-actions">
|
||||
<button class="action-download" type="button" disabled title="Download route" aria-label="Download route"><i class="bi bi-download"></i></button>
|
||||
<button class="action-logs" type="button" title="View & download logs" aria-label="View and download logs"><i class="bi bi-file-earmark-arrow-down"></i></button>
|
||||
<button class="action-delete" type="button" title="Delete route" aria-label="Delete route"><i class="bi bi-trash"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</section>`
|
||||
document.body.appendChild(overlay)
|
||||
|
||||
const [videoA, videoB] = overlay.querySelectorAll(".dashcam-video")
|
||||
let activeVideo = videoA
|
||||
let stagingVideo = videoB
|
||||
const videoShell = overlay.querySelector(".dashcam-video-shell")
|
||||
const playerState = overlay.querySelector(".dashcam-player-state")
|
||||
const segmentBar = overlay.querySelector(".dashcam-segment-bar")
|
||||
const segmentSelect = overlay.querySelector(".segment-select")
|
||||
const prevSegmentButton = overlay.querySelector(".action-prev-segment")
|
||||
const nextSegmentButton = overlay.querySelector(".action-next-segment")
|
||||
const downloadButton = overlay.querySelector(".action-download")
|
||||
const logsButton = overlay.querySelector(".action-logs")
|
||||
const cameraButtons = [...overlay.querySelectorAll(".camera-button")]
|
||||
let segments = []
|
||||
let current = 0
|
||||
let selectedCamera = null
|
||||
let logsData = null
|
||||
let showingPreview = false
|
||||
let wantsPlayback = true
|
||||
let qualityToken = 0
|
||||
let upgradeController = null
|
||||
let upgradeTimer = null
|
||||
let isUpgrading = false
|
||||
|
||||
const setPlayerMessage = (message, isError = false) => {
|
||||
playerState.textContent = message
|
||||
playerState.hidden = !message
|
||||
playerState.classList.toggle("error", isError)
|
||||
}
|
||||
const syncSegmentControls = () => {
|
||||
segmentSelect.value = String(current)
|
||||
segmentSelect.disabled = segments.length < 2
|
||||
prevSegmentButton.disabled = current <= 0
|
||||
nextSegmentButton.disabled = current >= segments.length - 1
|
||||
}
|
||||
const buildSegmentPicker = () => {
|
||||
segmentSelect.innerHTML = getSegmentOptions(segments)
|
||||
.map(option => `<option value="${option.index}">${escapeHtml(option.label)}</option>`)
|
||||
.join("")
|
||||
segmentBar.hidden = !segments.length
|
||||
}
|
||||
|
||||
const cancelUpgrade = () => {
|
||||
qualityToken += 1
|
||||
isUpgrading = false
|
||||
clearTimeout(upgradeTimer)
|
||||
upgradeTimer = null
|
||||
upgradeController?.abort()
|
||||
upgradeController = null
|
||||
stagingVideo.pause()
|
||||
stagingVideo.removeAttribute("src")
|
||||
stagingVideo.controls = false
|
||||
stagingVideo.load()
|
||||
}
|
||||
|
||||
const performSeamlessUpgrade = (fullUrl, token) => {
|
||||
if (token !== qualityToken || !showingPreview || !overlay) return
|
||||
isUpgrading = true
|
||||
|
||||
stagingVideo.muted = activeVideo.muted
|
||||
stagingVideo.volume = activeVideo.volume
|
||||
stagingVideo.playbackRate = activeVideo.playbackRate
|
||||
stagingVideo.src = fullUrl
|
||||
stagingVideo.preload = "auto"
|
||||
stagingVideo.load()
|
||||
|
||||
const cleanupStaging = () => {
|
||||
stagingVideo.removeEventListener("loadedmetadata", onMetadata)
|
||||
stagingVideo.removeEventListener("error", onStagingError)
|
||||
}
|
||||
|
||||
const onStagingError = () => {
|
||||
cleanupStaging()
|
||||
if (token !== qualityToken) return
|
||||
isUpgrading = false
|
||||
showingPreview = false
|
||||
}
|
||||
|
||||
const onMetadata = () => {
|
||||
if (token !== qualityToken || !showingPreview || !overlay) {
|
||||
cleanupStaging()
|
||||
return
|
||||
}
|
||||
|
||||
const syncAndSwap = () => {
|
||||
if (token !== qualityToken || !showingPreview || !overlay) {
|
||||
cleanupStaging()
|
||||
return
|
||||
}
|
||||
|
||||
const applySwap = () => {
|
||||
if (token !== qualityToken || !showingPreview || !overlay) {
|
||||
cleanupStaging()
|
||||
return
|
||||
}
|
||||
cleanupStaging()
|
||||
|
||||
const targetTime = Number.isFinite(activeVideo.currentTime) ? activeVideo.currentTime : 0
|
||||
const isPlaying = !activeVideo.paused && !activeVideo.ended
|
||||
|
||||
stagingVideo.muted = activeVideo.muted
|
||||
stagingVideo.volume = activeVideo.volume
|
||||
stagingVideo.playbackRate = activeVideo.playbackRate
|
||||
|
||||
if (Math.abs(stagingVideo.currentTime - targetTime) > 0.15) {
|
||||
try {
|
||||
stagingVideo.currentTime = targetTime
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (isPlaying && stagingVideo.paused) {
|
||||
stagingVideo.play().catch(() => {})
|
||||
} else if (!isPlaying && !stagingVideo.paused) {
|
||||
stagingVideo.pause()
|
||||
}
|
||||
|
||||
activeVideo.classList.remove("active")
|
||||
activeVideo.classList.add("staging")
|
||||
activeVideo.controls = false
|
||||
|
||||
stagingVideo.classList.remove("staging")
|
||||
stagingVideo.classList.add("active")
|
||||
// Keep native controls enabled across the quality swap so touch browsers
|
||||
// can reveal them again after their normal auto-hide.
|
||||
stagingVideo.controls = true
|
||||
|
||||
const oldActive = activeVideo
|
||||
activeVideo = stagingVideo
|
||||
stagingVideo = oldActive
|
||||
|
||||
stagingVideo.pause()
|
||||
stagingVideo.removeAttribute("src")
|
||||
stagingVideo.load()
|
||||
|
||||
showingPreview = false
|
||||
isUpgrading = false
|
||||
setPlayerMessage("")
|
||||
}
|
||||
|
||||
const isPlaying = !activeVideo.paused && !activeVideo.ended
|
||||
if (isPlaying) {
|
||||
stagingVideo.play().then(() => {
|
||||
if ("requestVideoFrameCallback" in stagingVideo) {
|
||||
stagingVideo.requestVideoFrameCallback(() => applySwap())
|
||||
} else {
|
||||
stagingVideo.addEventListener("timeupdate", applySwap, { once: true })
|
||||
}
|
||||
}).catch(() => {
|
||||
applySwap()
|
||||
})
|
||||
} else {
|
||||
if ("requestVideoFrameCallback" in stagingVideo) {
|
||||
stagingVideo.requestVideoFrameCallback(() => applySwap())
|
||||
} else {
|
||||
applySwap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const playbackTime = Number.isFinite(activeVideo.currentTime) ? activeVideo.currentTime : 0
|
||||
if (playbackTime > 0) {
|
||||
stagingVideo.addEventListener("seeked", syncAndSwap, { once: true })
|
||||
try {
|
||||
stagingVideo.currentTime = Math.min(playbackTime, Number.isFinite(stagingVideo.duration) ? stagingVideo.duration : playbackTime)
|
||||
} catch (_) {
|
||||
syncAndSwap()
|
||||
}
|
||||
} else {
|
||||
syncAndSwap()
|
||||
}
|
||||
}
|
||||
|
||||
stagingVideo.addEventListener("loadedmetadata", onMetadata, { once: true })
|
||||
stagingVideo.addEventListener("error", onStagingError, { once: true })
|
||||
}
|
||||
|
||||
// Request the real stream behind the playing preview without interrupting playback.
|
||||
const requestFullQuality = (segmentUrl, camera, attempt = 0) => {
|
||||
const token = ++qualityToken
|
||||
upgradeController?.abort()
|
||||
const controller = new AbortController()
|
||||
upgradeController = controller
|
||||
const fullUrl = cameraVideoUrl(segmentUrl, camera)
|
||||
const stillCurrent = () =>
|
||||
token === qualityToken && showingPreview && segments[current] === segmentUrl && selectedCamera === camera && Boolean(overlay)
|
||||
|
||||
fetch(fullUrl, { method: "HEAD", signal: controller.signal })
|
||||
.then(response => {
|
||||
if (!stillCurrent()) return
|
||||
if (upgradeController === controller) upgradeController = null
|
||||
if (response.ok) {
|
||||
performSeamlessUpgrade(fullUrl, token)
|
||||
return
|
||||
}
|
||||
if (response.status === 503 && attempt < FULL_QUALITY_RETRIES) {
|
||||
upgradeTimer = setTimeout(() => {
|
||||
if (stillCurrent()) requestFullQuality(segmentUrl, camera, attempt + 1)
|
||||
}, FULL_QUALITY_RETRY_MS)
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (upgradeController === controller) upgradeController = null
|
||||
if (error?.name !== "AbortError") console.error("Could not prepare full-quality route video:", error)
|
||||
})
|
||||
}
|
||||
|
||||
const scheduleUpgrade = (segmentUrl, camera) => {
|
||||
cancelUpgrade()
|
||||
upgradeTimer = setTimeout(() => {
|
||||
if (!showingPreview || segments[current] !== segmentUrl || selectedCamera !== camera) return
|
||||
requestFullQuality(segmentUrl, camera)
|
||||
}, FULL_QUALITY_SETTLE_MS)
|
||||
}
|
||||
|
||||
const loadSegment = (autoplay, { message, preview } = {}) => {
|
||||
const segmentUrl = segments[current]
|
||||
const camera = selectedCamera
|
||||
if (!segmentUrl || !camera) return
|
||||
cancelUpgrade()
|
||||
wantsPlayback = autoplay
|
||||
showingPreview = preview === undefined ? supportsLowQuality(camera) : preview
|
||||
// qcamera.ts scales the complete road frame to 526x330. Keep that same mapping
|
||||
// after the full stream arrives so its slightly wider aspect ratio is not cropped.
|
||||
videoShell.classList.toggle("qcamera-framing", showingPreview)
|
||||
if (message) setPlayerMessage(message)
|
||||
|
||||
stagingVideo.pause()
|
||||
stagingVideo.removeAttribute("src")
|
||||
stagingVideo.classList.remove("active")
|
||||
stagingVideo.classList.add("staging")
|
||||
stagingVideo.controls = false
|
||||
|
||||
activeVideo.classList.remove("staging")
|
||||
activeVideo.classList.add("active")
|
||||
activeVideo.controls = true
|
||||
activeVideo.src = cameraVideoUrl(segmentUrl, camera, showingPreview ? "low" : undefined)
|
||||
activeVideo.load()
|
||||
if (autoplay) activeVideo.play().catch(() => {})
|
||||
}
|
||||
|
||||
const playCurrentSegment = (autoplay = true) => {
|
||||
if (!segments[current] || !selectedCamera) return
|
||||
syncSegmentControls()
|
||||
loadSegment(autoplay)
|
||||
}
|
||||
const goToSegment = index => {
|
||||
if (!segments.length) return
|
||||
const target = Math.min(Math.max(index, 0), segments.length - 1)
|
||||
if (target === current) {
|
||||
syncSegmentControls()
|
||||
return
|
||||
}
|
||||
const keepPlaying = activeVideo.ended || (!activeVideo.paused && !activeVideo.error)
|
||||
current = target
|
||||
playCurrentSegment(keepPlaying)
|
||||
}
|
||||
overlay._cancelUpgrade = cancelUpgrade
|
||||
|
||||
const closeOnEscape = event => {
|
||||
if (document.querySelector(".route-logs-dialog")) return
|
||||
if (event.key === "Escape") {
|
||||
closeOverlay()
|
||||
return
|
||||
}
|
||||
if (!event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
goToSegment(current - 1)
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
goToSegment(current + 1)
|
||||
}
|
||||
}
|
||||
|
||||
overlay.addEventListener("click", event => { if (event.target === overlay) closeOverlay() })
|
||||
document.addEventListener("keydown", closeOnEscape)
|
||||
overlay._closeOnEscape = closeOnEscape
|
||||
overlay.querySelector(".dashcam-player-close").onclick = closeOverlay
|
||||
overlay.querySelector(".action-delete").onclick = () => deleteRoute(state.selectedRoute || route)
|
||||
overlay.querySelector(".action-rename").onclick = () => renameRoute(state.selectedRoute || route)
|
||||
|
||||
logsButton.onclick = () => openLogsDialog(route, logsButton, () => logsData, value => { logsData = value })
|
||||
downloadButton.onclick = () => {
|
||||
if (!selectedCamera) return
|
||||
const link = document.createElement("a")
|
||||
link.href = `/video/${route.name}/combined?camera=${encodeURIComponent(selectedCamera)}`
|
||||
link.download = `${routeLabel(state.selectedRoute || route)}-${selectedCamera}.mp4`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
}
|
||||
|
||||
const handleLoadedMetadata = event => {
|
||||
if (event.target !== activeVideo) return
|
||||
if (!showingPreview) return
|
||||
if (shouldUpgradeFromHeight(activeVideo.videoHeight)) {
|
||||
scheduleUpgrade(segments[current], selectedCamera)
|
||||
} else {
|
||||
showingPreview = false
|
||||
}
|
||||
}
|
||||
const handleLoadedData = event => {
|
||||
if (event.target === activeVideo) setPlayerMessage("")
|
||||
}
|
||||
const handlePlaying = event => {
|
||||
if (event.target === activeVideo) setPlayerMessage("")
|
||||
}
|
||||
const handleWaiting = () => {}
|
||||
const handleError = event => {
|
||||
if (event.target !== activeVideo) return
|
||||
// A dead preview drops through to the real stream rather than showing an error.
|
||||
if (showingPreview) {
|
||||
showingPreview = false
|
||||
cancelUpgrade()
|
||||
loadSegment(wantsPlayback, { preview: false })
|
||||
return
|
||||
}
|
||||
setPlayerMessage("This segment could not be played.", true)
|
||||
}
|
||||
const handleEnded = event => {
|
||||
if (event.target === activeVideo) goToSegment(current + 1)
|
||||
}
|
||||
const handleSeeking = event => {
|
||||
if (event.target !== activeVideo) return
|
||||
if (isUpgrading && stagingVideo.readyState >= 1) {
|
||||
try {
|
||||
stagingVideo.currentTime = activeVideo.currentTime
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
const handlePause = event => {
|
||||
if (event.target !== activeVideo) return
|
||||
if (isUpgrading && !stagingVideo.paused) stagingVideo.pause()
|
||||
}
|
||||
const handlePlay = event => {
|
||||
if (event.target !== activeVideo) return
|
||||
if (isUpgrading && stagingVideo.paused && stagingVideo.readyState >= 3) {
|
||||
stagingVideo.play().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
const bindVideoEvents = el => {
|
||||
el.addEventListener("loadedmetadata", handleLoadedMetadata)
|
||||
el.addEventListener("loadeddata", handleLoadedData)
|
||||
el.addEventListener("playing", handlePlaying)
|
||||
el.addEventListener("waiting", handleWaiting)
|
||||
el.addEventListener("error", handleError)
|
||||
el.addEventListener("ended", handleEnded)
|
||||
el.addEventListener("seeking", handleSeeking)
|
||||
el.addEventListener("pause", handlePause)
|
||||
el.addEventListener("play", handlePlay)
|
||||
}
|
||||
bindVideoEvents(videoA)
|
||||
bindVideoEvents(videoB)
|
||||
|
||||
prevSegmentButton.onclick = () => goToSegment(current - 1)
|
||||
nextSegmentButton.onclick = () => goToSegment(current + 1)
|
||||
segmentSelect.onchange = () => goToSegment(Number(segmentSelect.value))
|
||||
|
||||
for (const button of cameraButtons) {
|
||||
button.addEventListener("click", () => {
|
||||
if (button.disabled || button.dataset.camera === selectedCamera || !segments[current]) return
|
||||
selectedCamera = button.dataset.camera
|
||||
cameraButtons.forEach(candidate => candidate.classList.toggle("active", candidate === button))
|
||||
const playbackTime = Number.isFinite(activeVideo.currentTime) ? activeVideo.currentTime : 0
|
||||
const shouldResume = !activeVideo.paused && !activeVideo.ended
|
||||
activeVideo.addEventListener("loadedmetadata", () => {
|
||||
if (playbackTime > 0) {
|
||||
try {
|
||||
activeVideo.currentTime = Math.min(playbackTime, Number.isFinite(activeVideo.duration) ? activeVideo.duration : playbackTime)
|
||||
} catch (_) {}
|
||||
}
|
||||
}, { once: true })
|
||||
loadSegment(shouldResume, { message: "Switching camera…" })
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/routes/${route.name}`)
|
||||
const data = await response.json().catch(() => ({}))
|
||||
if (!response.ok) throw new Error(routeMetadataErrorMessage(response.status, data?.error))
|
||||
segments = Array.isArray(data.segment_urls) ? data.segment_urls.filter(url => typeof url === "string") : []
|
||||
const availableCameras = ["forward", "wide", "driver"].filter(camera => data.available_cameras?.includes(camera))
|
||||
if (!segments.length) throw new Error("No video segments are stored for this route")
|
||||
if (!availableCameras.length) throw new Error("No camera video is stored for this route")
|
||||
|
||||
selectedCamera = availableCameras.includes("forward") ? "forward" : availableCameras[0]
|
||||
for (const button of cameraButtons) {
|
||||
const available = availableCameras.includes(button.dataset.camera)
|
||||
button.hidden = !available
|
||||
button.disabled = !available
|
||||
button.classList.toggle("active", button.dataset.camera === selectedCamera)
|
||||
}
|
||||
downloadButton.disabled = false
|
||||
buildSegmentPicker()
|
||||
playCurrentSegment()
|
||||
} catch (error) {
|
||||
cameraButtons.forEach(button => { button.disabled = true })
|
||||
setPlayerMessage(error.message || "Could not load this route.", true)
|
||||
}
|
||||
}
|
||||
|
||||
function closeOverlay() {
|
||||
if (!overlay) return
|
||||
overlay._cancelUpgrade?.()
|
||||
document.removeEventListener("keydown", overlay._closeOnEscape)
|
||||
const videos = overlay.querySelectorAll("video")
|
||||
videos.forEach(v => {
|
||||
v.pause()
|
||||
v.removeAttribute("src")
|
||||
v.load()
|
||||
})
|
||||
overlay.remove()
|
||||
overlay = null
|
||||
state.selectedRoute = null
|
||||
}
|
||||
|
||||
async function togglePreserved(route, event) {
|
||||
event?.stopPropagation?.()
|
||||
const isPreserved = !route.is_preserved
|
||||
try {
|
||||
const response = await fetch(`/api/routes/${route.name}/preserve`, { method: isPreserved ? "POST" : "DELETE" })
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json()
|
||||
showSnackbar(errorData.error || "Failed to update preserved state...", "error")
|
||||
return
|
||||
}
|
||||
replaceRoute({ ...route, is_preserved: isPreserved })
|
||||
} catch (_) {
|
||||
showSnackbar("An error occurred...", "error")
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAllRoutes(includePreserved) {
|
||||
state.deleteMode = null
|
||||
state.isDeletingAll = true
|
||||
try {
|
||||
const response = await fetch(`/api/routes/delete_all?include_preserved=${includePreserved}`, { method: "DELETE" })
|
||||
const payload = await response.json().catch(() => ({}))
|
||||
if (!response.ok) throw new Error(payload.error || "Route deletion failed")
|
||||
await refresh()
|
||||
showSnackbar(payload.message || "Routes deleted!")
|
||||
} catch (error) {
|
||||
showSnackbar(error?.message || "An error occurred while deleting routes...", "error")
|
||||
} finally {
|
||||
state.isDeletingAll = false
|
||||
}
|
||||
}
|
||||
|
||||
function thumbnailFailed(event) {
|
||||
event.currentTarget.hidden = true
|
||||
event.currentTarget.parentElement?.classList.add("thumbnail-failed")
|
||||
}
|
||||
|
||||
export function RouteRecordings() {
|
||||
if (isGalaxyTunnel()) {
|
||||
return html`
|
||||
<div class="tunnel-notice">
|
||||
<div class="tunnel-notice-icon">🛰️</div>
|
||||
<h3 class="tunnel-notice-title">Dashcam Routes Unavailable via Galaxy</h3>
|
||||
<p class="tunnel-notice-body">Loading dashcam routes requires a direct connection.<br>Connect to your device's local network to use this feature.</p>
|
||||
</div>`
|
||||
}
|
||||
|
||||
if (state.selectedRoute && !overlay) openOverlay(state.selectedRoute)
|
||||
|
||||
return html`
|
||||
<div class="screen-recordings-wrapper dashcam-routes-wrapper">
|
||||
<section class="screen-recordings-widget dashcam-library">
|
||||
<header class="dashcam-library-header">
|
||||
<div class="dashcam-header-info">
|
||||
<p class="dashcam-library-eyebrow">Local recordings</p>
|
||||
<h1>Dashcam Routes</h1>
|
||||
${() => {
|
||||
const stats = computeRouteStats(state.routes)
|
||||
return html`<div class="dashcam-stats-bar"><span class="dashcam-stat-chip"><i class="bi bi-car-front-fill"></i> <strong>${stats.count}</strong> ${stats.count === 1 ? "drive" : "drives"}</span><span class="dashcam-stat-chip"><i class="bi bi-stopwatch-fill"></i> <strong>${stats.formattedDuration}</strong> total</span>${stats.preservedCount > 0 ? html`<span class="dashcam-stat-chip stat-chip-preserved"><i class="bi bi-heart-fill"></i> <strong>${stats.preservedCount}</strong> preserved</span>` : ""}</div>`
|
||||
}}
|
||||
</div>
|
||||
<div class="dashcam-header-controls">
|
||||
<button class="dashcam-refresh-button" type="button" @click="${refresh}" disabled="${() => state.loading || false}" title="Refresh routes">
|
||||
<i class="bi bi-arrow-clockwise"></i> Refresh
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="dashcam-toolbar">
|
||||
<div class="dashcam-search-box">
|
||||
<i class="bi bi-search dashcam-search-icon"></i>
|
||||
<input type="search" placeholder="Search route names, dates, or hash IDs..." aria-label="Search routes" value="${() => state.searchQuery}" @input="${event => { state.searchQuery = event.target.value }}">
|
||||
${() => state.searchQuery ? html`
|
||||
<button class="dashcam-search-clear" type="button" title="Clear search" @click="${() => { state.searchQuery = "" }}"><i class="bi bi-x"></i></button>
|
||||
` : ""}
|
||||
</div>
|
||||
<div class="dashcam-filter-group">
|
||||
<button class="${() => `dashcam-filter-pill ${!state.showPreservedOnly ? "active" : ""}`}" type="button" @click="${() => { state.showPreservedOnly = false }}">
|
||||
All Drives
|
||||
</button>
|
||||
<button class="${() => `dashcam-filter-pill ${state.showPreservedOnly ? "active" : ""}`}" type="button" @click="${() => { state.showPreservedOnly = true }}">
|
||||
<i class="bi bi-heart-fill"></i> Preserved
|
||||
</button>
|
||||
</div>
|
||||
<label class="dashcam-sort">
|
||||
<span>Sort</span>
|
||||
<select value="${() => state.sortOrder}" @input="${changeSortOrder}" @change="${changeSortOrder}">
|
||||
<option value="newest">Newest first</option>
|
||||
<option value="oldest">Oldest first</option>
|
||||
<option value="longest">Longest duration</option>
|
||||
<option value="shortest">Shortest duration</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="dashcam-view-toggle" aria-label="Layout view mode">
|
||||
<button class="${() => `dashcam-view-btn ${state.viewMode === "list" ? "active" : ""}`}" type="button" title="List View" @click="${() => { state.viewMode = "list" }}">
|
||||
<i class="bi bi-list-ul"></i>
|
||||
</button>
|
||||
<button class="${() => `dashcam-view-btn ${state.viewMode === "grid" ? "active" : ""}`}" type="button" title="Grid View" @click="${() => { state.viewMode = "grid" }}">
|
||||
<i class="bi bi-grid-fill"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${() => {
|
||||
const view = buildRouteView(state.routes, { preservedOnly: state.showPreservedOnly, searchQuery: state.searchQuery, sortOrder: state.sortOrder })
|
||||
const groups = groupRoutesForView(view.visible, state.sortOrder)
|
||||
const renderKey = routeViewRenderKey(view.visible, state.sortOrder, state.viewMode)
|
||||
const hasActiveSearch = Boolean(state.searchQuery.trim())
|
||||
|
||||
return html`
|
||||
${state.loading || hasActiveSearch ? html`
|
||||
<div class="dashcam-results-summary" aria-live="polite">
|
||||
${hasActiveSearch ? html`<span>${view.matching.length} matching drive${view.matching.length === 1 ? "" : "s"}</span>` : ""}
|
||||
${state.loading ? html`<span>Loading routes</span>` : ""}
|
||||
</div>
|
||||
` : ""}
|
||||
${state.error ? html`<p class="screen-recordings-message dashcam-error">${state.error}</p>` : ""}
|
||||
${state.isDeletingAll ? html`<p class="screen-recordings-message">Deleting routes…</p>` : ""}
|
||||
${!view.visible.length && state.loading ? html`<div class="dashcam-loading"><span></span><p>Finding local routes…</p></div>` : ""}
|
||||
${!view.visible.length && !state.loading && !state.isDeletingAll ? html`<div class="dashcam-empty-state"><i class="bi bi-camera-reels"></i><p>${state.routes.length ? "No routes match these filters." : "No routes found."}</p></div>` : ""}
|
||||
<div class="dashcam-date-groups" data-view-key="${renderKey}">
|
||||
${groups.map(group => html`
|
||||
<section class="dashcam-date-group">
|
||||
<div class="dashcam-date-group-header">
|
||||
<h2>${group.label}</h2>
|
||||
<span class="dashcam-date-group-count">${group.routes.length} ${group.routes.length === 1 ? "drive" : "drives"}</span>
|
||||
</div>
|
||||
${state.viewMode === "grid" ? html`<div class="screen-recordings-grid dashcam-routes-grid">
|
||||
${group.routes.map(route => html`
|
||||
<article class="${() => `recording-card dashcam-route-card ${route.is_preserved ? "is-preserved" : ""}`}" @click="${() => { state.selectedRoute = route }}">
|
||||
<div class="dashcam-card-top-bar">
|
||||
<button class="${() => `btn-route-action btn-preserve ${route.is_preserved ? "active" : ""}`}" type="button" aria-label="${() => route.is_preserved ? "Remove preservation" : "Preserve route"}" title="${() => route.is_preserved ? "Preserved (click to unpreserve)" : "Click to preserve"}" @click="${event => togglePreserved(route, event)}">
|
||||
<i class="${() => `bi ${route.is_preserved ? "bi-heart-fill" : "bi-heart"}`}"></i>
|
||||
</button>
|
||||
<span class="meta-pill id-pill" title="Route ID: ${route.name}"><i class="bi bi-hash"></i>${route.name.split("--").slice(1).join("--") || route.name}</span>
|
||||
</div>
|
||||
<div class="recording-preview-container dashcam-preview">
|
||||
<span class="dashcam-preview-fallback"><i class="bi bi-camera-video"></i><small>Preview unavailable</small></span>
|
||||
<img src="${route.png}" class="recording-preview" loading="lazy" alt="" @error="${thumbnailFailed}">
|
||||
<span class="dashcam-grid-play-overlay"><i class="bi bi-play-fill"></i></span>
|
||||
</div>
|
||||
<div class="dashcam-card-body">
|
||||
<div class="dashcam-route-title-row">
|
||||
<h3 title="${() => route.displayName}">${() => route.displayName}</h3>
|
||||
${() => route.isCustomName ? html`<span class="dashcam-custom-badge" title="Custom name"><i class="bi bi-tag-fill"></i></span>` : ""}
|
||||
</div>
|
||||
${() => route.isCustomName ? html`<p class="dashcam-card-date">${route.displayDate}</p>` : ""}
|
||||
<div class="dashcam-route-meta-pills">
|
||||
<span class="meta-pill duration-pill"><i class="bi bi-clock"></i> ${formatApproxDuration(route.approxDurationSeconds)}</span>
|
||||
<span class="meta-pill segments-pill"><i class="bi bi-collection-play"></i> ${route.segmentCount} seg</span>
|
||||
</div>
|
||||
<div class="dashcam-card-actions" @click="${event => event.stopPropagation()}">
|
||||
<button class="btn-route-action btn-play" type="button" title="Play route" @click="${() => { state.selectedRoute = route }}">
|
||||
<i class="bi bi-play-fill"></i> Play
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon" type="button" title="View logs" @click="${event => openLogsFromRow(route, event)}">
|
||||
<i class="bi bi-file-earmark-arrow-down"></i>
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon" type="button" title="Rename" @click="${() => renameRoute(route)}">
|
||||
<i class="bi bi-pencil"></i>
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon btn-danger-action" type="button" title="Delete" @click="${() => deleteRoute(route)}">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>`.key(route.name))}
|
||||
</div>` : html`<div class="dashcam-routes-list">
|
||||
${group.routes.map(route => html`
|
||||
<article class="${() => `dashcam-route-row ${route.is_preserved ? "is-preserved" : ""}`}" @click="${() => { state.selectedRoute = route }}">
|
||||
<div class="dashcam-mini-preview">
|
||||
<span class="dashcam-mini-fallback"><i class="bi bi-camera-video"></i></span>
|
||||
<img src="${route.png}" class="dashcam-mini-img" loading="lazy" alt="" @error="${thumbnailFailed}">
|
||||
<span class="dashcam-mini-play-overlay"><i class="bi bi-play-fill"></i></span>
|
||||
</div>
|
||||
<div class="dashcam-route-info">
|
||||
<div class="dashcam-route-title-row">
|
||||
<h3 class="dashcam-route-title" title="${() => route.displayName}">${() => route.displayName}</h3>
|
||||
${() => route.isCustomName ? html`<span class="dashcam-custom-badge" title="Custom name"><i class="bi bi-tag-fill"></i> Custom</span>` : ""}
|
||||
</div>
|
||||
${() => route.isCustomName ? html`<p class="dashcam-route-subdate"><i class="bi bi-calendar3"></i> ${route.displayDate}</p>` : ""}
|
||||
<div class="dashcam-route-meta-pills">
|
||||
<span class="meta-pill duration-pill" title="Estimated duration"><i class="bi bi-clock"></i> ${formatApproxDuration(route.approxDurationSeconds)}</span>
|
||||
<span class="meta-pill segments-pill" title="Segments recorded"><i class="bi bi-collection-play"></i> ${route.segmentCount} segment${route.segmentCount === 1 ? "" : "s"}</span>
|
||||
${() => route.is_preserved ? html`<span class="meta-pill preserved-pill" title="Preserved from deletion"><i class="bi bi-heart-fill"></i> Preserved</span>` : ""}
|
||||
<span class="meta-pill id-pill" title="Route ID: ${route.name}"><i class="bi bi-hash"></i>${route.name.split("--").slice(1).join("--") || route.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashcam-route-actions" @click="${event => event.stopPropagation()}">
|
||||
<button class="btn-route-action btn-play" type="button" title="Play recording" @click="${() => { state.selectedRoute = route }}">
|
||||
<i class="bi bi-play-fill"></i> <span>Play</span>
|
||||
</button>
|
||||
<button class="${() => `btn-route-action btn-preserve ${route.is_preserved ? "active" : ""}`}" type="button" aria-label="${() => route.is_preserved ? "Remove preservation" : "Preserve route"}" title="${() => route.is_preserved ? "Preserved (click to unpreserve)" : "Click to preserve"}" @click="${event => togglePreserved(route, event)}">
|
||||
<i class="${() => `bi ${route.is_preserved ? "bi-heart-fill" : "bi-heart"}`}"></i>
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon" type="button" title="View & download logs" @click="${event => openLogsFromRow(route, event)}">
|
||||
<i class="bi bi-file-earmark-arrow-down"></i>
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon" type="button" title="Rename route" @click="${() => renameRoute(route)}">
|
||||
<i class="bi bi-pencil"></i>
|
||||
</button>
|
||||
<button class="btn-route-action btn-icon btn-danger-action" type="button" title="Delete route" @click="${() => deleteRoute(route)}">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</article>`.key(route.name))}
|
||||
</div>`}
|
||||
</section>`.key(group.key))}
|
||||
</div>
|
||||
${view.truncated ? html`<p class="screen-recordings-message">Showing the first ${MAX_RENDERED_ROUTES} of ${view.matching.length} matching routes.</p>` : ""}`
|
||||
}}
|
||||
|
||||
${() => state.routes.length ? html`
|
||||
<footer class="dashcam-danger-zone">
|
||||
<div class="dashcam-danger-copy"><strong>Delete local routes</strong><span>Keep preserved routes, or remove everything.</span></div>
|
||||
<div class="dashcam-danger-actions">
|
||||
<button class="delete-all-button delete-non-preserved-button" type="button" @click="${() => { state.deleteMode = "non-preserved" }}" disabled="${() => state.isDeletingAll || state.routes.every(route => route.is_preserved) || false}">${() => state.isDeletingAll ? "Deleting…" : "Delete Non-Preserved"}</button>
|
||||
<button class="delete-all-button" type="button" @click="${() => { state.deleteMode = "all" }}" disabled="${() => state.isDeletingAll || false}">${() => state.isDeletingAll ? "Deleting…" : "Delete All Including Preserved"}</button>
|
||||
</div>
|
||||
</footer>` : ""}
|
||||
</section>
|
||||
${() => state.deleteMode ? Modal({
|
||||
title: state.deleteMode === "all" ? "Delete All Routes, Including Preserved?" : "Delete All Non-Preserved Routes?",
|
||||
message: state.deleteMode === "all"
|
||||
? "This permanently deletes every local route, including preserved routes. This action cannot be undone."
|
||||
: "This permanently deletes every non-preserved local route. Preserved routes will be kept.",
|
||||
onConfirm: () => deleteAllRoutes(state.deleteMode === "all"),
|
||||
onCancel: () => { state.deleteMode = null },
|
||||
confirmText: state.deleteMode === "all" ? "Delete Everything" : "Delete Non-Preserved",
|
||||
}) : ""}
|
||||
</div>`
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
export const MAX_RENDERED_ROUTES = 250
|
||||
const SEARCH_MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
|
||||
|
||||
function validDate(value) {
|
||||
if (!value) return null
|
||||
const date = value instanceof Date ? new Date(value.getTime()) : new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? null : date
|
||||
}
|
||||
|
||||
export function normalizeRouteSearchText(value) {
|
||||
return String(value || "")
|
||||
.normalize("NFKD")
|
||||
.replace(/\p{M}/gu, "")
|
||||
.toLocaleLowerCase()
|
||||
.replace(/(\d+)(?:st|nd|rd|th)\b/g, "$1")
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim()
|
||||
}
|
||||
|
||||
export function formatRouteDate(value, locale) {
|
||||
const date = validDate(value)
|
||||
if (!date) return "Unknown date"
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
dateStyle: "long",
|
||||
timeStyle: "short",
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
export function normalizeRoute(route, locale) {
|
||||
const timestamp = route?.timestamp == null ? null : String(route.timestamp)
|
||||
const startedAtDate = validDate(route?.startedAt)
|
||||
const timestampDate = validDate(timestamp)
|
||||
const routeDate = startedAtDate || timestampDate
|
||||
const displayDate = formatRouteDate(routeDate, locale)
|
||||
const isCustomName = Boolean(route?.isCustomName) || Boolean(timestamp && !timestampDate)
|
||||
const displayName = isCustomName ? timestamp : displayDate
|
||||
const dateAliases = routeDate ? [
|
||||
new Intl.DateTimeFormat(locale, { dateStyle: "long" }).format(routeDate),
|
||||
new Intl.DateTimeFormat("en-US", { month: "long", day: "numeric", year: "numeric" }).format(routeDate),
|
||||
new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric" }).format(routeDate),
|
||||
`${routeDate.getMonth() + 1}/${routeDate.getDate()}/${routeDate.getFullYear()}`,
|
||||
`${routeDate.getFullYear()}-${routeDate.getMonth() + 1}-${routeDate.getDate()}`,
|
||||
] : []
|
||||
const timeAliases = routeDate ? [
|
||||
new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }).format(routeDate),
|
||||
new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", hour12: true }).format(routeDate),
|
||||
`${String(routeDate.getHours()).padStart(2, "0")}:${String(routeDate.getMinutes()).padStart(2, "0")}`,
|
||||
] : []
|
||||
|
||||
return {
|
||||
...route,
|
||||
name: String(route?.name || ""),
|
||||
timestamp,
|
||||
startedAt: route?.startedAt || null,
|
||||
isCustomName,
|
||||
displayDate,
|
||||
displayName,
|
||||
_startedAtMs: startedAtDate?.getTime() ?? timestampDate?.getTime() ?? null,
|
||||
_searchIndex: {
|
||||
ids: [normalizeRouteSearchText(route?.name)].filter(Boolean),
|
||||
titles: [normalizeRouteSearchText(isCustomName ? displayName : "")].filter(Boolean),
|
||||
dates: dateAliases.map(normalizeRouteSearchText).filter(Boolean),
|
||||
times: timeAliases.map(normalizeRouteSearchText).filter(Boolean),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function formatTotalDuration(seconds) {
|
||||
const totalMinutes = Math.max(0, Math.round(Number(seconds) / 60) || 0)
|
||||
if (totalMinutes < 1) return "0 min"
|
||||
if (totalMinutes < 60) return `${totalMinutes} min`
|
||||
const hours = Math.floor(totalMinutes / 60)
|
||||
const remaining = totalMinutes % 60
|
||||
return remaining > 0 ? `${hours}h ${remaining}m` : `${hours}h`
|
||||
}
|
||||
|
||||
export function computeRouteStats(routes = []) {
|
||||
const list = Array.isArray(routes) ? routes : []
|
||||
let totalDurationSeconds = 0
|
||||
let preservedCount = 0
|
||||
let totalSegments = 0
|
||||
|
||||
for (const route of list) {
|
||||
if (route) {
|
||||
if (Number.isFinite(route.approxDurationSeconds)) {
|
||||
totalDurationSeconds += Math.max(0, route.approxDurationSeconds)
|
||||
}
|
||||
if (route.is_preserved) {
|
||||
preservedCount += 1
|
||||
}
|
||||
if (Number.isFinite(route.segmentCount)) {
|
||||
totalSegments += Math.max(0, route.segmentCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
count: list.length,
|
||||
totalDurationSeconds,
|
||||
formattedDuration: formatTotalDuration(totalDurationSeconds),
|
||||
preservedCount,
|
||||
totalSegments,
|
||||
}
|
||||
}
|
||||
|
||||
export function sortRoutes(routes, sortOrder = "newest") {
|
||||
if (sortOrder === "longest" || sortOrder === "shortest") {
|
||||
const direction = sortOrder === "longest" ? -1 : 1
|
||||
return [...routes].sort((left, right) => {
|
||||
const leftDur = Number.isFinite(left?.approxDurationSeconds) ? left.approxDurationSeconds : -1
|
||||
const rightDur = Number.isFinite(right?.approxDurationSeconds) ? right.approxDurationSeconds : -1
|
||||
if (leftDur !== rightDur) return (leftDur - rightDur) * direction
|
||||
return String(left?.name || "").localeCompare(String(right?.name || ""))
|
||||
})
|
||||
}
|
||||
|
||||
const direction = sortOrder === "oldest" ? 1 : -1
|
||||
return [...routes].sort((left, right) => {
|
||||
const leftTime = left?._startedAtMs
|
||||
const rightTime = right?._startedAtMs
|
||||
if (leftTime == null && rightTime == null) return String(left?.name || "").localeCompare(String(right?.name || ""))
|
||||
if (leftTime == null) return 1
|
||||
if (rightTime == null) return -1
|
||||
if (leftTime !== rightTime) return (leftTime - rightTime) * direction
|
||||
return String(left?.name || "").localeCompare(String(right?.name || "")) * -direction
|
||||
})
|
||||
}
|
||||
|
||||
export function routeMatchesSearch(route, searchQuery) {
|
||||
const rawQuery = String(searchQuery || "").trim()
|
||||
const normalizedQuery = normalizeRouteSearchText(searchQuery)
|
||||
const queryTokens = normalizedQuery.split(" ").filter(Boolean)
|
||||
if (!queryTokens.length) return true
|
||||
|
||||
const fallbackIndex = {
|
||||
ids: [route?.name],
|
||||
titles: [route?.timestamp, route?.displayName],
|
||||
dates: [route?.displayDate],
|
||||
times: [route?.displayDate],
|
||||
}
|
||||
const searchIndex = route?._searchIndex || Object.fromEntries(
|
||||
Object.entries(fallbackIndex).map(([key, values]) => [key, values.map(normalizeRouteSearchText).filter(Boolean)]),
|
||||
)
|
||||
|
||||
const hasMonth = queryTokens.some(token => token.length >= 3 && SEARCH_MONTHS.some(month => month.startsWith(token)))
|
||||
const isDateQuery = hasMonth || /\d\s*[/-]\s*\d/.test(rawQuery) || /\d+(?:st|nd|rd|th)\b/i.test(rawQuery) || /^\d{4}$/.test(normalizedQuery)
|
||||
const isTimeQuery = /^\d{1,2}$/.test(normalizedQuery) || /\d\s*:\s*\d/.test(rawQuery) || queryTokens.some(token => token === "am" || token === "pm")
|
||||
const compactQuery = normalizedQuery.replaceAll(" ", "")
|
||||
const isHexQuery = /^[0-9a-f]+$/.test(compactQuery)
|
||||
const isIdQuery = rawQuery.includes("--") || (isHexQuery && (
|
||||
compactQuery.length >= 8 || (compactQuery.length >= 4 && /\d/.test(compactQuery) && /[a-f]/.test(compactQuery))
|
||||
))
|
||||
const valuesFor = key => Array.isArray(searchIndex[key]) ? searchIndex[key] : []
|
||||
const matchesValue = (value, dateValue = false) => {
|
||||
if (value.includes(normalizedQuery)) return true
|
||||
const searchTokens = value.split(" ").filter(Boolean)
|
||||
return queryTokens.every(queryToken => searchTokens.some(searchToken => {
|
||||
// In a date query, "20" is a day prefix, not a match for the year "2026".
|
||||
if (dateValue && /^\d{1,2}$/.test(queryToken) && /^\d{4}$/.test(searchToken)) return false
|
||||
return searchToken.startsWith(queryToken)
|
||||
}))
|
||||
}
|
||||
|
||||
return valuesFor("titles").some(value => matchesValue(value))
|
||||
|| (isDateQuery && valuesFor("dates").some(value => matchesValue(value, true)))
|
||||
|| (isTimeQuery && valuesFor("times").some(value => matchesValue(value)))
|
||||
|| (isIdQuery && valuesFor("ids").some(value => matchesValue(value)))
|
||||
}
|
||||
|
||||
export function buildRouteView(routes, options = {}) {
|
||||
const matching = sortRoutes(
|
||||
routes.filter(route => (!options.preservedOnly || route.is_preserved) && routeMatchesSearch(route, options.searchQuery)),
|
||||
options.sortOrder,
|
||||
)
|
||||
return {
|
||||
matching,
|
||||
visible: matching.slice(0, MAX_RENDERED_ROUTES),
|
||||
truncated: matching.length > MAX_RENDERED_ROUTES,
|
||||
}
|
||||
}
|
||||
|
||||
export function routeViewRenderKey(routes, sortOrder = "newest", viewMode = "list") {
|
||||
const routeNames = Array.isArray(routes) ? routes.map(route => String(route?.name || "")).join(",") : ""
|
||||
return `${viewMode}:${sortOrder}:${routeNames}`
|
||||
}
|
||||
|
||||
function localDayKey(date) {
|
||||
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`
|
||||
}
|
||||
|
||||
export function groupRoutesByDate(routes, now = new Date(), locale) {
|
||||
const today = validDate(now) || new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const yesterday = new Date(today)
|
||||
yesterday.setDate(yesterday.getDate() - 1)
|
||||
const groups = []
|
||||
const byKey = new Map()
|
||||
|
||||
for (const route of routes) {
|
||||
const routeDate = route?._startedAtMs == null ? null : new Date(route._startedAtMs)
|
||||
const key = routeDate ? localDayKey(routeDate) : "unknown"
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
let label = "Unknown date"
|
||||
if (routeDate) {
|
||||
if (key === localDayKey(today)) label = "Today"
|
||||
else if (key === localDayKey(yesterday)) label = "Yesterday"
|
||||
else label = new Intl.DateTimeFormat(locale, { dateStyle: "long" }).format(routeDate)
|
||||
}
|
||||
group = { key, label, routes: [] }
|
||||
byKey.set(key, group)
|
||||
groups.push(group)
|
||||
}
|
||||
group.routes.push(route)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
export function groupRoutesForView(routes, sortOrder = "newest", now, locale) {
|
||||
// Date headers would scramble a duration sort, so show one flat group instead.
|
||||
if (sortOrder === "longest" || sortOrder === "shortest") {
|
||||
const list = Array.isArray(routes) ? [...routes] : []
|
||||
if (!list.length) return []
|
||||
return [{ key: sortOrder, label: sortOrder === "longest" ? "Longest first" : "Shortest first", routes: list }]
|
||||
}
|
||||
return groupRoutesByDate(routes, now, locale)
|
||||
}
|
||||
|
||||
export function formatApproxDuration(seconds) {
|
||||
const minutes = Math.max(0, Math.round(Number(seconds) / 60) || 0)
|
||||
if (minutes < 1) return "Less than 1 min"
|
||||
if (minutes < 60) return `About ${minutes} min`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const remaining = minutes % 60
|
||||
return `About ${hours} hr${remaining ? ` ${remaining} min` : ""}`
|
||||
}
|
||||
|
||||
export function parseStoredSegmentNumber(segmentUrl) {
|
||||
const cleanPath = String(segmentUrl || "").split(/[?#]/, 1)[0]
|
||||
const match = cleanPath.match(/--(\d+)\/?$/)
|
||||
if (!match) return null
|
||||
const value = Number(match[1])
|
||||
return Number.isSafeInteger(value) ? value : null
|
||||
}
|
||||
|
||||
export function getSegmentStatus(segmentUrls, playbackIndex) {
|
||||
if (!Array.isArray(segmentUrls) || !Number.isInteger(playbackIndex) || playbackIndex < 0 || playbackIndex >= segmentUrls.length) return ""
|
||||
const segmentNumber = parseStoredSegmentNumber(segmentUrls[playbackIndex])
|
||||
if (segmentNumber == null) return ""
|
||||
return `Segment ${segmentNumber}`
|
||||
}
|
||||
|
||||
export function getSegmentOptions(segmentUrls) {
|
||||
if (!Array.isArray(segmentUrls)) return []
|
||||
return segmentUrls.map((_, index) => ({
|
||||
index,
|
||||
label: getSegmentStatus(segmentUrls, index) || `Clip ${index + 1}`,
|
||||
}))
|
||||
}
|
||||
|
||||
export function cameraVideoUrl(segmentUrl, camera, quality) {
|
||||
const separator = String(segmentUrl).includes("?") ? "&" : "?"
|
||||
const url = `${segmentUrl}${separator}camera=${encodeURIComponent(camera)}`
|
||||
return quality ? `${url}&quality=${encodeURIComponent(quality)}` : url
|
||||
}
|
||||
|
||||
export function routeMetadataErrorMessage(status, serverError) {
|
||||
if (status === 404) {
|
||||
return "This route is no longer available on this device. Its local video segments may have been deleted or moved."
|
||||
}
|
||||
const detail = String(serverError || "").trim()
|
||||
return detail || `Could not load route details (${status}).`
|
||||
}
|
||||
|
||||
// loggerd only writes qcamera.ts alongside the road camera.
|
||||
export function supportsLowQuality(camera) {
|
||||
return camera === "forward"
|
||||
}
|
||||
|
||||
// qcamera is 526x330. Only a positively taller frame proves the real stream is already
|
||||
// playing; an unknown height upgrades rather than stranding the viewer on the preview.
|
||||
export function shouldUpgradeFromHeight(height) {
|
||||
return !(Number.isFinite(height) && height > 400)
|
||||
}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
.button-row {
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
justify-content: center;
|
||||
margin-top: var(--margin-sm);
|
||||
}
|
||||
|
||||
.delete-all-button {
|
||||
background-color: var(--danger-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
margin-top: var(--margin-sm);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
transition:
|
||||
background-color var(--transition-fast),
|
||||
box-shadow var(--transition-fast),
|
||||
transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.delete-all-button:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.dialog-box {
|
||||
background: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
min-width: var(--width-md);
|
||||
padding: var(--padding-base);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.dialog-box input {
|
||||
background: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
padding: var(--padding-xs) var(--padding-sm);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dialog-box p {
|
||||
margin: 0 0 var(--margin-sm) 0;
|
||||
}
|
||||
|
||||
.dialog-buttons {
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
justify-content: center;
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.dialog-buttons button {
|
||||
background: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
}
|
||||
|
||||
.dialog-overlay {
|
||||
align-items: center;
|
||||
background: rgba(0, 0, 0, var(--disabled-opacity));
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
inset: 0;
|
||||
justify-content: center;
|
||||
position: fixed;
|
||||
z-index: var(--z-tooltip);
|
||||
}
|
||||
|
||||
.media-player-content {
|
||||
background: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
padding: var(--padding-base);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.media-player-content .close-button {
|
||||
background-color: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
margin-top: var(--margin-sm);
|
||||
padding: var(--padding-base) var(--padding-xl);
|
||||
font-size: var(--font-size-base);
|
||||
}
|
||||
|
||||
.media-player-content video {
|
||||
border-radius: var(--border-radius-md);
|
||||
height: var(--width-lg);
|
||||
width: var(--width-xxl);
|
||||
}
|
||||
|
||||
.media-player-overlay {
|
||||
align-items: center;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
height: 100%;
|
||||
justify-content: center;
|
||||
left: 0;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
z-index: var(--z-modal);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .action-close {
|
||||
background-color: var(--danger-bg);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .action-delete {
|
||||
background-color: var(--danger-bg);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .action-rename {
|
||||
background-color: var(--input-bg);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .action-download {
|
||||
background-color: var(--color-confirm);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .action-download:hover {
|
||||
background-color: var(--color-confirm-hover);
|
||||
filter: brightness(90%);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .camera-button.active {
|
||||
box-shadow: inset 0 0 0 2px var(--main-fg);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .close-button {
|
||||
color: var(--text-color);
|
||||
transition: filter var(--transition-fast);
|
||||
}
|
||||
|
||||
.media-player-overlay .media-player-content .close-button:hover {
|
||||
filter: brightness(90%);
|
||||
}
|
||||
|
||||
.media-player-title {
|
||||
align-items: center;
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
justify-content: center;
|
||||
margin-bottom: var(--margin-base);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.action-rename-icon {
|
||||
cursor: pointer;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.media-player-title .action-rename-route {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.recording-card {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-md);
|
||||
overflow: hidden;
|
||||
text-align: center;
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.recording-card:hover {
|
||||
cursor: pointer;
|
||||
transform: var(--hover-scale-base);
|
||||
}
|
||||
|
||||
.recording-card a {
|
||||
color: var(--text-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.recording-filename {
|
||||
font-size: var(--font-size-sm);
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
padding: var(--padding-sm);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.recording-preview {
|
||||
aspect-ratio: 16 / 9;
|
||||
height: auto;
|
||||
object-fit: cover;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.recording-preview-container {
|
||||
aspect-ratio: 16 / 9;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.recording-preview-container .recording-preview {
|
||||
height: 100%;
|
||||
left: 0;
|
||||
object-fit: cover;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.screen-recordings-grid {
|
||||
display: grid;
|
||||
gap: var(--gap-md);
|
||||
grid-template-columns: repeat(auto-fill, minmax(var(--width-sm), 1fr));
|
||||
margin-top: var(--padding-lg);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.screen-recordings-grid.disabled {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.screen-recordings-message {
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-sm);
|
||||
margin-top: var(--padding-xl);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.screen-recordings-title {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.screen-recordings-widget {
|
||||
align-items: center;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-xl);
|
||||
max-width: var(--width-xxl);
|
||||
padding: var(--padding-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.screen-recordings-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.screen-recordings-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.media-player-content {
|
||||
width: 90%;
|
||||
padding: var(--padding-sm);
|
||||
}
|
||||
|
||||
.media-player-content video {
|
||||
width: 90vw !important;
|
||||
height: auto !important;
|
||||
}
|
||||
|
||||
.button-row {
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.media-player-content .close-button {
|
||||
padding: var(--padding-base) var(--padding-xl);
|
||||
font-size: var(--font-size-base);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { isGalaxyTunnel } from "/assets/js/utils.js"
|
||||
import { Modal } from "/assets/components/modal.js";
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
error: null,
|
||||
recordings: [],
|
||||
selectedRecording: null,
|
||||
showDeleteModal: false,
|
||||
recordingToDelete: null,
|
||||
showDeleteAllModal: false,
|
||||
progress: 0,
|
||||
total: 0,
|
||||
})
|
||||
|
||||
function getOrdinalSuffix(n) {
|
||||
const s = ["th", "st", "nd", "rd"];
|
||||
const v = n % 100;
|
||||
return s[(v - 20) % 10] || s[v] || s[0];
|
||||
}
|
||||
|
||||
function formatScreenRecordingDate(dateString) {
|
||||
const date = new Date(dateString);
|
||||
const month = date.toLocaleString("en-US", { month: "long" });
|
||||
const day = date.getDate();
|
||||
const year = date.getFullYear();
|
||||
let hour = date.getHours();
|
||||
const minute = date.getMinutes();
|
||||
const ampm = hour >= 12 ? "pm" : "am";
|
||||
hour = hour % 12;
|
||||
hour = hour ? hour : 12;
|
||||
const minuteStr = minute < 10 ? "0" + minute : minute;
|
||||
return `${month} ${day}${getOrdinalSuffix(day)}, ${year} - ${hour}:${minuteStr}${ampm}`;
|
||||
}
|
||||
|
||||
|
||||
async function fetchRecordings() {
|
||||
try {
|
||||
const response = await fetch("/api/screen_recordings/list");
|
||||
if (!response.ok) throw new Error("Network response was not ok");
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split("\n\n");
|
||||
buffer = lines.pop();
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("data: ")) {
|
||||
try {
|
||||
const data = JSON.parse(line.substring(6));
|
||||
if (data.progress !== undefined && data.total !== undefined) {
|
||||
state.progress = data.progress;
|
||||
state.total = data.total;
|
||||
}
|
||||
if (data.recordings) {
|
||||
state.recordings.push(...data.recordings);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
state.error = "Couldn't load recordings. Please try again later..."
|
||||
} finally {
|
||||
state.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
fetchRecordings()
|
||||
|
||||
function refresh() {
|
||||
state.loading = true
|
||||
state.recordings = []
|
||||
fetchRecordings()
|
||||
}
|
||||
|
||||
let overlay = null
|
||||
|
||||
function openDialog(htmlStr) {
|
||||
const o = document.createElement("div")
|
||||
o.className = "dialog-overlay"
|
||||
o.innerHTML = htmlStr
|
||||
document.body.appendChild(o)
|
||||
return o
|
||||
}
|
||||
|
||||
function closeDialog(o) { if (o) o.remove() }
|
||||
|
||||
async function renameFile(rec) {
|
||||
const base = rec.filename.replace(/\.mp4$/i, "")
|
||||
const dlg = openDialog(`
|
||||
<div class="dialog-box">
|
||||
<p>Rename “${rec.filename}”</p>
|
||||
<input class="rn-input" value="${base}" />
|
||||
<div class="dialog-buttons">
|
||||
<button class="btn-cancel">Cancel</button>
|
||||
<button class="btn-save">Save</button>
|
||||
</div>
|
||||
</div>`)
|
||||
dlg.querySelector(".btn-cancel").onclick = () => closeDialog(dlg)
|
||||
dlg.querySelector(".btn-save").onclick = async () => {
|
||||
const val = dlg.querySelector(".rn-input").value.trim()
|
||||
if (!val) return
|
||||
const oldFilename = rec.filename
|
||||
const newFilename = val + ".mp4"
|
||||
|
||||
const res = await fetch("/api/screen_recordings/rename", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ old: oldFilename, new: newFilename }),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
closeDialog(dlg)
|
||||
|
||||
const recordingToUpdate = state.recordings.find(r => r.filename === oldFilename)
|
||||
if (recordingToUpdate) {
|
||||
recordingToUpdate.filename = newFilename
|
||||
recordingToUpdate.is_custom_name = true
|
||||
recordingToUpdate.png = `/screen_recordings/${val}.png`
|
||||
}
|
||||
|
||||
const overlayTitleSpan = overlay.querySelector(".media-player-title span");
|
||||
if (overlayTitleSpan) {
|
||||
overlayTitleSpan.textContent = val.replace(/_/g, " ");
|
||||
}
|
||||
showSnackbar("Recording renamed!")
|
||||
} else {
|
||||
showSnackbar("Rename failed...", "error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDeleteFile(rec) {
|
||||
state.recordingToDelete = rec;
|
||||
state.showDeleteModal = true;
|
||||
}
|
||||
|
||||
async function deleteFile() {
|
||||
if (!state.recordingToDelete) return;
|
||||
const rec = state.recordingToDelete;
|
||||
|
||||
const res = await fetch(`/api/screen_recordings/delete/${encodeURIComponent(rec.filename)}`, { method: "DELETE" })
|
||||
if (res.ok) {
|
||||
closeOverlay();
|
||||
refresh();
|
||||
showSnackbar("Recording deleted!");
|
||||
} else {
|
||||
showSnackbar("Delete failed...", "error");
|
||||
}
|
||||
|
||||
state.showDeleteModal = false;
|
||||
state.recordingToDelete = null;
|
||||
}
|
||||
|
||||
function openOverlay(rec) {
|
||||
if (overlay) return
|
||||
overlay = document.createElement("div")
|
||||
overlay.className = "media-player-overlay"
|
||||
const displayName = rec.is_custom_name ? rec.filename.replace(/\.mp4$/i, "") : formatScreenRecordingDate(rec.timestamp);
|
||||
overlay.innerHTML = `
|
||||
<div class="media-player-content">
|
||||
<div class="media-player-title">
|
||||
<span>${displayName}</span>
|
||||
<i class="bi bi-pencil-fill action-rename-icon"></i>
|
||||
</div>
|
||||
<video controls autoplay muted>
|
||||
<source src="/api/screen_recordings/download/${rec.filename}" type="video/mp4">
|
||||
</video>
|
||||
<div class="button-row">
|
||||
<button class="close-button action-close">Close</button>
|
||||
<button class="close-button action-download">Download</button>
|
||||
<button class="close-button action-delete">Delete</button>
|
||||
</div>
|
||||
</div>`
|
||||
overlay.addEventListener("click", e => { if (e.target === overlay) closeOverlay() })
|
||||
overlay.querySelector(".action-close").onclick = closeOverlay
|
||||
overlay.querySelector(".action-rename-icon").onclick = () => renameFile(rec)
|
||||
overlay.querySelector(".action-delete").onclick = () => confirmDeleteFile(rec)
|
||||
overlay.querySelector(".action-download").onclick = () => {
|
||||
const link = document.createElement("a");
|
||||
link.href = `/api/screen_recordings/download/${rec.filename}`;
|
||||
link.download = rec.filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
document.body.appendChild(overlay)
|
||||
}
|
||||
|
||||
function closeOverlay() {
|
||||
if (!overlay) return
|
||||
overlay.remove()
|
||||
overlay = null
|
||||
state.selectedRecording = null
|
||||
}
|
||||
|
||||
async function deleteAllRecordings() {
|
||||
state.showDeleteAllModal = false
|
||||
state.isDeletingAll = true
|
||||
try {
|
||||
const res = await fetch("/api/screen_recordings/delete_all", { method: "DELETE" })
|
||||
if (!res.ok) throw new Error()
|
||||
await refresh()
|
||||
showSnackbar("All screen recordings deleted!")
|
||||
} catch {
|
||||
showSnackbar("An error occurred while deleting all screen recordings...", "error")
|
||||
} finally {
|
||||
state.isDeletingAll = false
|
||||
}
|
||||
}
|
||||
|
||||
export function ScreenRecordings() {
|
||||
if (isGalaxyTunnel()) {
|
||||
return html`
|
||||
<div class="tunnel-notice">
|
||||
<div class="tunnel-notice-icon">🛰️</div>
|
||||
<h3 class="tunnel-notice-title">Screen Recordings Unavailable via Galaxy</h3>
|
||||
<p class="tunnel-notice-body">Loading screen recordings requires a direct connection.<br>Connect to your device's local network to use this feature.</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (state.selectedRecording && !overlay) openOverlay(state.selectedRecording)
|
||||
|
||||
return html`
|
||||
<div class="screen-recordings-wrapper">
|
||||
<div class="screen-recordings-widget">
|
||||
<div class="screen-recordings-title">Screen Recordings</div>
|
||||
|
||||
${() => {
|
||||
if (state.loading && state.recordings.length === 0) return html`<p class="screen-recordings-message">Loading...</p>`
|
||||
if (state.error) return html`<p class="screen-recordings-message">${state.error}</p>`
|
||||
if (state.progress > 0 && state.progress < state.total) {
|
||||
return html`<p class="screen-recordings-message">Processing Recordings: ${state.progress} of ${state.total}</p>`
|
||||
}
|
||||
if (state.recordings.length === 0 && !state.loading) {
|
||||
return html`<p class="screen-recordings-message">No screen recordings found...</p>`
|
||||
}
|
||||
return ""
|
||||
}}
|
||||
|
||||
<div class="screen-recordings-grid">
|
||||
${() => state.recordings.map(rec => {
|
||||
const displayName = rec.is_custom_name ? rec.filename.replace(/\.mp4$/i, "").replace(/_/g, " ") : formatScreenRecordingDate(rec.timestamp)
|
||||
return html`
|
||||
<div
|
||||
class="recording-card"
|
||||
@click="${() => { state.selectedRecording = rec }}"
|
||||
>
|
||||
<div class="recording-preview-container">
|
||||
<img src="${rec.png}" class="recording-preview recording-preview-png" style="display:block;" loading="lazy">
|
||||
</div>
|
||||
<p class="recording-filename">${displayName}</p>
|
||||
</div>
|
||||
`
|
||||
})}
|
||||
</div>
|
||||
|
||||
${() => {
|
||||
if (state.recordings.length > 0) {
|
||||
return html`
|
||||
<button
|
||||
class="delete-all-button"
|
||||
@click="${() => (state.showDeleteAllModal = true)}"
|
||||
>
|
||||
Delete All Recordings
|
||||
</button>
|
||||
`
|
||||
}
|
||||
return ""
|
||||
}}
|
||||
</div>
|
||||
${() => state.showDeleteModal ? Modal({
|
||||
title: "Confirm Delete",
|
||||
message: `Are you sure you want to delete <strong>${state.recordingToDelete.filename}</strong>?`,
|
||||
onConfirm: deleteFile,
|
||||
onCancel: () => { state.showDeleteModal = false; state.recordingToDelete = null; },
|
||||
confirmText: "Delete"
|
||||
}) : ""}
|
||||
${() => state.showDeleteAllModal ? Modal({
|
||||
title: "Confirm Delete All",
|
||||
message: "Are you sure you want to delete all screen recordings? This action cannot be undone...",
|
||||
onConfirm: deleteAllRecordings,
|
||||
onCancel: () => { state.showDeleteAllModal = false; },
|
||||
confirmText: "Delete All"
|
||||
}) : ""}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { createBrowserHistory, createRouter } from "/assets/vendor/remix-router-1.3.1.js"
|
||||
import { hideSidebar } from "/assets/js/utils.js"
|
||||
import { DeviceSettings } from "/assets/components/tools/device_settings.js?v=favorite-c4-hint-1"
|
||||
import { Bluetooth } from "/assets/components/tools/bluetooth.js?v=bluetooth-live-15"
|
||||
import { WheelControls } from "/assets/components/tools/wheel_controls.js?v=controllers-3"
|
||||
import { DoorControl } from "/assets/components/tools/doors.js"
|
||||
import { ErrorLogs } from "/assets/components/tools/error_logs.js"
|
||||
import { VehicleFeatures } from "/assets/components/tools/vehicle_features.js"
|
||||
import { TSKManager } from "/assets/components/tools/tsk_manager.js"
|
||||
import { GalaxyPairing } from "/assets/components/tools/galaxy.js"
|
||||
import { Home } from "/assets/components/home/home.js"
|
||||
import { MapsManager } from "/assets/components/tools/maps.js"
|
||||
import { NavDestination } from "/assets/components/navigation/navigation_destination.js?v=nav-search-context-2"
|
||||
import { NavKeys } from "/assets/components/navigation/navigation_keys.js?v=app-keys-session-1"
|
||||
import { RouteRecordings } from "/assets/components/recordings/dashcam_routes.js"
|
||||
import { SettingsView } from "/assets/components/settings.js?v=router-cycle-fix-5"
|
||||
import { ScreenRecordings } from "/assets/components/recordings/screen_recordings.js"
|
||||
import { Sidebar } from "/assets/components/sidebar.js?v=sidebar-pin-2"
|
||||
import { SentryMode } from "/assets/components/tools/sentry.js"
|
||||
import { SpeedLimits } from "/assets/components/tools/speed_limits.js"
|
||||
import { ModelManager } from "/assets/components/tools/model_manager.js?v=20260906a"
|
||||
import { ModelLaboratory } from "/assets/components/tools/model_laboratory.js?v=model-lab-6"
|
||||
import { LivePlots } from "/assets/components/tools/plots.js"
|
||||
import { ThemeMaker } from "/assets/components/tools/theme_maker.js"
|
||||
import { TestingGround } from "/assets/components/tools/testing_ground.js"
|
||||
import { Tuning } from "/assets/components/tools/tuning.js?v=flm-route-length-1"
|
||||
import { Troubleshoot } from "/assets/components/tools/troubleshoot.js"
|
||||
import { TmuxLog } from "/assets/components/tools/tmux.js"
|
||||
import { ToggleControl } from "/assets/components/tools/toggles.js"
|
||||
import { VASMAnnotations } from "/assets/components/tools/v_asm.js"
|
||||
import { PipSideCamera } from "/assets/components/tools/pip_sidecam.js"
|
||||
import { UpdateManager } from "/assets/components/tools/update_manager.js"
|
||||
import { startSentryNotifications } from "/assets/components/sentry_notifications.js"
|
||||
|
||||
let router, routerState
|
||||
|
||||
function toRouterHref(href) {
|
||||
try {
|
||||
const url = new URL(href, window.location.origin)
|
||||
return `${url.pathname}${url.search}${url.hash}`
|
||||
} catch {
|
||||
return href
|
||||
}
|
||||
}
|
||||
|
||||
function createRoute(id, path, component) {
|
||||
return {
|
||||
id,
|
||||
path,
|
||||
loader: () => { },
|
||||
element: component,
|
||||
}
|
||||
}
|
||||
|
||||
function SafeHome() {
|
||||
return html`
|
||||
<div>
|
||||
<h1>Galaxy</h1>
|
||||
<p>Safe mode is active while UI rendering is being repaired.</p>
|
||||
<p>
|
||||
<a href="/galaxy">Galaxy Pairing</a> |
|
||||
<a href="/sentry">Sentry Mode</a> |
|
||||
<a href="/device_settings">Toggles</a> |
|
||||
<a href="/manage_updates">Software</a>
|
||||
</p>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function Root() {
|
||||
let routes = [
|
||||
createRoute("bluetooth", "/bluetooth", Bluetooth),
|
||||
createRoute("wheel_controls", "/wheel-controls", WheelControls),
|
||||
createRoute("doors", "/manage_doors", DoorControl),
|
||||
createRoute("tsk", "/manage_tsk", TSKManager),
|
||||
createRoute("device_settings", "/device_settings/:section?", DeviceSettings),
|
||||
createRoute("errorLogs", "/manage_error_logs", ErrorLogs),
|
||||
createRoute("galaxy", "/galaxy", GalaxyPairing),
|
||||
createRoute("navdestination", "/set_navigation_destination", NavDestination),
|
||||
createRoute("navkeys", "/manage_navigation_keys", NavKeys),
|
||||
createRoute("root", "/", Home),
|
||||
createRoute("classicRoot", "/classic", Home),
|
||||
createRoute("routes", "/dashcam_routes", RouteRecordings),
|
||||
createRoute("screen_recordings", "/screen_recordings", ScreenRecordings),
|
||||
createRoute("sentry", "/sentry", SentryMode),
|
||||
createRoute("settings", "/settings/:section/:subsection?", SettingsView),
|
||||
createRoute("speed_limits", "/download_speed_limits", SpeedLimits),
|
||||
createRoute("model_manager", "/manage_models", ModelManager),
|
||||
createRoute("model_laboratory", "/model_laboratory", ModelLaboratory),
|
||||
createRoute("tuning", "/tuning", Tuning),
|
||||
createRoute("lateral_maneuvers", "/lateral_maneuvers", Tuning),
|
||||
createRoute("maps", "/manage_maps", MapsManager),
|
||||
createRoute("plots", "/plots", LivePlots),
|
||||
createRoute("thememaker", "/theme_maker", ThemeMaker),
|
||||
createRoute("testing_ground", "/testing_ground", TestingGround),
|
||||
createRoute("troubleshoot", "/troubleshoot", Troubleshoot),
|
||||
createRoute("tmux", "/manage_tmux", TmuxLog),
|
||||
createRoute("toggles", "/manage_toggles", ToggleControl),
|
||||
createRoute("updates", "/manage_updates", UpdateManager),
|
||||
createRoute("vehicle_features", "/vehicle_features", VehicleFeatures),
|
||||
createRoute("v_asm", "/manage_v_asm", VASMAnnotations),
|
||||
createRoute("pip_sidecam", "/manage_pip_sidecam", PipSideCamera),
|
||||
]
|
||||
|
||||
router = createRouter({
|
||||
routes,
|
||||
history: createBrowserHistory(),
|
||||
}).initialize()
|
||||
|
||||
window.__theGalaxyNavigate = (href) => {
|
||||
router.navigate(toRouterHref(href))
|
||||
window.scrollTo(0, 0)
|
||||
}
|
||||
|
||||
routerState = reactive({
|
||||
activePath: "/",
|
||||
activePathFull: "/",
|
||||
initialized: false,
|
||||
navigation: { state: "loading" },
|
||||
errors: [],
|
||||
params: {},
|
||||
activeMatch: null,
|
||||
})
|
||||
|
||||
router.subscribe(({ initialized, navigation, matches, errors }) => {
|
||||
const match = Array.isArray(matches) && matches.length > 0
|
||||
? matches[matches.length - 1]
|
||||
: null
|
||||
Object.assign(routerState, {
|
||||
initialized,
|
||||
activePath: match?.route?.path || "",
|
||||
activePathFull: match?.pathname || "",
|
||||
navigation,
|
||||
params: match?.params || {},
|
||||
errors,
|
||||
activeMatch: match,
|
||||
})
|
||||
})
|
||||
|
||||
return html`
|
||||
${() => Sidebar(routerState.activePathFull)}
|
||||
<div class="content">
|
||||
${() => {
|
||||
if (!routerState.initialized) {
|
||||
return Home({ params: routerState.params })
|
||||
}
|
||||
|
||||
if (routerState.errors?.root?.status === 404) {
|
||||
return html`<h1>Not Found</h1>`
|
||||
}
|
||||
|
||||
const routeElement = routerState.activeMatch?.route?.element
|
||||
if (typeof routeElement !== "function") {
|
||||
console.warn("[router] no route element for path:", routerState.activePathFull)
|
||||
return Home({ params: routerState.params })
|
||||
}
|
||||
return routeElement({ params: routerState.params })
|
||||
}}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
export function Link(href, children, onClick, classes = "") {
|
||||
return html`<a
|
||||
class="${classes}"
|
||||
href="${() => href}"
|
||||
@click="${(e) => {
|
||||
e.preventDefault()
|
||||
router.navigate(toRouterHref(e.currentTarget.href))
|
||||
hideSidebar()
|
||||
onClick?.()
|
||||
}}"
|
||||
>${children}</a>`
|
||||
}
|
||||
|
||||
export function Navigate(href) {
|
||||
router.navigate(toRouterHref(href))
|
||||
window.scrollTo(0, 0)
|
||||
}
|
||||
|
||||
function mountRouterWhenReady() {
|
||||
const mountNode = document.getElementById("app")
|
||||
if (!mountNode) {
|
||||
// Some embedded browsers execute module scripts before <body> is fully available.
|
||||
setTimeout(mountRouterWhenReady, 0)
|
||||
return
|
||||
}
|
||||
|
||||
if (!window.__theGalaxyRouterMounted) {
|
||||
window.__theGalaxyRouterMounted = true
|
||||
Root()(mountNode)
|
||||
} else {
|
||||
console.warn("[router] duplicate mount prevented")
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", mountRouterWhenReady, { once: true })
|
||||
} else {
|
||||
mountRouterWhenReady()
|
||||
}
|
||||
|
||||
startSentryNotifications()
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import { galaxyPath } from "/assets/js/utils.js"
|
||||
|
||||
const STORAGE_KEY = "starpilot.sentry.last-event"
|
||||
const POLL_INTERVAL_MS = 5000
|
||||
const SERVICE_WORKER_PATH = "/service-worker.js"
|
||||
|
||||
let started = false
|
||||
let initialized = false
|
||||
|
||||
function lastSeenEventId() {
|
||||
try {
|
||||
return window.localStorage.getItem(STORAGE_KEY) || ""
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
function rememberEvent(eventId) {
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, eventId)
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
async function pollSentryEvent() {
|
||||
try {
|
||||
const response = await fetch(galaxyPath("/api/sentry/status"), { cache: "no-store" })
|
||||
if (!response.ok) return
|
||||
const payload = await response.json()
|
||||
const event = payload?.lastEvent
|
||||
const eventId = String(event?.eventId || "")
|
||||
if (!eventId) return
|
||||
|
||||
const previous = lastSeenEventId()
|
||||
rememberEvent(eventId)
|
||||
if (!initialized || eventId === previous) return
|
||||
if (typeof Notification === "undefined" || Notification.permission !== "granted") return
|
||||
|
||||
new Notification("StarPilot Sentry Mode", {
|
||||
body: String(event.message || "Movement detected while parked."),
|
||||
tag: `starpilot-sentry-${eventId}`,
|
||||
})
|
||||
} catch (error) {
|
||||
console.debug("Sentry notification poll failed:", error)
|
||||
} finally {
|
||||
initialized = true
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestSentryNotificationPermission() {
|
||||
if (typeof Notification === "undefined") return "unsupported"
|
||||
return Notification.requestPermission()
|
||||
}
|
||||
|
||||
function base64ToUint8Array(value) {
|
||||
const padding = "=".repeat((4 - (value.length % 4)) % 4)
|
||||
const normalized = (value + padding).replace(/-/g, "+").replace(/_/g, "/")
|
||||
const raw = window.atob(normalized)
|
||||
return Uint8Array.from(raw, (character) => character.charCodeAt(0))
|
||||
}
|
||||
|
||||
function subscriptionPayload(subscription) {
|
||||
if (typeof subscription.toJSON === "function") return subscription.toJSON()
|
||||
|
||||
const key = (name) => subscription.getKey(name)
|
||||
const encode = (value) => btoa(String.fromCharCode(...new Uint8Array(value)))
|
||||
return {
|
||||
endpoint: subscription.endpoint,
|
||||
expirationTime: subscription.expirationTime,
|
||||
keys: {
|
||||
p256dh: encode(key("p256dh")),
|
||||
auth: encode(key("auth")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function readJsonResponse(response) {
|
||||
const body = await response.text()
|
||||
if (!body) return {}
|
||||
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch {
|
||||
const contentType = response.headers?.get("content-type") || ""
|
||||
if (contentType.includes("text/html") || body.trim().startsWith("<")) {
|
||||
if (response.status === 200) {
|
||||
throw new Error("Galaxy returned an HTML page instead of JSON data. Check your session or connection.")
|
||||
}
|
||||
throw new Error(`Galaxy returned an HTML error page (${response.status}). Check the device connection or Galaxy tunnel.`)
|
||||
}
|
||||
throw new Error(`Galaxy returned an unexpected ${response.status} response. Check the device connection or Galaxy tunnel.`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function enableSentryPush() {
|
||||
if (typeof Notification === "undefined" || !("serviceWorker" in navigator) || !("PushManager" in window)) {
|
||||
return { ok: false, message: "This browser does not support Web Push notifications." }
|
||||
}
|
||||
if (!window.isSecureContext) {
|
||||
return { ok: false, message: "Browser notifications require Galaxy over HTTPS." }
|
||||
}
|
||||
|
||||
const permission = await requestSentryNotificationPermission()
|
||||
if (permission !== "granted") {
|
||||
return { ok: false, message: "Browser notification permission was not granted." }
|
||||
}
|
||||
|
||||
const configResponse = await fetch(galaxyPath("/api/sentry/push/config"), { cache: "no-store" })
|
||||
const config = await readJsonResponse(configResponse)
|
||||
if (!configResponse.ok || !config.enabled || !config.publicKey) {
|
||||
return { ok: false, message: config.error || "Galaxy Web Push is unavailable." }
|
||||
}
|
||||
|
||||
const serviceWorkerPath = galaxyPath(SERVICE_WORKER_PATH)
|
||||
const serviceWorkerScope = galaxyPath("/")
|
||||
await navigator.serviceWorker.register(serviceWorkerPath, { scope: serviceWorkerScope })
|
||||
const registration = await navigator.serviceWorker.ready
|
||||
let subscription = await registration.pushManager.getSubscription()
|
||||
if (!subscription) {
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: base64ToUint8Array(config.publicKey),
|
||||
})
|
||||
}
|
||||
|
||||
const response = await fetch(galaxyPath("/api/sentry/push/subscribe"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(subscriptionPayload(subscription)),
|
||||
})
|
||||
const payload = await readJsonResponse(response)
|
||||
if (!response.ok) return { ok: false, message: payload.error || "Galaxy could not save this browser." }
|
||||
return { ok: true, message: "Browser notifications enabled for this device." }
|
||||
}
|
||||
|
||||
export async function sendSentryTestNotification() {
|
||||
const response = await fetch(galaxyPath("/api/sentry/test-notification"), { method: "POST" })
|
||||
const payload = await readJsonResponse(response)
|
||||
if (!response.ok) throw new Error(payload.error || "Galaxy could not send the test notification.")
|
||||
return payload
|
||||
}
|
||||
|
||||
export function startSentryNotifications() {
|
||||
if (started) return
|
||||
started = true
|
||||
pollSentryEvent()
|
||||
window.setInterval(pollSentryEvent, POLL_INTERVAL_MS)
|
||||
}
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
@font-face {
|
||||
font-family: "password";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: url(/assets/vendor/fonts/password.ttf);
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.setting {
|
||||
margin-bottom: var(--margin-sm);
|
||||
max-width: calc(100vw - 3rem);
|
||||
}
|
||||
|
||||
.setting .description.collapsed {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.setting .title {
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.setting.subtoggle {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.dropdown {
|
||||
grid-area: b;
|
||||
justify-self: end;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.dropdown>select {
|
||||
appearance: none;
|
||||
background-color: var(--sidebar-bg);
|
||||
border: var(--border-width-thin) solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--main-fg);
|
||||
font-size: 1.15rem;
|
||||
padding: var(--padding-sm) 2em 0.675em var(--font-size-base);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.dropdown::after,
|
||||
.dropdown::before {
|
||||
--size: 0.3rem;
|
||||
content: "";
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
right: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.dropdown::before {
|
||||
border-bottom: var(--size) solid var(--main-fg);
|
||||
border-left: var(--size) solid transparent;
|
||||
border-right: var(--size) solid transparent;
|
||||
top: 40%;
|
||||
}
|
||||
|
||||
.dropdown::after {
|
||||
border-left: var(--size) solid transparent;
|
||||
border-right: var(--size) solid transparent;
|
||||
border-top: var(--size) solid var(--main-fg);
|
||||
top: 55%;
|
||||
}
|
||||
|
||||
input.password {
|
||||
font-family: "password";
|
||||
}
|
||||
|
||||
input.searchfield:focus {
|
||||
border-color: var(--success-bg);
|
||||
box-shadow: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input:checked+.slider {
|
||||
background-color: var(--success-bg);
|
||||
}
|
||||
|
||||
input:checked+.slider:before {
|
||||
transform: translateX(26px);
|
||||
}
|
||||
|
||||
input:checked+.slider.loading:before {
|
||||
animation: rotationChecked 1s linear infinite;
|
||||
}
|
||||
|
||||
input:focus+.slider {
|
||||
box-shadow: 0 0 var(--border-width-thin) var(--success-bg);
|
||||
}
|
||||
|
||||
.numberInput {
|
||||
align-items: center;
|
||||
border: var(--border-width-thin) solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-width-thick);
|
||||
display: flex;
|
||||
grid-column: 3;
|
||||
grid-row: 1;
|
||||
height: 50px;
|
||||
justify-content: space-between;
|
||||
white-space: nowrap;
|
||||
width: 150px;
|
||||
}
|
||||
|
||||
.numberInput button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
height: 100%;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
width: 40px;
|
||||
}
|
||||
|
||||
.numberInput button:active:not([disabled]) {
|
||||
background-color: var(--success-bg);
|
||||
}
|
||||
|
||||
.numberInput button[disabled] {
|
||||
color: grey;
|
||||
}
|
||||
|
||||
.options {
|
||||
color: var(--main-fg);
|
||||
display: flex;
|
||||
font-size: 1var(--border-width-base);
|
||||
gap: var(--border-radius-xl);
|
||||
max-width: 336px;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.options>input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.options>input:checked+label {
|
||||
background-color: var(--success-bg);
|
||||
color: var(--text-color);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.options label {
|
||||
background-color: var(--sidebar-bg);
|
||||
border-radius: 3rem;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
padding: var(--padding-xs) var(--padding-xs);
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
transition: color 250ms cubic-bezier(0, 0.95, 0.38, 0.98);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.setting {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
grid-template-areas: "a b b" "c c d";
|
||||
grid-template-columns: 4fr 4fr 1fr;
|
||||
margin-bottom: var(--border-radius-xl);
|
||||
padding-right: var(--font-size-xl);
|
||||
}
|
||||
|
||||
.setting .description {
|
||||
font-size: 0.8em;
|
||||
grid-area: c;
|
||||
grid-column: span 3;
|
||||
margin: 0;
|
||||
opacity: 0.5;
|
||||
padding-top: var(--padding-xs);
|
||||
}
|
||||
|
||||
.setting .description summary {
|
||||
margin-bottom: var(--border-radius-lg);
|
||||
}
|
||||
|
||||
.setting .options {
|
||||
align-items: center;
|
||||
grid-area: b;
|
||||
grid-column: span 2;
|
||||
justify-self: end;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.setting .savebutton {
|
||||
background-color: var(--success-bg);
|
||||
border: var(--border-width-thin) solid transparent;
|
||||
border-radius: var(--width-lg);
|
||||
color: var(--text-color);
|
||||
display: inline-block;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
justify-self: end;
|
||||
margin-left: var(--border-radius-xl);
|
||||
padding: var(--border-radius-lg);
|
||||
text-align: center;
|
||||
transition: background-color var(--transition-base), border-color var(--transition-base), color var(--transition-base), box-shadow var(--transition-base), filter var(--transition-base);
|
||||
white-space: normal;
|
||||
width: 6var(--border-width-thick);
|
||||
}
|
||||
|
||||
.setting .savebutton.loading {
|
||||
cursor: progress;
|
||||
}
|
||||
|
||||
.setting .textwrapper {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.setting .title {
|
||||
font-size: 1.var(--border-radius-xl);
|
||||
grid-area: a;
|
||||
margin-right: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.setting .title.wide {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.setting.subsetting_link {}
|
||||
|
||||
.setting.subtoggle {
|
||||
margin: 0 0 0 var(--padding-xl);
|
||||
}
|
||||
|
||||
.setting.subtoggle+.setting {
|
||||
margin-top: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.setting.subtoggle p {
|
||||
margin: var(--margin-sm) 0;
|
||||
}
|
||||
|
||||
.setting.subtoggle .title:before {
|
||||
border-bottom: var(--border-width-base) solid;
|
||||
border-color: gray;
|
||||
border-left: var(--border-width-base) solid;
|
||||
content: "";
|
||||
display: inline-block;
|
||||
height: var(--border-radius-lg);
|
||||
margin: 0 var(--margin-base) var(--margin-xs) 0;
|
||||
position: relative;
|
||||
width: 1var(--border-width-base);
|
||||
}
|
||||
|
||||
.settings {
|
||||
max-width: var(--max-width-content);
|
||||
}
|
||||
|
||||
.settings h1 {
|
||||
margin-bottom: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.settings .textinput,
|
||||
input.searchfield {
|
||||
appearance: none;
|
||||
background: var(--sidebar-bg);
|
||||
border: var(--border-width-thin) solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--main-fg);
|
||||
font-size: 13px;
|
||||
height: 46px;
|
||||
padding: var(--padding-xs) var(--padding-base);
|
||||
transition: border 0.15s ease;
|
||||
}
|
||||
|
||||
.settings input.searchfield {
|
||||
margin-top: var(--border-radius-xl);
|
||||
padding: 0.var(--border-radius-xl) var(--border-radius-xl);
|
||||
width: calc(100% - 5rem);
|
||||
}
|
||||
|
||||
.slider {
|
||||
background-color: var(--switch-inactive-bg);
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
transition: var(--transition-fast);
|
||||
}
|
||||
|
||||
.slider:before {
|
||||
background-color: var(--main-bg);
|
||||
border-radius: var(--border-radius-xl);
|
||||
bottom: var(--border-radius-sm);
|
||||
content: "";
|
||||
height: 26px;
|
||||
left: var(--border-radius-sm);
|
||||
position: absolute;
|
||||
transition: var(--transition-fast);
|
||||
width: 26px;
|
||||
}
|
||||
|
||||
.slider.loading:before {
|
||||
animation: rotation 1s linear infinite;
|
||||
background-color: none !important;
|
||||
border: var(--border-width-thick) solid var(--sidebar-fg);
|
||||
border-bottom-color: var(--main-fg);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.slider.round {
|
||||
border-radius: 34px;
|
||||
}
|
||||
|
||||
.slider.round:before {
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.switch {
|
||||
display: inline-block;
|
||||
grid-column: 3;
|
||||
grid-row: 1;
|
||||
height: 34px;
|
||||
justify-self: end;
|
||||
position: relative;
|
||||
width: 60px;
|
||||
}
|
||||
|
||||
i.switch {
|
||||
align-self: end;
|
||||
width: 34px;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
}
|
||||
|
||||
@keyframes rotation {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes rotationChecked {
|
||||
0% {
|
||||
transform: translateX(26px) rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: translateX(26px) rotate(360deg);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { html } from "/assets/vendor/arrow-core.js"
|
||||
import { upperFirst } from "/assets/js/utils.js"
|
||||
|
||||
function navigate(href) {
|
||||
// Avoid importing router.js here: settings.js is loaded by router.js, and
|
||||
// a cache-busted router URL would otherwise create a second router module.
|
||||
if (typeof window.__theGalaxyNavigate === "function") {
|
||||
return window.__theGalaxyNavigate(href)
|
||||
}
|
||||
window.location.assign(href)
|
||||
}
|
||||
|
||||
export function SettingsView({ params }) {
|
||||
const state = {
|
||||
selectedSection: params.section,
|
||||
selectedSubsection: params.subsection,
|
||||
settings: "[]",
|
||||
heading: params.section,
|
||||
}
|
||||
|
||||
getSettings().then((results) => {
|
||||
if (state.selectedSubsection) {
|
||||
const setting = results.find((item) => item.key === state.selectedSubsection) ?? {}
|
||||
|
||||
if (!setting.subsettings || Object.keys(setting.subsettings).length === 0) {
|
||||
return navigate(`/settings/${state.selectedSection}`)
|
||||
}
|
||||
|
||||
state.heading = setting.key
|
||||
state.settings = JSON.stringify([
|
||||
{
|
||||
...setting,
|
||||
description:
|
||||
setting.description +
|
||||
"<br><br><b>Disabling this will make settings below irrelevant</b>",
|
||||
subsettings: undefined,
|
||||
expanded: true,
|
||||
},
|
||||
...Object.entries(setting.subsettings).map(([key, value]) => ({
|
||||
key,
|
||||
section: state.selectedSection,
|
||||
...value,
|
||||
})),
|
||||
])
|
||||
return
|
||||
}
|
||||
|
||||
state.settings = JSON.stringify(results)
|
||||
})
|
||||
|
||||
return html`
|
||||
<div class="settings" id="settingsWrapper">
|
||||
<h1>${() => upperFirst(state.heading)} settings</h1>
|
||||
${() => {
|
||||
const settings = JSON.parse(state.settings).filter(
|
||||
(el) => el.section === state.selectedSection
|
||||
)
|
||||
return html`<div>${SettingsList(settings)}</div>`
|
||||
}}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function SettingsList(settings) {
|
||||
return settings.map((setting) => html`<div>${setting.key}</div>`)
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
#menu_button {
|
||||
align-items: center;
|
||||
background-color: var(--main-fg);
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
bottom: var(--border-radius-xl);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
height: 50px;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
position: fixed;
|
||||
right: var(--border-radius-xl);
|
||||
width: 50px;
|
||||
z-index: var(--z-modal);
|
||||
}
|
||||
|
||||
#menu_button i {
|
||||
color: var(--text-color);
|
||||
font-size: var(--padding-xl);
|
||||
}
|
||||
|
||||
#sidebarUnderlay {
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
height: 100dvh;
|
||||
left: 0;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
transition: var(--transition-fast);
|
||||
width: 100vw;
|
||||
z-index: var(--z-overlay);
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 50px;
|
||||
margin-left: var(--margin-xs);
|
||||
width: 50px;
|
||||
}
|
||||
|
||||
.menu-item-link {
|
||||
align-items: center;
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: inherit;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: var(--gap-sm);
|
||||
height: 100%;
|
||||
padding: var(--padding-xs);
|
||||
text-decoration: none;
|
||||
transition: all var(--transition-fast);
|
||||
white-space: nowrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: block;
|
||||
font-weight: var(--font-weight-bold);
|
||||
padding: 0.5em 0.1em;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background:
|
||||
radial-gradient(ellipse at 30% 80%, rgba(139, 108, 197, 0.06) 0%, transparent 60%),
|
||||
radial-gradient(ellipse at 70% 20%, rgba(94, 200, 200, 0.04) 0%, transparent 50%),
|
||||
var(--sidebar-bg);
|
||||
border-right: var(--border-width-thin) solid var(--sidebar-border-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: var(--border-radius-xl);
|
||||
height: 100dvh;
|
||||
justify-content: space-between;
|
||||
left: calc(-1 * var(--sidebar-width));
|
||||
min-width: var(--sidebar-width);
|
||||
overflow-y: auto;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
transition: var(--transition-fast);
|
||||
width: var(--sidebar-width);
|
||||
z-index: var(--z-sidebar);
|
||||
}
|
||||
|
||||
.sidebar a,
|
||||
.sidebar i,
|
||||
.sidebar li {
|
||||
color: var(--text-color);
|
||||
font-weight: var(--font-weight-normal);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sidebar hr {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar li a {
|
||||
color: inherit;
|
||||
display: block;
|
||||
height: 100%;
|
||||
text-decoration: none;
|
||||
transition: color var(--transition-fast);
|
||||
white-space: nowrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar .menu_section {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>a span {
|
||||
color: var(--text-color);
|
||||
display: inline-block;
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
margin-bottom: var(--padding-xs);
|
||||
padding-left: var(--padding-sm);
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul>li {
|
||||
border-radius: var(--border-radius-sm);
|
||||
margin-bottom: var(--padding-sm);
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
transition: background-color var(--transition-fast), box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul>li>a.menu-item-link {
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul>li.active,
|
||||
.sidebar .menu_section>li>ul>li:hover {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
box-shadow: var(--glow-primary);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul>li.active>a {
|
||||
color: var(--color-white);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>ul>li:hover>a {
|
||||
color: var(--color-white);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
}
|
||||
|
||||
.sidebar .title {
|
||||
align-items: center;
|
||||
background-color: var(--sidebar-active-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
column-gap: var(--gap-sm);
|
||||
display: flex;
|
||||
font-size: var(--font-size-xl);
|
||||
margin: var(--margin-sm) auto;
|
||||
max-width: 90%;
|
||||
padding: var(--padding-sm);
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.sidebar .title:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.sidebar .title a {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.sidebar .title_text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar .title_text a {
|
||||
line-height: var(--line-height-base);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar .title_text a:last-of-type {
|
||||
font-size: 0.6em;
|
||||
}
|
||||
|
||||
.sidebar .title_text p {
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
line-height: var(--line-height-base);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar-pin-button {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
font-size: var(--font-size-lg);
|
||||
margin-left: auto;
|
||||
padding: var(--padding-xs);
|
||||
}
|
||||
|
||||
.sidebar-pin-button:hover,
|
||||
.sidebar-pin-button:focus-visible {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.sidebar.visible {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.sidebar.pinned {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.sidebar_header a:last-of-type {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
font-style: italic;
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
}
|
||||
|
||||
.sidebar_header p {
|
||||
background: linear-gradient(135deg, #8b6cc5 0%, #5ec8c8 55%, #d4789c 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.sidebar_widget {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
margin: var(--margin-sm) auto;
|
||||
max-width: 90%;
|
||||
padding: var(--padding-sm);
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.sidebar_widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 767px) {
|
||||
#sidebarUnderlay {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
.sidebar .menu_section>li>a {
|
||||
font-size: var(--padding-sm);
|
||||
}
|
||||
|
||||
.sidebar .title {
|
||||
flex-direction: row;
|
||||
font-size: var(--border-radius-xl);
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (min-width: 768px) {
|
||||
#menu_button {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
html.galaxy-sidebar-pinned #menu_button {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
import { html } from "/assets/vendor/arrow-core.js";
|
||||
import { hideSidebar, upperFirst } from "/assets/js/utils.js";
|
||||
|
||||
const MENU_ITEMS = {
|
||||
home: [
|
||||
{ name: "Home", link: "/", icon: "bi-house-fill" },
|
||||
],
|
||||
recordings: [
|
||||
{ name: "Dashcam Routes", link: "/dashcam_routes", icon: "bi-camera-reels" },
|
||||
{ name: "Screen Recordings", link: "/screen_recordings", icon: "bi-record-circle" },
|
||||
],
|
||||
tools: [
|
||||
{ name: "Toggles", link: "/device_settings", icon: "bi-toggle-on" },
|
||||
{ name: "Bluetooth", link: "/bluetooth", icon: "bi-bluetooth" },
|
||||
{ name: "Download Speed Limits", link: "/download_speed_limits", icon: "bi-download" },
|
||||
{ name: "Error Logs", link: "/manage_error_logs", icon: "bi-exclamation-triangle" },
|
||||
{ name: "Galaxy", link: "/galaxy", icon: "bi-globe2" },
|
||||
{ name: "Sentry Mode", link: "/sentry", icon: "bi-shield-exclamation" },
|
||||
{ name: "Controllers", link: "/wheel-controls", icon: "bi-controller" },
|
||||
{ name: "Lateral Tuning", link: "/tuning", icon: "bi-sign-turn-right" },
|
||||
{ name: "Maps", link: "/manage_maps", icon: "bi-map" },
|
||||
{ name: "Navigation", link: "/set_navigation_destination", icon: "bi-geo-alt-fill" },
|
||||
{ name: "App Keys", link: "/manage_navigation_keys", icon: "bi-key-fill" },
|
||||
{ name: "Model Manager", link: "/manage_models", icon: "bi-cpu" },
|
||||
{ name: "Model Laboratory", link: "/model_laboratory", icon: "bi-bezier2" },
|
||||
{ name: "Plots", link: "/plots", icon: "bi-graph-up-arrow" },
|
||||
{ name: "Testing Ground", link: "/testing_ground", icon: "bi-bezier2" },
|
||||
{ name: "Troubleshoot", link: "/troubleshoot", icon: "bi-tools" },
|
||||
{ name: "V-Adj Spot Monitor", link: "/manage_v_asm", icon: "bi-eye" },
|
||||
{ name: "PiP Side Camera", link: "/manage_pip_sidecam", icon: "bi-badge-hd", developerOnly: true },
|
||||
{ name: "Theme Maker", link: "/theme_maker", icon: "bi-palette-fill" },
|
||||
{ name: "Tmux Log", link: "/manage_tmux", icon: "bi-terminal" },
|
||||
{ name: "Backup and Restore", link: "/manage_toggles", icon: "bi-arrow-repeat" },
|
||||
{ name: "Software", link: "/manage_updates", icon: "bi-arrow-up-circle" },
|
||||
{ name: "Vehicle Features", link: "/vehicle_features", icon: "bi-car-front" },
|
||||
],
|
||||
};
|
||||
|
||||
let galaxyDeveloperMode = false;
|
||||
const SIDEBAR_PINNED_KEY = "galaxySidebarPinned";
|
||||
let sidebarPinnedPreference = null;
|
||||
|
||||
function defaultSidebarPinned() {
|
||||
try {
|
||||
return window.matchMedia?.("(min-width: 768px)")?.matches ?? window.innerWidth >= 768;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sidebarPinned() {
|
||||
if (sidebarPinnedPreference !== null) return sidebarPinnedPreference;
|
||||
let stored;
|
||||
try {
|
||||
stored = window.localStorage?.getItem(SIDEBAR_PINNED_KEY);
|
||||
} catch {
|
||||
stored = null;
|
||||
}
|
||||
if (stored === "true" || stored === "false") {
|
||||
sidebarPinnedPreference = stored === "true";
|
||||
return sidebarPinnedPreference;
|
||||
}
|
||||
return defaultSidebarPinned();
|
||||
}
|
||||
|
||||
function setSidebarPinned(pinned) {
|
||||
sidebarPinnedPreference = Boolean(pinned);
|
||||
try {
|
||||
window.localStorage?.setItem(SIDEBAR_PINNED_KEY, String(sidebarPinnedPreference));
|
||||
} catch {
|
||||
}
|
||||
document.documentElement.classList.toggle("galaxy-sidebar-pinned", sidebarPinnedPreference);
|
||||
}
|
||||
|
||||
function matchesPath(currentPath, link) {
|
||||
if (link === "/") return currentPath === "/";
|
||||
if (link === "/tuning" && currentPath === "/lateral_maneuvers") return true;
|
||||
return currentPath === link || currentPath.startsWith(`${link}/`);
|
||||
}
|
||||
|
||||
function buildSectionMarkup(section, links, currentPath) {
|
||||
const linksMarkup = links.filter((link) => !link.developerOnly || galaxyDeveloperMode).map((link) => {
|
||||
const active = matchesPath(currentPath, link.link) ? "active" : "";
|
||||
return `
|
||||
<li class="${active}">
|
||||
<a class="menu-item-link" href="${link.link}">
|
||||
<i class="bi ${link.icon}"></i>
|
||||
<span>${upperFirst(link.name)}</span>
|
||||
</a>
|
||||
</li>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
return `
|
||||
<div class="sidebar_widget">
|
||||
<ul class="menu_section">
|
||||
<li>
|
||||
<span class="section-title">${upperFirst(section)}</span>
|
||||
<ul id="${section}">
|
||||
${linksMarkup}
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function refreshGalaxyDeveloperMode() {
|
||||
try {
|
||||
const response = await fetch("/api/params/all", { cache: "no-store" });
|
||||
if (!response.ok) return;
|
||||
const values = await response.json();
|
||||
const next = Boolean(values?.GalaxyDeveloperMode);
|
||||
if (next !== galaxyDeveloperMode) {
|
||||
galaxyDeveloperMode = next;
|
||||
renderSidebarIntoShell();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Unable to determine Galaxy Developer Mode:", error);
|
||||
}
|
||||
}
|
||||
|
||||
function bindSidebarHandlers() {
|
||||
const menuButton = document.getElementById("menu_button");
|
||||
const underlay = document.getElementById("sidebarUnderlay");
|
||||
|
||||
if (!menuButton || !underlay) return;
|
||||
|
||||
const pinButton = document.getElementById("sidebar_pin_button");
|
||||
pinButton?.addEventListener("click", () => {
|
||||
const pinned = !sidebarPinned();
|
||||
setSidebarPinned(pinned);
|
||||
const sidebar = document.getElementById("sidebar");
|
||||
hideSidebar();
|
||||
sidebar?.classList.toggle("pinned", pinned);
|
||||
pinButton.setAttribute("aria-pressed", String(pinned));
|
||||
pinButton.setAttribute("title", pinned ? "Unpin navigation" : "Pin navigation");
|
||||
pinButton.querySelector("i")?.classList.toggle("bi-pin-angle-fill", pinned);
|
||||
pinButton.querySelector("i")?.classList.toggle("bi-pin-angle", !pinned);
|
||||
});
|
||||
|
||||
if (menuButton.dataset.boundClick !== "1") {
|
||||
menuButton.dataset.boundClick = "1";
|
||||
menuButton.addEventListener("click", () => {
|
||||
const sidebar = document.getElementById("sidebar");
|
||||
const currentUnderlay = document.getElementById("sidebarUnderlay");
|
||||
if (!sidebar || !currentUnderlay) return;
|
||||
if (sidebar.classList.contains("pinned")) return;
|
||||
const open = sidebar.classList.toggle("visible");
|
||||
currentUnderlay.classList.toggle("hidden", !open);
|
||||
menuButton.setAttribute("aria-expanded", String(open));
|
||||
});
|
||||
}
|
||||
|
||||
underlay.onclick = hideSidebar;
|
||||
|
||||
document.querySelectorAll("#sidebar a.menu-item-link").forEach((anchor) => {
|
||||
if (anchor.dataset.boundClick === "1") return;
|
||||
anchor.dataset.boundClick = "1";
|
||||
anchor.addEventListener("click", (event) => {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.button !== 0) return;
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
|
||||
event.preventDefault();
|
||||
const href = anchor.getAttribute("href") || "/";
|
||||
const navigate = window.__theGalaxyNavigate;
|
||||
if (typeof navigate === "function") {
|
||||
navigate(href);
|
||||
} else {
|
||||
window.location.assign(href);
|
||||
}
|
||||
hideSidebar();
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderSidebarIntoShell(currentPath) {
|
||||
const shell = document.getElementById("sidebar_shell");
|
||||
if (!shell) return;
|
||||
|
||||
const activePath = currentPath || window.location.pathname;
|
||||
const pinned = sidebarPinned();
|
||||
const sectionsMarkup = Object.entries(MENU_ITEMS)
|
||||
.map(([section, links]) => buildSectionMarkup(section, links, activePath))
|
||||
.join("");
|
||||
|
||||
shell.innerHTML = `
|
||||
<div id="sidebarUnderlay" class="hidden"></div>
|
||||
<div id="sidebar" class="sidebar${pinned ? " pinned" : ""}">
|
||||
<div>
|
||||
<div class="title">
|
||||
<img class="logo" src="/assets/images/main_logo.png" alt="Galaxy logo" />
|
||||
<div class="title_text sidebar_header">
|
||||
<p>Galaxy</p>
|
||||
</div>
|
||||
<button id="sidebar_pin_button" class="sidebar-pin-button" type="button"
|
||||
aria-label="Toggle pinned navigation" aria-pressed="${pinned}"
|
||||
title="${pinned ? "Unpin navigation" : "Pin navigation"}">
|
||||
<i class="bi ${pinned ? "bi-pin-angle-fill" : "bi-pin-angle"}"></i>
|
||||
</button>
|
||||
</div>
|
||||
<hr />
|
||||
${sectionsMarkup}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
bindSidebarHandlers();
|
||||
}
|
||||
|
||||
export function Sidebar(currentPath) {
|
||||
setTimeout(() => {
|
||||
document.documentElement.classList.toggle("galaxy-sidebar-pinned", sidebarPinned());
|
||||
renderSidebarIntoShell(currentPath);
|
||||
refreshGalaxyDeveloperMode();
|
||||
}, 0);
|
||||
return html`<div id="sidebar_shell"></div>`;
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
.tailscale-button {
|
||||
background-color: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--border-radius-xl);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
transition: background-color var(--transition-fast), box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tailscale-button + .tailscale-button {
|
||||
margin-top: var(--padding-sm);
|
||||
}
|
||||
|
||||
.tailscale-button:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--secondary-fg);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
.tailscale-button-wrapper {
|
||||
height: calc(100% + 20px);
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tailscale-link {
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-sm);
|
||||
left: 50%;
|
||||
margin-top: var(--border-radius-sm);
|
||||
position: absolute;
|
||||
text-decoration: underline;
|
||||
top: 100%;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tailscale-text {
|
||||
color: var(--text-color);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tailscale-title {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tailscale-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tailscale-widget {
|
||||
align-items: center;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--main-fg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-xl);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.tailscale-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { Modal } from "/assets/components/modal.js";
|
||||
|
||||
export function TailscaleControl() {
|
||||
const state = reactive({
|
||||
status: "idle",
|
||||
installed: false,
|
||||
showUninstallModal: false,
|
||||
});
|
||||
|
||||
async function checkInstallStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/tailscale/installed")
|
||||
const result = await response.json()
|
||||
state.installed = result.installed
|
||||
} catch (error) {
|
||||
console.error("Failed to check Tailscale install status:", error)
|
||||
}
|
||||
}
|
||||
|
||||
function confirmUninstall() {
|
||||
state.showUninstallModal = true;
|
||||
}
|
||||
|
||||
async function handleAction() {
|
||||
if (state.status !== "idle") {
|
||||
return
|
||||
}
|
||||
|
||||
const action = state.installed ? "uninstall" : "install"
|
||||
state.status = state.installed ? "uninstalling" : "installing"
|
||||
|
||||
state.showUninstallModal = false;
|
||||
|
||||
showSnackbar(`${action.charAt(0).toUpperCase() + action.slice(1)} started...`)
|
||||
|
||||
const endpoint = state.installed ? "/api/tailscale/uninstall" : "/api/tailscale/setup"
|
||||
const response = await fetch(endpoint, { method: "POST" })
|
||||
const result = await response.json()
|
||||
|
||||
showSnackbar(result.message || `${action.charAt(0).toUpperCase() + action.slice(1)} triggered...`)
|
||||
|
||||
if (result.auth_url) {
|
||||
window.location.href = result.auth_url;
|
||||
}
|
||||
|
||||
// Refresh install status after action
|
||||
await checkInstallStatus();
|
||||
state.status = "idle"
|
||||
}
|
||||
|
||||
checkInstallStatus()
|
||||
|
||||
return html`
|
||||
<div class="toggle-control-widget" style="margin-top: 1.5rem">
|
||||
<section class="tailscale-widget">
|
||||
<div class="toggle-control-title">
|
||||
${() => state.installed ? 'Uninstall Tailscale' : 'Install Tailscale'}
|
||||
</div>
|
||||
<p class="tailscale-text">
|
||||
Tailscale creates a secure, private connection between your openpilot device and your phone or PC so you can access and control it from anywhere!<br><br>
|
||||
<strong style="color: #ff9494;">Note: Not recommended. Using Galaxy Tunnel is the preferred remote connection method.</strong>
|
||||
</p>
|
||||
<div class="tailscale-button-wrapper">
|
||||
<button
|
||||
class="tailscale-button"
|
||||
@click="${() => state.installed ? confirmUninstall() : handleAction()}"
|
||||
disabled="${() => state.status === 'installing' || state.status === 'uninstalling'}"
|
||||
>
|
||||
${() => {
|
||||
if (state.status === 'installing') return 'Installing...'
|
||||
if (state.status === 'uninstalling') return 'Uninstalling...'
|
||||
if (state.installed) return 'Uninstall'
|
||||
return 'Install'
|
||||
}}
|
||||
</button>
|
||||
<a class="tailscale-link" href="https://tailscale.com/download" target="_blank">
|
||||
Download Tailscale on your other devices
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
${() => state.showUninstallModal ? Modal({
|
||||
title: "Confirm Uninstall",
|
||||
message: "Are you sure you want to uninstall Tailscale?",
|
||||
onConfirm: handleAction,
|
||||
onCancel: () => { state.showUninstallModal = false; },
|
||||
confirmText: "Uninstall"
|
||||
}) : ""}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+457
@@ -0,0 +1,457 @@
|
||||
.bluetoothPage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
margin: 0 auto;
|
||||
max-width: var(--width-xxxl);
|
||||
padding: var(--padding-base) var(--padding-lg) var(--padding-xxl);
|
||||
}
|
||||
|
||||
.bluetoothHeader,
|
||||
.bluetoothTitle,
|
||||
.bluetoothToolbar,
|
||||
.bluetoothActions,
|
||||
.bluetoothDeviceName,
|
||||
.bluetoothSectionHeader,
|
||||
.bluetoothSectionHeader > div {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.bluetoothHeader {
|
||||
justify-content: space-between;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.bluetoothTitle {
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.bluetoothTitle > i {
|
||||
align-items: center;
|
||||
background: rgba(139, 108, 197, 0.16);
|
||||
border: 1px solid rgba(169, 140, 229, 0.34);
|
||||
border-radius: 16px;
|
||||
color: #b99bec;
|
||||
display: flex;
|
||||
font-size: 2rem;
|
||||
height: 58px;
|
||||
justify-content: center;
|
||||
width: 58px;
|
||||
}
|
||||
|
||||
.bluetoothHeader h2,
|
||||
.bluetoothHeader p,
|
||||
.bluetoothDeviceRow h3,
|
||||
.bluetoothDeviceRow p,
|
||||
.bluetoothEmptyPage h3,
|
||||
.bluetoothEmptyPage p,
|
||||
.bluetoothSectionHeader h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.bluetoothHeader p {
|
||||
margin-top: 4px;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.bluetoothNotice,
|
||||
.bluetoothError,
|
||||
.bluetoothPrompt {
|
||||
background: var(--sidebar-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-lg);
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.bluetoothNotice,
|
||||
.bluetoothPrompt {
|
||||
color: #ffe2a3;
|
||||
}
|
||||
|
||||
.bluetoothPromptHeader,
|
||||
.bluetoothPromptActions {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bluetoothPromptHeader {
|
||||
color: #ffe2a3;
|
||||
}
|
||||
|
||||
.bluetoothPromptHeader i {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.bluetoothPrompt p {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.bluetoothPromptPasskey {
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.bluetoothPromptInput {
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
font: inherit;
|
||||
margin-top: 12px;
|
||||
max-width: 260px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.bluetoothPromptActions {
|
||||
justify-content: flex-end;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.bluetoothPromptActions button {
|
||||
background: linear-gradient(135deg, #765bb6, #9474ce);
|
||||
border: 0;
|
||||
border-radius: var(--border-radius-md);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
font-weight: 700;
|
||||
padding: 9px 14px;
|
||||
}
|
||||
|
||||
.bluetoothPromptActions button.bluetoothPromptReject {
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.bluetoothPromptActions button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.bluetoothError {
|
||||
color: #ff9ab3;
|
||||
}
|
||||
|
||||
.bluetoothAudioCountdown {
|
||||
align-items: center;
|
||||
background: rgba(64, 201, 124, 0.12);
|
||||
border: 1px solid rgba(64, 201, 124, 0.45);
|
||||
border-radius: var(--border-radius-lg);
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.bluetoothAudioCountdown strong {
|
||||
color: #b8ffd4;
|
||||
font-size: 2rem;
|
||||
min-width: 72px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bluetoothSwitch,
|
||||
.bluetoothToolbar button,
|
||||
.bluetoothActions button {
|
||||
align-items: center;
|
||||
background: linear-gradient(135deg, #765bb6, #9474ce);
|
||||
border: 0;
|
||||
border-radius: var(--border-radius-md);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
font-weight: 700;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
padding: 10px 14px;
|
||||
transition: filter 140ms ease, opacity 140ms ease, transform 140ms ease;
|
||||
}
|
||||
|
||||
.bluetoothSwitch:hover,
|
||||
.bluetoothToolbar button:hover:not(:disabled),
|
||||
.bluetoothActions button:hover:not(:disabled) {
|
||||
filter: brightness(1.1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.bluetoothSwitch input {
|
||||
accent-color: #c4a7ff;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.bluetoothToolbar {
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bluetoothToolbar button.scanning i {
|
||||
animation: bluetoothSpin 1s linear infinite;
|
||||
}
|
||||
|
||||
.bluetoothToolbar .bluetoothSecondaryButton {
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.bluetoothScanHint {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.86rem;
|
||||
margin-left: auto;
|
||||
opacity: 0.78;
|
||||
}
|
||||
|
||||
.bluetoothDeviceList {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.bluetoothSection {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bluetoothSectionHeader {
|
||||
background: var(--input-bg);
|
||||
justify-content: space-between;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.bluetoothSectionHeader > div {
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bluetoothSectionHeader i {
|
||||
color: #b99bec;
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.bluetoothSectionHeader h3 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.bluetoothSectionHeader > span {
|
||||
background: rgba(169, 140, 229, 0.16);
|
||||
border-radius: 999px;
|
||||
color: #d9c9ff;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
min-width: 26px;
|
||||
padding: 4px 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bluetoothSectionBody > .bluetoothDeviceRow + .bluetoothDeviceRow {
|
||||
border-top: 1px solid var(--sidebar-border-color);
|
||||
}
|
||||
|
||||
.bluetoothDeviceRow {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
grid-template-columns: 48px minmax(180px, 1fr) auto;
|
||||
padding: 15px 16px;
|
||||
transition: background-color 140ms ease;
|
||||
}
|
||||
|
||||
.bluetoothDeviceRow:hover {
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
|
||||
.bluetoothDeviceRow.connected {
|
||||
box-shadow: inset 3px 0 0 #40c97c;
|
||||
}
|
||||
|
||||
.bluetoothDeviceIcon {
|
||||
align-items: center;
|
||||
background: rgba(169, 140, 229, 0.12);
|
||||
border: 1px solid rgba(169, 140, 229, 0.24);
|
||||
border-radius: 50%;
|
||||
color: #cbb2fa;
|
||||
display: flex;
|
||||
font-size: 1.25rem;
|
||||
height: 44px;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
}
|
||||
|
||||
.bluetoothDeviceDetails {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bluetoothDeviceName {
|
||||
gap: 9px;
|
||||
}
|
||||
|
||||
.bluetoothDeviceName h3 {
|
||||
font-size: 1rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bluetoothConnectedDot {
|
||||
background: #40c97c;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 3px rgba(64, 201, 124, 0.13);
|
||||
flex: 0 0 auto;
|
||||
height: 8px;
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.bluetoothDeviceRow p {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
margin-top: 3px;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.bluetoothDeviceStatus {
|
||||
color: #cbb2fa;
|
||||
display: inline-block;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.bluetoothActions {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.bluetoothActions button.selected {
|
||||
background: linear-gradient(135deg, #258b58, #40c97c);
|
||||
}
|
||||
|
||||
.bluetoothActions .bluetoothIconButton {
|
||||
min-width: 42px;
|
||||
padding-left: 12px;
|
||||
padding-right: 12px;
|
||||
}
|
||||
|
||||
.bluetoothActions .bluetoothForgetButton {
|
||||
background: rgba(217, 90, 123, 0.13);
|
||||
border: 1px solid rgba(217, 90, 123, 0.34);
|
||||
color: #ff9ab3;
|
||||
}
|
||||
|
||||
.bluetoothToolbar button:disabled,
|
||||
.bluetoothActions button:disabled,
|
||||
.bluetoothSwitch:has(input:disabled) {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.45;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.bluetoothEmptyState,
|
||||
.bluetoothEmptyPage,
|
||||
.bluetoothLoading {
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bluetoothEmptyState {
|
||||
padding: 28px 18px;
|
||||
}
|
||||
|
||||
.bluetoothEmptyPage {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-lg);
|
||||
padding: 46px 20px;
|
||||
}
|
||||
|
||||
.bluetoothEmptyPage > i {
|
||||
color: #b99bec;
|
||||
display: block;
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.bluetoothEmptyPage p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.bluetoothLoading {
|
||||
padding: 36px;
|
||||
}
|
||||
|
||||
.bluetoothLoading span {
|
||||
animation: bluetoothBounce 1.1s infinite ease-in-out;
|
||||
background: #b99bec;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
height: 8px;
|
||||
margin: 0 4px;
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.bluetoothLoading span:nth-child(2) {
|
||||
animation-delay: 0.14s;
|
||||
}
|
||||
|
||||
.bluetoothLoading span:nth-child(3) {
|
||||
animation-delay: 0.28s;
|
||||
}
|
||||
|
||||
@keyframes bluetoothSpin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes bluetoothBounce {
|
||||
0%, 60%, 100% { opacity: 0.35; transform: translateY(0); }
|
||||
30% { opacity: 1; transform: translateY(-7px); }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.bluetoothPage {
|
||||
padding-left: var(--padding-base);
|
||||
padding-right: var(--padding-base);
|
||||
}
|
||||
|
||||
.bluetoothHeader,
|
||||
.bluetoothToolbar {
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.bluetoothHeader {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.bluetoothSwitch {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.bluetoothScanHint {
|
||||
flex-basis: 100%;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.bluetoothDeviceRow {
|
||||
grid-template-columns: 44px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.bluetoothActions {
|
||||
grid-column: 1 / -1;
|
||||
justify-content: flex-start;
|
||||
padding-left: 58px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.bluetoothToolbar button {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.bluetoothActions {
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.bluetoothActions button:not(.bluetoothIconButton) {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
}
|
||||
+476
@@ -0,0 +1,476 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { escapeHtml, galaxyPath } from "/assets/js/utils.js"
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
busy: "",
|
||||
powerTarget: null,
|
||||
available: false,
|
||||
enabled: false,
|
||||
powered: false,
|
||||
discovering: false,
|
||||
offroad: false,
|
||||
selectedAudio: "",
|
||||
pairingAddress: "",
|
||||
devices: [],
|
||||
revision: 0,
|
||||
deviceSignature: "",
|
||||
refreshing: false,
|
||||
lastUpdated: 0,
|
||||
prompt: null,
|
||||
audioTestAddress: "",
|
||||
audioTestLabel: "",
|
||||
error: "",
|
||||
})
|
||||
|
||||
let initialized = false
|
||||
let audioTestTimer = null
|
||||
let pollTimer = null
|
||||
let refreshRequested = false
|
||||
let refreshPromise = null
|
||||
const POLL_INTERVAL_MS = 750
|
||||
const ACTIVE_POLL_INTERVAL_MS = 250
|
||||
|
||||
function bluetoothPageActive() {
|
||||
const currentPath = window.location.pathname.replace(/\/+$/, "")
|
||||
const bluetoothPath = galaxyPath("/bluetooth").replace(/\/+$/, "")
|
||||
return document.querySelector(".bluetoothPage") !== null || currentPath === bluetoothPath
|
||||
}
|
||||
|
||||
function pollDelay() {
|
||||
return state.busy || state.discovering || state.pairingAddress ? ACTIVE_POLL_INTERVAL_MS : POLL_INTERVAL_MS
|
||||
}
|
||||
|
||||
function schedulePoll(delay = pollDelay()) {
|
||||
if (pollTimer !== null) clearTimeout(pollTimer)
|
||||
pollTimer = setTimeout(async () => {
|
||||
pollTimer = null
|
||||
try {
|
||||
if (bluetoothPageActive() && document.visibilityState !== "hidden" && state.busy !== "power") {
|
||||
await refresh()
|
||||
}
|
||||
} finally {
|
||||
schedulePoll()
|
||||
}
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function startAudioTestCountdown(address, delayMs, requestStartedAt) {
|
||||
if (audioTestTimer !== null) clearInterval(audioTestTimer)
|
||||
const halfRoundTripMs = Math.max(0, (performance.now() - requestStartedAt) / 2)
|
||||
const deadline = performance.now() + Math.max(0, delayMs - halfRoundTripMs)
|
||||
state.audioTestAddress = address
|
||||
|
||||
const update = () => {
|
||||
const remaining = deadline - performance.now()
|
||||
if (remaining > 0) {
|
||||
state.audioTestLabel = String(Math.max(1, Math.ceil(remaining / 1000)))
|
||||
} else if (remaining > -3000) {
|
||||
state.audioTestLabel = "NOW"
|
||||
} else {
|
||||
state.audioTestLabel = ""
|
||||
state.audioTestAddress = ""
|
||||
clearInterval(audioTestTimer)
|
||||
audioTestTimer = null
|
||||
}
|
||||
}
|
||||
update()
|
||||
audioTestTimer = setInterval(update, 50)
|
||||
}
|
||||
|
||||
async function request(operation, body = {}) {
|
||||
const requestStartedAt = performance.now()
|
||||
state.busy = operation
|
||||
if (operation === "power") state.powerTarget = !!body.enabled
|
||||
schedulePoll(250)
|
||||
try {
|
||||
const response = await fetch(galaxyPath(`/api/bluetooth/${operation}`), {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const payload = await response.json()
|
||||
if (!response.ok) throw new Error(payload.error || "Bluetooth operation failed")
|
||||
if (operation === "test_audio") {
|
||||
startAudioTestCountdown(String(body.address || ""), Number(payload.audio_test_delay_ms || 3000), requestStartedAt)
|
||||
}
|
||||
state.error = ""
|
||||
await refresh()
|
||||
} catch (error) {
|
||||
state.error = error?.message || "Bluetooth operation failed"
|
||||
} finally {
|
||||
state.busy = ""
|
||||
if (operation === "power") state.powerTarget = null
|
||||
schedulePoll(250)
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshOnce() {
|
||||
const statusUrl = `${galaxyPath("/api/bluetooth/status")}?_=${Date.now()}`
|
||||
const response = await fetch(statusUrl, { cache: "no-store" })
|
||||
const payload = await response.json()
|
||||
state.available = !!payload.available
|
||||
state.enabled = !!payload.enabled
|
||||
state.powered = !!payload.powered
|
||||
state.discovering = !!payload.discovering
|
||||
state.offroad = !!payload.offroad
|
||||
state.selectedAudio = String(payload.selected_audio || "")
|
||||
state.pairingAddress = String(payload.pairing_address || "")
|
||||
const devices = Array.isArray(payload.devices) ? payload.devices : []
|
||||
const deviceSignature = JSON.stringify({
|
||||
enabled: state.enabled,
|
||||
discovering: state.discovering,
|
||||
selectedAudio: state.selectedAudio,
|
||||
pairingAddress: state.pairingAddress,
|
||||
devices,
|
||||
})
|
||||
state.devices = devices
|
||||
if (state.deviceSignature !== deviceSignature) {
|
||||
state.deviceSignature = deviceSignature
|
||||
state.revision++
|
||||
}
|
||||
state.lastUpdated = Date.now()
|
||||
state.prompt = payload.prompt || null
|
||||
state.error = payload.error || (response.ok ? "" : "Bluetooth service unavailable")
|
||||
}
|
||||
|
||||
function pairingPromptNeedsValue() {
|
||||
return state.prompt && (state.prompt.kind === "pin" || state.prompt.kind === "passkey")
|
||||
}
|
||||
|
||||
function respondToPairingPrompt(accepted) {
|
||||
const prompt = state.prompt
|
||||
if (!prompt || state.busy === "pairing_response") return
|
||||
const input = document.getElementById("bluetoothPairingValue")
|
||||
const value = input?.value.trim() || ""
|
||||
if (accepted && prompt.kind === "pin" && !value) {
|
||||
state.error = "Enter the PIN to continue pairing."
|
||||
input?.focus()
|
||||
return
|
||||
}
|
||||
if (accepted && prompt.kind === "passkey" && !/^\d{1,6}$/.test(value)) {
|
||||
state.error = "Enter the numeric passkey to continue pairing."
|
||||
input?.focus()
|
||||
return
|
||||
}
|
||||
request("pairing_response", { prompt_id: prompt.id, accepted, value })
|
||||
}
|
||||
|
||||
function pairingPrompt() {
|
||||
const prompt = state.prompt
|
||||
if (!prompt) return ""
|
||||
const name = prompt.name || "Bluetooth device"
|
||||
const valuePrompt = pairingPromptNeedsValue()
|
||||
const message = prompt.kind === "confirmation"
|
||||
? "Confirm the pairing request on this device."
|
||||
: prompt.kind === "authorization"
|
||||
? "Allow this device to connect?"
|
||||
: prompt.kind === "pin"
|
||||
? "Enter the PIN supplied by the device."
|
||||
: prompt.kind === "passkey"
|
||||
? "Enter the device passkey."
|
||||
: "Follow the instructions on the device."
|
||||
return html`
|
||||
<div class="bluetoothPrompt">
|
||||
<div class="bluetoothPromptHeader"><i class="bi bi-shield-check" aria-hidden="true"></i><strong>Bluetooth pairing request</strong></div>
|
||||
<p><strong>${name}</strong> — ${message}</p>
|
||||
${prompt.value ? html`<p class="bluetoothPromptPasskey">Passkey: <strong>${prompt.value}</strong></p>` : ""}
|
||||
${() => valuePrompt ? html`
|
||||
<input id="bluetoothPairingValue" class="bluetoothPromptInput" inputmode="numeric" autocomplete="one-time-code"
|
||||
placeholder="${() => prompt.kind === "pin" ? "PIN" : "Passkey"}" disabled="${() => state.busy === "pairing_response"}" />
|
||||
` : ""}
|
||||
${prompt.display_only ? "" : html`
|
||||
<div class="bluetoothPromptActions">
|
||||
<button class="bluetoothPromptReject" disabled="${() => state.busy === "pairing_response"}" @click="${() => respondToPairingPrompt(false)}">Cancel</button>
|
||||
<button disabled="${() => state.busy === "pairing_response"}" @click="${() => respondToPairingPrompt(true)}">Allow</button>
|
||||
</div>
|
||||
`}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
refreshRequested = true
|
||||
if (refreshPromise !== null) return refreshPromise
|
||||
|
||||
state.refreshing = true
|
||||
refreshPromise = (async () => {
|
||||
while (refreshRequested) {
|
||||
refreshRequested = false
|
||||
try {
|
||||
await refreshOnce()
|
||||
} catch (error) {
|
||||
state.available = false
|
||||
state.error = error?.message || "Bluetooth service unavailable"
|
||||
} finally {
|
||||
state.loading = false
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
try {
|
||||
await refreshPromise
|
||||
} finally {
|
||||
refreshPromise = null
|
||||
state.refreshing = false
|
||||
}
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
if (initialized) return
|
||||
initialized = true
|
||||
window.addEventListener("focus", refresh)
|
||||
window.addEventListener("pageshow", refresh)
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState !== "hidden" && bluetoothPageActive()) refresh()
|
||||
})
|
||||
refresh()
|
||||
schedulePoll(0)
|
||||
}
|
||||
|
||||
function normalizedAddress(device) {
|
||||
return String(device.address || "").toUpperCase()
|
||||
}
|
||||
|
||||
function isPairing(device) {
|
||||
return !!state.pairingAddress && state.pairingAddress.toUpperCase() === normalizedAddress(device)
|
||||
}
|
||||
|
||||
function deviceIcon(device) {
|
||||
if (device.audio && device.controller) return "bi-headset"
|
||||
if (device.audio) return "bi-headphones"
|
||||
if (device.controller) return "bi-controller"
|
||||
return "bi-bluetooth"
|
||||
}
|
||||
|
||||
function deviceCapabilities(device) {
|
||||
const capabilities = []
|
||||
if (device.audio) capabilities.push("Audio")
|
||||
if (device.controller) capabilities.push("Controller")
|
||||
return capabilities.join(" · ") || "Bluetooth device"
|
||||
}
|
||||
|
||||
function deviceStatus(device) {
|
||||
if (isPairing(device)) return "Pairing…"
|
||||
if (device.connected) {
|
||||
const audioSelected = state.selectedAudio.toUpperCase() === normalizedAddress(device)
|
||||
if (!device.paired) return audioSelected ? "Connected · Ready to pair · Audio output" : "Connected · Ready to pair"
|
||||
return audioSelected ? "Connected · Audio output" : "Connected"
|
||||
}
|
||||
return device.paired ? "Saved" : "Ready to pair"
|
||||
}
|
||||
|
||||
function knownDevices() {
|
||||
return state.devices.filter((device) => device.paired || device.trusted || device.connected)
|
||||
}
|
||||
|
||||
function availableDevices() {
|
||||
return state.devices.filter((device) => !device.paired && !device.trusted && !device.connected)
|
||||
}
|
||||
|
||||
function deviceActions(device) {
|
||||
const audioSelected = () => state.selectedAudio.toUpperCase() === device.address.toUpperCase()
|
||||
const pairing = () => isPairing(device)
|
||||
return html`
|
||||
<div class="bluetoothActions">
|
||||
${!device.paired ? html`
|
||||
<button disabled="${() => !state.offroad || !!state.busy || pairing()}" @click="${() => request("pair", { address: device.address })}">
|
||||
${() => pairing() ? "Pairing…" : "Pair"}
|
||||
</button>
|
||||
` : ""}
|
||||
${device.paired || device.connected ? html`
|
||||
<button disabled="${() => !!state.busy}" @click="${() => request(device.connected ? "disconnect" : "connect", { address: device.address })}">
|
||||
${device.connected ? "Disconnect" : "Connect"}
|
||||
</button>
|
||||
` : ""}
|
||||
${device.paired || device.connected ? html`
|
||||
${device.audio ? html`
|
||||
<button class="${() => audioSelected() ? "selected" : ""}"
|
||||
disabled="${() => !!state.busy}" @click="${() => request("select_audio", { address: audioSelected() ? "" : device.address })}">
|
||||
${() => audioSelected() ? "Stop Using for Audio" : "Use for Audio"}
|
||||
</button>
|
||||
${device.connected ? html`
|
||||
<button disabled="${() => !state.offroad || !!state.busy || !!state.audioTestLabel}" @click="${() => request("test_audio", { address: device.address })}">
|
||||
${() => state.audioTestAddress === device.address && state.audioTestLabel ? `Test Audio: ${state.audioTestLabel}` : "Test Audio"}
|
||||
</button>
|
||||
` : ""}
|
||||
` : ""}
|
||||
${device.paired ? html`<button class="bluetoothIconButton bluetoothForgetButton" title="Forget device" aria-label="Forget ${device.name}"
|
||||
disabled="${() => !state.offroad || !!state.busy}" @click="${() => {
|
||||
if (window.confirm(`Forget ${device.name}?`)) request("forget", { address: device.address })
|
||||
}}"><i class="bi bi-trash3" aria-hidden="true"></i></button>` : ""}
|
||||
` : ""}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function deviceRow(device) {
|
||||
return html`
|
||||
<div class="${() => `bluetoothDeviceRow ${device.connected ? "connected" : ""}`}">
|
||||
<div class="bluetoothDeviceIcon"><i class="bi ${deviceIcon(device)}" aria-hidden="true"></i></div>
|
||||
<div class="bluetoothDeviceDetails">
|
||||
<div class="bluetoothDeviceName">
|
||||
<h3>${device.name}</h3>
|
||||
${device.connected ? html`<span class="bluetoothConnectedDot" title="Connected"></span>` : ""}
|
||||
</div>
|
||||
<p>${deviceCapabilities(device)}</p>
|
||||
<span class="bluetoothDeviceStatus">${() => deviceStatus(device)}</span>
|
||||
</div>
|
||||
${deviceActions(device)}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
function deviceSection(title, icon, devices, emptyText = "", revision = null) {
|
||||
const revisionAttribute = revision === null ? "" : ` data-revision="${revision}"`
|
||||
return html`
|
||||
<section class="bluetoothSection"${revisionAttribute}>
|
||||
<div class="bluetoothSectionHeader">
|
||||
<div><i class="bi ${icon}" aria-hidden="true"></i><h3>${title}</h3></div>
|
||||
<span>${devices.length}</span>
|
||||
</div>
|
||||
<div class="bluetoothSectionBody">
|
||||
${devices.length ? devices.map(deviceRow) : html`
|
||||
<div class="bluetoothEmptyState">${emptyText}</div>
|
||||
`}
|
||||
</div>
|
||||
</section>
|
||||
`
|
||||
}
|
||||
|
||||
function renderDisabledAttribute(disabled) {
|
||||
return disabled ? " disabled" : ""
|
||||
}
|
||||
|
||||
function renderDeviceActions(device) {
|
||||
const selected = state.selectedAudio.toUpperCase() === device.address.toUpperCase()
|
||||
const pairing = isPairing(device)
|
||||
const address = escapeHtml(device.address)
|
||||
const name = escapeHtml(device.name)
|
||||
const actions = []
|
||||
if (!device.paired) {
|
||||
actions.push("<button data-bluetooth-operation=\"pair\" data-address=\"" + address + "\"" +
|
||||
renderDisabledAttribute(!state.offroad || !!state.busy || pairing) + ">" + (pairing ? "Pairing…" : "Pair") + "</button>")
|
||||
}
|
||||
if (device.paired || device.connected) {
|
||||
const operation = device.connected ? "disconnect" : "connect"
|
||||
actions.push("<button data-bluetooth-operation=\"" + operation + "\" data-address=\"" + address + "\"" +
|
||||
renderDisabledAttribute(!!state.busy) + ">" + (device.connected ? "Disconnect" : "Connect") + "</button>")
|
||||
if (device.audio) {
|
||||
actions.push("<button class=\"" + (selected ? "selected" : "") + "\" data-bluetooth-operation=\"select_audio\" data-address=\"" +
|
||||
(selected ? "" : address) + "\"" + renderDisabledAttribute(!!state.busy) + ">" +
|
||||
(selected ? "Stop Using for Audio" : "Use for Audio") + "</button>")
|
||||
if (device.connected) {
|
||||
const testing = state.audioTestAddress.toUpperCase() === device.address.toUpperCase() && !!state.audioTestLabel
|
||||
actions.push("<button data-bluetooth-operation=\"test_audio\" data-address=\"" + address + "\"" +
|
||||
renderDisabledAttribute(!state.offroad || !!state.busy || !!state.audioTestLabel) + ">" +
|
||||
(testing ? "Test Audio: " + escapeHtml(state.audioTestLabel) : "Test Audio") + "</button>")
|
||||
}
|
||||
}
|
||||
if (device.paired) {
|
||||
actions.push("<button class=\"bluetoothIconButton bluetoothForgetButton\" data-bluetooth-operation=\"forget\" data-address=\"" +
|
||||
address + "\" data-device-name=\"" + name + "\" title=\"Forget device\" aria-label=\"Forget " + name + "\"" +
|
||||
renderDisabledAttribute(!state.offroad || !!state.busy) + "><i class=\"bi bi-trash3\" aria-hidden=\"true\"></i></button>")
|
||||
}
|
||||
}
|
||||
return "<div class=\"bluetoothActions\">" + actions.join("") + "</div>"
|
||||
}
|
||||
|
||||
function renderDeviceRow(device) {
|
||||
const name = escapeHtml(device.name)
|
||||
return "<div class=\"bluetoothDeviceRow " + (device.connected ? "connected" : "") + "\">" +
|
||||
"<div class=\"bluetoothDeviceIcon\"><i class=\"bi " + deviceIcon(device) + "\" aria-hidden=\"true\"></i></div>" +
|
||||
"<div class=\"bluetoothDeviceDetails\"><div class=\"bluetoothDeviceName\"><h3>" + name +
|
||||
"</h3>" + (device.connected ? "<span class=\"bluetoothConnectedDot\" title=\"Connected\"></span>" : "") +
|
||||
"</div><p>" + deviceCapabilities(device) + "</p><span class=\"bluetoothDeviceStatus\">" +
|
||||
escapeHtml(deviceStatus(device)) + "</span></div>" + renderDeviceActions(device) + "</div>"
|
||||
}
|
||||
|
||||
function renderDeviceSection(title, icon, devices, emptyText = "", revision = null) {
|
||||
const revisionAttribute = revision === null ? "" : " data-revision=\"" + revision + "\""
|
||||
const rows = devices.length
|
||||
? devices.map(renderDeviceRow).join("")
|
||||
: "<div class=\"bluetoothEmptyState\">" + escapeHtml(emptyText) + "</div>"
|
||||
return html(["<section class=\"bluetoothSection\"" + revisionAttribute + ">" +
|
||||
"<div class=\"bluetoothSectionHeader\"><div><i class=\"bi " + icon + "\" aria-hidden=\"true\"></i><h3>" + title +
|
||||
"</h3></div><span>" + devices.length + "</span></div><div class=\"bluetoothSectionBody\">" + rows +
|
||||
"</div></section>"])
|
||||
}
|
||||
|
||||
function handleDeviceListClick(event) {
|
||||
const target = event.target
|
||||
const button = target && typeof target.closest === "function"
|
||||
? target.closest("button[data-bluetooth-operation]")
|
||||
: null
|
||||
if (!button) return
|
||||
const operation = button.dataset.bluetoothOperation
|
||||
const address = button.dataset.address || ""
|
||||
if (operation === "forget" && !window.confirm("Forget " + (button.dataset.deviceName || "this device") + "?")) return
|
||||
request(operation, { address })
|
||||
}
|
||||
|
||||
export function Bluetooth() {
|
||||
initialize()
|
||||
return html`
|
||||
<div class="bluetoothPage">
|
||||
<div class="bluetoothHeader">
|
||||
<div class="bluetoothTitle">
|
||||
<i class="bi bi-bluetooth" aria-hidden="true"></i>
|
||||
<div>
|
||||
<h2>Bluetooth</h2>
|
||||
<p>Connect speakers, headphones, media controls, and controllers.</p>
|
||||
</div>
|
||||
</div>
|
||||
<label class="bluetoothSwitch">
|
||||
<input type="checkbox" checked="${() => state.enabled}" disabled="${() => !state.available || !state.offroad || !!state.busy}"
|
||||
@change="${(event) => request("power", { enabled: event.target.checked })}" />
|
||||
<span>${() => state.busy === "power"
|
||||
? `Turning Bluetooth ${state.powerTarget ? "on" : "off"}…`
|
||||
: state.enabled ? "On" : "Off"}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
${() => !state.offroad ? html`<div class="bluetoothNotice">Scanning, pairing, and forgetting devices are available offroad only.</div>` : ""}
|
||||
${() => state.error ? html`<div class="bluetoothError">${state.error}</div>` : ""}
|
||||
${pairingPrompt}
|
||||
${() => state.audioTestLabel ? html`
|
||||
<div class="bluetoothAudioCountdown">
|
||||
<strong>${state.audioTestLabel}</strong>
|
||||
<span>The test sound is sent at NOW. The audible gap is Bluetooth latency.</span>
|
||||
</div>
|
||||
` : ""}
|
||||
|
||||
<div class="bluetoothToolbar">
|
||||
<button disabled="${() => !state.offroad || !state.enabled || !!state.busy}"
|
||||
class="${() => state.discovering ? "scanning" : ""}"
|
||||
@click="${() => request(state.discovering ? "stop_scan" : "scan")}">
|
||||
<i class="${() => `bi ${state.discovering ? "bi-arrow-repeat" : "bi-search"}`}" aria-hidden="true"></i>
|
||||
${() => state.discovering ? "Searching…" : "Search for Devices"}
|
||||
</button>
|
||||
<button class="bluetoothSecondaryButton" disabled="${() => !!state.busy}" @click="${refresh}">
|
||||
<i class="bi bi-arrow-clockwise" aria-hidden="true"></i> Refresh
|
||||
</button>
|
||||
<span class="bluetoothLiveStatus" aria-live="polite">${() => state.busy ? "Updating…" : state.lastUpdated ? "Live" : ""}</span>
|
||||
<span class="bluetoothScanHint">Put a device in pairing mode before searching.</span>
|
||||
</div>
|
||||
|
||||
<div class="bluetoothDeviceList" @click="${handleDeviceListClick}">
|
||||
${() => state.loading ? html`<div class="bluetoothLoading"><span></span><span></span><span></span></div>` : ""}
|
||||
${() => !state.loading && !state.enabled ? html`
|
||||
<div class="bluetoothEmptyPage">
|
||||
<i class="bi bi-bluetooth" aria-hidden="true"></i>
|
||||
<h3>Bluetooth is off</h3>
|
||||
<p>Turn it on to reconnect saved devices or find something new.</p>
|
||||
</div>
|
||||
` : ""}
|
||||
${() => !state.loading && state.enabled
|
||||
? renderDeviceSection("My Devices", "bi-check2-circle", knownDevices(), "No saved devices yet.", state.revision)
|
||||
: ""}
|
||||
${() => !state.loading && state.enabled
|
||||
? renderDeviceSection("Available Devices", "bi-radar", availableDevices(), state.discovering ? "Searching for nearby devices…" : "No nearby devices found. Start a search to try again.")
|
||||
: ""}
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
.controllerActionDialog {
|
||||
--picker-bg: var(--sidebar-bg, #191923);
|
||||
--picker-field: var(--main-bg, #101018);
|
||||
--picker-border: var(--sidebar-border-color, #454052);
|
||||
--picker-radius: var(--border-radius-lg, 12px);
|
||||
--picker-accent: #bda2ff;
|
||||
box-sizing: border-box;
|
||||
width: min(720px, calc(100% - 24px));
|
||||
max-width: calc(100% - 24px);
|
||||
max-height: calc(100dvh - 24px);
|
||||
padding: 20px;
|
||||
border: 1px solid var(--picker-border);
|
||||
border-radius: var(--picker-radius);
|
||||
background: var(--picker-bg);
|
||||
color: var(--text-color, #e8e8f0);
|
||||
font: inherit;
|
||||
overflow: hidden;
|
||||
}
|
||||
.controllerActionDialog[open] { display: flex; flex-direction: column; gap: 12px; }
|
||||
.controllerActionDialog::backdrop { background: rgba(0, 0, 0, .65); backdrop-filter: blur(4px); }
|
||||
.controllerActionDialog--dipper {
|
||||
--picker-bg: var(--surface-container-high, #211b32);
|
||||
--picker-field: var(--surface-container);
|
||||
--picker-border: var(--outline-variant);
|
||||
--picker-radius: var(--radius-lg);
|
||||
--picker-accent: var(--primary);
|
||||
color: var(--on-surface);
|
||||
}
|
||||
.controllerActionDialog header { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
|
||||
.controllerActionDialog h3, .controllerActionDialog p { margin: 0; }
|
||||
.controllerActionDialog h3 { font-size: 1.15em; }
|
||||
.controllerActionDialog [data-current] { overflow-wrap: anywhere; }
|
||||
.controllerActionDialog label { display: grid; gap: 6px; font-size: .9em; }
|
||||
.controllerActionDialog input, .controllerActionDialog select {
|
||||
box-sizing: border-box; width: 100%; min-width: 0; min-height: 44px;
|
||||
background: var(--picker-field); color: inherit; border: 1px solid var(--picker-border);
|
||||
border-radius: var(--border-radius-md, var(--radius-sm, 8px)); padding: 10px; font: inherit;
|
||||
}
|
||||
/* Native option popups do not consistently inherit the select background. */
|
||||
.controllerActionDialog select { color-scheme: dark; }
|
||||
.controllerActionDialog select option {
|
||||
background-color: var(--picker-bg, #211b32);
|
||||
color: var(--on-surface, var(--text-color, #e8e8f0));
|
||||
}
|
||||
.controllerActionDialog button { cursor: pointer; font: inherit; min-height: 44px; }
|
||||
.controllerActionDialog--classic button {
|
||||
border: 1px solid var(--picker-border); border-radius: var(--border-radius-md, 8px);
|
||||
background: var(--picker-field); color: inherit; padding: 10px 14px;
|
||||
}
|
||||
.controllerActionResults { min-height: 0; overflow-y: auto; overscroll-behavior: contain; display: flex; flex-direction: column; gap: 8px; }
|
||||
.controllerActionDialog .controllerActionOption {
|
||||
flex: none; display: flex; flex-direction: column; align-items: stretch; white-space: normal;
|
||||
text-align: left; width: 100%; height: auto; gap: 5px; padding: 12px; overflow-wrap: anywhere;
|
||||
}
|
||||
.controllerActionOption small { font-size: .85em; opacity: .72; font-weight: normal; }
|
||||
.controllerActionDialog--dipper .controllerActionOption { color: var(--on-surface); border-radius: var(--radius-sm); }
|
||||
.controllerActionDialog .controllerActionOption[aria-pressed="true"] { border: 2px solid var(--picker-accent); }
|
||||
.controllerActionDialog :focus-visible { outline: 2px solid var(--picker-accent); outline-offset: -2px; }
|
||||
.controllerActionDialog button:disabled { cursor: not-allowed; opacity: .5; }
|
||||
.controllerActionDialog [data-count] { font-size: .85em; opacity: .72; }
|
||||
@media (max-width: 480px), (max-height: 500px) {
|
||||
.controllerActionDialog { padding: 12px; }
|
||||
.controllerActionDialog[open] { gap: 8px; }
|
||||
}
|
||||
|
||||
.controllerActionDialog .controllerActionCategory[hidden] { display: none; }
|
||||
.controllerActionGroup { flex: none; border: 1px solid var(--picker-border); border-radius: var(--radius-sm, 8px); }
|
||||
.controllerActionGroup summary { padding: 12px; cursor: pointer; min-height: 44px; box-sizing: border-box; overflow-wrap: anywhere; }
|
||||
.controllerActionGroupItems { display: grid; gap: 8px; padding: 0 8px 8px; }
|
||||
|
||||
.controllerActionDialog--dipper .controllerActionSubgroup { background: var(--surface-container, #211c31); }
|
||||
.controllerActionDialog--dipper .controllerActionSubgroup > summary { font-size: .95em; }
|
||||
|
||||
/* Clear parent/child hierarchy in both shared New Galaxy pickers. */
|
||||
.controllerActionDialog--dipper .controllerActionResults > .controllerActionGroup > summary { font-weight: 650; }
|
||||
.controllerActionDialog--dipper .controllerActionGroupItems { padding-inline-start: 20px; }
|
||||
.controllerActionDialog--dipper .controllerActionSubgroup {
|
||||
border-inline-start: 3px solid color-mix(in srgb, var(--picker-accent) 48%, var(--picker-border));
|
||||
background: var(--surface-container-low, #191522);
|
||||
}
|
||||
.controllerActionDialog--dipper .controllerActionSubgroup > summary { font-weight: 450; color: var(--on-surface-variant); }
|
||||
@media (max-width: 480px) {
|
||||
.controllerActionDialog--dipper .controllerActionGroupItems { padding-inline-start: 14px; }
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
import { longitudinalModeLayout, LONGITUDINAL_MODE_KEY } from "./longitudinal_mode.mjs"
|
||||
|
||||
const stylesheet = new URL("./controller_action_picker.css", import.meta.url).href
|
||||
|
||||
const layoutUrl = "/assets/components/tools/device_settings_layout.json?v=settings-tier-1"
|
||||
|
||||
function settingsAnchor(key) {
|
||||
if (["ExperimentalMode", "ConditionalExperimental", "ConditionalChill"].includes(key)) return LONGITUDINAL_MODE_KEY
|
||||
if (["__starpilot_controller_action__:cycle_driving_personality", "__starpilot_favorite_action__:toggle_traffic_mode"].includes(key)) return "CustomPersonalities"
|
||||
return key
|
||||
}
|
||||
|
||||
function settingOwner(option, layout) {
|
||||
const key = settingsAnchor(option.key || "")
|
||||
const sections = longitudinalModeLayout(layout)
|
||||
const section = sections.findLast(section => section.params?.some(param => param.key === key))
|
||||
return { key, section }
|
||||
}
|
||||
|
||||
export function actionCategory(option, layout = []) {
|
||||
const { section } = settingOwner(option, layout)
|
||||
if (section) return section.name
|
||||
return option.section === "Actions" ? "Controller Actions" : String(option.section || "Other")
|
||||
}
|
||||
|
||||
export function actionHierarchy(option, layout = []) {
|
||||
const { key, section } = settingOwner(option, layout)
|
||||
if (!section) return []
|
||||
const byKey = new Map(section.params.map(param => [param.key, param]))
|
||||
const own = byKey.get(key)
|
||||
let node = own?.is_parent_toggle || key !== option.key ? own : byKey.get(own?.parent_key)
|
||||
const path = [], seen = new Set()
|
||||
while (node && !seen.has(node.key)) {
|
||||
seen.add(node.key)
|
||||
path.unshift({ key: node.key, label: node.label || node.key })
|
||||
node = byKey.get(node.parent_key)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
export function actionGroups(options, layout = []) {
|
||||
const root = { items: [], groups: [] }
|
||||
for (const option of options) {
|
||||
let node = root
|
||||
for (const part of actionHierarchy(option, layout)) {
|
||||
let child = node.groups.find(group => group.key === part.key)
|
||||
if (!child) { child = { ...part, count: 0, items: [], groups: [] }; node.groups.push(child) }
|
||||
child.count++
|
||||
node = child
|
||||
}
|
||||
node.items.push(option)
|
||||
}
|
||||
const order = new Map(longitudinalModeLayout(layout).flatMap(section => section.params).map((param, i) => [param.key, i]))
|
||||
order.set(LONGITUDINAL_MODE_KEY, -1)
|
||||
const sort = node => {
|
||||
node.groups.sort((a, b) => (order.get(a.key) ?? Infinity) - (order.get(b.key) ?? Infinity))
|
||||
node.groups.forEach(sort)
|
||||
}
|
||||
sort(root)
|
||||
return root
|
||||
}
|
||||
|
||||
export function actionCategories(options, layout = []) {
|
||||
const available = new Set(options.map(option => actionCategory(option, layout)))
|
||||
const ordered = layout.map(section => section.name).filter(name => available.has(name))
|
||||
return [...new Set([...ordered, ...available])]
|
||||
}
|
||||
|
||||
export function filterActions(options, query = "", category = "", layout = []) {
|
||||
const words = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)
|
||||
return options.filter(option => (!category || actionCategory(option, layout) === category) &&
|
||||
words.every(word => [option.label, option.key, option.description, option.picker_label,
|
||||
option.picker_description, actionCategory(option, layout), ...actionHierarchy(option, layout).map(part => part.label)].join(" ").toLocaleLowerCase().includes(word)))
|
||||
}
|
||||
|
||||
export function openControllerActionPicker({ theme = "classic", index, trigger, getOptions, getSlot, isDisabled, onSelect, title = `Controller Action #${index + 1}`, slotAttribute = "data-controller-action-slot", noun = "actions" }) {
|
||||
if (isDisabled()) return () => {}
|
||||
if (!document.querySelector('link[data-controller-picker]')) {
|
||||
const link = document.createElement("link")
|
||||
link.rel = "stylesheet"
|
||||
link.href = stylesheet
|
||||
link.dataset.controllerPicker = ""
|
||||
document.head.append(link)
|
||||
}
|
||||
const dialog = document.createElement("dialog")
|
||||
dialog.className = `controllerActionDialog ${theme === "dipper" ? "controllerActionDialog--dipper" : "controllerActionDialog--classic"}`
|
||||
dialog.setAttribute("aria-labelledby", "controllerActionTitle")
|
||||
dialog.innerHTML = `<header><h3 id="controllerActionTitle">Controller Action #${index + 1}</h3><button type="button" data-cancel>Cancel</button></header>
|
||||
<p data-current></p>
|
||||
<label class="controllerActionSearch">Search all actions<input type="search" placeholder="Search by name, setting or description" autocomplete="off"></label>
|
||||
<label class="controllerActionCategory">Category<select aria-label="Category"></select></label>
|
||||
<p data-count role="status" aria-live="polite"></p>
|
||||
<div class="controllerActionResults"></div>`
|
||||
dialog.querySelector("h3").textContent = title
|
||||
dialog.querySelector(".controllerActionSearch").firstChild.textContent = `Search all ${noun}`
|
||||
const grouped = theme === "dipper"
|
||||
const expanded = new Set()
|
||||
if (grouped) dialog.querySelector(".controllerActionCategory").hidden = true
|
||||
const input = dialog.querySelector("input")
|
||||
const category = dialog.querySelector("select")
|
||||
const results = dialog.querySelector(".controllerActionResults")
|
||||
const current = dialog.querySelector("[data-current]")
|
||||
const count = dialog.querySelector("[data-count]")
|
||||
const buttonClass = theme === "dipper" ? "gx-btn gx-btn--tonal" : ""
|
||||
dialog.querySelector("[data-cancel]").className = buttonClass
|
||||
if (theme === "dipper") {
|
||||
input.className = "gx-field"
|
||||
category.className = "gx-field"
|
||||
}
|
||||
let signature = ""
|
||||
let layout = []
|
||||
let closed = false
|
||||
let timer
|
||||
const fitViewport = () => {
|
||||
let zoom = 1
|
||||
for (let node = dialog; node; node = node.parentElement) zoom *= Number.parseFloat(getComputedStyle(node).zoom) || 1
|
||||
const viewport = window.visualViewport
|
||||
dialog.style.maxHeight = `${(viewport?.height || window.innerHeight) / zoom - 24}px`
|
||||
dialog.style.maxWidth = `${(viewport?.width || window.innerWidth) / zoom - 24}px`
|
||||
}
|
||||
const close = () => {
|
||||
if (closed) return
|
||||
closed = true
|
||||
clearInterval(timer)
|
||||
window.removeEventListener("resize", fitViewport)
|
||||
window.visualViewport?.removeEventListener("resize", fitViewport)
|
||||
dialog.close()
|
||||
dialog.remove()
|
||||
const target = trigger?.isConnected ? trigger : document.querySelector(`[${slotAttribute}="${index}"]`)
|
||||
target?.focus({ preventScroll: true })
|
||||
}
|
||||
dialog.addEventListener("cancel", event => { event.preventDefault(); close() })
|
||||
dialog.addEventListener("keydown", event => {
|
||||
if (event.key !== "Tab") return
|
||||
const controls = [...dialog.querySelectorAll("button:not(:disabled), input, select, summary")].filter(node => node.getClientRects().length)
|
||||
const first = controls[0]
|
||||
const last = controls[controls.length - 1]
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault(); last.focus()
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault(); first.focus()
|
||||
}
|
||||
})
|
||||
dialog.querySelector("[data-cancel]").addEventListener("click", close)
|
||||
const render = () => {
|
||||
const options = getOptions()
|
||||
const slot = getSlot() || {}
|
||||
const key = slot.key || ""
|
||||
const disabled = isDisabled()
|
||||
const next = JSON.stringify([options, key, slot.label, disabled, input.value, category.value])
|
||||
if (signature === next) return
|
||||
signature = next
|
||||
const categories = actionCategories(options, layout)
|
||||
const selectedCategory = category.value
|
||||
category.replaceChildren(new Option("All categories", ""), ...categories.map(name => new Option(name, name)))
|
||||
category.value = categories.includes(selectedCategory) ? selectedCategory : ""
|
||||
const selected = options.find(option => option.key === key)
|
||||
current.textContent = `Current: ${selected?.label || slot.label || key || "Not configured"}${key && !selected ? " (unavailable)" : ""}`
|
||||
const matches = filterActions(options, input.value, category.value, layout)
|
||||
count.textContent = disabled ? "Selection is currently unavailable." : `${matches.length} ${matches.length === 1 ? noun.replace(/s$/, "") : noun}`
|
||||
const focusedKey = results.contains(document.activeElement) ? document.activeElement.dataset.actionKey : null
|
||||
results.replaceChildren()
|
||||
const add = (option, categoryName, container = results) => {
|
||||
const button = document.createElement("button")
|
||||
button.type = "button"
|
||||
button.className = `controllerActionOption ${buttonClass}`
|
||||
button.dataset.actionKey = option.key
|
||||
button.setAttribute("aria-pressed", String(option.key === key))
|
||||
button.disabled = disabled
|
||||
const title = document.createElement("strong")
|
||||
title.textContent = `${option.key === key ? "✓ " : ""}${option.label}`
|
||||
const detail = document.createElement("small")
|
||||
detail.textContent = [categoryName, option.description].filter(Boolean).join(" · ")
|
||||
button.append(title, detail)
|
||||
button.addEventListener("click", () => {
|
||||
if (isDisabled() || (option.key && !getOptions().some(item => item.key === option.key))) { render(); return }
|
||||
close()
|
||||
onSelect(option.key)
|
||||
})
|
||||
container.append(button)
|
||||
if (focusedKey === option.key) button.focus({ preventScroll: true })
|
||||
}
|
||||
add({ key: "", label: "Not configured", description: "Clear this assignment" }, "")
|
||||
if (grouped) {
|
||||
for (const name of categories) {
|
||||
const items = matches.filter(option => actionCategory(option, layout) === name)
|
||||
if (!items.length) continue
|
||||
const group = document.createElement("details")
|
||||
group.className = "controllerActionGroup"
|
||||
group.open = !!input.value.trim() || expanded.has(name)
|
||||
const summary = document.createElement("summary")
|
||||
summary.textContent = `${name} (${items.length})`
|
||||
const body = document.createElement("div")
|
||||
body.className = "controllerActionGroupItems"
|
||||
group.append(summary, body)
|
||||
group.addEventListener("toggle", () => {
|
||||
if (!input.value.trim()) group.open ? expanded.add(name) : expanded.delete(name)
|
||||
})
|
||||
results.append(group)
|
||||
const populate = (node, container, path) => {
|
||||
for (const option of node.items) add(option, path.join(" · "), container)
|
||||
for (const child of node.groups) {
|
||||
const id = [...path, child.key].join("/")
|
||||
const subgroup = document.createElement("details")
|
||||
subgroup.className = "controllerActionGroup controllerActionSubgroup"
|
||||
subgroup.open = !!input.value.trim() || expanded.has(id)
|
||||
const heading = document.createElement("summary")
|
||||
heading.textContent = `${child.label} (${child.count})`
|
||||
const content = document.createElement("div")
|
||||
content.className = "controllerActionGroupItems"
|
||||
subgroup.append(heading, content)
|
||||
subgroup.addEventListener("toggle", () => {
|
||||
if (!input.value.trim()) subgroup.open ? expanded.add(id) : expanded.delete(id)
|
||||
})
|
||||
container.append(subgroup)
|
||||
populate(child, content, [...path, child.label])
|
||||
}
|
||||
}
|
||||
populate(actionGroups(items, layout), body, [name])
|
||||
}
|
||||
} else {
|
||||
for (const option of matches) add(option, actionCategory(option, layout))
|
||||
}
|
||||
if (!matches.length) {
|
||||
const empty = document.createElement("p")
|
||||
empty.textContent = "No matching actions. Try another search or category."
|
||||
results.append(empty)
|
||||
}
|
||||
}
|
||||
input.addEventListener("input", () => {
|
||||
category.value = ""
|
||||
render()
|
||||
results.scrollTop = 0
|
||||
})
|
||||
category.addEventListener("change", () => { render(); results.scrollTop = 0 })
|
||||
document.body.append(dialog)
|
||||
fitViewport()
|
||||
window.addEventListener("resize", fitViewport)
|
||||
window.visualViewport?.addEventListener("resize", fitViewport)
|
||||
render()
|
||||
dialog.showModal()
|
||||
input.focus()
|
||||
fetch(layoutUrl, { cache: "no-store" }).then(response => {
|
||||
if (!response.ok) throw new Error("Settings catalogue unavailable")
|
||||
return response.json()
|
||||
}).then(data => {
|
||||
if (closed || !Array.isArray(data)) return
|
||||
layout = data.filter(section => section && typeof section.name === "string" && Array.isArray(section.params))
|
||||
signature = ""
|
||||
render()
|
||||
}).catch(() => {})
|
||||
timer = setInterval(() => {
|
||||
if (!document.querySelector(`[${slotAttribute}="${index}"]`)) close()
|
||||
else render()
|
||||
}, 250)
|
||||
return close
|
||||
}
|
||||
+1401
File diff suppressed because it is too large
Load Diff
+2981
File diff suppressed because it is too large
Load Diff
+5205
File diff suppressed because it is too large
Load Diff
+65
@@ -0,0 +1,65 @@
|
||||
.door-control-button {
|
||||
background-color: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--border-radius-xl);
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
transition: background-color var(--transition-fast), box-shadow var(--transition-fast), color var(--transition-fast), transform var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.door-control-button:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--secondary-fg);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.door-control-button + .door-control-button {
|
||||
margin-top: var(--padding-sm);
|
||||
}
|
||||
|
||||
.door-control-text {
|
||||
color: var(--text-color);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.door-control-title {
|
||||
background-color: var(--input-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-lg);
|
||||
font-weight: var(--font-weight-bold);
|
||||
padding: var(--padding-sm);
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.door-control-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.door-control-widget {
|
||||
align-items: center;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-md);
|
||||
color: var(--main-fg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-xl);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-lg);
|
||||
transform-origin: top center;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.door-control-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { html } from "/assets/vendor/arrow-core.js"
|
||||
|
||||
export function DoorControl () {
|
||||
async function lockDoors () {
|
||||
const response = await fetch("/api/doors/lock", { method: "POST" })
|
||||
const result = await response.json()
|
||||
showSnackbar(result.message || "Doors locked!")
|
||||
}
|
||||
|
||||
async function unlockDoors () {
|
||||
const response = await fetch("/api/doors/unlock", { method: "POST" })
|
||||
const result = await response.json()
|
||||
showSnackbar(result.message || "Doors unlocked!")
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="door-control-wrapper">
|
||||
<section class="door-control-widget">
|
||||
<div class="door-control-title">Lock/Unlock Doors</div>
|
||||
<p class="door-control-text">
|
||||
Remotely lock or unlock your car doors using the buttons below.
|
||||
</p>
|
||||
<button class="door-control-button" @click="${lockDoors}">🔒 Lock Doors</button>
|
||||
<button class="door-control-button" @click="${unlockDoors}">🔓 Unlock Doors</button>
|
||||
</section>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
.error-logs-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
#errorLogs {
|
||||
max-width: calc(100% - var(--padding-xl));
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#errorLogs > div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: var(--padding-xl);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#errorLogs .fileEntry {
|
||||
border: none;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: var(--padding-sm) var(--border-radius-xl);
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
#errorLogs .fileEntry:hover {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
#errorLogs #fileList {
|
||||
color: var(--text-color);
|
||||
margin-bottom: var(--border-radius-xl);
|
||||
overflow-y: auto;
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
#errorLogs #fileList,
|
||||
#errorLogs #fileViewer {
|
||||
background-color: var(--sidebar-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
max-width: calc(100% - var(--padding-xl));
|
||||
scrollbar-color: var(--thumb-color) var(--track-color);
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
padding: var(--padding-base);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#errorLogs #fileList:hover,
|
||||
#errorLogs #fileViewer:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer {
|
||||
scrollbar-width: auto;
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer button {
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
color: var(--secondary-fg);
|
||||
height: calc(3 * var(--border-width-thick));
|
||||
padding: var(--padding-sm);
|
||||
transition:
|
||||
background-color var(--transition-base),
|
||||
box-shadow var(--transition-fast),
|
||||
color var(--transition-fast),
|
||||
transform var(--transition-fast);
|
||||
width: calc(3 * var(--border-width-thick));
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer button:hover {
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
#errorLogs #fileViewer pre {
|
||||
color: var(--main-fg);
|
||||
font-family: var(--font-mono);
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
margin-top: var(--padding-sm);
|
||||
}
|
||||
|
||||
#errorLogs p {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.time-since {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media only screen and (min-width: 769px) {
|
||||
.error-logs-wrapper {
|
||||
margin: 0 auto;
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
#errorLogs .fileEntry {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.time-since {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.error-logs-wrapper #errorLogs #fileList {
|
||||
background-color: var(--sidebar-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
margin-left: 0;
|
||||
max-width: calc(100% - var(--padding-xl));
|
||||
overflow-y: auto;
|
||||
padding: var(--padding-base);
|
||||
scrollbar-color: var(--thumb-color) var(--track-color);
|
||||
scrollbar-width: auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.error-logs-wrapper #errorLogs #fileList .fileEntry {
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
}
|
||||
|
||||
.error-logs-wrapper #errorLogs #fileList .fileEntry:not(:last-child) {
|
||||
border-bottom: 1px solid var(--sidebar-border-color);
|
||||
}
|
||||
|
||||
.error-logs-wrapper #errorLogs #fileList .fileEntry:hover {
|
||||
background-color: var(--sidebar-active-bg);
|
||||
}
|
||||
|
||||
.error-logs-wrapper #errorLogs #fileList .fileEntry.header {
|
||||
background-color: var(--secondary-bg);
|
||||
cursor: default;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.delete-all-button {
|
||||
background-color: var(--danger-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
margin-top: var(--margin-sm);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
text-align: center;
|
||||
transition:
|
||||
background-color var(--transition-fast),
|
||||
box-shadow var(--transition-fast),
|
||||
transform var(--transition-fast);
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.delete-all-button:hover {
|
||||
background-color: var(--danger-hover-bg);
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.delete-all-button[disabled] {
|
||||
cursor: not-allowed;
|
||||
opacity: var(--disabled-opacity);
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js";
|
||||
import { formatSecondsToHuman, parseErrorLogToDate } from "/assets/js/utils.js";
|
||||
import { Modal } from "/assets/components/modal.js";
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
files: [],
|
||||
selectedLog: undefined,
|
||||
confirmDelete: {
|
||||
visible: false,
|
||||
filename: null,
|
||||
},
|
||||
showDeleteAllModal: false,
|
||||
});
|
||||
|
||||
;(async () => {
|
||||
const res = await fetch("/api/error_logs", {
|
||||
headers: { Accept: "application/json" }
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
state.files = data.map(f => {
|
||||
const date = parseErrorLogToDate(f);
|
||||
return {
|
||||
filename: f,
|
||||
date: date.toLocaleString(),
|
||||
timeSince: (Date.now() - date.getTime()) / 1000,
|
||||
};
|
||||
});
|
||||
|
||||
state.loading = false;
|
||||
})();
|
||||
|
||||
async function deleteAllLogs() {
|
||||
state.showDeleteAllModal = false;
|
||||
try {
|
||||
const res = await fetch('/api/error_logs/delete_all', { method: 'DELETE' });
|
||||
if (res.ok) {
|
||||
showSnackbar("All error logs deleted!");
|
||||
state.files = [];
|
||||
state.selectedLog = undefined;
|
||||
} else {
|
||||
showSnackbar("Delete all failed...", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
showSnackbar("An error occurred while deleting error logs...", "error");
|
||||
}
|
||||
}
|
||||
|
||||
export function ErrorLogs() {
|
||||
return html`
|
||||
<div class="error-logs-wrapper">
|
||||
<div id="errorLogs">
|
||||
<div id="fileList">
|
||||
${() =>
|
||||
state.loading
|
||||
? html`<div class="fileEntry"><p>Loading...</p></div>`
|
||||
: state.files.length === 0
|
||||
? html`<div class="fileEntry"><p>No error logs!</p></div>`
|
||||
: state.files.map(file => html`
|
||||
<div class="fileEntry"
|
||||
@click="${() => {
|
||||
state.selectedLog = state.selectedLog === file.filename ? undefined : file.filename;
|
||||
}}">
|
||||
<p>${file.date}</p>
|
||||
<p class="time-since">
|
||||
${file.timeSince < 60 ? "just now" : `${formatSecondsToHuman(file.timeSince, "minutes")} ago`}
|
||||
</p>
|
||||
</div>
|
||||
`)
|
||||
}
|
||||
${() =>
|
||||
state.files.length > 0
|
||||
? html`
|
||||
<div style="text-align: center; padding: 1rem;">
|
||||
<button
|
||||
class="delete-all-button"
|
||||
@click="${() => (state.showDeleteAllModal = true)}"
|
||||
>
|
||||
Delete All Error Logs
|
||||
</button>
|
||||
</div>
|
||||
`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
${() =>
|
||||
state.selectedLog ? Logviewer(state.selectedLog, () => (state.selectedLog = undefined)) : ""
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
${() => state.confirmDelete.visible ? Modal({
|
||||
title: "Confirm Delete",
|
||||
message: html`Are you sure you want to delete <strong>${state.confirmDelete.filename}</strong>?`,
|
||||
onConfirm: async () => {
|
||||
const filename = state.confirmDelete.filename;
|
||||
if (!filename) return;
|
||||
await fetch(`/api/error_logs/${filename}`, {
|
||||
method: "DELETE"
|
||||
});
|
||||
state.files = state.files.filter(f => f.filename !== filename);
|
||||
state.confirmDelete.visible = false;
|
||||
state.confirmDelete.filename = null;
|
||||
if (state.selectedLog === filename) {
|
||||
state.selectedLog = undefined;
|
||||
}
|
||||
},
|
||||
onCancel: () => {
|
||||
state.confirmDelete.visible = false;
|
||||
state.confirmDelete.filename = null;
|
||||
}
|
||||
}) : ""}
|
||||
${() => state.showDeleteAllModal ? Modal({
|
||||
title: "Confirm Delete All",
|
||||
message: "Are you sure you want to delete all error logs? This action cannot be undone...",
|
||||
onConfirm: deleteAllLogs,
|
||||
onCancel: () => { state.showDeleteAllModal = false; },
|
||||
confirmText: "Delete All"
|
||||
}) : ""}
|
||||
`;
|
||||
}
|
||||
|
||||
function Logviewer(filename, closeFn) {
|
||||
const logState = reactive({
|
||||
loading: true,
|
||||
content: ""
|
||||
});
|
||||
|
||||
;(async () => {
|
||||
const res = await fetch(`/api/error_logs/${filename}`);
|
||||
logState.content = await res.text();
|
||||
logState.loading = false;
|
||||
|
||||
setTimeout(() => {
|
||||
window.scrollTo({
|
||||
top: document.body.scrollHeight,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 0);
|
||||
})();
|
||||
|
||||
const deleteLog = () => {
|
||||
state.confirmDelete.filename = filename;
|
||||
state.confirmDelete.visible = true;
|
||||
};
|
||||
|
||||
const copyLog = () => {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(logState.content);
|
||||
} else {
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = logState.content;
|
||||
textArea.style.position = "fixed";
|
||||
textArea.style.left = "-9999px";
|
||||
document.body.appendChild(textArea);
|
||||
textArea.focus();
|
||||
textArea.select();
|
||||
try {
|
||||
document.execCommand("copy");
|
||||
} catch (err) {
|
||||
console.error("Fallback: Oops, unable to copy", err);
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
}
|
||||
showSnackbar("Copied to clipboard!");
|
||||
};
|
||||
|
||||
return html`
|
||||
<div id="fileViewer">
|
||||
<div>
|
||||
<p>${filename}</p>
|
||||
<button @click="${closeFn}">
|
||||
<i class="bi bi-x-lg"></i>
|
||||
</button>
|
||||
<button @click="${deleteLog}">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
<button @click="${copyLog}">
|
||||
<i class="bi bi-clipboard"></i>
|
||||
</button>
|
||||
<a href="/api/error_logs/${filename}" download>
|
||||
<button>
|
||||
<i class="bi bi-download"></i>
|
||||
</button>
|
||||
</a>
|
||||
</div>
|
||||
<pre>${() => (logState.loading ? "Loading..." : logState.content)}</pre>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
/* ――― Galaxy Pairing Widget ――― */
|
||||
.galaxy-wrapper {
|
||||
max-width: var(--width-xxxl);
|
||||
padding: var(--padding-base) var(--padding-lg) var(--padding-xxl);
|
||||
}
|
||||
|
||||
.galaxy-loading {
|
||||
color: var(--text-muted);
|
||||
padding: var(--padding-xl);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.galaxy-widget {
|
||||
align-items: center;
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-lg);
|
||||
max-width: var(--width-lg);
|
||||
padding: var(--padding-xl);
|
||||
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.galaxy-widget:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
/* ――― Status Badge ――― */
|
||||
.galaxy-status-badge {
|
||||
align-items: center;
|
||||
border-radius: 2rem;
|
||||
display: inline-flex;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-bold);
|
||||
gap: var(--gap-xs);
|
||||
padding: 0.3rem 1rem;
|
||||
}
|
||||
|
||||
.galaxy-paired {
|
||||
background-color: rgba(94, 200, 200, 0.15);
|
||||
color: var(--success-fg);
|
||||
}
|
||||
|
||||
.galaxy-unpaired {
|
||||
background-color: rgba(224, 85, 119, 0.15);
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
/* ――― Text ――― */
|
||||
.galaxy-text {
|
||||
color: var(--text-color);
|
||||
line-height: var(--line-height-base);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ――― URL Link ――― */
|
||||
.galaxy-url {
|
||||
color: var(--main-fg);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
transition: color var(--transition-fast);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.galaxy-url:hover {
|
||||
color: var(--accent-hover-bg);
|
||||
}
|
||||
|
||||
/* ――― Input Group ――― */
|
||||
.galaxy-input-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-sm);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.galaxy-input {
|
||||
background-color: var(--input-bg);
|
||||
border: var(--border-style-input);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-sizing: border-box;
|
||||
color: var(--text-color);
|
||||
font-family: var(--font-body);
|
||||
font-size: var(--font-size-base);
|
||||
outline: none;
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
transition: box-shadow var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.galaxy-input:focus {
|
||||
box-shadow: 0 0 0 2px var(--main-fg);
|
||||
}
|
||||
|
||||
/* ――― Buttons ――― */
|
||||
.galaxy-button {
|
||||
background-color: var(--input-bg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-lg);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
text-align: center;
|
||||
transition: background-color var(--transition-fast), box-shadow var(--transition-fast), transform var(--transition-fast);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.galaxy-button:hover:not(:disabled) {
|
||||
box-shadow: var(--shadow-md);
|
||||
transform: var(--hover-scale-sm);
|
||||
}
|
||||
|
||||
.galaxy-button:disabled {
|
||||
opacity: var(--disabled-opacity);
|
||||
}
|
||||
|
||||
.galaxy-button-danger {
|
||||
background-color: rgba(224, 85, 119, 0.2);
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
.galaxy-button-danger:hover:not(:disabled) {
|
||||
background-color: rgba(224, 85, 119, 0.35);
|
||||
}
|
||||
|
||||
/* ――― Mobile ――― */
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.galaxy-wrapper {
|
||||
padding: var(--padding-sm) var(--padding-base) var(--padding-xl);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
import { isGalaxyTunnel } from "/assets/js/utils.js"
|
||||
import { Modal } from "/assets/components/modal.js"
|
||||
|
||||
const state = reactive({
|
||||
paired: false,
|
||||
url: "",
|
||||
password: "",
|
||||
loading: true,
|
||||
submitting: false,
|
||||
showUnpairModal: false,
|
||||
fetched: false,
|
||||
})
|
||||
|
||||
async function fetchStatus() {
|
||||
state.loading = true
|
||||
try {
|
||||
const res = await fetch("/api/galaxy/status")
|
||||
const data = await res.json()
|
||||
state.paired = data.paired
|
||||
state.url = data.url
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch Galaxy status:", e)
|
||||
}
|
||||
state.loading = false
|
||||
}
|
||||
|
||||
async function pair() {
|
||||
if (state.submitting) return
|
||||
const pw = state.password.trim()
|
||||
if (pw.length < 6) {
|
||||
showSnackbar("Password must be at least 6 characters.")
|
||||
return
|
||||
}
|
||||
|
||||
state.submitting = true
|
||||
try {
|
||||
const res = await fetch("/api/galaxy/pair", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ password: pw }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (res.ok) {
|
||||
state.paired = true
|
||||
state.url = data.url
|
||||
state.password = ""
|
||||
// Clear the DOM input value directly (Arrow.js doesn't two-way bind)
|
||||
const input = document.querySelector(".galaxy-input")
|
||||
if (input) input.value = ""
|
||||
showSnackbar(data.message || "Paired!")
|
||||
} else {
|
||||
showSnackbar(data.error || "Pairing failed.")
|
||||
}
|
||||
} catch (e) {
|
||||
showSnackbar("Network error — is the device reachable?")
|
||||
}
|
||||
state.submitting = false
|
||||
}
|
||||
|
||||
async function unpair() {
|
||||
state.showUnpairModal = false
|
||||
state.submitting = true
|
||||
try {
|
||||
const res = await fetch("/api/galaxy/unpair", { method: "POST" })
|
||||
const data = await res.json()
|
||||
if (res.ok) {
|
||||
state.paired = false
|
||||
state.url = ""
|
||||
showSnackbar(data.message || "Unpaired!")
|
||||
} else {
|
||||
showSnackbar(data.error || "Unpairing failed.")
|
||||
}
|
||||
} catch (e) {
|
||||
showSnackbar("Network error — is the device reachable?")
|
||||
}
|
||||
state.submitting = false
|
||||
}
|
||||
|
||||
export function GalaxyPairing() {
|
||||
if (isGalaxyTunnel()) {
|
||||
return html`
|
||||
<div class="tunnel-notice">
|
||||
<div class="tunnel-notice-icon">🛰️</div>
|
||||
<h3 class="tunnel-notice-title">Galaxy Pairing Unavailable via Galaxy</h3>
|
||||
<p class="tunnel-notice-body">Galaxy pairing requires a direct connection.<br>Connect to your device's local network to use this feature.</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (!state.fetched) {
|
||||
state.fetched = true
|
||||
fetchStatus()
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="galaxy-wrapper">
|
||||
<h2>Galaxy</h2>
|
||||
|
||||
${() => {
|
||||
if (state.loading) {
|
||||
return html`<div class="galaxy-loading">Checking pairing status…</div>`
|
||||
}
|
||||
|
||||
if (state.paired) {
|
||||
return html`
|
||||
<section class="galaxy-widget">
|
||||
<div class="galaxy-status-badge galaxy-paired">
|
||||
<i class="bi bi-check-circle-fill"></i> Paired
|
||||
</div>
|
||||
<p class="galaxy-text">
|
||||
Your device is paired with Galaxy. Access it remotely at:
|
||||
</p>
|
||||
<a class="galaxy-url" href="${state.url}" target="_blank" rel="noopener">
|
||||
${state.url}
|
||||
</a>
|
||||
<button
|
||||
class="galaxy-button galaxy-button-danger"
|
||||
@click="${() => { state.showUnpairModal = true }}"
|
||||
disabled="${() => state.submitting}"
|
||||
>
|
||||
${() => state.submitting ? "Unpairing…" : "Unpair"}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
${() => state.showUnpairModal ? Modal({
|
||||
title: "Confirm Unpair",
|
||||
message: "Are you sure you want to unpair from Galaxy? You will lose remote access until you pair again.",
|
||||
onConfirm: unpair,
|
||||
onCancel: () => { state.showUnpairModal = false },
|
||||
confirmText: "Unpair",
|
||||
}) : ""}
|
||||
`
|
||||
}
|
||||
|
||||
return html`
|
||||
<section class="galaxy-widget">
|
||||
<div class="galaxy-status-badge galaxy-unpaired">
|
||||
<i class="bi bi-x-circle-fill"></i> Not Paired
|
||||
</div>
|
||||
<p class="galaxy-text">
|
||||
Pair your device with Galaxy to access The Galaxy remotely from anywhere.
|
||||
Set a password to secure your connection.
|
||||
</p>
|
||||
<div class="galaxy-input-group">
|
||||
<input
|
||||
class="galaxy-input"
|
||||
type="password"
|
||||
placeholder="Password (min 6 characters)"
|
||||
@input="${(e) => { state.password = e.target.value }}"
|
||||
@keydown="${(e) => { if (e.key === 'Enter') pair() }}"
|
||||
/>
|
||||
<button
|
||||
class="galaxy-button"
|
||||
@click="${pair}"
|
||||
disabled="${() => state.submitting || state.password.trim().length < 6}"
|
||||
>
|
||||
${() => state.submitting ? "Pairing…" : "Pair"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
`
|
||||
}}
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
busy: false,
|
||||
error: "",
|
||||
data: null,
|
||||
})
|
||||
|
||||
let initialized = false
|
||||
let pollHandle = null
|
||||
const POLL_INTERVAL_MS = 3000
|
||||
|
||||
function isLateralManeuversRouteActive() {
|
||||
return window.location.pathname === "/lateral_maneuvers"
|
||||
}
|
||||
|
||||
function safeNumber(value, fallback = 0) {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? n : fallback
|
||||
}
|
||||
|
||||
function formatAgeSeconds(value) {
|
||||
const sec = safeNumber(value, -1)
|
||||
if (sec < 0) return "unknown"
|
||||
if (sec < 1) return "just now"
|
||||
if (sec < 60) return `${Math.round(sec)}s ago`
|
||||
const min = sec / 60
|
||||
if (min < 60) return `${Math.round(min)}m ago`
|
||||
const hr = min / 60
|
||||
return `${Math.round(hr)}h ago`
|
||||
}
|
||||
|
||||
function normalizeStatusPayload(payload) {
|
||||
const normalized = payload && typeof payload === "object" ? { ...payload } : {}
|
||||
normalized.history = Array.isArray(normalized.history) ? normalized.history : []
|
||||
return normalized
|
||||
}
|
||||
|
||||
async function fetchStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/lateral_maneuvers/status")
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || response.statusText || "Failed to load maneuver status")
|
||||
}
|
||||
|
||||
state.data = normalizeStatusPayload(payload)
|
||||
state.error = ""
|
||||
} catch (error) {
|
||||
state.error = error?.message || "Failed to load maneuver status"
|
||||
} finally {
|
||||
state.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (!pollHandle) return
|
||||
clearTimeout(pollHandle)
|
||||
pollHandle = null
|
||||
}
|
||||
|
||||
function ensurePolling() {
|
||||
if (pollHandle) return
|
||||
|
||||
const poll = async () => {
|
||||
if (!isLateralManeuversRouteActive()) {
|
||||
stopPolling()
|
||||
return
|
||||
}
|
||||
|
||||
if (document.visibilityState !== "visible") {
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
return
|
||||
}
|
||||
|
||||
await fetchStatus()
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
async function runAction(action) {
|
||||
if (state.busy) return
|
||||
state.busy = true
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/lateral_maneuvers/${action}`, { method: "POST" })
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || response.statusText || `Failed to ${action} maneuvers`)
|
||||
}
|
||||
|
||||
state.data = normalizeStatusPayload(payload)
|
||||
state.error = ""
|
||||
showSnackbar(payload.message || "Action complete.")
|
||||
} catch (error) {
|
||||
const message = error?.message || `Failed to ${action} maneuvers`
|
||||
state.error = message
|
||||
showSnackbar(message, "error")
|
||||
} finally {
|
||||
state.busy = false
|
||||
}
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
if (initialized) return
|
||||
initialized = true
|
||||
fetchStatus()
|
||||
ensurePolling()
|
||||
}
|
||||
|
||||
function statusLine(label, value) {
|
||||
return html`<p><strong>${label}:</strong> ${value}</p>`
|
||||
}
|
||||
|
||||
export function LateralManeuvers() {
|
||||
initialize()
|
||||
|
||||
return html`
|
||||
<div class="longManeuverPage">
|
||||
<h2>Lateral Maneuvers</h2>
|
||||
|
||||
<div class="longManeuverCard">
|
||||
<p class="longManeuverIntro">
|
||||
Arm the lateral maneuver suite from your phone and monitor progress live.
|
||||
</p>
|
||||
|
||||
<div class="longManeuverActions">
|
||||
<button
|
||||
class="longManeuverButton"
|
||||
disabled="${() => state.busy || false}"
|
||||
@click="${() => runAction("start")}">
|
||||
Start / Arm
|
||||
</button>
|
||||
<button
|
||||
class="longManeuverButton danger"
|
||||
disabled="${() => state.busy || false}"
|
||||
@click="${() => runAction("stop")}">
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
|
||||
${() => state.loading ? html`<p class="longManeuverMuted">Loading status...</p>` : ""}
|
||||
${() => state.error ? html`<p class="longManeuverError">${state.error}</p>` : ""}
|
||||
|
||||
${() => state.data ? html`
|
||||
<div class="longManeuverStatusGrid">
|
||||
${statusLine("Mode Enabled", state.data.modeEnabled ? "Yes" : "No")}
|
||||
${statusLine("State", state.data.state || "idle")}
|
||||
${statusLine("Onroad", state.data.isOnroad ? "Yes" : "No")}
|
||||
${statusLine("Engaged", state.data.isEngaged ? "Yes" : "No")}
|
||||
${statusLine("Phase", state.data.phase || "n/a")}
|
||||
${statusLine("Step", `${safeNumber(state.data.stepIndex, 0)}/${safeNumber(state.data.stepTotal, 0)}`)}
|
||||
${statusLine("Run", `${safeNumber(state.data.runIndex, 0)}/${safeNumber(state.data.runTotal, 0)}`)}
|
||||
${statusLine("Updated", formatAgeSeconds(state.data.updatedAgeSec))}
|
||||
</div>
|
||||
|
||||
<div class="longManeuverCurrent">
|
||||
<p><strong>Current Maneuver:</strong> ${state.data.maneuver || "n/a"}</p>
|
||||
<p><strong>Popup Text:</strong> ${state.data.uiText1 || ""} ${state.data.uiText2 ? `| ${state.data.uiText2}` : ""}</p>
|
||||
</div>
|
||||
|
||||
<div class="longManeuverInstructions">
|
||||
<h3>Quick Guide</h3>
|
||||
<ol>
|
||||
<li>Find a large, empty, straight, flat road or lot with no traffic.</li>
|
||||
<li>Press <strong>Start / Arm</strong> here, then engage openpilot and set the requested speed manually.</li>
|
||||
<li>Keep full supervision and be ready to steer or disengage immediately at all times.</li>
|
||||
<li>Do not touch the wheel during a run. Steering input or speed drift can reset the current maneuver.</li>
|
||||
<li>When the status says complete, collect logs and generate the HTML report if needed.</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div class="longManeuverHistory">
|
||||
<h3>Progress Chain</h3>
|
||||
${() => (state.data.history || []).length ? html`
|
||||
<ol>
|
||||
${(state.data.history || []).slice().reverse().map((line) => html`<li>${line}</li>`)}
|
||||
</ol>
|
||||
` : html`<p class="longManeuverMuted">No steps logged yet.</p>`}
|
||||
</div>
|
||||
` : ""}
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
.longManeuverPage {
|
||||
max-width: var(--width-xxl);
|
||||
}
|
||||
|
||||
.longManeuverCard {
|
||||
background-color: var(--secondary-bg);
|
||||
border-radius: var(--border-radius-md);
|
||||
color: var(--text-color);
|
||||
max-width: 90%;
|
||||
padding: var(--border-radius-xl);
|
||||
}
|
||||
|
||||
.longManeuverIntro {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.longManeuverActions {
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.longManeuverButton {
|
||||
background: var(--main-fg);
|
||||
border: none;
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-demi-bold);
|
||||
padding: var(--padding-sm) var(--padding-base);
|
||||
}
|
||||
|
||||
.longManeuverButton:hover {
|
||||
transform: var(--hover-scale-sm);
|
||||
transition: transform var(--transition-fast), background-color var(--transition-fast);
|
||||
}
|
||||
|
||||
.longManeuverButton:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.longManeuverButton.danger {
|
||||
background: var(--danger-bg);
|
||||
}
|
||||
|
||||
.longManeuverButton.danger:hover {
|
||||
background: var(--danger-hover-bg);
|
||||
}
|
||||
|
||||
.longManeuverError {
|
||||
color: var(--danger-fg);
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.longManeuverMuted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.longManeuverStatusGrid {
|
||||
display: grid;
|
||||
gap: 0.5em 1em;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.longManeuverStatusGrid p {
|
||||
font-size: var(--font-size-sm);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.longManeuverCurrent {
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.longManeuverCurrent p {
|
||||
font-size: var(--font-size-sm);
|
||||
margin: 0 0 var(--margin-xs);
|
||||
}
|
||||
|
||||
.longManeuverInstructions,
|
||||
.longManeuverHistory {
|
||||
margin-top: var(--margin-base);
|
||||
}
|
||||
|
||||
.longManeuverInstructions h3,
|
||||
.longManeuverHistory h3 {
|
||||
margin-bottom: var(--margin-xs);
|
||||
}
|
||||
|
||||
.longManeuverInstructions ol,
|
||||
.longManeuverHistory ol {
|
||||
margin: var(--margin-xs) 0 0;
|
||||
padding-left: 1.4rem;
|
||||
}
|
||||
|
||||
.longManeuverInstructions li,
|
||||
.longManeuverHistory li {
|
||||
font-size: var(--font-size-sm);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) and (orientation: portrait) {
|
||||
.longManeuverCard {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.longManeuverActions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.longManeuverStatusGrid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js"
|
||||
|
||||
const state = reactive({
|
||||
loading: true,
|
||||
busy: false,
|
||||
error: "",
|
||||
data: null,
|
||||
})
|
||||
|
||||
let initialized = false
|
||||
let pollHandle = null
|
||||
const POLL_INTERVAL_MS = 3000
|
||||
|
||||
function isLongitudinalManeuversRouteActive() {
|
||||
return window.location.pathname === "/longitudinal_maneuvers"
|
||||
}
|
||||
|
||||
function safeNumber(value, fallback = 0) {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? n : fallback
|
||||
}
|
||||
|
||||
function formatAgeSeconds(value) {
|
||||
const sec = safeNumber(value, -1)
|
||||
if (sec < 0) return "unknown"
|
||||
if (sec < 1) return "just now"
|
||||
if (sec < 60) return `${Math.round(sec)}s ago`
|
||||
const min = sec / 60
|
||||
if (min < 60) return `${Math.round(min)}m ago`
|
||||
const hr = min / 60
|
||||
return `${Math.round(hr)}h ago`
|
||||
}
|
||||
|
||||
function normalizeStatusPayload(payload) {
|
||||
const normalized = payload && typeof payload === "object" ? { ...payload } : {}
|
||||
normalized.support = normalized.support && typeof normalized.support === "object" ? normalized.support : {}
|
||||
normalized.caveats = Array.isArray(normalized.caveats) ? normalized.caveats : []
|
||||
normalized.skippedManeuvers = Array.isArray(normalized.skippedManeuvers) ? normalized.skippedManeuvers : []
|
||||
normalized.history = Array.isArray(normalized.history) ? normalized.history : []
|
||||
return normalized
|
||||
}
|
||||
|
||||
function getSupportValue(key) {
|
||||
const data = state.data && typeof state.data === "object" ? state.data : {}
|
||||
const support = data.support && typeof data.support === "object" ? data.support : {}
|
||||
return support[key]
|
||||
}
|
||||
|
||||
function formatSupportBool(key) {
|
||||
return getSupportValue(key) ? "Yes" : "No"
|
||||
}
|
||||
|
||||
function formatSupportNumber(key, unit) {
|
||||
const value = Number(getSupportValue(key))
|
||||
return Number.isFinite(value) ? `${value.toFixed(2)} ${unit}` : "n/a"
|
||||
}
|
||||
|
||||
async function fetchStatus() {
|
||||
try {
|
||||
const response = await fetch("/api/longitudinal_maneuvers/status")
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || response.statusText || "Failed to load maneuver status")
|
||||
}
|
||||
|
||||
state.data = normalizeStatusPayload(payload)
|
||||
state.error = ""
|
||||
} catch (error) {
|
||||
state.error = error?.message || "Failed to load maneuver status"
|
||||
} finally {
|
||||
state.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (!pollHandle) return
|
||||
clearTimeout(pollHandle)
|
||||
pollHandle = null
|
||||
}
|
||||
|
||||
function ensurePolling() {
|
||||
if (pollHandle) return
|
||||
|
||||
const poll = async () => {
|
||||
if (!isLongitudinalManeuversRouteActive()) {
|
||||
pollHandle = null
|
||||
return
|
||||
}
|
||||
|
||||
if (document.visibilityState !== "visible") {
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
return
|
||||
}
|
||||
|
||||
await fetchStatus()
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
pollHandle = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
async function runAction(action) {
|
||||
if (state.busy) return
|
||||
state.busy = true
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/longitudinal_maneuvers/${action}`, { method: "POST" })
|
||||
const payload = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || response.statusText || `Failed to ${action} maneuvers`)
|
||||
}
|
||||
|
||||
state.data = normalizeStatusPayload(payload)
|
||||
state.error = ""
|
||||
showSnackbar(payload.message || "Action complete.")
|
||||
} catch (error) {
|
||||
const message = error?.message || `Failed to ${action} maneuvers`
|
||||
state.error = message
|
||||
showSnackbar(message, "error")
|
||||
} finally {
|
||||
state.busy = false
|
||||
}
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
if (initialized) return
|
||||
initialized = true
|
||||
fetchStatus()
|
||||
ensurePolling()
|
||||
}
|
||||
|
||||
function statusLine(label, value) {
|
||||
return html`<p><strong>${label}:</strong> ${value}</p>`
|
||||
}
|
||||
|
||||
export function LongitudinalManeuvers() {
|
||||
initialize()
|
||||
|
||||
return html`
|
||||
<div class="longManeuverPage">
|
||||
<h2>Long Maneuvers</h2>
|
||||
|
||||
<div class="longManeuverCard">
|
||||
<p class="longManeuverIntro">
|
||||
Run the longitudinal maneuver suite from your phone and monitor progress live.
|
||||
</p>
|
||||
|
||||
<div class="longManeuverActions">
|
||||
<button
|
||||
class="longManeuverButton"
|
||||
disabled="${() => state.busy || false}"
|
||||
@click="${() => runAction("start")}">
|
||||
Start / Arm
|
||||
</button>
|
||||
<button
|
||||
class="longManeuverButton danger"
|
||||
disabled="${() => state.busy || false}"
|
||||
@click="${() => runAction("stop")}"> Stop
|
||||
</button>
|
||||
</div>
|
||||
|
||||
${() => state.loading ? html`<p class="longManeuverMuted">Loading status...</p>` : ""}
|
||||
${() => state.error ? html`<p class="longManeuverError">${state.error}</p>` : ""}
|
||||
|
||||
${() => state.data ? html`
|
||||
<div class="longManeuverStatusGrid">
|
||||
${statusLine("Mode Enabled", state.data.modeEnabled ? "Yes" : "No")}
|
||||
${statusLine("State", state.data.state || "idle")}
|
||||
${statusLine("Onroad", state.data.isOnroad ? "Yes" : "No")}
|
||||
${statusLine("Engaged", state.data.isEngaged ? "Yes" : "No")}
|
||||
${statusLine("Phase", state.data.phase || "n/a")}
|
||||
${statusLine("Paddle Mode", state.data.paddleMode || "auto")}
|
||||
${statusLine("Step", `${safeNumber(state.data.stepIndex, 0)}/${safeNumber(state.data.stepTotal, 0)}`)}
|
||||
${statusLine("Run", `${safeNumber(state.data.runIndex, 0)}/${safeNumber(state.data.runTotal, 0)}`)}
|
||||
${statusLine("Updated", formatAgeSeconds(state.data.updatedAgeSec))}
|
||||
</div>
|
||||
|
||||
<div class="longManeuverCurrent">
|
||||
<p><strong>Current Maneuver:</strong> ${state.data.maneuver || "n/a"}</p>
|
||||
<p><strong>Popup Text:</strong> ${state.data.uiText1 || ""} ${state.data.uiText2 ? `| ${state.data.uiText2}` : ""}</p>
|
||||
</div>
|
||||
|
||||
<div class="longManeuverStatusGrid">
|
||||
${statusLine("openpilot Long", formatSupportBool("openpilotLongitudinalControl"))}
|
||||
${statusLine("Full Stop + Go", formatSupportBool("fullStopAndGo"))}
|
||||
${statusLine("Auto Resume", formatSupportBool("autoResumeFromStop"))}
|
||||
${statusLine("Resume Assist", formatSupportBool("requiresResumeAssist"))}
|
||||
${statusLine("Expected Zero", formatSupportBool("expectedToReachZero"))}
|
||||
${statusLine("Min Enable", formatSupportNumber("minEnableSpeed", "m/s"))}
|
||||
${statusLine("Stop Accel", formatSupportNumber("stopAccel", "m/s^2"))}
|
||||
</div>
|
||||
|
||||
${(state.data.caveats || []).length ? html`
|
||||
<div class="longManeuverInstructions">
|
||||
<h3>Platform Caveats</h3>
|
||||
<ul>
|
||||
${(state.data.caveats || []).map((line) => html`<li>${line}</li>`)}
|
||||
</ul>
|
||||
</div>
|
||||
` : ""}
|
||||
|
||||
${(state.data.skippedManeuvers || []).length ? html`
|
||||
<div class="longManeuverInstructions">
|
||||
<h3>Expected Skips</h3>
|
||||
<ul>
|
||||
${(state.data.skippedManeuvers || []).map((line) => html`<li>${line}</li>`)}
|
||||
</ul>
|
||||
</div>
|
||||
` : ""}
|
||||
|
||||
<div class="longManeuverInstructions">
|
||||
<h3>Quick Guide</h3>
|
||||
<ol>
|
||||
<li>Find a large, empty, straight road or lot with no traffic.</li>
|
||||
<li>Press <strong>Start / Arm</strong> here, then engage openpilot with SET.</li>
|
||||
<li>Keep full supervision and be ready to disengage at all times.</li>
|
||||
<li>Review the platform caveats before starting. Low-speed maneuvers can be skipped automatically on cars that do not fully stop.</li>
|
||||
<li>When the status says complete, collect logs and generate your HTML report.</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div class="longManeuverHistory">
|
||||
<h3>Progress Chain</h3>
|
||||
${() => (state.data.history || []).length ? html`
|
||||
<ol>
|
||||
${(state.data.history || []).slice().reverse().map((line) => html`<li>${line}</li>`)}
|
||||
</ol>
|
||||
` : html`<p class="longManeuverMuted">No steps logged yet.</p>`}
|
||||
</div>
|
||||
` : ""}
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
export const LONGITUDINAL_MODE_KEY = "LongitudinalControlMode"
|
||||
export const LONGITUDINAL_MODES = [
|
||||
{ value: "chill", label: "Chill" },
|
||||
{ value: "experimental", label: "Experimental" },
|
||||
{ value: "conditional_experimental", label: "Conditional Experimental" },
|
||||
{ value: "conditional_chill", label: "Conditional Chill" },
|
||||
]
|
||||
|
||||
export function longitudinalModeLayout(layout) {
|
||||
return layout.map(section => {
|
||||
const params = section.params || []
|
||||
if (!params.some(p => p.key === "ConditionalExperimental")) return section
|
||||
const byKey = new Map(params.map(p => [p.key, p]))
|
||||
function owner(p) {
|
||||
const seen = new Set()
|
||||
while (p?.parent_key && !seen.has(p.parent_key)) {
|
||||
if (p.parent_key === "ConditionalExperimental") return "conditional_experimental"
|
||||
if (p.parent_key === "ConditionalChill") return "conditional_chill"
|
||||
seen.add(p.parent_key)
|
||||
p = byKey.get(p.parent_key)
|
||||
}
|
||||
return null
|
||||
}
|
||||
return { ...section, params: params.flatMap(p => {
|
||||
if (p.key === "ConditionalChill" || p.key === "ExperimentalMode") return []
|
||||
if (p.key === "ConditionalExperimental") return [{
|
||||
key: LONGITUDINAL_MODE_KEY, label: "Longitudinal control mode", data_type: "string",
|
||||
ui_type: "dropdown", settings_tier: "simple", options: LONGITUDINAL_MODES, is_parent_toggle: true,
|
||||
description: "Chill: conventional speed control. Experimental: model-controlled gas and brakes. Conditional Experimental: Chill, switching to Experimental under your chosen conditions. Conditional Chill: Experimental, switching to Chill for simple cruising.",
|
||||
}]
|
||||
const mode = owner(p)
|
||||
return [{ ...p, ...(mode ? { longitudinal_mode: mode, settings_tier: "simple" } : {}),
|
||||
...(["ConditionalExperimental", "ConditionalChill"].includes(p.parent_key) ? { parent_key: LONGITUDINAL_MODE_KEY } : {}) }]
|
||||
}) }
|
||||
})
|
||||
}
|
||||
|
||||
export function validLongitudinalSnapshot(data) {
|
||||
return !!data && LONGITUDINAL_MODES.some(mode => mode.value === data.mode) &&
|
||||
typeof data.locked === "boolean" && typeof data.reason === "string" &&
|
||||
typeof data.experimental_confirmed === "boolean" &&
|
||||
["ExperimentalMode", "ConditionalExperimental", "ConditionalChill"].every(key => typeof data.values?.[key] === "boolean")
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
.maps-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-lg);
|
||||
max-width: 1400px;
|
||||
padding: var(--padding-base) var(--padding-lg) var(--padding-xxl);
|
||||
}
|
||||
|
||||
.maps-card {
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
color: var(--text-color);
|
||||
padding: var(--padding-lg);
|
||||
}
|
||||
|
||||
.maps-hero {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-lg);
|
||||
}
|
||||
|
||||
.maps-hero-copy h1,
|
||||
.maps-selected-summary h2,
|
||||
.maps-section-header h2,
|
||||
.maps-group-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.maps-hero-copy p,
|
||||
.maps-section-header p,
|
||||
.maps-group-header p,
|
||||
.maps-muted,
|
||||
.maps-error,
|
||||
.maps-warning {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.maps-status-grid {
|
||||
display: grid;
|
||||
gap: var(--gap-sm);
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
}
|
||||
|
||||
.maps-stat {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-base);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
min-height: 5.25rem;
|
||||
padding: 0.8rem;
|
||||
}
|
||||
|
||||
.maps-stat-label {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.82rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.maps-stat-value {
|
||||
font-size: 1rem;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.maps-progress-card {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-base);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
padding: 0.85rem;
|
||||
}
|
||||
|
||||
.maps-progress-header,
|
||||
.maps-progress-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.55rem 1rem;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.maps-progress-meta,
|
||||
.maps-progress-note,
|
||||
.maps-progress-location {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.84rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.maps-progress-track {
|
||||
background: var(--input-bg);
|
||||
border-radius: 999px;
|
||||
height: 0.65rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.maps-progress-fill {
|
||||
background: var(--success-bg);
|
||||
border-radius: inherit;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
transition: width 0.35s ease;
|
||||
}
|
||||
|
||||
.maps-error {
|
||||
color: var(--danger-fg);
|
||||
}
|
||||
|
||||
.maps-warning {
|
||||
color: var(--warning-bg);
|
||||
}
|
||||
|
||||
.maps-action-row,
|
||||
.maps-toolbar-row,
|
||||
.maps-toolbar-meta,
|
||||
.maps-group-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--gap-sm);
|
||||
}
|
||||
|
||||
.maps-btn {
|
||||
border: none;
|
||||
border-radius: var(--border-radius-base);
|
||||
color: var(--text-color);
|
||||
min-height: 2.35rem;
|
||||
padding: 0.5rem 0.9rem;
|
||||
}
|
||||
|
||||
.maps-btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.maps-btn-primary {
|
||||
background: var(--success-bg);
|
||||
color: var(--color-black);
|
||||
}
|
||||
|
||||
.maps-btn-primary:hover:not(:disabled) {
|
||||
background: var(--success-hover-bg);
|
||||
}
|
||||
|
||||
.maps-btn-secondary {
|
||||
background: var(--sidebar-active-bg);
|
||||
}
|
||||
|
||||
.maps-btn-secondary:hover:not(:disabled) {
|
||||
background: var(--accent-hover-bg);
|
||||
}
|
||||
|
||||
.maps-btn-danger {
|
||||
background: var(--danger-bg);
|
||||
}
|
||||
|
||||
.maps-btn-danger:hover:not(:disabled) {
|
||||
background: var(--danger-hover-bg);
|
||||
}
|
||||
|
||||
.maps-btn-small {
|
||||
min-height: 1.9rem;
|
||||
padding: 0.3rem 0.65rem;
|
||||
}
|
||||
|
||||
.maps-toolbar-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-md);
|
||||
}
|
||||
|
||||
.maps-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.maps-field span {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.maps-search-field {
|
||||
flex: 1 1 24rem;
|
||||
}
|
||||
|
||||
.maps-schedule-field {
|
||||
min-width: 13rem;
|
||||
}
|
||||
|
||||
.maps-input,
|
||||
.maps-select {
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-base);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-size-base);
|
||||
min-height: 2.3rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
}
|
||||
|
||||
.maps-schedule-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.maps-selected-summary {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-sm);
|
||||
}
|
||||
|
||||
.maps-chip-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.maps-chip {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: 999px;
|
||||
color: var(--text-color);
|
||||
font-size: 0.82rem;
|
||||
padding: 0.2rem 0.6rem;
|
||||
}
|
||||
|
||||
.maps-section-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-md);
|
||||
}
|
||||
|
||||
.maps-section-header {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.maps-section-header p,
|
||||
.maps-group-header p {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.maps-group-grid {
|
||||
display: grid;
|
||||
gap: var(--gap-md);
|
||||
grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
|
||||
}
|
||||
|
||||
.maps-group-card {
|
||||
background: var(--secondary-bg);
|
||||
border: 1px solid var(--sidebar-border-color);
|
||||
border-radius: var(--border-radius-base);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap-sm);
|
||||
padding: 0.85rem;
|
||||
}
|
||||
|
||||
.maps-group-header {
|
||||
align-items: flex-start;
|
||||
display: flex;
|
||||
gap: var(--gap-sm);
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.maps-region-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
max-height: 21rem;
|
||||
overflow-y: auto;
|
||||
padding-right: 0.15rem;
|
||||
}
|
||||
|
||||
.maps-region-row {
|
||||
align-items: center;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--border-radius-sm);
|
||||
display: grid;
|
||||
gap: 0.6rem;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
|
||||
.maps-region-row:hover {
|
||||
border-color: var(--sidebar-border-color);
|
||||
}
|
||||
|
||||
.maps-region-label {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.maps-region-code {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.maps-page {
|
||||
padding: var(--padding-sm) var(--padding-base) var(--padding-xl);
|
||||
}
|
||||
|
||||
.maps-action-row,
|
||||
.maps-toolbar-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.maps-btn,
|
||||
.maps-schedule-field,
|
||||
.maps-search-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.maps-schedule-button {
|
||||
align-self: stretch;
|
||||
}
|
||||
|
||||
.maps-section-header,
|
||||
.maps-group-header {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.maps-progress-meta {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
}
|
||||
+623
@@ -0,0 +1,623 @@
|
||||
import { html, reactive } from "/assets/vendor/arrow-core.js";
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 15000;
|
||||
const ACTIVE_POLL_INTERVAL_MS = 1000;
|
||||
const IDLE_POLL_INTERVAL_MS = 4000;
|
||||
|
||||
const state = reactive({
|
||||
actionBusy: false,
|
||||
catalogLoaded: false,
|
||||
catalogSections: [],
|
||||
error: "",
|
||||
fetched: false,
|
||||
loadingCatalog: true,
|
||||
loadingStatus: true,
|
||||
savingSchedule: false,
|
||||
savingSelection: false,
|
||||
scheduleDraft: "2",
|
||||
scheduleSaved: "2",
|
||||
scheduleOptions: [],
|
||||
search: "",
|
||||
selectedDraft: [],
|
||||
selectedSaved: [],
|
||||
status: {
|
||||
cancelling: false,
|
||||
downloading: false,
|
||||
hasSelection: false,
|
||||
isOnroad: false,
|
||||
lastUpdate: "Never",
|
||||
mapsPresent: false,
|
||||
scheduleLabel: "Monthly",
|
||||
selectedCount: 0,
|
||||
storageBytes: 0,
|
||||
storageKnown: false,
|
||||
downloadProgress: {
|
||||
active: false,
|
||||
cancelled: false,
|
||||
completed: false,
|
||||
downloadedBytes: 0,
|
||||
downloadedFiles: 0,
|
||||
estimatedDownloadBytes: 0,
|
||||
estimateSource: "",
|
||||
etaSeconds: 0,
|
||||
percent: 0,
|
||||
phase: "idle",
|
||||
primaryLocation: "",
|
||||
storageKnown: false,
|
||||
totalFiles: 0,
|
||||
},
|
||||
},
|
||||
tokenLabels: {},
|
||||
});
|
||||
|
||||
let pollingHandle = null;
|
||||
let statusInFlight = false;
|
||||
|
||||
function notify(message, variant = "success") {
|
||||
if (typeof showSnackbar === "function") {
|
||||
showSnackbar(message, variant);
|
||||
} else if (variant === "error") {
|
||||
console.error(message);
|
||||
} else {
|
||||
console.log(message);
|
||||
}
|
||||
}
|
||||
|
||||
function isMapsRouteActive() {
|
||||
return window.location.pathname === "/manage_maps";
|
||||
}
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timerId = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
|
||||
promise.then((value) => {
|
||||
clearTimeout(timerId);
|
||||
resolve(value);
|
||||
}).catch((error) => {
|
||||
clearTimeout(timerId);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchJson(url, options = {}) {
|
||||
const response = await withTimeout(fetch(url, options), REQUEST_TIMEOUT_MS, `${url} request`);
|
||||
const payload = await withTimeout(response.json(), REQUEST_TIMEOUT_MS, `${url} JSON parse`);
|
||||
if (!response.ok) {
|
||||
throw new Error(payload?.error || payload?.message || `Request failed (${response.status})`);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (value <= 0) return "0 MB";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1);
|
||||
const scaled = value / (1024 ** index);
|
||||
return `${scaled >= 10 || index === 0 ? scaled.toFixed(0) : scaled.toFixed(2)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
const value = Math.max(0, Math.round(Number(seconds || 0)));
|
||||
if (value < 60) return `${value}s`;
|
||||
const minutes = Math.floor(value / 60);
|
||||
const remainingSeconds = value % 60;
|
||||
if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h ${minutes % 60}m`;
|
||||
}
|
||||
|
||||
function normalizeDownloadProgress(progress) {
|
||||
const value = progress && typeof progress === "object" ? progress : {};
|
||||
return {
|
||||
active: Boolean(value.active),
|
||||
cancelled: Boolean(value.cancelled),
|
||||
completed: Boolean(value.completed),
|
||||
downloadedBytes: Number(value.downloadedBytes || 0),
|
||||
downloadedFiles: Number(value.downloadedFiles || 0),
|
||||
estimatedDownloadBytes: Number(value.estimatedDownloadBytes || 0),
|
||||
estimateSource: String(value.estimateSource || ""),
|
||||
etaSeconds: Number(value.etaSeconds || 0),
|
||||
percent: Math.max(0, Math.min(100, Number(value.percent || 0))),
|
||||
phase: String(value.phase || "idle"),
|
||||
primaryLocation: String(value.primaryLocation || ""),
|
||||
storageKnown: Boolean(value.storageKnown),
|
||||
totalFiles: Number(value.totalFiles || 0),
|
||||
};
|
||||
}
|
||||
|
||||
function uniqueSorted(values) {
|
||||
return [...new Set(values)].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
}
|
||||
|
||||
function arraysEqual(a, b) {
|
||||
if (a.length !== b.length) return false;
|
||||
return a.every((value, index) => value === b[index]);
|
||||
}
|
||||
|
||||
function selectionDirty() {
|
||||
return !arraysEqual(state.selectedDraft, state.selectedSaved);
|
||||
}
|
||||
|
||||
function scheduleDirty() {
|
||||
return state.scheduleDraft !== state.scheduleSaved;
|
||||
}
|
||||
|
||||
function getTokenLabel(token) {
|
||||
return state.tokenLabels[token] || token;
|
||||
}
|
||||
|
||||
function setDraftSelection(nextSelection) {
|
||||
state.selectedDraft = uniqueSorted(nextSelection);
|
||||
}
|
||||
|
||||
function toggleToken(token, enabled) {
|
||||
const next = new Set(state.selectedDraft);
|
||||
if (enabled) {
|
||||
next.add(token);
|
||||
} else {
|
||||
next.delete(token);
|
||||
}
|
||||
setDraftSelection([...next]);
|
||||
}
|
||||
|
||||
function setGroup(group, enabled) {
|
||||
const next = new Set(state.selectedDraft);
|
||||
for (const region of group.regions || []) {
|
||||
if (enabled) {
|
||||
next.add(region.token);
|
||||
} else {
|
||||
next.delete(region.token);
|
||||
}
|
||||
}
|
||||
setDraftSelection([...next]);
|
||||
}
|
||||
|
||||
function applyStatus(payload) {
|
||||
const hadSelectionChanges = selectionDirty();
|
||||
const hadScheduleChanges = scheduleDirty();
|
||||
const selectedLocations = Array.isArray(payload.selectedLocations) ? uniqueSorted(payload.selectedLocations) : [];
|
||||
state.status = {
|
||||
cancelling: Boolean(payload.cancelling),
|
||||
downloading: Boolean(payload.downloading),
|
||||
hasSelection: Boolean(payload.hasSelection),
|
||||
isOnroad: Boolean(payload.isOnroad),
|
||||
lastUpdate: payload.lastUpdate || "Never",
|
||||
mapsPresent: Boolean(payload.mapsPresent),
|
||||
scheduleLabel: payload.scheduleLabel || "Monthly",
|
||||
selectedCount: Number(payload.selectedCount || 0),
|
||||
storageBytes: Number(payload.storageBytes || 0),
|
||||
storageKnown: Boolean(payload.storageKnown),
|
||||
downloadProgress: normalizeDownloadProgress(payload.downloadProgress),
|
||||
};
|
||||
state.selectedSaved = selectedLocations;
|
||||
if (!hadSelectionChanges) {
|
||||
state.selectedDraft = selectedLocations;
|
||||
}
|
||||
|
||||
const scheduleValue = String(payload.scheduleValue ?? "2");
|
||||
state.scheduleSaved = scheduleValue;
|
||||
if (!hadScheduleChanges) {
|
||||
state.scheduleDraft = scheduleValue;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCatalog() {
|
||||
const payload = await fetchJson("/api/maps/catalog");
|
||||
state.catalogSections = Array.isArray(payload.sections) ? payload.sections : [];
|
||||
state.scheduleOptions = Array.isArray(payload.scheduleOptions) ? payload.scheduleOptions : [];
|
||||
|
||||
const tokenLabels = {};
|
||||
for (const section of state.catalogSections) {
|
||||
for (const group of section.groups || []) {
|
||||
for (const region of group.regions || []) {
|
||||
tokenLabels[region.token] = region.label;
|
||||
}
|
||||
}
|
||||
}
|
||||
state.tokenLabels = tokenLabels;
|
||||
state.catalogLoaded = true;
|
||||
state.loadingCatalog = false;
|
||||
}
|
||||
|
||||
async function fetchStatus() {
|
||||
if (statusInFlight) return;
|
||||
statusInFlight = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/status");
|
||||
applyStatus(payload);
|
||||
state.error = "";
|
||||
} catch (error) {
|
||||
state.error = error?.message || String(error);
|
||||
} finally {
|
||||
state.loadingStatus = false;
|
||||
statusInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function initializeMaps() {
|
||||
state.loadingCatalog = true;
|
||||
state.loadingStatus = true;
|
||||
try {
|
||||
await fetchCatalog();
|
||||
await fetchStatus();
|
||||
} catch (error) {
|
||||
state.error = error?.message || String(error);
|
||||
state.loadingCatalog = false;
|
||||
state.loadingStatus = false;
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePolling() {
|
||||
if (pollingHandle) return;
|
||||
|
||||
const poll = async () => {
|
||||
if (!isMapsRouteActive()) {
|
||||
pollingHandle = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await fetchStatus();
|
||||
} finally {
|
||||
const nextDelay = state.status.downloading ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
|
||||
pollingHandle = setTimeout(poll, nextDelay);
|
||||
}
|
||||
};
|
||||
|
||||
pollingHandle = setTimeout(poll, ACTIVE_POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
async function saveSelection() {
|
||||
if (state.savingSelection || !selectionDirty()) return;
|
||||
|
||||
state.savingSelection = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/selection", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ selectedLocations: state.selectedDraft }),
|
||||
});
|
||||
if (payload.status) {
|
||||
applyStatus(payload.status);
|
||||
}
|
||||
notify(payload.message || "Map selection saved.");
|
||||
} catch (error) {
|
||||
notify(error?.message || "Failed to save map selection.", "error");
|
||||
} finally {
|
||||
state.savingSelection = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSchedule() {
|
||||
if (state.savingSchedule || !scheduleDirty()) return;
|
||||
|
||||
state.savingSchedule = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/schedule", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ schedule: state.scheduleDraft }),
|
||||
});
|
||||
if (payload.status) {
|
||||
applyStatus(payload.status);
|
||||
}
|
||||
notify(payload.message || "Map schedule updated.");
|
||||
} catch (error) {
|
||||
notify(error?.message || "Failed to update map schedule.", "error");
|
||||
} finally {
|
||||
state.savingSchedule = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startDownload() {
|
||||
if (state.actionBusy || state.status.downloading || state.status.isOnroad || state.selectedDraft.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.actionBusy = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
selectedLocations: state.selectedDraft,
|
||||
schedule: state.scheduleDraft,
|
||||
}),
|
||||
});
|
||||
if (payload.status) {
|
||||
applyStatus(payload.status);
|
||||
}
|
||||
notify(payload.message || "Map download started.");
|
||||
} catch (error) {
|
||||
notify(error?.message || "Failed to start map download.", "error");
|
||||
} finally {
|
||||
state.actionBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelDownload() {
|
||||
if (state.actionBusy || !state.status.downloading) return;
|
||||
|
||||
state.actionBusy = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/cancel", { method: "POST" });
|
||||
if (payload.status) {
|
||||
applyStatus(payload.status);
|
||||
}
|
||||
notify(payload.message || "Map download cancellation requested.");
|
||||
} catch (error) {
|
||||
notify(error?.message || "Failed to cancel map download.", "error");
|
||||
} finally {
|
||||
state.actionBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMaps() {
|
||||
if (state.actionBusy || state.status.downloading || state.status.isOnroad || !state.status.mapsPresent) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.actionBusy = true;
|
||||
try {
|
||||
const payload = await fetchJson("/api/maps/remove", { method: "POST" });
|
||||
if (payload.status) {
|
||||
applyStatus(payload.status);
|
||||
}
|
||||
notify(payload.message || "Maps removed.");
|
||||
} catch (error) {
|
||||
notify(error?.message || "Failed to remove maps.", "error");
|
||||
} finally {
|
||||
state.actionBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetDraftSelection() {
|
||||
state.selectedDraft = [...state.selectedSaved];
|
||||
}
|
||||
|
||||
function clearDraftSelection() {
|
||||
state.selectedDraft = [];
|
||||
}
|
||||
|
||||
function getVisibleRegions(group) {
|
||||
const query = state.search.trim().toLowerCase();
|
||||
if (!query) return group.regions || [];
|
||||
|
||||
return (group.regions || []).filter((region) => {
|
||||
const haystack = `${region.label} ${region.code} ${region.token}`.toLowerCase();
|
||||
return haystack.includes(query);
|
||||
});
|
||||
}
|
||||
|
||||
function getVisibleSections() {
|
||||
return state.catalogSections.map((section) => {
|
||||
const groups = (section.groups || [])
|
||||
.map((group) => ({ ...group, visibleRegions: getVisibleRegions(group) }))
|
||||
.filter((group) => group.visibleRegions.length > 0);
|
||||
return { ...section, groups };
|
||||
}).filter((section) => section.groups.length > 0);
|
||||
}
|
||||
|
||||
function selectedCountForGroup(group) {
|
||||
const groupTokens = new Set((group.regions || []).map((region) => region.token));
|
||||
return state.selectedDraft.filter((token) => groupTokens.has(token)).length;
|
||||
}
|
||||
|
||||
function selectedCountForSection(section) {
|
||||
const sectionTokens = new Set(section.groups.flatMap((group) => (group.regions || []).map((region) => region.token)));
|
||||
return state.selectedDraft.filter((token) => sectionTokens.has(token)).length;
|
||||
}
|
||||
|
||||
function renderSelectedSummary() {
|
||||
if (state.selectedDraft.length === 0) {
|
||||
return html`<p class="maps-muted">No regions selected.</p>`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="maps-chip-list">
|
||||
${state.selectedDraft.map((token) => html`<span class="maps-chip">${getTokenLabel(token)}</span>`)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function downloadSizeLabel() {
|
||||
const progress = state.status.downloadProgress;
|
||||
if (!selectionDirty() && progress.estimatedDownloadBytes > 0) {
|
||||
return `~${formatBytes(progress.estimatedDownloadBytes)} additional`;
|
||||
}
|
||||
if (state.selectedDraft.length > 0) {
|
||||
return "Not yet available";
|
||||
}
|
||||
return "Select regions";
|
||||
}
|
||||
|
||||
function storageLabel() {
|
||||
return state.status.storageKnown ? formatBytes(state.status.storageBytes) : "Calculating…";
|
||||
}
|
||||
|
||||
function renderDownloadProgress() {
|
||||
const progress = state.status.downloadProgress;
|
||||
const visible = state.status.downloading || (!selectionDirty() && (progress.completed || progress.cancelled || progress.estimatedDownloadBytes > 0));
|
||||
if (!visible) return "";
|
||||
|
||||
const isActive = state.status.downloading;
|
||||
const title = isActive ? "Download Progress" : progress.completed ? "Last Download" : progress.cancelled ? "Download Cancelled" : "Download Estimate";
|
||||
const sizeLabel = progress.estimatedDownloadBytes > 0 ? `~${formatBytes(progress.estimatedDownloadBytes)} additional storage` : "Storage estimate unavailable";
|
||||
const storedLabel = progress.downloadedBytes > 0 ? `${formatBytes(progress.downloadedBytes)} added storage` : "Storage reconciles after completion";
|
||||
const filesLabel = progress.totalFiles > 0 ? `${progress.downloadedFiles} / ${progress.totalFiles} files` : "Waiting for map service...";
|
||||
const etaLabel = isActive && progress.etaSeconds > 0 ? `About ${formatDuration(progress.etaSeconds)} remaining` : "ETA unavailable until files start arriving";
|
||||
const sourceLabel = progress.estimateSource === "previous_additional_storage"
|
||||
? "Estimate based on additional storage from the last download of this exact selection."
|
||||
: "File progress comes from mapd; storage is reconciled after the transfer ends.";
|
||||
|
||||
return html`
|
||||
<div class="maps-progress-card">
|
||||
<div class="maps-progress-header">
|
||||
<strong>${title}</strong>
|
||||
<span>${Math.round(progress.percent)}%</span>
|
||||
</div>
|
||||
<div class="maps-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(progress.percent)}">
|
||||
<div class="maps-progress-fill" style="width: ${progress.percent}%;"></div>
|
||||
</div>
|
||||
<div class="maps-progress-meta">
|
||||
<span>${sizeLabel}</span>
|
||||
<span>${storedLabel}</span>
|
||||
<span>${filesLabel}</span>
|
||||
<span>${etaLabel}</span>
|
||||
</div>
|
||||
${progress.primaryLocation ? html`<p class="maps-progress-location">Current region: ${progress.primaryLocation}</p>` : ""}
|
||||
<p class="maps-progress-note">${sourceLabel}</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderGroup(group) {
|
||||
const selectedCount = selectedCountForGroup(group);
|
||||
|
||||
return html`
|
||||
<article class="maps-group-card">
|
||||
<div class="maps-group-header">
|
||||
<div>
|
||||
<h3>${group.title}</h3>
|
||||
<p>${selectedCount} selected</p>
|
||||
</div>
|
||||
<div class="maps-group-actions">
|
||||
<button class="maps-btn maps-btn-secondary maps-btn-small" @click="${() => setGroup(group, true)}">Select All</button>
|
||||
<button class="maps-btn maps-btn-secondary maps-btn-small" @click="${() => setGroup(group, false)}">Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="maps-region-list">
|
||||
${group.visibleRegions.map((region) => html`
|
||||
<label class="maps-region-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked="${() => state.selectedDraft.includes(region.token)}"
|
||||
@change="${(event) => toggleToken(region.token, event.target.checked)}"
|
||||
/>
|
||||
<span class="maps-region-label">${region.label}</span>
|
||||
<span class="maps-region-code">${region.code}</span>
|
||||
</label>
|
||||
`)}
|
||||
</div>
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
||||
export function MapsManager() {
|
||||
if (!state.fetched) {
|
||||
state.fetched = true;
|
||||
initializeMaps();
|
||||
}
|
||||
ensurePolling();
|
||||
|
||||
const visibleSections = () => getVisibleSections();
|
||||
|
||||
return html`
|
||||
<div class="maps-page">
|
||||
<section class="maps-card maps-hero">
|
||||
<div class="maps-hero-copy">
|
||||
<h1>Maps</h1>
|
||||
<p>Select regions, start downloads, and manage offline maps entirely from Galaxy.</p>
|
||||
</div>
|
||||
<div class="maps-status-grid">
|
||||
<div class="maps-stat">
|
||||
<span class="maps-stat-label">Downloader</span>
|
||||
<span class="maps-stat-value">${() => state.loadingStatus ? "Checking..." : (state.status.downloading ? (state.status.cancelling ? "Cancelling" : "Downloading") : "Idle")}</span>
|
||||
</div>
|
||||
<div class="maps-stat">
|
||||
<span class="maps-stat-label">Saved Regions</span>
|
||||
<span class="maps-stat-value">${() => state.status.selectedCount}</span>
|
||||
</div>
|
||||
<div class="maps-stat">
|
||||
<span class="maps-stat-label">Additional Storage</span>
|
||||
<span class="maps-stat-value">${() => downloadSizeLabel()}</span>
|
||||
</div>
|
||||
<div class="maps-stat">
|
||||
<span class="maps-stat-label">Last Updated</span>
|
||||
<span class="maps-stat-value">${() => state.status.lastUpdate}</span>
|
||||
</div>
|
||||
<div class="maps-stat">
|
||||
<span class="maps-stat-label">Storage Used</span>
|
||||
<span class="maps-stat-value">${() => storageLabel()}</span>
|
||||
</div>
|
||||
</div>
|
||||
${() => state.error ? html`<p class="maps-error">${state.error}</p>` : ""}
|
||||
${() => state.status.isOnroad ? html`<p class="maps-warning">Map downloads and removal are blocked while driving.</p>` : ""}
|
||||
${() => selectionDirty() ? html`<p class="maps-warning">You have unsaved region changes. Downloading now will use the current Galaxy selection.</p>` : ""}
|
||||
${() => scheduleDirty() ? html`<p class="maps-warning">You have an unsaved schedule change. Downloading now will also apply it.</p>` : ""}
|
||||
${() => renderDownloadProgress()}
|
||||
<div class="maps-action-row">
|
||||
<button
|
||||
class="maps-btn maps-btn-primary"
|
||||
@click="${() => state.status.downloading ? cancelDownload() : startDownload()}"
|
||||
disabled="${() => state.loadingStatus || state.actionBusy || state.status.isOnroad || (!state.status.downloading && state.selectedDraft.length === 0)}"
|
||||
>
|
||||
${() => state.status.downloading ? (state.status.cancelling ? "Cancelling..." : "Cancel Download") : "Download Maps"}
|
||||
</button>
|
||||
<button
|
||||
class="maps-btn maps-btn-danger"
|
||||
@click="${removeMaps}"
|
||||
disabled="${() => state.loadingStatus || state.actionBusy || state.status.downloading || state.status.isOnroad || !state.status.mapsPresent}"
|
||||
>Remove Maps</button>
|
||||
<button
|
||||
class="maps-btn maps-btn-secondary"
|
||||
@click="${saveSelection}"
|
||||
disabled="${() => state.loadingCatalog || state.savingSelection || !selectionDirty()}"
|
||||
>${() => state.savingSelection ? "Saving..." : "Save Selection"}</button>
|
||||
<button class="maps-btn maps-btn-secondary" @click="${resetDraftSelection}" disabled="${() => !selectionDirty()}">Reset</button>
|
||||
<button class="maps-btn maps-btn-secondary" @click="${clearDraftSelection}" disabled="${() => state.selectedDraft.length === 0}">Clear All</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="maps-card maps-toolbar-card">
|
||||
<div class="maps-toolbar-row">
|
||||
<label class="maps-field maps-search-field">
|
||||
<span>Search Regions</span>
|
||||
<input
|
||||
class="maps-input"
|
||||
type="search"
|
||||
placeholder="Filter by name or code"
|
||||
value="${() => state.search}"
|
||||
@input="${(event) => { state.search = event.target.value; }}"
|
||||
/>
|
||||
</label>
|
||||
<label class="maps-field maps-schedule-field">
|
||||
<span>Auto Update Schedule</span>
|
||||
<select class="maps-select" value="${() => state.scheduleDraft}" @change="${(event) => { state.scheduleDraft = event.target.value; }}">
|
||||
${() => state.scheduleOptions.map((option) => html`<option value="${option.value}">${option.label}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
<button class="maps-btn maps-btn-secondary maps-schedule-button" @click="${saveSchedule}" disabled="${() => state.savingSchedule || !scheduleDirty()}">
|
||||
${() => state.savingSchedule ? "Applying..." : "Apply Schedule"}
|
||||
</button>
|
||||
</div>
|
||||
<div class="maps-toolbar-meta">
|
||||
<span class="maps-muted">Saved schedule: ${() => state.status.scheduleLabel}</span>
|
||||
<span class="maps-muted">Draft regions: ${() => state.selectedDraft.length}</span>
|
||||
</div>
|
||||
<div class="maps-selected-summary">
|
||||
<h2>Selected Regions</h2>
|
||||
${() => renderSelectedSummary()}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
${() => state.loadingCatalog ? html`<section class="maps-card"><p class="maps-muted">Loading map catalog...</p></section>` : ""}
|
||||
${() => !state.loadingCatalog && visibleSections().length === 0 ? html`<section class="maps-card"><p class="maps-muted">No regions match the current search.</p></section>` : ""}
|
||||
${() => visibleSections().map((section) => html`
|
||||
<section class="maps-card maps-section-card">
|
||||
<div class="maps-section-header">
|
||||
<div>
|
||||
<h2>${section.title}</h2>
|
||||
<p>${selectedCountForSection(section)} selected</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="maps-group-grid">
|
||||
${section.groups.map((group) => renderGroup(group))}
|
||||
</div>
|
||||
</section>
|
||||
`)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user